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

@@ -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","验证码无效或已失效,请重新获取"); }
}