Files
moyi-model-intelligence-hub/control-plane-java/src/main/java/com/moyi/controlplane/auth/VerificationDispatchService.java
T
xpp ba5dbc195e
Repository verification / backend (push) Canceled after 0s
Repository verification / frontend (push) Canceled after 0s
fix:"隔离验证码投递并统一密码重置受理"
2026-10-22 08:49:04 +08:00

135 lines
8.4 KiB
Java

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(); }
}
}