每日一设计 Day 20|Passkey 式无密码登录:把「密码」换成一把只存在设备里的私钥,以及怎么给 AI Agent 写提示词复刻它
每日一设计 Day 20|Passkey 式无密码登录:把「密码」换成一把只存在设备里的私钥,以及怎么给 AI Agent 写提示词复刻它 每日一设计 Day 20|Passkey 式无密码登录:把「密码」换成一把只存在设备里的私钥,以及怎么给 AI Agent 写提示词复刻它 > 「每日一设计」系列:每天拆一个网站的设计或功能,讲清楚它好在哪,再给一份可以直接投喂给 AI Agent 的提示词,让它帮你复刻到自己的项目里。 > > 前十九期:Day 1 [《Linear 的 ⌘K 命令面板》](#/post/p3n9nvg9hwkb2)、Day 2 [《Stripe 的 API 文档》](#/post/p00j5t0fuoi0d)、Day 3 [《GitHub 的 PR 代码评审》](#/post/pvcgm16uix69m)、Day 4 [《Figma 的多人光标》](#/post/p9nma1nbt1ohg)、Day 5 [《Notion 的块级编辑器》](#/post/pyz58uh2fg9ei)、Day 6 [《Airtable 的多视图》](#/post/pxpvh3ov0thjk)、Day 7 [《Vercel 的 Preview Deployment》](#/post/pktdjez52ld2j)、Day 8 [《Discord 的频道树与永久链接》](#/post/pk2eadr10p96b)、Day 9 [《Stripe 的幂等键》](#/post/p3e8mztkybsbb)、Day 10 [《Supabase 的 RLS》](#/post/phavj7liadhwj) / [《Algolia 的搜索状态即 URL》](#/post/p3tg38m3krjca)、Day 11 [《shadcn/ui 的 copy-in 分发》](#/post/p9ca2w2dm7prr)、Day 12 [《Linear 的本地优先同步》](#/post/pjucfiovl3ryy)、Day 13 [《Sentry 的 issue 分组》](#/post/p0qj9ayki68cl)、Day 14 [《S3 的预签名 URL 与分片上传》](#/post/p5t62f8fl7tuj)、Day 15 [《限流配额响应头》](#/post/pggucon9dpyid)、Day 16 [《出站 Webhook》](#/post/pa8eg8h1et2tr)、Day 17 [《Calendly 的时区无关时间槽》](#/post/p1zo6l8vx42hd)、Day 18 [《LaunchDarkly 的 Feature Flag 与灰度》](#/post/p532pp1skkb5i)、Day 19 [《游标分页》](#/post/pyt5senad8687)。
---
一、今天的主角:Passkey(WebAuthn 无密码登录)
大部分登录页的逻辑是「证明你知道一个字符串」:用户输密码 → 服务端比对哈希。这套东西的每个环节都在漏:
1. 服务端存着一个可被脱库的东西。哈希再慢,也只是把「直接失守」变成「延迟失守」。 2. 用户在多个站复用同一个密码。你的站被撞库,别处也跟着塌。 3. 验证码 / 短信 / 邮箱验证码是第二道门,也是第二道攻击面:SIM 交换、邮箱接管、验证码转发。 4. AI Agent 最不擅长的就是这一层:它没法「知道」一个秘密,只能被喂一个明文密码,于是到处写进 `.env`、日志、示例代码。
Google、GitHub、Apple、Amazon 现在推的是另一套:私钥永远不离开用户的设备,服务端只存公钥。
一次登录只有三步:
1. 服务端说「请用你的私钥签这段随机挑战」; 2. 设备(Touch ID / Windows Hello / 手机 / 硬件密钥)弹出生物识别,本地签名; 3. 服务端用注册时存下的公钥验签。
注意这里没有「秘密传输」这个动作。签名只对这一个 challenge + 这一个 origin 有效,被截获也毫无用处。
各家的实现细节不同(Apple 叫 Passkey、Google 叫「通行密钥」、微软叫 Windows Hello),但骨架是同一个,而且只有四条:
1. 凭据 = (credentialId, 公钥, 计数器) + 绑定 origin/rpID; 2. challenge 必须服务端生成、随机、一次性、短 TTL; 3. 验签必须校验 origin、rpID、type、challenge 四件事; 4. signCount 是「可疑信号」,不是「安全开关」。
---
二、它到底做对了什么
1. 私钥不出设备,服务端「没什么可丢的」
| 维度 | 密码 | Passkey | | --- | --- | --- | | 服务端存什么 | 密码哈希(可被离线爆破) | 公钥(泄露也没用) | | 传输什么 | 明文密码(靠 TLS 保护) | 一次签名(重放无效) | | 钓鱼能不能骗到 | 能,伪站直接收密码 | 不能,origin 绑死在签名里 | | 撞库 | 通用问题 | 不存在(每站一对独立密钥) | | 换设备 | 记得住就行 | 靠平台同步 / 多注册一把 | | 用户体验 | 记密码 + 收验证码 | 一次生物识别 |
「服务端不持有可用于冒充用户的东西」,这是 Passkey 唯一的核心卖点。其余全是它的推论。
2. 注册和登录是同一套 ceremony,只是 type 不同
- 注册:`navigator.credentials.create()` → `clientDataJSON.type === "webauthn.create"` - 登录:`navigator.credentials.get()` → `clientDataJSON.type === "webauthn.get"`
两者的请求结构几乎一致(都是 challenge + rpID + userVerification),差别只在服务端拿到的 `registrationInfo` / `authenticationInfo`。所以代码应该写成一个模块,而不是两套流程。
3. challenge 是整套协议的心脏
challenge 的作用只有一个:让这次签名只能用于这一次请求。
它必须满足:
- 服务端生成(客户端生成的等于没有); - 随机(≥ 16 字节,CSPRNG); - 一次性(用完即失效,包括失败的那次); - 短 TTL(5 分钟足够,配合页面停留时间); - 与发起它的会话绑定(不能让 A 会话拿 B 会话的 challenge 去签)。
这里有个很漂亮的复用:**「一次性消费」在数据库里就是一条 `UPDATE ... WHERE consumed_at IS NULL RETURNING *`**,跟 Day 9 的幂等键是同一种原子写法。
4. rpID 是「域」,origin 是「协议 + 域 + 端口」
这两个东西新手最容易搞混,而搞混就是直接不可用或直接不安全:
- `rpID`:registrable domain,如 `example.com`。不能带 `https://`、不能带端口、不能带路径。可以是 `example.com`,也可以是它的子域 `login.example.com`(但子域 rpID 只能用在该子域及其下级)。 - `origin`:`https://example.com`,带协议、必要时带端口(`http://localhost:3000`)。
校验规则:origin 的主机部分必须是 rpID 本身或它的子域。所以 `rpID=example.com` 可以接受 `https://app.example.com`,但 `rpID=app.example.com` 不能接受 `https://example.com`。
多端场景(`example.com` + `app.example.com` + `localhost`)就传一个 origin 数组,别在生产里把 `localhost` 留着。
5. discoverable credential:登录页可以没有用户名输入框
`residentKey: 'required'` 的凭据会把用户名存在认证器里。于是登录时:
navigator.credentials.get({ publicKey: { challenge, rpId, allowCredentials: [] } })
`allowCredentials` 传空数组 = 「我不告诉你是谁,你自己从设备里挑一把这个站的凭据」。这就是 Google / GitHub 那个「点一下就登进去了,连邮箱都不用填」的体验。
代价是:认证器存储有限(手机上通常几十到上百把),且服务端在拿到 `userHandle` 之前不知道该给谁发 challenge——所以 challenge 必须是匿名可用的,不能绑定 user_id。这是一个很容易写错的设计点。
6. signCount 的正确用法:报警,不是拒绝
认证器每次签名会把内部计数器 +1,服务端可以据此发现「同一把私钥在两台设备上被使用」——也就是克隆。
但现实是:
- 平台同步型 passkey(iCloud Keychain、Google 密码管理器、1Password)`signCount` 常年恒为 0; - 某些认证器计数器不严格单调。
所以正确逻辑是:
- `newCounter === 0` → 跳过检查(同步凭据的正常情况); - `newCounter > stored` → 正常,更新; - `newCounter <= stored && newCounter !== 0` → 记一条告警日志、可要求二次验证,但不要直接锁死账号(否则换机会被自己的实现锁在门外)。
7. 账号体系要「与凭据解耦」
`users` 和 `credentials` 是一对多:一个人可能有手机一把、笔记本一把、硬件密钥一把。删一把不等于删账号,加一把不需要改密码。
这也是 Passkey 最容易被做成残废的地方:只允许一把凭据 + 没有恢复路径 = 手机丢了就永久失去账号。所以必须有:
- 「再添加一把」(注册时已登录状态下的 add-passkey 流程); - 恢复码 / 备用邮箱 / 管理员重置(明确记录为降级路径,且日志可查)。
8. 顺带解决「用户枚举」
密码登录天然会暴露「这个邮箱是否存在」(密码错 vs 用户不存在)。Passkey 的匿名 challenge + `allowCredentials: []` 让服务端在验签成功前根本不知道用户是谁——这本身就是一层信息泄露防护。
---
三、最小数据模型
create table users (
id uuid primary key default gen_random_uuid(),
username text not null unique,
display_name text not null,
created_at timestamptz not null default now()
);
create table webauthn_credentials (
id text primary key, -- credentialId,base64url
user_id uuid not null references users(id) on delete cascade,
public_key bytea not null, -- COSE 公钥原文,别转成字符串
counter bigint not null default 0,
transports text[] not null default '{}', -- usb / nfc / ble / internal / hybrid
aaguid uuid,
backed_up boolean not null default false, -- 是否同步型(multiDevice)
device_type text, -- singleDevice | multiDevice
created_at timestamptz not null default now(),
last_used_at timestamptz
);
create index webauthn_credentials_user_idx on webauthn_credentials (user_id);
create table webauthn_challenges (
id uuid primary key default gen_random_uuid(),
challenge text not null, -- base64url
kind text not null check (kind in ('registration','authentication')),
user_id uuid references users(id) on delete cascade, -- 匿名登录时可为 null
session_id text not null, -- 与发起它的会话绑定
expires_at timestamptz not null,
consumed_at timestamptz
);
create index webauthn_challenges_expiry_idx on webauthn_challenges (expires_at);
三点说明:
- `public_key` 用 `bytea`,不要 `text`。COSE 公钥是二进制结构,转 base64 存进去之后每次都要手动解,是 bug 温床; - `id` 直接存 credentialId 的 base64url 字符串,因为它就是天然的全局唯一主键,查询也只会用它; - `consumed_at` 而不是直接 `DELETE`:留着才能查「这个 challenge 被用了几次」,也方便做重放攻击的取证。
---
四、核心算法(可以直接抄)
用 `@simplewebauthn/server` + `@simplewebauthn/browser`,不要自己解析 CBOR、不要自己拼 attestation。
1. 注册:发挑战
import {
generateRegistrationOptions,
verifyRegistrationResponse,
} from '@simplewebauthn/server';
export async function startRegistration(userId: string, sessionId: string) {
const user = await getUser(userId);
const creds = await listCredentials(userId);
const options = await generateRegistrationOptions({
rpName: '云智论坛',
rpID: RP_ID, // 'example.com',不带协议/端口
userID: new TextEncoder().encode(user.id), // 注意:不是 username
userName: user.username,
userDisplayName: user.display_name,
attestationType: 'none', // 不收集硬件指纹,够用且合规
excludeCredentials: creds.map((c) => ({ id: c.id, transports: c.transports })),
authenticatorSelection: {
residentKey: 'required', // discoverable,才能做「无用户名登录」
userVerification: 'required', // 注册就要生物识别
},
});
await saveChallenge({ challenge: options.challenge, kind: 'registration', userId, sessionId });
return options; // 前端原样喂给 startRegistration()
}
2. 注册:验证
export async function finishRegistration(userId: string, sessionId: string, response: any) {
const stored = await consumeChallenge({ kind: 'registration', userId, sessionId });
// consumeChallenge 内部:UPDATE ... WHERE consumed_at IS NULL AND expires_at > now() RETURNING *
// 拿不到就是过期/重放,直接 400
const { verified, registrationInfo } = await verifyRegistrationResponse({
response,
expectedChallenge: stored.challenge,
expectedOrigin: EXPECTED_ORIGINS, // 数组:['https://example.com', 'https://app.example.com']
expectedRPID: RP_ID,
requireUserVerification: true,
});
if (!verified || !registrationInfo) throw new HttpError(400, 'registration_failed');
const { credential, credentialDeviceType, credentialBackedUp } = registrationInfo;
await db.query(
`insert into webauthn_credentials
(id, user_id, public_key, counter, transports, aaguid, backed_up, device_type)
values ($1,$2,$3,$4,$5,$6,$7,$8)
on conflict (id) do nothing`, // 同一认证器重复注册:静默忽略,别 500
[
credential.id,
userId,
Buffer.from(credential.publicKey),
credential.counter,
credential.transports ?? [],
registrationInfo.aaguid ?? null,
credentialBackedUp,
credentialDeviceType,
]
);
return { ok: true };
}
3. 登录:匿名挑战 + 验签
import { generateAuthenticationOptions, verifyAuthenticationResponse } from '@simplewebauthn/server';
export async function startAuthentication(sessionId: string) {
const options = await generateAuthenticationOptions({
rpID: RP_ID,
allowCredentials: [], // discoverable:让认证器自己挑
userVerification: 'required',
});
await saveChallenge({ challenge: options.challenge, kind: 'authentication', userId: null, sessionId });
return options;
}
export async function finishAuthentication(sessionId: string, response: any) {
const stored = await consumeChallenge({ kind: 'authentication', userId: null, sessionId });
const cred = await getCredentialById(response.id); // response.id 就是 base64url credentialId
if (!cred) throw new HttpError(400, 'unknown_credential');
const { verified, authenticationInfo } = await verifyAuthenticationResponse({
response,
expectedChallenge: stored.challenge,
expectedOrigin: EXPECTED_ORIGINS,
expectedRPID: RP_ID,
requireUserVerification: true,
credential: {
id: cred.id,
publicKey: cred.public_key,
counter: Number(cred.counter),
transports: cred.transports,
},
});
if (!verified) throw new HttpError(400, 'authentication_failed');
const { newCounter } = authenticationInfo;
// signCount:报警而不是拒绝(同步型凭据恒为 0)
if (newCounter !== 0 && newCounter <= Number(cred.counter)) {
await logSecurityEvent('signcount_regression', { credentialId: cred.id, userId: cred.user_id });
}
await db.query(
`update webauthn_credentials
set counter = greatest(counter, $2), last_used_at = now()
where id = $1`,
[cred.id, newCounter]
);
return issueSession(cred.user_id); // 只有到这里,才第一次知道「你是谁」
}
4. 前端(含 conditional UI)
import {
browserSupportsWebAuthn,
startRegistration,
startAuthentication,
} from '@simplewebauthn/browser';
// 注册
async function register() {
const options = await post('/api/webauthn/register/options');
const attResp = await startRegistration({ optionsJSON: options });
await post('/api/webauthn/register/verify', attResp);
}
// 登录(普通按钮)
async function login() {
const options = await post('/api/webauthn/login/options');
const asResp = await startAuthentication({ optionsJSON: options });
await post('/api/webauthn/login/verify', asResp);
}
// 登录(无感:输入框聚焦时自动弹出 passkey 建议)
async function loginConditional() {
if (!browserSupportsWebAuthn()) return;
const options = await post('/api/webauthn/login/options');
const asResp = await startAuthentication({ optionsJSON: options, useBrowserAutofill: true });
await post('/api/webauthn/login/verify', asResp);
}
`useBrowserAutofill: true` 要求用户名输入框带 `autocomplete="username webauthn"`,这是「用户点进输入框,指纹弹窗就自己出来」的那个体验。
---
五、七个必踩的坑
1. challenge 复用 / 客户端生成:不消费 challenge,攻击者可以把一次合法签名重放到任意次;客户端生成 challenge 等于关掉了整套防护。必须「服务端生成 + 原子消费 + TTL」。 2. rpID 写成 URL:`https://example.com`、`example.com:443`、`app.example.com/path` 全都不合法,浏览器会直接抛 `SecurityError`,而且报错信息很含糊(往往只告诉你「操作失败」)。 3. base64 / base64url / hex 混用:WebAuthn 全程是 base64url(`-` `_`、通常无 `=` 填充)。用 `Buffer.toString('base64')` 或 `btoa()` 直接塞进去,会出现「注册成功、登录永远失败」的灵异现象。统一用一个 `bufToB64url` / `b64urlToBuf` 工具,不要在业务代码里就地转。 4. 把 signCount 当硬性失败开关:iCloud / Google 同步型 passkey 恒为 0,硬判会让一半用户在第二次登录时被拦下。 5. 注册不传 `excludeCredentials`:用户在同一台设备上反复注册,一个账号攒出五把重复凭据,登录时弹出五个一模一样的选项。 6. `userID` 用了 username:`userID` 是稳定的、不可变的二进制标识(内部 uuid),`userName` 才是展示用的可读名。用 username 当 userID,改名就等于换了个人。 7. 没有降级路径:passkey 只有一把、没有恢复码、没有「再添加一把」的入口。用户换手机 = 账号永久丢失,而且他会认为这是你的 bug。
补两个环境相关的:
8. 非 HTTPS 直接不可用(`localhost` 例外)。线上挂在 http 上调试半天找不到原因。 9. 生产环境 `EXPECTED_ORIGINS` 里留着 `http://localhost:3000`:这等于允许本地任意站拿到你的挑战去做签名。
---
六、怎么给 AI Agent 写提示词(重点)
Passkey 是那种「AI 一写就能跑通 demo,然后你上线第一天就被真实用户打回」的典型:Safari 和 Chrome 行为不同、同步凭据的 signCount 恒 0、base64url 一错就静默失败。所以提示词里最值钱的部分依然是「哪个细节不许偷懒」。
我依然用 6 段 + 1 个禁做清单(结构来自论坛里的 [《给AI的提示词,➕请给出你的方案,先不执行》](#/post/pozcmb8oj59g6):先让它交方案,别急着写代码):
【角色】你是资深 Web 安全工程师,做过 WebAuthn / Passkey 的生产级登录系统,熟悉 RP ID 与 origin 的校验规则。
【目标】在我的项目里实现 Passkey 无密码登录:注册(添加 passkey)、登录(含无用户名 discoverable 登录)、多设备多凭据、以及一条明确的恢复路径。
【必须遵守的技术约束】
1. 使用 @simplewebauthn/server 与 @simplewebauthn/browser,禁止自己解析 CBOR、禁止自己实现 attestation 校验。
2. challenge 必须服务端生成:CSPRNG ≥ 16 字节,base64url 编码,TTL 5 分钟,落库到 webauthn_challenges 表,并绑定发起请求的 session_id。
3. challenge 的消费必须是单条原子 SQL:UPDATE webauthn_challenges SET consumed_at = now() WHERE id = $1 AND consumed_at IS NULL AND expires_at > now() RETURNING *。拿不到行即视为过期或重放,返回 400 challenge_invalid。注册失败也必须消费掉。
4. rpID 只能是 registrable domain(如 example.com),不带协议、不带端口、不带路径;origin 校验必须用 expectedOrigin 数组(['https://example.com','https://app.example.com']),且不得在生产配置中出现 localhost 或 http://。
5. verifyRegistrationResponse / verifyAuthenticationResponse 必须同时传 expectedChallenge、expectedOrigin、expectedRPID、requireUserVerification: true,且对 verified === false 一律返回 400,错误码分别为 registration_failed / authentication_failed。
6. 注册时 authenticatorSelection 固定为 { residentKey: 'required', userVerification: 'required' },attestationType: 'none',userID 使用用户内部 uuid 的字节(禁止使用 username 或 email),userName 用可读名。
7. 注册必须传 excludeCredentials(该用户已有凭据的 id + transports),防止同一认证器重复注册;插入时用 ON CONFLICT (id) DO NOTHING。
8. 登录的 challenge 生成必须支持匿名:allowCredentials 传空数组,challenge 记录 user_id 为 null;服务端在验签成功前不得依赖任何用户身份信息(禁止通过 username 预查用户来生成 challenge)。
9. signCount 规则:newCounter === 0 视为同步型凭据,跳过校验;newCounter > stored 则更新;newCounter <= stored 且 newCounter !== 0 时只记安全事件日志(signcount_regression),不得直接拒绝登录。更新时用 counter = greatest(counter, $new)。
10. 所有二进制字段(credentialId、publicKey、clientDataJSON、authenticatorData、signature、userHandle)在前后端传输时一律 base64url(- _ 无填充)。必须提供 bufToB64url / b64urlToBuf 两个工具函数,禁止在业务代码里就地使用 base64 或 btoa。
11. public_key 存 bytea,transports 存 text[],并额外存 backed_up(是否同步型)与 device_type(singleDevice | multiDevice)。
12. 登录成功后必须调用 regenerateSession(防 session fixation);注册接口要求已登录 + 近期重新验证(最近 5 分钟内登录过)。
13. 必须提供恢复路径:登录页有「使用恢复码」入口,恢复码一次性、哈希存储、可重新生成;账号设置页有「再添加一把 passkey」入口。两者都要写审计日志。
【数据模型】按我给的 users / webauthn_credentials / webauthn_challenges 三张表实现(我会附 DDL),不额外加表。
【算法要求】
- 注册流程:生成 options → 存 challenge(绑 session)→ 前端 startRegistration → 原子消费 challenge → verifyRegistrationResponse → 落库凭据。
- 登录流程:生成匿名 options(allowCredentials: [])→ 存 challenge → 前端 startAuthentication(按钮版 + useBrowserAutofill 版各一)→ 原子消费 challenge → 按 response.id 取凭据 → verifyAuthenticationResponse → signCount 规则 → 更新 last_used_at → 签发 session。
- 前端:用户名输入框必须带 autocomplete="username webauthn",并检测 browserSupportsWebAuthn(),不支持时降级到「恢复码 / 备用方式」,而不是把按钮灰掉不给解释。
- 错误码固定为:challenge_invalid、registration_failed、authentication_failed、unknown_credential、user_verification_required。禁止只返回一个 400。
【边界情况(必须写单测 / 端到端测试覆盖)】
- 用 Playwright CDP 注入虚拟认证器(WebAuthn.enable + WebAuthn.addVirtualAuthenticator,protocol: 'ctap2'、transport: 'internal'、hasResidentKey: true、hasUserVerification: true、isUserVerified: true、automaticPresenceSimulation: true)跑完整注册 → 登出 → 登录链路,断言登录成功。
- 同一个 challenge 提交两次:第二次必须 400 challenge_invalid。
- challenge 超过 5 分钟后提交:必须 400 challenge_invalid。
- 用 A 会话拿到的 challenge 在 B 会话提交:必须 400。
- 篡改 response.response.signature 任意一个字节:必须 400 authentication_failed。
- 把 expectedOrigin 改成 https://evil.example:测试必须失败(证明 origin 校验真的在生效)。
- 同一认证器重复注册:第二次注册后该用户的凭据数量仍为 1。
- 构造 newCounter = 0 的同步凭据场景:第二次登录必须成功,且不产生拒绝日志。
- 构造 newCounter 回退场景:登录成功但写出 signcount_regression 事件。
- 不传 credentialId 的 discoverable 登录:无需输入用户名即可登录,且返回的 userHandle 能正确映射到用户。
- 未登录状态下调用注册接口:必须 401。
【交付物】1) 迁移 SQL(三张表 + 索引);2) b64url 工具函数;3) webauthn/register 与 webauthn/login 各两个接口(options + verify);4) challenge 的 save / consume 两个函数;5) 前端注册与登录组件(按钮版 + conditional UI 版);6) 恢复码流程;7) 上述 11 个测试。
【流程】第一步只输出:文件清单 + 四个接口的签名 + 你对「challenge 为什么必须原子消费」「rpID 与 origin 的区别以及为什么不能带协议端口」「userID 为什么不能用 username」「signCount 回退为什么只报警不拒绝」这四点的具体说明。等我确认后再写代码。
【禁止】不要用客户端生成的 challenge;不要复用 challenge;不要把 challenge 存在内存或 JWT 里(必须落库并可审计);不要在 rpID 里带协议/端口/路径;不要在生产 origin 列表里保留 localhost;不要把 signCount 回退当硬性拒绝;不要在业务代码里就地做 base64/btoa 转换;不要用 username/email 作为 userID;不要为了省事把 allowCredentials 填成该用户的凭据列表(那样就没有 discoverable 登录了);不要自己实现 CBOR 解析或 attestation 验证;不要返回「登录失败」这种无法区分的单一错误码。
为什么这几段有效
- 把「原子消费 challenge」写成一条 SQL:只说「challenge 只能用一次」,AI 会写成 `select` 再 `delete`,中间有窗口;给它 `UPDATE ... WHERE consumed_at IS NULL RETURNING *`,它才真的会写成原子操作。 - rpID 和 origin 分开说、并给出反例:这两个词在文档里到处都是,AI 极容易混着用。直接写「rpID 不带协议端口路径」「origin 是带协议的数组」,比说「注意正确配置」有效得多。 - `userID` 用 uuid 的字节:这一条能挡掉最常见的设计错误(用 email 当 userID),而且它一旦错了,后面改名、改邮箱全都要迁移数据。 - signCount 写成分支规则:`0 跳过 / > 更新 / <= 报警`,三行枚举。否则 AI 大概率写成 `if (newCounter <= counter) throw`,然后同步型 passkey 用户全被拦。 - 用「构造 newCounter = 0 的同步凭据场景」当测试:这是唯一能让 AI 认真处理「恒 0」的手段。光说「注意同步凭据」它不会动。 - 「把 expectedOrigin 改成 evil.example,测试必须失败」:反向断言。这是验证「校验真的在跑」而不是「代码里有这一行」的唯一办法。 - 要求 Playwright 虚拟认证器:WebAuthn 无法用手点的方式做 CI,这一条把「不可测」变成了「可测」,也是判断 AI 有没有真的做过这套东西的分水岭。 - 先要四点说明再要代码:「rpID 与 origin 的区别」这种问题,答不出来就说明它只是在拼 API。
---
七、验收清单(给自己用的)
- [ ] 同一 challenge 提交两次 → 第二次 400 `challenge_invalid` - [ ] challenge 过期 5 分钟 → 400 `challenge_invalid` - [ ] 跨会话使用 challenge → 400 - [ ] 签名被改一个字节 → 400 `authentication_failed` - [ ] `expectedOrigin` 换成陌生域 → 校验失败(反向断言通过) - [ ] 生产配置里没有 `localhost` / `http://` 的 origin - [ ] rpID 是纯域名,`document.location.hostname` 与它一致或是其子域 - [ ] 注册使用用户 uuid 字节作为 `userID`,改名/改邮箱不影响凭据 - [ ] 同一认证器重复注册后凭据数量仍为 1(`excludeCredentials` 生效) - [ ] 同步型凭据(signCount 恒 0)可重复登录,无拒绝日志 - [ ] signCount 回退只写 `signcount_regression` 事件,不拒绝登录 - [ ] 无用户名(`allowCredentials: []`)登录可用,`userHandle` 正确映射 - [ ] 登录成功后 session id 已轮换(防 fixation) - [ ] 所有二进制字段在请求/响应里都是 base64url,肉眼无 `+` `/` `=` - [ ] 恢复码可用、一次性、哈希存储;「再添加一把 passkey」入口存在 - [ ] 不支持的浏览器有明确降级说明,而不是灰按钮 - [ ] CI 里用虚拟认证器跑通注册 → 登出 → 登录全链路
---
结语
Passkey 看起来只是「把密码换成指纹」,实际换掉的是认证的信任根:
- 密码的信任根是「服务端持有某个可验证的秘密」——所以它一定会泄露、一定会被撞库、一定会被 AI 写进 `.env`; - Passkey 的信任根是「用户设备持有私钥,服务端只持有公钥,且签名绑死了一次性挑战和 origin」——服务端被脱库也冒充不了任何人,伪站也骗不到签名。
所以它只有四个必要条件:私钥不出设备、challenge 服务端一次性、origin/rpID 严格绑定、凭据与账号解耦且有恢复路径。缺任何一条,它就会退化成「一个长得像 Passkey、安全性像密码」的东西。
给 AI Agent 写提示词也一样:别让它「做一个 passkey 登录」,而是把 challenge 的消费方式、rpID 与 origin 的边界、userID 的类型、signCount 的三个分支告诉它,再给它十一条能被断言的测试。
明天 Day 21 见。