package com.moyi.controlplane.auth; import com.moyi.controlplane.common.ApiException; import com.moyi.controlplane.security.SecretCipher; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.*; import java.time.*; import java.util.*; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class TotpService { private final JdbcTemplate jdbc;private final SecretCipher cipher; private static final SecureRandom RANDOM=new SecureRandom(); public TotpService(JdbcTemplate jdbc,SecretCipher cipher) {this.jdbc=jdbc;this.cipher=cipher;} public Map status(UUID user) { var rows=jdbc.queryForList("SELECT enabled FROM user_totp WHERE user_id=?",user); return Map.of("enabled",!rows.isEmpty()&&Boolean.TRUE.equals(rows.getFirst().get("enabled")),"recoveryRemaining",jdbc.queryForObject("SELECT count(*) FROM user_totp_recovery WHERE user_id=? AND used_at IS NULL",Integer.class,user)); } @Transactional public Map begin(UUID user,String account) { jdbc.queryForList("SELECT id FROM users WHERE id=? FOR UPDATE",user); if(Boolean.TRUE.equals(status(user).get("enabled"))) throw new ApiException("MFA_ALREADY_ENABLED","双因素认证已经启用",409); byte[] bytes=new byte[20];RANDOM.nextBytes(bytes);String secret=base32(bytes); if(jdbc.update("INSERT INTO user_totp(user_id,secret_ciphertext,pending_until) VALUES (?,?,now()+interval '10 minutes') ON CONFLICT(user_id) DO UPDATE SET secret_ciphertext=excluded.secret_ciphertext,pending_until=excluded.pending_until,last_step=-1,updated_at=now() WHERE user_totp.enabled=false",user,cipher.encrypt(secret))!=1) throw new ApiException("MFA_ALREADY_ENABLED","双因素认证已经启用",409); String label=java.net.URLEncoder.encode("MOYI:"+account,StandardCharsets.UTF_8).replace("+","%20"); return Map.of("secret",secret,"uri","otpauth://totp/"+label+"?secret="+secret+"&issuer=MOYI&algorithm=SHA1&digits=6&period=30","expiresInSeconds",600); } @Transactional(noRollbackFor=ApiException.class) public List confirm(UUID user,String code) { var row=locked(user); if(row.isEmpty()||Boolean.TRUE.equals(row.get("enabled"))||row.get("pending_until")==null||!((java.sql.Timestamp)row.get("pending_until")).toInstant().isAfter(Instant.now())) throw new ApiException("MFA_SETUP_EXPIRED","设置已过期,请重新生成",400); verifyRow(user,row,code,false); jdbc.update("UPDATE user_totp SET enabled=true,pending_until=NULL,updated_at=now() WHERE user_id=?",user); jdbc.update("DELETE FROM user_totp_recovery WHERE user_id=?",user); var codes=new ArrayList(); for(int i=0;i<10;i++) {byte[] random=new byte[12];RANDOM.nextBytes(random);String recovery=HexFormat.of().formatHex(random);codes.add(recovery);jdbc.update("INSERT INTO user_totp_recovery(user_id,code_hash) VALUES (?,?)",user,hash(recovery));} return codes; } @Transactional(noRollbackFor=ApiException.class) public void verifyLogin(UUID user,String code) { var row=locked(user);if(row.isEmpty()||!Boolean.TRUE.equals(row.get("enabled"))) return; if(code==null||code.isBlank()) throw new ApiException("MFA_REQUIRED","请输入认证器验证码或一次性恢复码",401); verifyRow(user,row,code,true); } @Transactional(noRollbackFor=ApiException.class) public void disable(UUID user,String code) { var row=locked(user);if(row.isEmpty()||!Boolean.TRUE.equals(row.get("enabled"))) throw new ApiException("MFA_NOT_ENABLED","双因素认证未启用",400); verifyRow(user,row,code,true); jdbc.update("DELETE FROM user_totp_recovery WHERE user_id=?",user);jdbc.update("DELETE FROM user_totp WHERE user_id=?",user); } private Map locked(UUID user) {var rows=jdbc.queryForList("SELECT * FROM user_totp WHERE user_id=? FOR UPDATE",user);return rows.isEmpty()?Map.of():rows.getFirst();} private void verifyRow(UUID user,Map row,String code,boolean recoveryAllowed) { Instant now=Instant.now();boolean fresh=((java.sql.Timestamp)row.get("attempt_window")).toInstant().isAfter(now.minusSeconds(300)); int attempts=fresh?((Number)row.get("attempts")).intValue():0; if(attempts>=5) throw new ApiException("MFA_RATE_LIMITED","验证码尝试次数过多,请 5 分钟后重试",429); jdbc.update("UPDATE user_totp SET attempts=?,attempt_window=CASE WHEN ? THEN attempt_window ELSE now() END WHERE user_id=?",attempts+1,fresh,user); String normalized=code==null?"":code.strip(); if(recoveryAllowed&&normalized.matches("[0-9a-fA-F]{24}")&&jdbc.update("UPDATE user_totp_recovery SET used_at=now() WHERE user_id=? AND code_hash=? AND used_at IS NULL",user,hash(normalized.toLowerCase(Locale.ROOT)))==1) {jdbc.update("UPDATE user_totp SET attempts=0 WHERE user_id=?",user);return;} long step=now.getEpochSecond()/30,last=((Number)row.get("last_step")).longValue();String secret=cipher.decrypt(row.get("secret_ciphertext").toString()); for(long candidate=step-1;candidate<=step+1;candidate++) { if(candidate>last&&MessageDigest.isEqual(totp(secret,candidate).getBytes(StandardCharsets.US_ASCII),normalized.getBytes(StandardCharsets.US_ASCII))) { jdbc.update("UPDATE user_totp SET last_step=?,attempts=0,updated_at=now() WHERE user_id=?",candidate,user);return; } } throw new ApiException("INVALID_MFA_CODE","验证码无效或已使用",401); } static String totp(String secret,long step) { try {Mac mac=Mac.getInstance("HmacSHA1");mac.init(new SecretKeySpec(decode32(secret),"HmacSHA1"));byte[] value=mac.doFinal(ByteBuffer.allocate(8).putLong(step).array());int offset=value[value.length-1]&15;int number=ByteBuffer.wrap(value,offset,4).getInt()&0x7fffffff;return String.format(Locale.ROOT,"%06d",number%1000000);} catch(Exception e) {throw new IllegalStateException(e);} } static String base32(byte[] data) {String alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";StringBuilder result=new StringBuilder();int bits=0,buffer=0;for(byte b:data) {buffer=(buffer<<8)|(b&255);bits+=8;while(bits>=5) {bits-=5;result.append(alphabet.charAt((buffer>>bits)&31));}}if(bits>0) result.append(alphabet.charAt((buffer<<(5-bits))&31));return result.toString();} private static byte[] decode32(String text) {var out=new java.io.ByteArrayOutputStream();int bits=0,buffer=0;for(char c:text.toCharArray()) {int n="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".indexOf(c);if(n<0) throw new IllegalArgumentException();buffer=(buffer<<5)|n;bits+=5;if(bits>=8) {bits-=8;out.write((buffer>>bits)&255);}}return out.toByteArray();} private static String hash(String value) {try {return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)));} catch(Exception e) {throw new IllegalStateException(e);}} }