fix:"隔离验证码投递并统一密码重置受理"
Repository verification / backend (push) Canceled after 0s
Repository verification / frontend (push) Canceled after 0s

This commit is contained in:
xpp committed 2026-10-22 08:49:04 +08:00
1 parent 02c21e5c19
commit ba5dbc195e
16 files changed
+639 -57

No files matched your search

@@ -26,6 +26,11 @@ public class CloudVerificationSender implements VerificationSender {
@Override
public void send(String channel,String account,String code) {
send(channel,account,code,VerificationPurpose.REGISTRATION);
}
@Override
public void send(String channel,String account,String code,VerificationPurpose purpose) {
if(!available(channel)) throw new ApiException("VERIFICATION_UNAVAILABLE","该验证码发送服务尚未配置,请联系管理员",503);
try {
if("email".equals(channel)) {
@@ -47,8 +52,8 @@ public class CloudVerificationSender implements VerificationSender {
SimpleMailMessage message=new SimpleMailMessage();
message.setFrom(value("MOYI_SMTP_FROM"));
message.setTo(account);
message.setSubject("MOYI 注册验证码");
message.setText("您的注册验证码为:"+code+",5 分钟内有效。请勿向他人泄露。若非本人操作,请忽略此邮件。");
message.setSubject("MOYI "+purpose.label+"验证码");
message.setText("您的"+purpose.label+"验证码为:"+code+",5 分钟内有效。请勿向他人泄露。若非本人操作,请忽略此邮件。");
mail.send(message);
} else {
Config config=new Config().setAccessKeyId(value("MOYI_SMS_ACCESS_KEY_ID")).setAccessKeySecret(value("MOYI_SMS_ACCESS_KEY_SECRET")).setEndpoint("dysmsapi.aliyuncs.com").setProtocol("https");
@@ -57,8 +62,7 @@ public class CloudVerificationSender implements VerificationSender {
.setSignName(value("MOYI_SMS_SIGN_NAME")).setTemplateCode(value("MOYI_SMS_TEMPLATE_CODE")).setTemplateParam("{\"code\":\""+code+"\"}");
var response=client.sendSmsWithOptions(request,new RuntimeOptions().setAutoretry(false).setConnectTimeout(5000).setReadTimeout(10000));
if(response.getBody()==null || !"OK".equals(response.getBody().getCode())) {
String resultCode = response.getBody() == null ? "EMPTY_RESPONSE" : String.valueOf(response.getBody().getCode());
log.warn("Aliyun SMS verification rejected: resultCode={}", resultCode);
log.warn("Aliyun SMS verification rejected");
throw new IllegalStateException("SMS rejected");
}
}
@@ -0,0 +1,134 @@
package com.moyi.controlplane.auth;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.moyi.controlplane.common.ApiException;
import com.moyi.controlplane.security.SecretCipher;
import jakarta.annotation.PreDestroy;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
/** Durable, encrypted single-attempt delivery. Never hold a DB transaction over a mail/SMS call. */
@Service
public class VerificationDispatchService {
private static final Logger log = LoggerFactory.getLogger(VerificationDispatchService.class);
private final JdbcTemplate jdbc;
private final VerificationSender sender;
private final SecretCipher cipher;
private final ObjectMapper json;
private final TransactionTemplate transactions;
private final ExecutorService workers = new ThreadPoolExecutor(0, 2, 30, TimeUnit.SECONDS, new SynchronousQueue<>(),
task -> { var thread=new Thread(task, "verification-delivery"); thread.setDaemon(true); return thread; },
new ThreadPoolExecutor.AbortPolicy());
public VerificationDispatchService(JdbcTemplate jdbc, VerificationSender sender, SecretCipher cipher,
ObjectMapper json, PlatformTransactionManager manager) {
this.jdbc=jdbc; this.sender=sender; this.cipher=cipher; this.json=json;
transactions=new TransactionTemplate(manager);
transactions.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
}
public boolean available(String channel) { return cipher.isConfigured() && sender.available(channel); }
/** Called only after common quotas; code generation and queue insert commit or roll back together. */
@Transactional(propagation=Propagation.MANDATORY)
public void enqueue(VerificationPurpose purpose, String account, String code, String codeHash) {
UUID id=UUID.randomUUID();
String payload;
try { payload=cipher.encrypt(json.writeValueAsString(Map.of("id",id.toString(),"purpose",purpose.key,"account",account,"code",code))); }
catch (ApiException error) { throw error; }
catch (Exception error) { throw new ApiException("VERIFICATION_QUEUE_FAILED", "验证码服务暂时不可用", 503); }
jdbc.update("INSERT INTO "+purpose.table+"(account,code_hash,expires_at,delivery_id) VALUES (?,?,clock_timestamp()+interval '5 minutes',?) ON CONFLICT(account) DO UPDATE SET code_hash=excluded.code_hash,expires_at=excluded.expires_at,attempts=0,consumed=false,created_at=clock_timestamp(),delivery_id=excluded.delivery_id", account,codeHash,id);
jdbc.update("INSERT INTO verification_delivery_outbox(id,purpose,payload_ciphertext) VALUES (?,?,?)",id,purpose.key,payload);
}
@Scheduled(fixedDelayString="${moyi.auth.verification-dispatch-interval-ms:1000}")
public void dispatchPending() {
// No queue behind these two workers: a slow provider cannot consume unbounded threads/tasks.
for (int i=0;i<2;i++) {
try { workers.submit(() -> {
try { dispatchOne(); }
catch (RuntimeException error) { log.warn("Verification delivery persistence failed; no automatic replay"); }
}); } catch (RejectedExecutionException busyOrStopping) { break; }
}
}
private record Attempt(UUID id, VerificationPurpose purpose, String ciphertext) {
@Override public String toString() { return "VerificationAttempt[id="+id+"]"; }
}
/** Package-visible for isolated deterministic database tests; not an HTTP operation. */
boolean dispatchOne() {
Attempt attempt=transactions.execute(status -> {
var rows=jdbc.queryForList("SELECT id,purpose,payload_ciphertext FROM verification_delivery_outbox WHERE status='queued' AND expires_at>clock_timestamp() ORDER BY created_at,id LIMIT 1 FOR UPDATE SKIP LOCKED");
if (rows.isEmpty()) return null;
var row=rows.getFirst(); UUID id=(UUID)row.get("id");
jdbc.update("UPDATE verification_delivery_outbox SET status='sending',started_at=clock_timestamp() WHERE id=?",id);
return new Attempt(id,VerificationPurpose.fromKey(String.valueOf(row.get("purpose"))),String.valueOf(row.get("payload_ciphertext")));
});
if (attempt==null) { cleanupExpired(); return false; }
try {
var payload=json.readTree(cipher.decrypt(attempt.ciphertext()));
if (!attempt.id().toString().equals(payload.path("id").asText())
|| !attempt.purpose().key.equals(payload.path("purpose").asText())
|| !payload.path("code").asText().matches("[0-9]{6}")) throw new IllegalArgumentException("Invalid delivery envelope");
String account=payload.path("account").asText(), code=payload.path("code").asText();
if (!isCurrent(attempt,account)) { finish(attempt,"discarded","SUPERSEDED_OR_INACTIVE"); return true; }
if (Thread.currentThread().isInterrupted()) { finish(attempt,"failed","INTERRUPTED"); return true; }
String channel=account.contains("@")?"email":"phone";
// At this point the claim is committed and its connection is released.
sender.send(channel,account,code,attempt.purpose());
} catch (Exception error) {
// Do not attach/log exceptions: providers can echo recipients, OTPs or credentials.
finish(attempt,"failed","DELIVERY_FAILED");
return true;
}
// A storage failure here leaves 'sending'. Never re-send an ambiguously accepted message.
finish(attempt,"sent",null);
return true;
}
private boolean isCurrent(Attempt attempt, String account) {
String activeUser=attempt.purpose()==VerificationPurpose.PASSWORD_RESET
? " AND EXISTS(SELECT 1 FROM users WHERE account=c.account AND status='active')" : "";
return Boolean.TRUE.equals(jdbc.queryForObject("SELECT EXISTS(SELECT 1 FROM "+attempt.purpose().table+" c WHERE account=? AND delivery_id=? AND consumed=false AND attempts<5 AND expires_at>clock_timestamp()"+activeUser+")",Boolean.class,account,attempt.id()));
}
private void finish(Attempt attempt, String state, String failureCode) {
transactions.executeWithoutResult(status -> {
int changed=jdbc.update("UPDATE verification_delivery_outbox SET status=?,payload_ciphertext=NULL,finished_at=clock_timestamp(),failure_code=? WHERE id=? AND status='sending'",state,failureCode,attempt.id());
if (changed>0 && !"sent".equals(state)) {
jdbc.update("UPDATE "+attempt.purpose().table+" SET consumed=true WHERE delivery_id=?",attempt.id());
}
});
}
private void cleanupExpired() {
transactions.executeWithoutResult(status -> {
// 'sending' abandoned on restart is never retried. Erase the encrypted payload after expiry.
jdbc.update("UPDATE verification_delivery_outbox SET status='discarded',payload_ciphertext=NULL,finished_at=clock_timestamp(),failure_code='EXPIRED' WHERE id IN (SELECT id FROM verification_delivery_outbox WHERE status IN ('queued','sending') AND expires_at<=clock_timestamp() LIMIT 100 FOR UPDATE SKIP LOCKED)");
jdbc.update("DELETE FROM verification_delivery_outbox WHERE id IN (SELECT id FROM verification_delivery_outbox WHERE finished_at<clock_timestamp()-interval '2 days' LIMIT 100)");
for (var purpose : VerificationPurpose.values()) jdbc.update("DELETE FROM "+purpose.table+" WHERE account IN (SELECT account FROM "+purpose.table+" WHERE expires_at<clock_timestamp()-interval '1 day' LIMIT 100 FOR UPDATE SKIP LOCKED)");
});
}
@PreDestroy public void close() {
workers.shutdownNow();
try { workers.awaitTermination(3,TimeUnit.SECONDS); }
catch (InterruptedException error) { Thread.currentThread().interrupt(); }
}
}
@@ -0,0 +1,14 @@
package com.moyi.controlplane.auth;
/** Closed purpose set: SQL identifiers and message intent must never come from a request. */
public enum VerificationPurpose {
REGISTRATION("registration", "registration_codes", "注册"),
PASSWORD_RESET("password-reset", "password_reset_codes", "密码重置");
final String key, table, label;
VerificationPurpose(String key, String table, String label) { this.key=key; this.table=table; this.label=label; }
static VerificationPurpose fromKey(String key) {
for (var purpose : values()) if (purpose.key.equals(key)) return purpose;
throw new IllegalArgumentException("Invalid verification purpose");
}
}
@@ -3,4 +3,5 @@ package com.moyi.controlplane.auth;
public interface VerificationSender {
boolean available(String channel);
void send(String channel, String account, String code);
default void send(String channel, String account, String code, VerificationPurpose purpose) { send(channel,account,code); }
}
@@ -4,7 +4,6 @@ import com.moyi.controlplane.common.ApiException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.nio.charset.StandardCharsets;
import java.time.OffsetDateTime;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
@@ -16,13 +15,13 @@ import org.springframework.transaction.annotation.Transactional;
@Service
public class VerificationService {
private final JdbcTemplate jdbc;
private final VerificationSender sender;
private final VerificationDispatchService dispatch;
private final String pepper;
private final SecureRandom random=new SecureRandom();
public VerificationService(JdbcTemplate jdbc,VerificationSender sender,@Value("${moyi.auth.password-pepper}") String pepper) {
this.jdbc=jdbc; this.sender=sender; this.pepper=pepper;
public VerificationService(JdbcTemplate jdbc,VerificationDispatchService dispatch,@Value("${moyi.auth.password-pepper}") String pepper) {
this.jdbc=jdbc; this.dispatch=dispatch; this.pepper=pepper;
}
public Map<String,Boolean> capabilities() { return Map.of("email",sender.available("email"),"phone",sender.available("phone")); }
public Map<String,Boolean> capabilities() { return Map.of("email",dispatch.available("email"),"phone",dispatch.available("phone")); }
public String normalize(String raw) {
String account=raw==null?"":raw.trim().toLowerCase(Locale.ROOT);
if(!account.contains("@")) account=account.replaceAll("[\\s-]","");
@@ -33,29 +32,33 @@ public class VerificationService {
private String registrationDigest(String account,String code) { return digest("registration",account,code); }
private String resetDigest(String account,String code) { return digest("password-reset",account,code); }
@Transactional(noRollbackFor=ApiException.class)
@Transactional
public Map<String,Object> send(String raw,String invitation,String ip) {
String account=normalize(raw), channel=account.contains("@")?"email":"phone";
if(!sender.available(channel)) throw new ApiException("VERIFICATION_UNAVAILABLE","该验证码发送服务尚未配置,请联系管理员",503);
if(!dispatch.available(channel)) throw new ApiException("VERIFICATION_UNAVAILABLE","该验证码发送服务尚未配置,请联系管理员",503);
Integer invites=jdbc.queryForObject("SELECT count(*) FROM invitation_codes WHERE code_hash=? AND disabled_at IS NULL AND used_count<max_uses AND (expires_at IS NULL OR expires_at>now())",Integer.class,AuthService.hashSecret(invitation==null?"":invitation.trim()));
if(invites==null || invites==0) throw new ApiException("INVITATION_INVALID","请先填写有效邀请码",403);
String source=ip==null?"unknown":ip;
// One global lock bounds aggregate sending and serializes account/IP limits across replicas.
jdbc.queryForList("SELECT pg_advisory_xact_lock(734092615)");
Integer limited=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE account=? AND created_at>now()-interval '60 seconds'",Integer.class,account);
Integer daily=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE account=? AND created_at>now()-interval '24 hours'",Integer.class,account);
Integer hourly=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE ip_address=? AND created_at>now()-interval '1 hour'",Integer.class,source);
Integer total=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE created_at>now()-interval '24 hours'",Integer.class);
if(limited>0 || daily>=10 || hourly>=30 || total>=1000) throw new ApiException("VERIFICATION_RATE_LIMIT","发送过于频繁,请稍后重试",429);
admitSend(account,ip);
String code=String.format(Locale.ROOT,"%06d",random.nextInt(1000000));
jdbc.update("INSERT INTO verification_send_events(id,account,ip_address) VALUES (?,?,?)",UUID.randomUUID(),account,source);
jdbc.update("INSERT INTO registration_codes(account,code_hash,expires_at) VALUES (?,?,now()+interval '5 minutes') ON CONFLICT(account) DO UPDATE SET code_hash=excluded.code_hash, expires_at=excluded.expires_at, attempts=0, consumed=false, created_at=now()",account,registrationDigest(account,code));
try { sender.send(channel,account,code); }
catch(ApiException exception) { jdbc.update("UPDATE registration_codes SET consumed=true WHERE account=?",account); throw exception; }
jdbc.update("DELETE FROM verification_send_events WHERE created_at<now()-interval '2 days'");
return Map.of("sent",true,"retryAfterSeconds",60,"expiresInSeconds",300);
dispatch.enqueue(VerificationPurpose.REGISTRATION,account,code,registrationDigest(account,code));
return accepted();
}
private void admitSend(String account,String ip) {
String source=ip==null || ip.isBlank()?"unknown":ip;
// This lock covers only bounded DB work, NEVER the mail/SMS provider.
jdbc.queryForObject("SELECT set_config('lock_timeout','2s',true)",String.class);
jdbc.queryForList("SELECT pg_advisory_xact_lock(734092615)");
jdbc.update("DELETE FROM verification_send_events WHERE id IN (SELECT id FROM verification_send_events WHERE created_at<clock_timestamp()-interval '2 days' LIMIT 500)");
Integer limited=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE account=? AND created_at>clock_timestamp()-interval '60 seconds'",Integer.class,account);
Integer daily=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE account=? AND created_at>clock_timestamp()-interval '24 hours'",Integer.class,account);
Integer hourly=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE ip_address=? AND created_at>clock_timestamp()-interval '1 hour'",Integer.class,source);
Integer total=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE created_at>clock_timestamp()-interval '24 hours'",Integer.class);
if(limited>0 || daily>=10 || hourly>=30 || total>=1000) throw new ApiException("VERIFICATION_RATE_LIMIT","发送过于频繁,请稍后重试",429);
jdbc.update("INSERT INTO verification_send_events(id,account,ip_address,created_at) VALUES (?,?,?,clock_timestamp())",UUID.randomUUID(),account,source);
}
private Map<String,Object> accepted() { return Map.of("sent",true,"retryAfterSeconds",60,"expiresInSeconds",300); }
@Transactional(noRollbackFor=ApiException.class)
public void consume(String raw,String code) {
String account=normalize(raw);
@@ -69,39 +72,30 @@ public class VerificationService {
jdbc.update("UPDATE registration_codes SET consumed=true WHERE account=?",account);
}
@Transactional(noRollbackFor=ApiException.class)
@Transactional
public Map<String,Object> sendReset(String raw,String ip) {
String account=normalize(raw), channel=account.contains("@")?"email":"phone";
if(!sender.available(channel)) throw new ApiException("VERIFICATION_UNAVAILABLE","该验证码发送服务尚未配置,请联系管理员",503);
Integer exists=jdbc.queryForObject("SELECT count(*) FROM users WHERE account=? AND status='active'",Integer.class,account);
// Do not reveal whether an account exists. The client receives the same response either way.
if(exists==null || exists==0) return Map.of("sent",true,"retryAfterSeconds",60,"expiresInSeconds",300);
String source=ip==null?"unknown":ip;
jdbc.queryForList("SELECT pg_advisory_xact_lock(734092615)");
Integer limited=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE account=? AND created_at>now()-interval '60 seconds'",Integer.class,account);
Integer daily=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE account=? AND created_at>now()-interval '24 hours'",Integer.class,account);
Integer hourly=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE ip_address=? AND created_at>now()-interval '1 hour'",Integer.class,source);
Integer total=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE created_at>now()-interval '24 hours'",Integer.class);
if(limited>0 || daily>=10 || hourly>=30 || total>=1000) throw new ApiException("VERIFICATION_RATE_LIMIT","发送过于频繁,请稍后重试",429);
if(!dispatch.available(channel)) throw new ApiException("VERIFICATION_UNAVAILABLE","该验证码发送服务尚未配置,请联系管理员",503);
// Exact same request-side DB/crypto path for active, unknown and disabled accounts.
// Existence is checked ONLY in the worker; no network result reaches this receipt.
admitSend(account,ip);
String code=String.format(Locale.ROOT,"%06d",random.nextInt(1000000));
jdbc.update("INSERT INTO verification_send_events(id,account,ip_address) VALUES (?,?,?)",UUID.randomUUID(),account,source);
jdbc.update("INSERT INTO password_reset_codes(account,code_hash,expires_at) VALUES (?,?,now()+interval '5 minutes') ON CONFLICT(account) DO UPDATE SET code_hash=excluded.code_hash, expires_at=excluded.expires_at, attempts=0, consumed=false, created_at=now()",account,resetDigest(account,code));
try { sender.send(channel,account,code); }
catch(ApiException exception) { jdbc.update("UPDATE password_reset_codes SET consumed=true WHERE account=?",account); throw exception; }
return Map.of("sent",true,"retryAfterSeconds",60,"expiresInSeconds",300);
dispatch.enqueue(VerificationPurpose.PASSWORD_RESET,account,code,resetDigest(account,code));
return accepted();
}
@Transactional(noRollbackFor=ApiException.class)
public String consumeReset(String raw,String code) {
String account=normalize(raw);
var rows=jdbc.queryForList("SELECT * FROM password_reset_codes WHERE account=? FOR UPDATE",account);
if(rows.isEmpty()) throw new ApiException("VERIFICATION_INVALID","请先获取验证码");
if(rows.isEmpty()) throw invalidResetCode();
var row=rows.getFirst();
java.time.Instant expiry=((java.sql.Timestamp)row.get("expires_at")).toInstant();
if(Boolean.TRUE.equals(row.get("consumed")) || expiry.isBefore(java.time.Instant.now()) || ((Number)row.get("attempts")).intValue()>=5) throw new ApiException("VERIFICATION_EXPIRED","验证码已失效,请重新获取");
if(Boolean.TRUE.equals(row.get("consumed")) || !expiry.isAfter(java.time.Instant.now()) || ((Number)row.get("attempts")).intValue()>=5) throw invalidResetCode();
jdbc.update("UPDATE password_reset_codes SET attempts=attempts+1 WHERE account=?",account);
if(code==null || !code.matches("[0-9]{6}") || !MessageDigest.isEqual(String.valueOf(row.get("code_hash")).getBytes(StandardCharsets.UTF_8),resetDigest(account,code).getBytes(StandardCharsets.UTF_8))) throw new ApiException("VERIFICATION_INVALID","验证码错误");
if(code==null || !code.matches("[0-9]{6}") || !MessageDigest.isEqual(String.valueOf(row.get("code_hash")).getBytes(StandardCharsets.UTF_8),resetDigest(account,code).getBytes(StandardCharsets.UTF_8))) throw invalidResetCode();
jdbc.update("UPDATE password_reset_codes SET consumed=true WHERE account=?",account);
return account;
}
private ApiException invalidResetCode() { return new ApiException("VERIFICATION_INVALID","验证码无效或已失效,请重新获取"); }
}
@@ -40,6 +40,9 @@ public class SecretCipher {
}
}
/** Readiness only; never expose key material. */
public boolean isConfigured() { return key != null; }
public String decrypt(String encoded) {
if (key == null) throw new ApiException("CREDENTIAL_ENCRYPTION_NOT_CONFIGURED", "请先配置供应商凭证加密密钥", 500);
try {
@@ -0,0 +1,21 @@
-- One immutable generation per delivery. No plaintext recipient or OTP is stored in this queue.
ALTER TABLE registration_codes ADD COLUMN delivery_id uuid;
ALTER TABLE password_reset_codes ADD COLUMN delivery_id uuid;
CREATE INDEX registration_codes_expiry_idx ON registration_codes(expires_at);
CREATE TABLE verification_delivery_outbox (
id uuid PRIMARY KEY,
purpose varchar(24) NOT NULL CHECK (purpose IN ('registration','password-reset')),
payload_ciphertext text,
status varchar(16) NOT NULL DEFAULT 'queued' CHECK (status IN ('queued','sending','sent','failed','discarded')),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
expires_at timestamptz NOT NULL DEFAULT clock_timestamp()+interval '5 minutes',
started_at timestamptz,
finished_at timestamptz,
failure_code varchar(32),
CHECK ((status IN ('queued','sending') AND payload_ciphertext IS NOT NULL)
OR (status IN ('sent','failed','discarded') AND payload_ciphertext IS NULL))
);
CREATE INDEX verification_delivery_queue_idx ON verification_delivery_outbox(created_at,id) WHERE status='queued';
CREATE INDEX verification_delivery_expiry_idx ON verification_delivery_outbox(expires_at) WHERE status IN ('queued','sending');
CREATE INDEX verification_delivery_finished_idx ON verification_delivery_outbox(finished_at) WHERE status IN ('sent','failed','discarded');