后端 - 新增 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>
129 lines
4.4 KiB
JavaScript
129 lines
4.4 KiB
JavaScript
'use strict';
|
||
|
||
const { Service } = require('egg');
|
||
|
||
/** 每天额度按北京时间(UTC+8)切日,避免服务器时区不同导致「第二天」算错 */
|
||
const DAY_OFFSET_MS = 8 * 3600 * 1000;
|
||
|
||
/**
|
||
* 邮件发送日额度(每个邮箱每天最多 N 封)
|
||
*
|
||
* 注册验证码、找回密码重置链接**共用同一个额度**(同一个邮箱一天最多 `config.email.dailyLimit` 封,默认 10),
|
||
* 超出直接拒绝,提示「明天再试」—— 防止被人拿一个邮箱刷爆发信配额 / 骚扰收件人。
|
||
*
|
||
* 存 Redis:
|
||
* - `packs:mailquota:<email>:<yyyy-MM-dd>` 当天已发次数(TTL 到当天 24 点 + 1 分钟)
|
||
*
|
||
* 用法:
|
||
* ```js
|
||
* const quota = await ctx.service.mailQuota.consume(email); // 先占额度
|
||
* if (!quota.ok) return { ok: false, message: quota.message };
|
||
* ...
|
||
* await ctx.service.mailQuota.refund(email); // 没发出去就还回去
|
||
* ```
|
||
*/
|
||
class MailQuotaService extends Service {
|
||
get redis() {
|
||
return this.app.redis;
|
||
}
|
||
|
||
get limit() {
|
||
const value = Number((this.app.config.email || {}).dailyLimit);
|
||
return Number.isFinite(value) && value > 0 ? value : 10;
|
||
}
|
||
|
||
/** 北京时间下的「今天」:yyyy-MM-dd */
|
||
today() {
|
||
const shifted = new Date(Date.now() + DAY_OFFSET_MS);
|
||
const pad = num => String(num).padStart(2, '0');
|
||
return `${shifted.getUTCFullYear()}-${pad(shifted.getUTCMonth() + 1)}-${pad(shifted.getUTCDate())}`;
|
||
}
|
||
|
||
/** 距离北京时间今天结束还有多少秒(+60 秒缓冲),用作 key 的 TTL */
|
||
secondsUntilTomorrow() {
|
||
const shifted = new Date(Date.now() + DAY_OFFSET_MS);
|
||
const midnight = Date.UTC(
|
||
shifted.getUTCFullYear(),
|
||
shifted.getUTCMonth(),
|
||
shifted.getUTCDate() + 1,
|
||
);
|
||
const remain = Math.ceil((midnight - shifted.getTime()) / 1000) + 60;
|
||
return Math.max(remain, 60);
|
||
}
|
||
|
||
keyOf(email) {
|
||
const normalized = String(email || '').trim().toLowerCase();
|
||
return `${this.app.config.cache.prefix}mailquota:${normalized}:${this.today()}`;
|
||
}
|
||
|
||
/** 只读:今天这个邮箱已经发了几封 */
|
||
async used(email) {
|
||
if (!this.redis) return 0;
|
||
try {
|
||
const value = await this.redis.get(this.keyOf(email));
|
||
return Number(value) || 0;
|
||
} catch (err) {
|
||
this.ctx.logger.warn('[mailquota] 读取失败 %s : %s', email, err.message);
|
||
return 0;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 占用一次额度
|
||
* @param {string} email 邮箱
|
||
* @return {Promise<{ok:boolean, used:number, limit:number, remaining:number, message?:string}>}
|
||
*/
|
||
async consume(email) {
|
||
if (!this.redis) return { ok: true, used: 0, limit: this.limit, remaining: this.limit };
|
||
|
||
const normalized = String(email || '').trim().toLowerCase();
|
||
if (!normalized) return { ok: true, used: 0, limit: this.limit, remaining: this.limit };
|
||
|
||
const key = this.keyOf(normalized);
|
||
try {
|
||
const used = await this.redis.incr(key);
|
||
if (used === 1) await this.redis.expire(key, this.secondsUntilTomorrow());
|
||
|
||
if (used > this.limit) {
|
||
// 超额的这次不计入(回退),避免越堆越高
|
||
await this.redis.decr(key);
|
||
this.ctx.logger.warn('[mailquota] %s 今日邮件已达上限 %s 封,拒绝发送', normalized, this.limit);
|
||
return {
|
||
ok: false,
|
||
used: this.limit,
|
||
limit: this.limit,
|
||
remaining: 0,
|
||
message: `该邮箱今天已发送 ${this.limit} 封邮件,达到上限,请明天再试`,
|
||
};
|
||
}
|
||
|
||
return {
|
||
ok: true,
|
||
used,
|
||
limit: this.limit,
|
||
remaining: Math.max(this.limit - used, 0),
|
||
};
|
||
} catch (err) {
|
||
// 计数失败不应挡住正常业务(Redis 抖动时优先保证能发信)
|
||
this.ctx.logger.error('[mailquota] 计数失败 %s : %s', normalized, err.message);
|
||
return { ok: true, used: 0, limit: this.limit, remaining: this.limit };
|
||
}
|
||
}
|
||
|
||
/** 还回一次额度(发信失败 / 被更短的重发节流拦下时调用) */
|
||
async refund(email) {
|
||
if (!this.redis) return;
|
||
const normalized = String(email || '').trim().toLowerCase();
|
||
if (!normalized) return;
|
||
try {
|
||
const key = this.keyOf(normalized);
|
||
const left = await this.redis.decr(key);
|
||
if (left < 0) await this.redis.del(key);
|
||
} catch (err) {
|
||
this.ctx.logger.warn('[mailquota] 回退失败 %s : %s', normalized, err.message);
|
||
}
|
||
}
|
||
}
|
||
|
||
module.exports = MailQuotaService;
|