packServer/backend/app/service/verify_code.js
liufumingren dd9482a3fe 注册 / 找回密码:先判邮箱占用 + 每邮箱每天最多 10 封
后端
- 新增 service/mail_quota.js:每个邮箱每天最多 config.email.dailyLimit(默认 10,EMAIL_DAILY_LIMIT)封,
  注册验证码与找回密码**共用**额度;按北京时间切日,key TTL 到次日 0 点;
  发信失败 / 被 60 秒节流拦下会还回额度;超限返回 429 daily_limit「… 请明天再试」
- service.user.findByEmail() / emailExists():LOWER(email) 查询(大小写不敏感)+ paranoid:false
  (软删除账号仍占用邮箱),单测环境无 sequelize 时退化为等值查询
- register/code:先判邮箱已占用 → 409 email_taken(含「忘记密码可找回」提示),一封邮件都不发;
  发送失败/超限统一返回 429 + status(daily_limit / send_failed)
- register:提交时再判一次邮箱占用(防发码后被抢注)
- forgot:改用 findByEmail(大小写/软删除一致),日额度与注册共用,超限 429
- 单测:新增「邮箱已使用不发信」「每日 10 封上限(注册/找回)」4 个用例;fake-redis 补 decr

前端
- 登录页获取验证码:先做邮箱格式校验,并展示后端 409/429 的具体文案
- 忘记密码页:邮箱格式校验 + 小写归一,429 文案直接显示

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-21 18:03:31 +08:00

138 lines
5.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const { Service } = require('egg');
/** 场景 → Redis key 段(不同场景的验证码互不影响) */
const SCENES = { register: 'verify:register' };
/** 6 位数字验证码 */
function randomCode() {
return String(Math.floor(Math.random() * 1000000)).padStart(6, '0');
}
/**
* 邮箱验证码:生成 / 校验 / 消费
*
* 存在 Redis:
* - `packs:verify:<scene>:<email>` 验证码本身(TTL = config.email.codeTtl,默认 10 分钟)
* - `packs:verify:<scene>:<email>:sent` 重发节流标记(SET NX,TTL = resendInterval,默认 60 秒)
* - `packs:verify:<scene>:<email>:try` 错误次数(超过 maxAttempts 作废验证码)
* - `packs:mailquota:<email>:<date>` 当日发信次数(见 `service/mail_quota.js`,默认每天 10 封)
*
* 对外不抛异常,统一返回 `{ ok, message }`,方便页面回提示(不弹 500)。
*/
class VerifyCodeService extends Service {
get redis() {
return this.app.redis;
}
get cfg() {
return this.app.config.email;
}
keyOf(scene, email) {
const segment = SCENES[scene] || scene;
return `${this.app.config.cache.prefix}${segment}:${email}`;
}
/**
* 生成验证码并发邮件
*
* 顺序(都很重要):
* 1. **日额度**:同一邮箱一天最多 `config.email.dailyLimit` 封(默认 10),超出直接拒绝,不发信;
* 2. **重发节流**:`resendInterval` 秒内只发一次(被拦下会把刚占的日额度还回去);
* 3. 真正发信;发失败同样还额度,避免用户被自己的失败重试耗光当天次数。
*
* @param {string} scene 场景(register)
* @param {string} email 邮箱(调用方保证已小写归一)
* @return {Promise<{ok:boolean, message?:string, reason?:string, code?:string, devMode?:boolean, ttl?:number, resendInterval?:number}>}
*/
async send(scene, email) {
if (!this.redis) return { ok: false, message: '验证码服务不可用(Redis 未就绪)' };
const key = this.keyOf(scene, email);
// 1) 日额度(每个邮箱每天最多 N 封)
const quota = await this.ctx.service.mailQuota.consume(email);
if (!quota.ok) {
return { ok: false, reason: 'daily_limit', message: quota.message };
}
try {
// 2) 重发节流:SET NX 原子占位,间隔内只允许发一次
const locked = await this.redis.set(`${key}:sent`, '1', 'EX', this.cfg.resendInterval, 'NX');
if (locked !== 'OK') {
await this.ctx.service.mailQuota.refund(email);
return { ok: false, message: `验证码已发送,请 ${this.cfg.resendInterval} 秒后再试` };
}
const code = randomCode();
await this.redis.setex(key, this.cfg.codeTtl, code);
await this.redis.del(`${key}:try`);
const mail = await this.ctx.service.mail.sendVerifyCode(email, code, { ttl: this.cfg.codeTtl });
if (mail.failed) {
await this.redis.del(`${key}:sent`); // 发失败就不要占着节流位
await this.ctx.service.mailQuota.refund(email);
return { ok: false, message: '验证码邮件发送失败,请稍后再试' };
}
this.ctx.logger.info('[verify] %s 验证码已生成: %s (devMode=%s, 今日第 %s/%s 封)',
scene, email, !!mail.devMode, quota.used, quota.limit);
// 生产环境绝不回传验证码(即使配置误开 devMode 也兜底)
const exposeDevCode = this.app.config.env !== 'prod' && !!mail.devMode;
return {
ok: true,
ttl: this.cfg.codeTtl,
resendInterval: this.cfg.resendInterval,
remaining: quota.remaining,
devMode: exposeDevCode,
// 开发模式才把验证码回传给页面(生产走邮件)
code: exposeDevCode ? code : undefined,
};
} catch (err) {
this.ctx.logger.error('[verify] 验证码发送失败 %s : %s', email, err.message);
await this.ctx.service.mailQuota.refund(email).catch(() => {});
return { ok: false, message: '验证码服务暂不可用,请稍后再试' };
}
}
/**
* 校验验证码(不消费,注册成功后再 consume,这样用户名冲突时可以改完重提)
* @return {Promise<{ok:boolean, message?:string}>}
*/
async check(scene, email, code) {
if (!this.redis) return { ok: false, message: '验证码服务不可用(Redis 未就绪)' };
const key = this.keyOf(scene, email);
try {
const expect = await this.redis.get(key);
if (!expect) return { ok: false, message: '验证码已过期,请重新获取' };
const tries = await this.redis.incr(`${key}:try`);
await this.redis.expire(`${key}:try`, this.cfg.codeTtl);
if (tries > this.cfg.maxAttempts) {
await this.redis.del(key);
return { ok: false, message: '验证码错误次数过多,请重新获取' };
}
if (String(code) !== String(expect)) {
return { ok: false, message: '邮箱验证码不正确' };
}
return { ok: true };
} catch (err) {
this.ctx.logger.error('[verify] 验证码校验失败 %s : %s', email, err.message);
return { ok: false, message: '验证码服务暂不可用,请稍后再试' };
}
}
/** 消费掉验证码(注册成功后调用) */
async consume(scene, email) {
if (!this.redis) return;
const key = this.keyOf(scene, email);
await this.redis.del(key);
await this.redis.del(`${key}:try`);
}
}
module.exports = VerifyCodeService;