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:
1 parent
d2ef362a98
commit
971ccc3703
56 files changed
+3498
-193
No files matched your search
@@ -19,7 +19,10 @@ import type {
|
||||
DshInstance,
|
||||
DshInstanceRole,
|
||||
DshInstanceStatus,
|
||||
EmailCodeCounts,
|
||||
EmailCodeRow,
|
||||
PublicUser,
|
||||
RecordEmailCodeInput,
|
||||
SessionRow,
|
||||
SessionUser,
|
||||
UpsertBusinessPluginInput,
|
||||
@@ -57,6 +60,24 @@ export interface DbAdapter {
|
||||
findSessionWithUser(tokenHash: string): Promise<SessionUser | undefined>
|
||||
/** Whether the user has any session that has not yet expired (idle reap). */
|
||||
hasActiveSession(userId: string): Promise<boolean>
|
||||
/** Registration e-mail lookup (v10, case-insensitive). */
|
||||
findUserByEmail(email: string): Promise<User | undefined>
|
||||
// e-mail verification codes (v10) — 注册页「邮箱验证码」的存储 + 防爆破计数来源
|
||||
/** Append one `email_codes` row (sent / throttled / failed). */
|
||||
recordEmailCode(input: RecordEmailCodeInput): Promise<void>
|
||||
/** Rolling counters for one (email, ip) pair — the brute-force guard's only input. */
|
||||
emailCodeCounts(email: string, ip: string | null, since: number): Promise<EmailCodeCounts>
|
||||
/** The newest **deliverable** code for (email, purpose), or undefined. */
|
||||
latestSentEmailCode(email: string, purpose: string): Promise<EmailCodeRow | undefined>
|
||||
/**
|
||||
* 记一次校验失败:`attempts + 1`;`consume` 为真时同时打上 `consumed_at`(= 该码作废)。
|
||||
* 返回 false 表示该行已不存在(例如被并发守卫先行作废)。
|
||||
*/
|
||||
bumpEmailCodeAttempts(id: string, consume: boolean, now: number): Promise<boolean>
|
||||
/** 校验通过:打上 `consumed_at`(**单次使用**)。返回 false = 在写入前已被别人用掉。 */
|
||||
consumeEmailCode(id: string, now: number): Promise<boolean>
|
||||
/** 删除早于 `before` 的 `email_codes` 行(自维护,避免表无限增长)。 */
|
||||
purgeEmailCodes(before: number): Promise<number>
|
||||
// audit
|
||||
audit(actor: string | null, action: string, detail?: string | null): Promise<void>
|
||||
// workspaces / plugins
|
||||
|
||||
+96
-4
@@ -16,6 +16,7 @@ import {
|
||||
toDomain,
|
||||
toDshHost,
|
||||
toDshInstance,
|
||||
toEmailCode,
|
||||
toPublicUser,
|
||||
toSession,
|
||||
toUser,
|
||||
@@ -33,7 +34,10 @@ import {
|
||||
type DshInstance,
|
||||
type DshInstanceRole,
|
||||
type DshInstanceStatus,
|
||||
type EmailCodeCounts,
|
||||
type EmailCodeRow,
|
||||
type PublicUser,
|
||||
type RecordEmailCodeInput,
|
||||
type SessionRow,
|
||||
type SessionUser,
|
||||
type UpsertBusinessPluginInput,
|
||||
@@ -50,7 +54,9 @@ import {
|
||||
// both backends. This is process-global and idempotent.
|
||||
types.setTypeParser(20, (value: string) => Number(value))
|
||||
|
||||
const USER_COLS = 'id, username, pass_hash, role, home_dir, api_key_ref, created_at, approved_by, uid'
|
||||
const USER_COLS = 'id, username, pass_hash, role, home_dir, api_key_ref, created_at, approved_by, uid, email'
|
||||
const EMAIL_CODE_COLS =
|
||||
'id, email, purpose, code_hash, status, attempts, ip, username, reason, created_at, expires_at, consumed_at'
|
||||
const DOMAIN_COLS = 'id, user_id, domain, verified, nginx_config, updated_at'
|
||||
const BUSINESS_PLUGIN_COLS = 'id, name, description, version, tgz_path, file_size, uploaded_by, created_at, updated_at'
|
||||
const HOST_COLS = 'id, endpoint, via, network_id, agent_token, capacity_mb, used_mb, status, last_heartbeat'
|
||||
@@ -114,8 +120,9 @@ export class PgAdapter implements DbAdapter {
|
||||
try {
|
||||
return await withTx(this.pool, async (client) => {
|
||||
const { rows } = await client.query(
|
||||
'INSERT INTO users (id, username, pass_hash, role, home_dir, created_at) VALUES ($1, $2, $3, $4, $5, $6) RETURNING row_id',
|
||||
[input.id, input.username, input.passHash, input.role, input.homeDir, createdAt],
|
||||
'INSERT INTO users (id, username, pass_hash, role, home_dir, email, created_at) '
|
||||
+ 'VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING row_id',
|
||||
[input.id, input.username, input.passHash, input.role, input.homeDir, input.email ?? null, createdAt],
|
||||
)
|
||||
const uid = this.baseUid + Number((rows[0] as { row_id: number }).row_id)
|
||||
await client.query('UPDATE users SET uid = $1 WHERE id = $2', [uid, input.id])
|
||||
@@ -129,6 +136,7 @@ export class PgAdapter implements DbAdapter {
|
||||
created_at: createdAt,
|
||||
approved_by: null,
|
||||
uid,
|
||||
email: input.email ?? null,
|
||||
}
|
||||
})
|
||||
} catch (e) {
|
||||
@@ -140,7 +148,6 @@ export class PgAdapter implements DbAdapter {
|
||||
const { rows } = await this.pool.query(`SELECT ${USER_COLS} FROM users WHERE username = $1`, [username])
|
||||
return rows.length > 0 ? toUser(rows[0] as Record<string, unknown>) : undefined
|
||||
}
|
||||
|
||||
async findUserBySlug(slug: string): Promise<User | undefined> {
|
||||
const { rows } = await this.pool.query(`SELECT ${USER_COLS} FROM users WHERE LOWER(username) = $1`, [
|
||||
slug.toLowerCase(),
|
||||
@@ -153,6 +160,91 @@ export class PgAdapter implements DbAdapter {
|
||||
return rows.length > 0 ? toUser(rows[0] as Record<string, unknown>) : undefined
|
||||
}
|
||||
|
||||
/** v10:注册邮箱查重(大小写不敏感)。 */
|
||||
async findUserByEmail(email: string): Promise<User | undefined> {
|
||||
const { rows } = await this.pool.query(`SELECT ${USER_COLS} FROM users WHERE LOWER(email) = $1`, [
|
||||
email.toLowerCase(),
|
||||
])
|
||||
return rows.length > 0 ? toUser(rows[0] as Record<string, unknown>) : undefined
|
||||
}
|
||||
|
||||
// ── v10 邮箱验证码(注册页)—— 与 SQLite 版同款语义,见 repo.ts 注释 ───────────
|
||||
|
||||
async recordEmailCode(input: RecordEmailCodeInput): Promise<void> {
|
||||
await this.pool.query(
|
||||
'INSERT INTO email_codes '
|
||||
+ '(id, email, purpose, code_hash, status, attempts, ip, username, reason, created_at, expires_at, consumed_at) '
|
||||
+ 'VALUES ($1, $2, $3, $4, $5, 0, $6, $7, $8, $9, $10, NULL)',
|
||||
[
|
||||
input.id,
|
||||
input.email,
|
||||
input.purpose,
|
||||
input.codeHash,
|
||||
input.status,
|
||||
input.ip ?? null,
|
||||
input.username ?? null,
|
||||
input.reason ?? null,
|
||||
input.createdAt,
|
||||
input.expiresAt ?? null,
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
async emailCodeCounts(email: string, ip: string | null, since: number): Promise<EmailCodeCounts> {
|
||||
const { rows } = await this.pool.query(
|
||||
`SELECT
|
||||
(SELECT COUNT(*) FROM email_codes WHERE email = $1 AND created_at >= $2) AS email_total,
|
||||
(SELECT COUNT(*) FROM email_codes WHERE email = $1 AND created_at >= $2 AND status = 'sent') AS email_sent,
|
||||
(SELECT COALESCE(MAX(created_at), 0) FROM email_codes WHERE email = $1) AS email_last_at,
|
||||
(SELECT COUNT(*) FROM email_codes WHERE ip IS NOT NULL AND ip = $3 AND created_at >= $2) AS ip_total,
|
||||
(SELECT COUNT(*) FROM email_codes WHERE created_at >= $2) AS global_total`,
|
||||
[email, since, ip],
|
||||
)
|
||||
const row = rows[0] as Record<string, unknown>
|
||||
return {
|
||||
emailTotal: Number(row.email_total ?? 0),
|
||||
emailSent: Number(row.email_sent ?? 0),
|
||||
emailLastAt: Number(row.email_last_at ?? 0),
|
||||
ipTotal: Number(row.ip_total ?? 0),
|
||||
globalTotal: Number(row.global_total ?? 0),
|
||||
}
|
||||
}
|
||||
|
||||
async latestSentEmailCode(email: string, purpose: string): Promise<EmailCodeRow | undefined> {
|
||||
const { rows } = await this.pool.query(
|
||||
`SELECT ${EMAIL_CODE_COLS} FROM email_codes WHERE email = $1 AND purpose = $2 AND status = 'sent' `
|
||||
+ 'ORDER BY created_at DESC LIMIT 1',
|
||||
[email, purpose],
|
||||
)
|
||||
return rows.length > 0 ? toEmailCode(rows[0] as Record<string, unknown>) : undefined
|
||||
}
|
||||
|
||||
async bumpEmailCodeAttempts(id: string, consume: boolean, now: number): Promise<boolean> {
|
||||
const { rowCount } = consume
|
||||
? await this.pool.query(
|
||||
'UPDATE email_codes SET attempts = attempts + 1, consumed_at = $1 WHERE id = $2 AND consumed_at IS NULL',
|
||||
[now, id],
|
||||
)
|
||||
: await this.pool.query(
|
||||
'UPDATE email_codes SET attempts = attempts + 1 WHERE id = $1 AND consumed_at IS NULL',
|
||||
[id],
|
||||
)
|
||||
return (rowCount ?? 0) > 0
|
||||
}
|
||||
|
||||
async consumeEmailCode(id: string, now: number): Promise<boolean> {
|
||||
const { rowCount } = await this.pool.query(
|
||||
'UPDATE email_codes SET consumed_at = $1 WHERE id = $2 AND consumed_at IS NULL',
|
||||
[now, id],
|
||||
)
|
||||
return (rowCount ?? 0) > 0
|
||||
}
|
||||
|
||||
async purgeEmailCodes(before: number): Promise<number> {
|
||||
const { rowCount } = await this.pool.query('DELETE FROM email_codes WHERE created_at < $1', [before])
|
||||
return rowCount ?? 0
|
||||
}
|
||||
|
||||
async listPublicUsers(): Promise<PublicUser[]> {
|
||||
const { rows } = await this.pool.query(`SELECT ${USER_COLS} FROM users ORDER BY created_at ASC`)
|
||||
return rows.map((row) => toPublicUser(toUser(row as Record<string, unknown>)))
|
||||
|
||||
+80
-3
@@ -17,6 +17,7 @@ import {
|
||||
toDomain,
|
||||
toDshHost,
|
||||
toDshInstance,
|
||||
toEmailCode,
|
||||
toPublicUser,
|
||||
toSession,
|
||||
toUser,
|
||||
@@ -34,7 +35,10 @@ import {
|
||||
type DshInstance,
|
||||
type DshInstanceRole,
|
||||
type DshInstanceStatus,
|
||||
type EmailCodeCounts,
|
||||
type EmailCodeRow,
|
||||
type PublicUser,
|
||||
type RecordEmailCodeInput,
|
||||
type SessionRow,
|
||||
type SessionUser,
|
||||
type UpsertBusinessPluginInput,
|
||||
@@ -45,7 +49,9 @@ import {
|
||||
type Workspace,
|
||||
} from './types.js'
|
||||
|
||||
const USER_COLS = 'id, username, pass_hash, role, home_dir, api_key_ref, created_at, approved_by, uid'
|
||||
const USER_COLS = 'id, username, pass_hash, role, home_dir, api_key_ref, created_at, approved_by, uid, email'
|
||||
const EMAIL_CODE_COLS =
|
||||
'id, email, purpose, code_hash, status, attempts, ip, username, reason, created_at, expires_at, consumed_at'
|
||||
const DOMAIN_COLS = 'id, user_id, domain, verified, nginx_config, updated_at'
|
||||
const BUSINESS_PLUGIN_COLS = 'id, name, description, version, tgz_path, file_size, uploaded_by, created_at, updated_at'
|
||||
const INSTANCE_COLS =
|
||||
@@ -56,8 +62,8 @@ export function createUser(db: Database, input: CreateUserInput, baseUid: number
|
||||
const createdAt = Date.now()
|
||||
return db.transaction((): User => {
|
||||
const info = prepare(db,
|
||||
'INSERT INTO users (id, username, pass_hash, role, home_dir, created_at) VALUES (?, ?, ?, ?, ?, ?)',
|
||||
).run(input.id, input.username, input.passHash, input.role, input.homeDir, createdAt)
|
||||
'INSERT INTO users (id, username, pass_hash, role, home_dir, email, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||
).run(input.id, input.username, input.passHash, input.role, input.homeDir, input.email ?? null, createdAt)
|
||||
// SQLite's implicit rowid is the per-user incrementing integer; uid = baseUid + it.
|
||||
const uid = baseUid + Number(info.lastInsertRowid)
|
||||
prepare(db, 'UPDATE users SET uid = ? WHERE id = ?').run(uid, input.id)
|
||||
@@ -71,6 +77,7 @@ export function createUser(db: Database, input: CreateUserInput, baseUid: number
|
||||
created_at: createdAt,
|
||||
approved_by: null,
|
||||
uid,
|
||||
email: input.email ?? null,
|
||||
}
|
||||
})()
|
||||
}
|
||||
@@ -86,6 +93,76 @@ export function findUserBySlug(db: Database, slug: string): User | undefined {
|
||||
return row ? toUser(row as Record<string, unknown>) : undefined
|
||||
}
|
||||
|
||||
/** v10:注册邮箱查重(大小写不敏感)。 */
|
||||
export function findUserByEmail(db: Database, email: string): User | undefined {
|
||||
const row = prepare(db, `SELECT ${USER_COLS} FROM users WHERE LOWER(email) = ?`).get(email.toLowerCase())
|
||||
return row ? toUser(row as Record<string, unknown>) : undefined
|
||||
}
|
||||
|
||||
// ── v10 邮箱验证码 ────────────────────────────────────────────────────────────
|
||||
// 全部计数都**现算**(不维护冗余计数器):省掉"计数器与事实不一致"的整类缺陷,
|
||||
// 代价只是一次带索引的 COUNT;量级(每邮箱每小时个位数行)完全够用。
|
||||
|
||||
export function recordEmailCode(db: Database, input: RecordEmailCodeInput): void {
|
||||
prepare(db,
|
||||
`INSERT INTO email_codes (${EMAIL_CODE_COLS}) VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?, NULL)`,
|
||||
).run(
|
||||
input.id,
|
||||
input.email,
|
||||
input.purpose,
|
||||
input.codeHash,
|
||||
input.status,
|
||||
input.ip ?? null,
|
||||
input.username ?? null,
|
||||
input.reason ?? null,
|
||||
input.createdAt,
|
||||
input.expiresAt ?? null,
|
||||
)
|
||||
}
|
||||
|
||||
export function emailCodeCounts(db: Database, email: string, ip: string | null, since: number): EmailCodeCounts {
|
||||
const row = prepare(db, `
|
||||
SELECT
|
||||
(SELECT COUNT(*) FROM email_codes WHERE email = ? AND created_at >= ?) AS email_total,
|
||||
(SELECT COUNT(*) FROM email_codes WHERE email = ? AND created_at >= ? AND status = 'sent') AS email_sent,
|
||||
(SELECT COALESCE(MAX(created_at), 0) FROM email_codes WHERE email = ?) AS email_last_at,
|
||||
(SELECT COUNT(*) FROM email_codes WHERE ip IS NOT NULL AND ip = ? AND created_at >= ?) AS ip_total,
|
||||
(SELECT COUNT(*) FROM email_codes WHERE created_at >= ?) AS global_total
|
||||
`).get(email, since, email, since, email, ip, since, since) as Record<string, unknown>
|
||||
return {
|
||||
emailTotal: Number(row.email_total ?? 0),
|
||||
emailSent: Number(row.email_sent ?? 0),
|
||||
emailLastAt: Number(row.email_last_at ?? 0),
|
||||
ipTotal: Number(row.ip_total ?? 0),
|
||||
globalTotal: Number(row.global_total ?? 0),
|
||||
}
|
||||
}
|
||||
|
||||
export function latestSentEmailCode(db: Database, email: string, purpose: string): EmailCodeRow | undefined {
|
||||
const row = prepare(db,
|
||||
`SELECT ${EMAIL_CODE_COLS} FROM email_codes WHERE email = ? AND purpose = ? AND status = 'sent' `
|
||||
+ 'ORDER BY created_at DESC LIMIT 1',
|
||||
).get(email, purpose)
|
||||
return row ? toEmailCode(row as Record<string, unknown>) : undefined
|
||||
}
|
||||
|
||||
export function bumpEmailCodeAttempts(db: Database, id: string, consume: boolean, now: number): boolean {
|
||||
const info = consume
|
||||
? prepare(db, 'UPDATE email_codes SET attempts = attempts + 1, consumed_at = ? WHERE id = ? AND consumed_at IS NULL')
|
||||
.run(now, id)
|
||||
: prepare(db, 'UPDATE email_codes SET attempts = attempts + 1 WHERE id = ? AND consumed_at IS NULL').run(id)
|
||||
return info.changes > 0
|
||||
}
|
||||
|
||||
export function consumeEmailCode(db: Database, id: string, now: number): boolean {
|
||||
const info = prepare(db, 'UPDATE email_codes SET consumed_at = ? WHERE id = ? AND consumed_at IS NULL').run(now, id)
|
||||
return info.changes > 0
|
||||
}
|
||||
|
||||
export function purgeEmailCodes(db: Database, before: number): number {
|
||||
return prepare(db, 'DELETE FROM email_codes WHERE created_at < ?').run(before).changes
|
||||
}
|
||||
|
||||
export function findUserById(db: Database, id: string): User | undefined {
|
||||
const row = prepare(db, `SELECT ${USER_COLS} FROM users WHERE id = ?`).get(id)
|
||||
return row ? toUser(row as Record<string, unknown>) : undefined
|
||||
|
||||
@@ -382,6 +382,66 @@ const PG_V9 = `
|
||||
ALTER TABLE dsh_hosts ADD COLUMN network_id TEXT NOT NULL DEFAULT 'ops';
|
||||
`
|
||||
|
||||
// v10(注册页人机验证 + 邮箱验证码):`users.email` + `email_codes` 事件表。
|
||||
//
|
||||
// 为什么放 DB 而不是进程内 Map:① 本表既是**验证码存储**,也是**防爆破计数器的唯一来源**
|
||||
// (冷却 / 每时每刻配额 / 试错次数全靠 `COUNT(*)` 现算)—— 进程内的计数器**一次 restart 即清零**,
|
||||
// 而 deployment 恰好天天重启,等于把限流关掉;② 发码是被外部触发的花钱动作(邮件配额),
|
||||
// 必须可审计(`audit_log` 只记"发生过",记不了"每分钟多少次");③ PG/SQLite 双后端可查。
|
||||
//
|
||||
// 表设计取舍:**只建一张事件表**,把"发送请求"与"校验失败"都记成行(`status` 区分)——
|
||||
// 比"验证码表 + 计数器表 + 黑名单表"三张表少两次 JOIN、且天然是取证时间线。
|
||||
// · `status`:`sent`(已发出,可校验)/ `throttled`(被限流,占位计入配额)/ `failed`(驱动发信失败)
|
||||
// · 只有 `sent` 且 `consumed_at IS NULL` 且未过期的那一行可被校验通过。
|
||||
// · `code_hash` **不存明文**:sha256(email:purpose:code:pepper),pepper = 平台 `encryptionSecret`。
|
||||
// · `attempts` 记该码**已被试错几次**,达上限即 `consumed_at` 打上(作废,必须重新获取)。
|
||||
// ⚠️ 时间戳仍是 **epoch 毫秒 BIGINT**(与全库一致,勿用 timestamptz)。
|
||||
// ⚠️ `users.email` 唯一索引:存量行全为 NULL ⇒ 两方言都允许多个 NULL ⇒ 迁移不会失败;
|
||||
// 用 `LOWER(email)` 保证大小写不敏感唯一(注册时不区分大小写)。
|
||||
const SQLITE_V10 = `
|
||||
ALTER TABLE users ADD COLUMN email TEXT;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_users_email ON users (LOWER(email));
|
||||
CREATE TABLE IF NOT EXISTS email_codes (
|
||||
id TEXT PRIMARY KEY,
|
||||
email TEXT NOT NULL,
|
||||
purpose TEXT NOT NULL,
|
||||
code_hash TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'sent'
|
||||
CHECK (status IN ('sent','throttled','failed')),
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
ip TEXT,
|
||||
username TEXT,
|
||||
reason TEXT,
|
||||
created_at INTEGER NOT NULL,
|
||||
expires_at INTEGER,
|
||||
consumed_at INTEGER
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_email_codes_email ON email_codes (email, purpose, created_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_email_codes_ip ON email_codes (ip, created_at);
|
||||
`
|
||||
|
||||
const PG_V10 = `
|
||||
ALTER TABLE users ADD COLUMN email TEXT;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_users_email ON users (LOWER(email));
|
||||
CREATE TABLE IF NOT EXISTS email_codes (
|
||||
id TEXT PRIMARY KEY,
|
||||
email TEXT NOT NULL,
|
||||
purpose TEXT NOT NULL,
|
||||
code_hash TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'sent'
|
||||
CHECK (status IN ('sent','throttled','failed')),
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
ip TEXT,
|
||||
username TEXT,
|
||||
reason TEXT,
|
||||
created_at BIGINT NOT NULL,
|
||||
expires_at BIGINT,
|
||||
consumed_at BIGINT
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_email_codes_email ON email_codes (email, purpose, created_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_email_codes_ip ON email_codes (ip, created_at);
|
||||
`
|
||||
|
||||
interface Migration {
|
||||
version: number
|
||||
name: string
|
||||
@@ -399,6 +459,7 @@ const MIGRATIONS: readonly Migration[] = [
|
||||
{ version: 7, name: 'cluster host registry + instance lease', sqlite: SQLITE_V7, pg: PG_V7 },
|
||||
{ version: 8, name: 'host reachability via (覆盖网络 S2)', sqlite: SQLITE_V8, pg: PG_V8 },
|
||||
{ version: 9, name: 'host network id (覆盖网络 P0-1)', sqlite: SQLITE_V9, pg: PG_V9 },
|
||||
{ version: 10, name: 'user email + email verification codes', sqlite: SQLITE_V10, pg: PG_V10 },
|
||||
]
|
||||
|
||||
/** Apply unapplied SQLite migrations inside a single transaction. */
|
||||
|
||||
@@ -14,6 +14,8 @@ import { openDatabase, type Database } from './connection.js'
|
||||
import { mapSqliteError } from './errors.js'
|
||||
import {
|
||||
audit as auditSync,
|
||||
bumpEmailCodeAttempts as bumpEmailCodeAttemptsSync,
|
||||
consumeEmailCode as consumeEmailCodeSync,
|
||||
countAdmins as countAdminsSync,
|
||||
createSession as createSessionSync,
|
||||
createUser as createUserSync,
|
||||
@@ -24,6 +26,7 @@ import {
|
||||
deleteUser as deleteUserSync,
|
||||
deleteUserInstances as deleteUserInstancesSync,
|
||||
deleteUserSessions as deleteUserSessionsSync,
|
||||
emailCodeCounts as emailCodeCountsSync,
|
||||
findBusinessPlugin as findBusinessPluginSync,
|
||||
findDomainById as findDomainByIdSync,
|
||||
findDomainByUser as findDomainByUserSync,
|
||||
@@ -31,6 +34,7 @@ import {
|
||||
findSession as findSessionSync,
|
||||
findSessionWithUser as findSessionWithUserSync,
|
||||
hasActiveSession as hasActiveSessionSync,
|
||||
findUserByEmail as findUserByEmailSync,
|
||||
findUserById as findUserByIdSync,
|
||||
findUserBySlug as findUserBySlugSync,
|
||||
findUserByUsername as findUserByUsernameSync,
|
||||
@@ -40,6 +44,7 @@ import {
|
||||
getEnabledPluginIds as getEnabledPluginIdsSync,
|
||||
getOrCreateWorkspace as getOrCreateWorkspaceSync,
|
||||
getSharedModelEnabled as getSharedModelEnabledSync,
|
||||
latestSentEmailCode as latestSentEmailCodeSync,
|
||||
listBusinessPlugins as listBusinessPluginsSync,
|
||||
listCredentialKeys as listCredentialKeysSync,
|
||||
listCredentialLandingRows as listCredentialLandingRowsSync,
|
||||
@@ -48,6 +53,8 @@ import {
|
||||
listInstancesByRole as listInstancesByRoleSync,
|
||||
listPublicUsers as listPublicUsersSync,
|
||||
listUsersWithoutUid as listUsersWithoutUidSync,
|
||||
purgeEmailCodes as purgeEmailCodesSync,
|
||||
recordEmailCode as recordEmailCodeSync,
|
||||
selectCredentialKey as selectCredentialKeySync,
|
||||
setCredentialKey as setCredentialKeySync,
|
||||
setDomainVerified as setDomainVerifiedSync,
|
||||
@@ -86,7 +93,10 @@ import type {
|
||||
DshInstance,
|
||||
DshInstanceRole,
|
||||
DshInstanceStatus,
|
||||
EmailCodeCounts,
|
||||
EmailCodeRow,
|
||||
PublicUser,
|
||||
RecordEmailCodeInput,
|
||||
SessionRow,
|
||||
SessionUser,
|
||||
UpsertBusinessPluginInput,
|
||||
@@ -176,6 +186,35 @@ export class SqliteAdapter implements DbAdapter {
|
||||
auditSync(this.db, actor, action, detail)
|
||||
}
|
||||
|
||||
// ── v10 邮箱验证码(注册页)────────────────────────────────────────────────
|
||||
async findUserByEmail(email: string): Promise<User | undefined> {
|
||||
return findUserByEmailSync(this.db, email)
|
||||
}
|
||||
|
||||
async recordEmailCode(input: RecordEmailCodeInput): Promise<void> {
|
||||
recordEmailCodeSync(this.db, input)
|
||||
}
|
||||
|
||||
async emailCodeCounts(email: string, ip: string | null, since: number): Promise<EmailCodeCounts> {
|
||||
return emailCodeCountsSync(this.db, email, ip, since)
|
||||
}
|
||||
|
||||
async latestSentEmailCode(email: string, purpose: string): Promise<EmailCodeRow | undefined> {
|
||||
return latestSentEmailCodeSync(this.db, email, purpose)
|
||||
}
|
||||
|
||||
async bumpEmailCodeAttempts(id: string, consume: boolean, now: number): Promise<boolean> {
|
||||
return bumpEmailCodeAttemptsSync(this.db, id, consume, now)
|
||||
}
|
||||
|
||||
async consumeEmailCode(id: string, now: number): Promise<boolean> {
|
||||
return consumeEmailCodeSync(this.db, id, now)
|
||||
}
|
||||
|
||||
async purgeEmailCodes(before: number): Promise<number> {
|
||||
return purgeEmailCodesSync(this.db, before)
|
||||
}
|
||||
|
||||
async findWorkspaceByPath(userId: string, relPath: string): Promise<Workspace | undefined> {
|
||||
return findWorkspaceByPathSync(this.db, userId, relPath)
|
||||
}
|
||||
|
||||
@@ -23,8 +23,29 @@ export interface User {
|
||||
approved_by: string | null
|
||||
/** Assigned Linux uid; null until backfilled/assigned (legacy rows). */
|
||||
uid: number | null
|
||||
/** Registration e-mail (v10); null for the legacy rows created before v10. */
|
||||
email: string | null
|
||||
}
|
||||
|
||||
/** One `email_codes` row: a sent code *or* a rejected/failed send attempt. */
|
||||
export interface EmailCodeRow {
|
||||
id: string
|
||||
email: string
|
||||
purpose: string
|
||||
code_hash: string | null
|
||||
status: EmailCodeStatus
|
||||
attempts: number
|
||||
ip: string | null
|
||||
username: string | null
|
||||
reason: string | null
|
||||
created_at: number
|
||||
expires_at: number | null
|
||||
consumed_at: number | null
|
||||
}
|
||||
|
||||
/** `sent` = a deliverable code; the other two only feed the brute-force counters. */
|
||||
export type EmailCodeStatus = 'sent' | 'throttled' | 'failed'
|
||||
|
||||
/** The user shape safe to return over the wire. */
|
||||
export interface PublicUser {
|
||||
id: string
|
||||
@@ -194,6 +215,36 @@ export interface CreateUserInput {
|
||||
passHash: string
|
||||
role: UserRole
|
||||
homeDir: string
|
||||
/** Registration e-mail (v10, optional so the legacy/k8s paths keep working). */
|
||||
email?: string | null
|
||||
}
|
||||
|
||||
/** Insert one `email_codes` row (send attempt, throttled attempt or failed send). */
|
||||
export interface RecordEmailCodeInput {
|
||||
id: string
|
||||
email: string
|
||||
purpose: string
|
||||
codeHash: string | null
|
||||
status: EmailCodeStatus
|
||||
ip?: string | null
|
||||
username?: string | null
|
||||
reason?: string | null
|
||||
createdAt: number
|
||||
expiresAt?: number | null
|
||||
}
|
||||
|
||||
/** Rolling counters used by the brute-force guard (all computed from `email_codes`). */
|
||||
export interface EmailCodeCounts {
|
||||
/** Rows for this e-mail since `since`. */
|
||||
emailTotal: number
|
||||
/** Rows for this e-mail since `since` that were actually deliverable (`sent`). */
|
||||
emailSent: number
|
||||
/** Most recent row timestamp for this e-mail (any status), or 0 when none. */
|
||||
emailLastAt: number
|
||||
/** Rows from this ip since `since` (empty ip ⇒ 0). */
|
||||
ipTotal: number
|
||||
/** Global row count since `since` (protects the provider's daily quota). */
|
||||
globalTotal: number
|
||||
}
|
||||
|
||||
export interface CreateSessionInput {
|
||||
@@ -236,6 +287,24 @@ export function toUser(row: Record<string, unknown>): User {
|
||||
created_at: row.created_at as number,
|
||||
approved_by: (row.approved_by as string | null) ?? null,
|
||||
uid: (row.uid as number | null) ?? null,
|
||||
email: (row.email as string | null) ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
export function toEmailCode(row: Record<string, unknown>): EmailCodeRow {
|
||||
return {
|
||||
id: row.id as string,
|
||||
email: row.email as string,
|
||||
purpose: row.purpose as string,
|
||||
code_hash: (row.code_hash as string | null) ?? null,
|
||||
status: row.status as EmailCodeStatus,
|
||||
attempts: Number(row.attempts ?? 0),
|
||||
ip: (row.ip as string | null) ?? null,
|
||||
username: (row.username as string | null) ?? null,
|
||||
reason: (row.reason as string | null) ?? null,
|
||||
created_at: Number(row.created_at),
|
||||
expires_at: row.expires_at === null || row.expires_at === undefined ? null : Number(row.expires_at),
|
||||
consumed_at: row.consumed_at === null || row.consumed_at === undefined ? null : Number(row.consumed_at),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user