Skip to content

Commit 5e313d7

Browse files
authored
feat(auth): support passkey naming and totp labels with schema_v7 (#65)
## Summary - 添加 Passkey 名称与 TOTP 标签支持,上限 50 字、去首尾空格、可选且可空。 - 引入 schema_v7 增量迁移(避开生产库账本历史 v1..v6 编号),存量库按 PRAGMA 动态探测幂等补齐列,基线 schema_v1 同步补齐两列。 - 提供 Passkey 命名/改名与 TOTP 标签启用/修改/停用清除接口,UserView 与 PasskeyView 均对齐回显。 ## Changes - **Database & Migrations**: 基线 `worker/src/lib/schema.ts` 与 `worker/src/db/schema.sql` 增加 `passkey_credentials.name` 与 `user_2fa.totp_label` 可空列;`worker/src/lib/migrations.ts` 新增 `schema_v7` 增量迁移,存量库动态补齐缺列。 - **Queries & Views**: `worker/src/db/queries/passkeys.ts` 暴露 `PasskeyView.name`,支持 `insertPasskey` 带 name 与 `updatePasskeyName`;`worker/src/db/queries/twofa.ts` 支持 `totp_label` 读写与更新;`worker/src/lib/user-view.ts` 暴露 `UserView.totpLabel`。 - **Routes & Input Sanitization**: `worker/src/lib/account.ts` 实现 `normalizeTag`(trim + slice(0,50) + 空串转 null);`worker/src/routes/me.ts` 新增 `PATCH /api/me/passkeys/:id`;`worker/src/routes/twofa-manage.ts` 在 passkey 注册、totp 启用/改标签/停用中对齐标签处理,并显式校验非法/缺省 body。 - **Tests**: `worker/test/migrations-ledger.test.ts` 与 `worker/test/setup.test.ts` 更新账本断言,覆盖生产库 v1..v6 存量增量补齐与幂等验证;新增 `worker/test/passkey-name-totp-label.test.ts` 完整覆盖 10 项冻结契约。 ## Testing - `pnpm --filter ./worker test`: 30 passed, 223 passed - `pnpm test`: Worker 223 passed, Web 170 passed - `pnpm check:identity` / `pnpm lint` / `pnpm format:check` / `pnpm typecheck` / `pnpm check:deploy`: 全量通过 - GitHub Actions CI (PR #65): Run 45322975570 全绿通过 (Validate 51s)
1 parent b5aeaaf commit 5e313d7

14 files changed

Lines changed: 796 additions & 56 deletions

‎worker/src/db/queries/passkeys.ts‎

Lines changed: 31 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
/**
22
* 通行密钥凭据的读写(表 `passkey_credentials`,结构对齐 eNotify)。
33
*
4-
* 公钥与 credential_id 只进数据库、不进任何面向用户的 DTO;列表接口只暴露
5-
* id / 创建时间 / 最近使用时间 / transports,供设置页展示与删除。
4+
* 公钥与 credential_id 只进数据库、不进任何面向用户的 DTO;列表接口暴露
5+
* id / 名称 (name) / 创建时间 / 最近使用时间 / transports,供设置页展示、改名与删除。
66
*/
77
import { passkeysTable } from "../../lib/tables"
88

@@ -15,10 +15,12 @@ export interface PasskeyRow {
1515
transports: string
1616
created_at: string
1717
last_used_at: string | null
18+
name: string | null
1819
}
1920

2021
export interface PasskeyView {
2122
id: number
23+
name: string | null
2224
createdAt: string
2325
lastUsedAt: string | null
2426
transports: string[]
@@ -27,6 +29,7 @@ export interface PasskeyView {
2729
function toView(row: PasskeyRow): PasskeyView {
2830
return {
2931
id: row.id,
32+
name: row.name ?? null,
3033
createdAt: row.created_at,
3134
lastUsedAt: row.last_used_at,
3235
transports: row.transports
@@ -46,7 +49,7 @@ export async function listPasskeys(
4649
const rows = await db
4750
.prepare(
4851
`SELECT id, user_id, credential_id, public_key, counter, transports,
49-
created_at, last_used_at
52+
created_at, last_used_at, name
5053
FROM ${passkeysTable(prefix)}
5154
WHERE user_id = ?
5255
ORDER BY id ASC`
@@ -87,7 +90,7 @@ export async function findPasskeyByCredentialId(
8790
return db
8891
.prepare(
8992
`SELECT id, user_id, credential_id, public_key, counter, transports,
90-
created_at, last_used_at
93+
created_at, last_used_at, name
9194
FROM ${passkeysTable(prefix)}
9295
WHERE user_id = ? AND credential_id = ?`
9396
)
@@ -103,7 +106,7 @@ export async function findPasskeyByCredential(
103106
return db
104107
.prepare(
105108
`SELECT id, user_id, credential_id, public_key, counter, transports,
106-
created_at, last_used_at
109+
created_at, last_used_at, name
107110
FROM ${passkeysTable(prefix)}
108111
WHERE credential_id = ?`
109112
)
@@ -120,25 +123,45 @@ export async function insertPasskey(
120123
publicKey: string
121124
counter: number
122125
transports: string[]
126+
name?: string | null
123127
}
124128
): Promise<void> {
125129
await db
126130
.prepare(
127131
`INSERT INTO ${passkeysTable(prefix)}
128-
(user_id, credential_id, public_key, counter, transports, created_at, last_used_at)
129-
VALUES (?, ?, ?, ?, ?, ?, NULL)`
132+
(user_id, credential_id, public_key, counter, transports, created_at, last_used_at, name)
133+
VALUES (?, ?, ?, ?, ?, ?, NULL, ?)`
130134
)
131135
.bind(
132136
input.userId,
133137
input.credentialId,
134138
input.publicKey,
135139
input.counter,
136140
input.transports.join(","),
137-
new Date().toISOString()
141+
new Date().toISOString(),
142+
input.name ?? null
138143
)
139144
.run()
140145
}
141146

147+
export async function updatePasskeyName(
148+
db: D1Database,
149+
prefix: string,
150+
userId: number,
151+
id: number,
152+
name: string | null
153+
): Promise<boolean> {
154+
const result = await db
155+
.prepare(
156+
`UPDATE ${passkeysTable(prefix)}
157+
SET name = ?
158+
WHERE id = ? AND user_id = ?`
159+
)
160+
.bind(name, id, userId)
161+
.run()
162+
return result.meta.changes === 1
163+
}
164+
142165
/** 记一次成功断言:更新签名计数器与最近使用时间(防重放)。 */
143166
export async function touchPasskey(
144167
db: D1Database,

‎worker/src/db/queries/twofa.ts‎

Lines changed: 34 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ export interface TwoFactorRow {
99
totp_secret: string | null
1010
totp_enabled: number
1111
email_2fa_enabled: number
12+
totp_label: string | null
1213
updated_at: string
1314
}
1415

@@ -19,7 +20,7 @@ export async function getTwoFactor(
1920
): Promise<TwoFactorRow | null> {
2021
return db
2122
.prepare(
22-
`SELECT user_id, totp_secret, totp_enabled, email_2fa_enabled, updated_at
23+
`SELECT user_id, totp_secret, totp_enabled, email_2fa_enabled, totp_label, updated_at
2324
FROM ${user2faTable(prefix)} WHERE user_id = ?`
2425
)
2526
.bind(userId)
@@ -30,19 +31,47 @@ export async function upsertTwoFactor(
3031
db: D1Database,
3132
prefix: string,
3233
userId: number,
33-
patch: { totpSecret?: string | null; totpEnabled: number }
34+
patch: {
35+
totpSecret?: string | null
36+
totpEnabled: number
37+
totpLabel?: string | null
38+
}
3439
): Promise<void> {
3540
const now = new Date().toISOString()
3641
await db
3742
.prepare(
38-
`INSERT INTO ${user2faTable(prefix)} (user_id, totp_secret, totp_enabled, updated_at)
39-
VALUES (?, ?, ?, ?)
43+
`INSERT INTO ${user2faTable(prefix)} (user_id, totp_secret, totp_enabled, totp_label, updated_at)
44+
VALUES (?, ?, ?, ?, ?)
4045
ON CONFLICT(user_id) DO UPDATE SET
4146
totp_secret = excluded.totp_secret,
4247
totp_enabled = excluded.totp_enabled,
48+
totp_label = excluded.totp_label,
4349
updated_at = excluded.updated_at`
4450
)
45-
.bind(userId, patch.totpSecret ?? null, patch.totpEnabled, now)
51+
.bind(
52+
userId,
53+
patch.totpSecret ?? null,
54+
patch.totpEnabled,
55+
patch.totpLabel ?? null,
56+
now
57+
)
58+
.run()
59+
}
60+
61+
export async function updateTotpLabel(
62+
db: D1Database,
63+
prefix: string,
64+
userId: number,
65+
label: string | null
66+
): Promise<void> {
67+
const now = new Date().toISOString()
68+
await db
69+
.prepare(
70+
`UPDATE ${user2faTable(prefix)}
71+
SET totp_label = ?, updated_at = ?
72+
WHERE user_id = ? AND totp_enabled = 1`
73+
)
74+
.bind(label, now, userId)
4675
.run()
4776
}
4877

‎worker/src/db/schema.sql‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@ CREATE TABLE IF NOT EXISTS {prefix}user_2fa (
2525
totp_secret TEXT,
2626
totp_enabled INTEGER NOT NULL DEFAULT 0,
2727
updated_at TEXT NOT NULL,
28-
email_2fa_enabled INTEGER NOT NULL DEFAULT 0
28+
email_2fa_enabled INTEGER NOT NULL DEFAULT 0,
29+
totp_label TEXT
2930
);
3031

3132
CREATE TABLE IF NOT EXISTS {prefix}passkey_credentials (
@@ -36,7 +37,8 @@ CREATE TABLE IF NOT EXISTS {prefix}passkey_credentials (
3637
counter INTEGER NOT NULL DEFAULT 0,
3738
transports TEXT NOT NULL DEFAULT '',
3839
created_at TEXT NOT NULL,
39-
last_used_at TEXT
40+
last_used_at TEXT,
41+
name TEXT
4042
);
4143

4244
CREATE TABLE IF NOT EXISTS {prefix}sessions (

‎worker/src/lib/account.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,10 @@ export async function requirePassword(
3535
}
3636
return null
3737
}
38+
39+
/** 名称/标签规范化:去首尾空格、截断上限 50 字、空串转 null。 */
40+
export function normalizeTag(value: unknown): string | null {
41+
if (typeof value !== "string") return null
42+
const trimmed = value.trim()
43+
return trimmed.length > 0 ? trimmed.slice(0, 50) : null
44+
}

‎worker/src/lib/migrations-runner.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -125,9 +125,9 @@ function migrationError(name: string, err: unknown): Error {
125125
* 才记账;失败立即抛出,不记录该迁移、也不继续后续迁移(下次 setup 会重跑它,
126126
* 各阶段都是幂等的)。
127127
*
128-
* 生产库只读兼容:生产库历史上已应用过 schema_v1..v6,其账本中已存在 schema_v1。
129-
* 坍缩为单一 V1 后,applied.has("schema_v1") 命中直接 skipped,不执行任何 DDL,
130-
* 不写生产库账本(0 次写入),不丢数据。
128+
* 生产库兼容:生产库历史上已应用过 schema_v1..v6,其账本中已存在 schema_v1..v6。
129+
* 单一基线 schema_v1 在 applied.has("schema_v1") 命中直接 skipped;后续增量迁移(如 schema_v7)
130+
* 避开历史编号,存量库未应用时正常执行 prepare/sql 并在成功后记账。
131131
*/
132132
export async function runLedgerMigrations(
133133
env: Env

‎worker/src/lib/migrations.ts‎

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
* 表名/索引名一律经 tables.ts(基线迁移经 schema.ts 的 `{prefix}` 占位)拼装,不写死前缀。
1313
*/
1414
import { SCHEMA_INDEXES, SCHEMA_TABLES, baselineStatements } from "./schema"
15-
import { tableName } from "./tables"
15+
import { passkeysTable, tableName, user2faTable } from "./tables"
1616

1717
/** 迁移执行时能拿到的东西:库与生效前缀。 */
1818
export interface MigrationContext {
@@ -29,6 +29,18 @@ export interface Migration {
2929

3030
/** 唯一基线迁移名(坍缩为单一 V1)。 */
3131
export const BASELINE_MIGRATION = "schema_v1"
32+
export const SCHEMA_V7_MIGRATION = "schema_v7"
33+
34+
async function hasColumn(
35+
db: D1Database,
36+
table: string,
37+
column: string
38+
): Promise<boolean> {
39+
const info = await db
40+
.prepare(`PRAGMA table_info(${table})`)
41+
.all<{ name: string }>()
42+
return (info.results || []).some((col) => col.name === column)
43+
}
3244

3345
export function getMigrations(prefix: string): Migration[] {
3446
const statements = baselineStatements(prefix)
@@ -50,5 +62,26 @@ export function getMigrations(prefix: string): Migration[] {
5062
}
5163
}
5264

53-
return [{ name: BASELINE_MIGRATION, sql }]
65+
return [
66+
{ name: BASELINE_MIGRATION, sql },
67+
{
68+
name: SCHEMA_V7_MIGRATION,
69+
sql: "",
70+
async prepare(ctx: MigrationContext) {
71+
const passkeys = passkeysTable(ctx.prefix)
72+
const user2fa = user2faTable(ctx.prefix)
73+
74+
if (!(await hasColumn(ctx.db, passkeys, "name"))) {
75+
await ctx.db
76+
.prepare(`ALTER TABLE ${passkeys} ADD COLUMN name TEXT`)
77+
.run()
78+
}
79+
if (!(await hasColumn(ctx.db, user2fa, "totp_label"))) {
80+
await ctx.db
81+
.prepare(`ALTER TABLE ${user2fa} ADD COLUMN totp_label TEXT`)
82+
.run()
83+
}
84+
}
85+
}
86+
]
5487
}

‎worker/src/lib/schema.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,8 @@ export const SCHEMA_TABLES: SchemaTable[] = [
4949
totp_secret TEXT,
5050
totp_enabled INTEGER NOT NULL DEFAULT 0,
5151
updated_at TEXT NOT NULL,
52-
email_2fa_enabled INTEGER NOT NULL DEFAULT 0
52+
email_2fa_enabled INTEGER NOT NULL DEFAULT 0,
53+
totp_label TEXT
5354
)`
5455
},
5556
{
@@ -62,7 +63,8 @@ export const SCHEMA_TABLES: SchemaTable[] = [
6263
counter INTEGER NOT NULL DEFAULT 0,
6364
transports TEXT NOT NULL DEFAULT '',
6465
created_at TEXT NOT NULL,
65-
last_used_at TEXT
66+
last_used_at TEXT,
67+
name TEXT
6668
)`
6769
},
6870
{

‎worker/src/lib/user-view.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ export interface UserView {
2323
/** 首登强制改密标记;true 时前端引导改密后再放行。 */
2424
mustChangePassword: boolean
2525
totpEnabled: boolean
26+
totpLabel: string | null
2627
emailTwoFactorEnabled: boolean
2728
passkeyCount: number
2829
profileLocks: {
@@ -48,6 +49,7 @@ export async function buildUserView(
4849
emailVerified: user.email_verified === 1,
4950
mustChangePassword: user.must_change_password === 1,
5051
totpEnabled: Boolean(twoFactor?.totp_enabled),
52+
totpLabel: twoFactor?.totp_label ?? null,
5153
emailTwoFactorEnabled: Boolean(twoFactor?.email_2fa_enabled),
5254
passkeyCount,
5355
profileLocks: await readProfileLockSettings(env)

‎worker/src/routes/me.ts‎

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,13 @@ import { Hono } from "hono"
1616
import type { Context } from "hono"
1717
import { hashPassword } from "../core/auth"
1818
import { revokeAllSessions } from "../core/session"
19-
import { deletePasskey, listPasskeyViews } from "../db/queries/passkeys"
19+
import {
20+
deletePasskey,
21+
listPasskeyViews,
22+
updatePasskeyName
23+
} from "../db/queries/passkeys"
2024
import { findUserById, updateUserFields } from "../db/queries/users"
21-
import { currentUserId, requirePassword } from "../lib/account"
25+
import { currentUserId, normalizeTag, requirePassword } from "../lib/account"
2226
import { apiError, readJsonBody } from "../lib/http"
2327
import { readProfileLockSettings } from "../lib/settings"
2428
import { getTablePrefix } from "../lib/table-prefix"
@@ -131,6 +135,30 @@ meRoutes.get("/passkeys", async (c) => {
131135
})
132136
})
133137

138+
meRoutes.patch("/passkeys/:id", async (c) => {
139+
const id = Number(c.req.param("id"))
140+
if (!Number.isInteger(id)) {
141+
return apiError(c, 404, "PASSKEY_NOT_FOUND", "Passkey not found")
142+
}
143+
const body = await readJsonBody<{ name?: unknown }>(c)
144+
if (!body || typeof body !== "object") {
145+
return apiError(c, 400, "INVALID_REQUEST", "Invalid request body")
146+
}
147+
const name = normalizeTag(body.name)
148+
const prefix = getTablePrefix(c.env)
149+
const updated = await updatePasskeyName(
150+
c.env.DB,
151+
prefix,
152+
currentUserId(c),
153+
id,
154+
name
155+
)
156+
if (!updated) {
157+
return apiError(c, 404, "PASSKEY_NOT_FOUND", "Passkey not found")
158+
}
159+
return c.json({ success: true })
160+
})
161+
134162
meRoutes.delete("/passkeys/:id", async (c) => {
135163
const body = await readJsonBody<{ password?: unknown }>(c)
136164
const denied = await requirePassword(c, body?.password)

0 commit comments

Comments
 (0)