feat(auth): 注册页人机验证 + 邮箱验证码;品牌标识去 DeepSeek(附域名迁移线 序㊿ 补提交)

三条线合并入库 —— 均已完成并上线(源码与生产一致,此前只部署未入仓)。
⚠️ 其中域名迁移线为**另一会话**产出,本会话只做入库、**未复验其正确性**(它自报零回归)。

【档案 134 · 注册页人机验证 + 邮箱验证码】
- DB 迁移 v10:users.email(唯一索引 LOWER(email))+ email_codes 事件表(2 索引)
- 新增模块 src/web/{register-guard,mail,turnstile,email-code}.ts
- routes/auth.ts:新增 GET /api/auth/register/config、POST /api/auth/register/email-code;
  注册接口加人机验证与验证码校验;config.ts 新增 12 项配置(默认空 ⇒ 不配 = 老行为)
- 邮件走**可插拔驱动**(brevo/http/log),发件人 [email protected](Brevo 域名已认证 + DKIM + SPF)
- 防爆破:三层配额(邮箱 6/h、8/天;IP 20/h;全局 200/h)+ 递增冷却阶梯
  (60→60→180→300→900→1800s)+ 试错 5 次作废 + 码只存哈希 + 单次使用 + 与用户名绑定
- Turnstile 服务端校 **success + action + hostname 三项**:sitekey 是公开的,
  只校 success 时"拿我们的 sitekey 在自己站点替真人取合法 token 再打我们接口"这条路是通的
- 新增 test/register-guard.test.mjs(19 用例)

【档案 137 · 品牌标识改造 — 去 DeepSeek 图形】
- login/register/admin 页头:删 DeepSeek 鲸鱼图标 + 「DeepSeek」文字图形
  → 平台标识(中文「能力枢纽」/英语及其他语言「CapabilityNet」,走 i18n 词条 brand.name)
- portal 顶栏换图标(页面名「管理门户」保留)
- 新建 web/favicon.svg(平台自有 hub 图标,避开 DeepSeek 蓝)+ 四页 favicon 指向它
- 新增 test/i18n-brand.test.mjs(node:vm 跑真实 i18n.js,六条语言路径断言渲染结果)
- scripts/verify-static.mjs 新增 SVG 段:XML 注释不得含 ASCII 双连字符(否则整份 SVG
  解析失败、图标静默不显示 —— 实际踩到过)
- 🔴 会话页面(实例内官方 dsh 界面)的标识**按用户要求未动**(也受 R2 约束)

【档案 135/136 · 域名迁移线(另一会话产出)】
- 域名收敛为 ai1net.com;旧域 alotbuy.com 降级为 301 过渡装置
- src/net/relay/{addr-override,directory,rendezvous,switcher}.ts 种子与候选链更新;
  src/web/server.ts、src/worker/relay-tunnel.ts、scripts/verify-cluster-domain.mjs
- 档案 136 = 控制面按两台中继取并集(**已立项、未落地**)

验证(本会话两条线):新增单测 21 条全通过|全量 221 pass / 0 fail / 1 skipped|
verify-static 全合格|其余 10 个 verify 脚本全 OK|线上实测:Turnstile 假 token 403、
发码 delivered、四页 deepseek 命中 0、favicon 200。
This commit is contained in:
admin committed 2026-09-19 09:11:24 +08:00
1 parent d2ef362a98
commit 971ccc3703
56 files changed
+3498 -193

No files matched your search

+196 -3
View File
@@ -14,6 +14,18 @@ import { catalogDiagnostics, isCatalogProvider, isCnProvider, listCatalogProvide
import { PROTOCOLS } from '../model-landing.js'
import { readTextOrEmpty, writeHomeFile } from '../home-files.js'
import { isLocaleId, reconcileLocalePreference } from '../locale-pref.js'
import {
captchaActive,
captchaPartiallyConfigured,
consumeRegisterCode,
emailCodeActive,
guardPolicyFromConfig,
isValidEmail,
normalizeEmail,
requestRegisterCode,
turnstileSettingsFromConfig,
} from '../email-code.js'
import { verifyTurnstile } from '../turnstile.js'
import { join } from 'node:path'
import {
clearSessionCookie,
@@ -42,10 +54,87 @@ const registerSchema = {
properties: {
username: { type: 'string', minLength: 3, maxLength: 32, pattern: '^[a-zA-Z0-9_-]+$' },
password: { type: 'string', minLength: 8, maxLength: 128 },
// 档案 134:邮箱 + 验证码 + 人机验证 token 一律**可选**声明 ——
// 「必填」由配置决定(`emailCodeActive` / `captchaActive`),schema 只保证形状与长度。
// 这样同一份代码在"没配邮件的环境"里仍是老行为,不用改 schema 再发一次版。
email: { type: 'string', maxLength: 254 },
code: { type: 'string', maxLength: 16 },
captchaToken: { type: 'string', maxLength: 4096 },
},
},
} as const
const emailCodeSchema = {
body: {
type: 'object',
required: ['username', 'email'],
additionalProperties: false,
properties: {
username: { type: 'string', minLength: 3, maxLength: 32, pattern: '^[a-zA-Z0-9_-]+$' },
email: { type: 'string', minLength: 6, maxLength: 254 },
captchaToken: { type: 'string', maxLength: 4096 },
},
},
} as const
interface RegisterBody {
username: string
password: string
email?: string
code?: string
captchaToken?: string
}
/**
* 真实客户端 IP(防爆破的**次要**维度)。
*
* 站点经 Cloudflare → 宝塔 nginx → `127.0.0.1:3080`,`trustProxy` 已开 ⇒ `request.ip` 取 XFF 首项
* (由 CF 覆写,不可由访客伪造)。这里优先用 `CF-Connecting-IP`(CF 的权威口径,且不受链路上
* 其它代理拼接 XFF 的影响)。
* ⚠️ **它是次要维度**:源站若可被直连,头仍可伪造 —— 因此真正的承重维度是
* **邮箱维度**(攻击者无法伪造目标地址)与**全局闸门**(保护邮件服务商配额)。IP 维度只用来
* 让"同一台机器猛撞"更快被拦住。
*/
function clientIp(request: { headers: Record<string, unknown>; ip: string }): string | null {
const header = request.headers['cf-connecting-ip']
const value = Array.isArray(header) ? header[0] : header
if (typeof value === 'string' && value.trim() !== '') return value.trim()
return request.ip === '' ? null : request.ip
}
/** 人机验证:配置齐了才校;未配置时**放行**(老行为),并由调用方必要时告警。 */
async function checkCaptcha(
app: { config: unknown; log: { warn: (message: string) => void } },
token: string | undefined,
ip: string | null,
): Promise<{ ok: true } | { ok: false; error: string }> {
const config = app.config as Parameters<typeof captchaActive>[0]
if (!captchaActive(config)) {
// 「密钥给了但没给期望主机名」⇒ 人机验证**静默不生效**。这是最危险的形态
// (看起来配了、实际没防住),所以每次走到这里都留一条告警,让它在日志里可见。
// 去重只做在同一进程内,不影响可观测性(重启后第一条仍会打出来)。
if (captchaPartiallyConfigured(config)) captchaWarnOnce(app)
return { ok: true }
}
const verdict = await verifyTurnstile(turnstileSettingsFromConfig(config), token ?? '', ip ?? undefined)
if (verdict.ok) return { ok: true }
// 上游故障与"token 不对"必须可分:前者是运维问题,后者是访客问题。
const upstream = verdict.error !== null && verdict.error.startsWith('network_error')
app.log.warn(`[register] Turnstile 校验失败 ip=${ip ?? '-'} err=${verdict.error ?? ''}`)
return { ok: false, error: upstream ? 'captcha_unavailable' : 'captcha_failed' }
}
let captchaPartialWarned = false
/** 只在进程内第一条上告警,避免被机器人刷日志。 */
function captchaWarnOnce(app: { log: { warn: (message: string) => void } }): void {
if (captchaPartialWarned) return
captchaPartialWarned = true
app.log.warn(
'[register] Turnstile 已配 siteKey/secret,但期望主机名列表为空 ⇒ 人机验证**未启用**'
+ '(请设 DSHS_TURNSTILE_HOSTNAMES=<域名[,www.域名]>)',
)
}
const loginSchema = {
body: {
type: 'object',
@@ -64,23 +153,127 @@ interface Credentials {
}
export const authRoutes: FastifyPluginAsync = async (app) => {
/**
* 注册页需要知道的**公开**配置(档案 134)。
*
* 为什么要一个端点而不是把 sitekey 写进 HTML:
* · sitekey 随环境变(本地/测试/线上各一个 Turnstile widget),写死会让"换环境忘记换 key"
* 变成一次静默失效 —— 人机验证看起来在,其实一直在报 `invalid-input-secret`;
* · 前端据此**决定要不要渲染**控件,而不是渲染一个永远失败的控件。
* ⚠️ 只回**公钥**。服务端密钥永不出现在任何响应里。
*/
app.get('/api/auth/register/config', async (_request, reply) => {
reply.header('cache-control', 'no-store')
const captchaOn = captchaActive(app.config)
return {
captcha: {
enabled: captchaOn,
// 未启用时给空串 ⇒ 前端不会去加载 CF 脚本(少一个第三方请求)。
siteKey: captchaOn ? app.config.turnstileSiteKey : '',
// ⚠️ `action` 必须由**服务端**下发且与 siteverify 校验的一致:两边各写一份常量,
// 一旦漂掉就是"过不了验证且看不出原因"(CF 只回 action 不匹配,不说是谁配错)。
action: app.config.turnstileAction,
},
emailCode: {
enabled: emailCodeActive(app.config),
ttlSeconds: Math.round(app.config.emailCodeTtlMs / 1000),
maxAttempts: app.config.emailCodeMaxAttempts,
},
// 前端做即时校验用(避免"提交了才说格式错"),与后端同一份口径。
usernamePattern: '^[a-zA-Z0-9_-]{3,32}$',
minPasswordLength: 8,
}
})
/**
* 请求邮箱验证码(档案 134)。
*
* 顺序不可交换:**人机验证 → 配额/冷却 → 发信 → 落事件**。
* 反过来的话,机器人只需猛点就能把真用户的配额吃光(用自己的拒绝服务挡住别人)。
*/
app.post(
'/api/auth/register/email-code',
{ schema: emailCodeSchema, config: { rateLimit: { max: 5, timeWindow: '1 minute' } } },
async (request, reply) => {
const body = request.body as { username: string; email: string; captchaToken?: string }
const ip = clientIp(request as unknown as { headers: Record<string, unknown>; ip: string })
if (!emailCodeActive(app.config)) return reply.code(503).send({ error: 'email_code_disabled' })
const captcha = await checkCaptcha(app, body.captchaToken, ip)
if (!captcha.ok) return reply.code(403).send({ error: captcha.error })
const outcome = await requestRegisterCode(
{ db: app.db, config: app.config, onWarn: (message) => app.log.warn(message) },
{ email: body.email, username: body.username, ip },
)
if (!outcome.ok) {
await app.db.audit(null, 'register_code_rejected', JSON.stringify({ reason: outcome.error, ip }))
if (outcome.retryAfterSeconds > 0) reply.header('retry-after', String(outcome.retryAfterSeconds))
return reply.code(outcome.status).send({
error: outcome.error,
retryAfterSeconds: outcome.retryAfterSeconds,
})
}
await app.db.audit(null, 'register_code_sent', JSON.stringify({ ip }))
return reply.header('retry-after', String(outcome.retryAfterSeconds)).send({
ok: true,
retryAfterSeconds: outcome.retryAfterSeconds,
expiresInSeconds: outcome.expiresInSeconds,
})
},
)
app.post(
'/api/auth/register',
{ schema: registerSchema, config: { rateLimit: { max: 5, timeWindow: '1 minute' } } },
async (request, reply) => {
const { username, password } = request.body as Credentials
const { username, password } = request.body as RegisterBody
const body = request.body as RegisterBody
const ip = clientIp(request as unknown as { headers: Record<string, unknown>; ip: string })
const email = normalizeEmail(body.email ?? '')
// ① 先做**无副作用**的占用检查:命中就不必浪费一次人机验证与一个验证码。
if ((await app.db.findUserByUsername(username)) !== undefined) {
return reply.code(409).send({ error: 'username_taken' })
}
if (email !== '' && (await app.db.findUserByEmail(email)) !== undefined) {
return reply.code(409).send({ error: 'email_taken' })
}
// ② 人机验证(配置齐了才校)。
const captcha = await checkCaptcha(app, body.captchaToken, ip)
if (!captcha.ok) return reply.code(403).send({ error: captcha.error })
// ③ 邮箱验证码(配置齐了才强制)。**校验通过即消费**,同一码不能建两个账号。
if (emailCodeActive(app.config)) {
if (email === '' || !isValidEmail(email)) return reply.code(400).send({ error: 'email_required' })
const verdict = await consumeRegisterCode(
{ db: app.db, config: app.config },
{ email, username, code: (body.code ?? '').trim(), ip },
)
if (!verdict.ok) {
await app.db.audit(null, 'register_code_invalid', JSON.stringify({ reason: verdict.error, ip }))
return reply.code(verdict.status).send({ error: verdict.error, attemptsLeft: verdict.attemptsLeft })
}
}
const id = randomUUID()
const homeDir = homeRoot(userRoot(app.config.dataRoot, id))
const passHash = await hashPassword(password)
// Create the user first so `initUserRoot` resolves the DB-assigned uid
// (baseUid + row_id) instead of the hash fallback — the per-user Pods and
// the DSH Pod must run as the *same* uid or the DSH cannot write its dirs.
const user = await app.db.createUser({ id, username, passHash, role: 'pending', homeDir })
const user = await app.db.createUser({
id,
username,
passHash,
role: 'pending',
homeDir,
email: email === '' ? null : email,
})
await app.userFs.initUserRoot(id, user.uid ?? undefined)
await app.db.audit(id, 'register', JSON.stringify({ username }))
await app.db.audit(id, 'register', JSON.stringify({ username, email: email === '' ? null : email }))
return reply.code(201).send({ user: { id, username, role: 'pending' } })
},
)