@geektr.cloud/acrux-auth 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +796 -2
  3. package/package.json +59 -3
  4. package/src/components/AuthError.vue +45 -0
  5. package/src/components/AuthLogin.vue +201 -0
  6. package/src/components/PubKeyClient.vue +477 -0
  7. package/src/index.ts +82 -0
  8. package/src/next.ts +22 -0
  9. package/src/passkey-client.ts +159 -0
  10. package/src/passkey-metadata.ts +56 -0
  11. package/src/pubkey-client.ts +183 -0
  12. package/src/pubkey-proof.ts +179 -0
  13. package/src/pubkey-transport.ts +107 -0
  14. package/src/pubkey-types.ts +41 -0
  15. package/src/server/http.ts +27 -0
  16. package/src/server/identity.ts +22 -0
  17. package/src/server/index.ts +10 -0
  18. package/src/server/passkey/challenge.ts +70 -0
  19. package/src/server/passkey/config.ts +97 -0
  20. package/src/server/passkey/index.ts +10 -0
  21. package/src/server/passkey/routes.ts +310 -0
  22. package/src/server/passkey/store.ts +84 -0
  23. package/src/server/provider.ts +90 -0
  24. package/src/server/providers/cloudflare.ts +83 -0
  25. package/src/server/providers/custom.ts +47 -0
  26. package/src/server/providers/github.ts +112 -0
  27. package/src/server/providers/google.ts +45 -0
  28. package/src/server/providers/index.ts +4 -0
  29. package/src/server/pubkey/errors.ts +32 -0
  30. package/src/server/pubkey/fixtures.ts +156 -0
  31. package/src/server/pubkey/http.ts +91 -0
  32. package/src/server/pubkey/index.ts +10 -0
  33. package/src/server/pubkey/keys.ts +166 -0
  34. package/src/server/pubkey/resolve.ts +189 -0
  35. package/src/server/pubkey/resolver.ts +111 -0
  36. package/src/server/pubkey/verify.ts +119 -0
  37. package/src/server/pubkey/wkd.ts +78 -0
  38. package/src/server/pubkey-passkey/index.ts +14 -0
  39. package/src/server/pubkey-passkey/routes.ts +260 -0
  40. package/src/server/routes.ts +340 -0
  41. package/src/server/session.ts +86 -0
  42. package/src/server/userpass.ts +104 -0
  43. package/src/types.ts +82 -0
@@ -0,0 +1,159 @@
1
+ import "webauthn-polyfills";
2
+ import type { PasskeyRegistrationMetadata } from "./passkey-metadata";
3
+
4
+ const DEFAULT_BASE_PATH = "/api/auth/passkey";
5
+
6
+ export interface PasskeyClientOptions {
7
+ /** 默认 `/api/auth/passkey`;只允许同源路径。 */
8
+ basePath?: string;
9
+ }
10
+
11
+ export interface PasskeyStatus {
12
+ enabled: boolean;
13
+ }
14
+
15
+ /** 注册成功后的 env 配置值与公开元数据;`public_key` 是 COSE 公钥的未填充 base64url。 */
16
+ export interface PasskeyRegistrationResult {
17
+ id: string;
18
+ public_key: string;
19
+ /** 旧服务端可能不返回;当前服务端注册成功时提供。 */
20
+ metadata?: PasskeyRegistrationMetadata;
21
+ }
22
+
23
+ export interface PasskeyAuthenticationResult {
24
+ authenticated: boolean;
25
+ }
26
+
27
+ export class PasskeyRequestError extends Error {
28
+ readonly status: number;
29
+
30
+ constructor(status: number) {
31
+ super(`Passkey request failed with status ${status}`);
32
+ this.name = "PasskeyRequestError";
33
+ this.status = status;
34
+ }
35
+ }
36
+
37
+ interface PasskeyCredentialJSON {
38
+ id: string;
39
+ [key: string]: unknown;
40
+ }
41
+
42
+ interface SignalCapablePublicKeyCredential {
43
+ signalUnknownCredential?: (options: { rpId: string; credentialId: string }) => Promise<void>;
44
+ }
45
+
46
+ const resolveBasePath = (options: PasskeyClientOptions): string =>
47
+ (options.basePath ?? DEFAULT_BASE_PATH).replace(/\/+$/, "");
48
+
49
+ const credentialConstructor = (): typeof PublicKeyCredential | undefined =>
50
+ (globalThis as unknown as { PublicKeyCredential?: typeof PublicKeyCredential }).PublicKeyCredential;
51
+
52
+ const signalCapableConstructor = (): SignalCapablePublicKeyCredential | undefined =>
53
+ (globalThis as unknown as { PublicKeyCredential?: SignalCapablePublicKeyCredential }).PublicKeyCredential;
54
+
55
+ const fetchJson = async <T>(url: string, init?: RequestInit): Promise<T> => {
56
+ const response = await fetch(url, { credentials: "same-origin", ...init });
57
+ if (!response.ok) throw new PasskeyRequestError(response.status);
58
+ try {
59
+ return (await response.json()) as T;
60
+ } catch {
61
+ throw new PasskeyRequestError(response.status);
62
+ }
63
+ };
64
+
65
+ const post = (url: string, body?: unknown): Promise<Response> =>
66
+ fetch(url, {
67
+ method: "POST",
68
+ credentials: "same-origin",
69
+ ...(body === undefined ? {} : { headers: { "content-type": "application/json" }, body: JSON.stringify(body) }),
70
+ });
71
+
72
+ const requireCredentialConstructor = (): typeof PublicKeyCredential => {
73
+ const constructor = credentialConstructor();
74
+ if (
75
+ !constructor ||
76
+ typeof constructor.parseCreationOptionsFromJSON !== "function" ||
77
+ typeof constructor.parseRequestOptionsFromJSON !== "function"
78
+ ) {
79
+ throw new Error("Passkeys are not supported in this browser");
80
+ }
81
+ return constructor;
82
+ };
83
+
84
+ const signalUnknownCredential = async (rpId: string | undefined, credentialId: string): Promise<void> => {
85
+ const constructor = signalCapableConstructor();
86
+ if (!rpId || !constructor?.signalUnknownCredential) return;
87
+ try {
88
+ await constructor.signalUnknownCredential({ rpId, credentialId });
89
+ } catch {
90
+ // 渐进增强;Signal API 失败不改变登录结果。
91
+ }
92
+ };
93
+
94
+ /**
95
+ * 检测当前环境是否具备原生 WebAuthn 与 JSON 序列化能力。
96
+ * `webauthn-polyfills` 已作为模块副作用导入,覆盖旧浏览器的 parse / toJSON。
97
+ *
98
+ * 不读取 `getClientCapabilities` 的能力位:即使没有平台认证器,
99
+ * USB / NFC 安全密钥仍可完成流程,不能用能力位隐藏入口。
100
+ */
101
+ export const supportsPasskeys = async (): Promise<boolean> => {
102
+ if (typeof window === "undefined" || !window.isSecureContext) return false;
103
+ if (typeof navigator === "undefined" || !navigator.credentials) return false;
104
+
105
+ const constructor = credentialConstructor();
106
+ return Boolean(
107
+ constructor &&
108
+ typeof constructor.parseCreationOptionsFromJSON === "function" &&
109
+ typeof constructor.parseRequestOptionsFromJSON === "function",
110
+ );
111
+ };
112
+
113
+ export const getPasskeyStatus = (options: PasskeyClientOptions = {}): Promise<PasskeyStatus> =>
114
+ fetchJson<PasskeyStatus>(`${resolveBasePath(options)}/status`);
115
+
116
+ /** 注册必须已登录;成功后直接返回可写入 env 的 `{ id, public_key }`。 */
117
+ export const registerPasskey = async (options: PasskeyClientOptions = {}): Promise<PasskeyRegistrationResult> => {
118
+ const constructor = requireCredentialConstructor();
119
+ const basePath = resolveBasePath(options);
120
+
121
+ const optionsResponse = await post(`${basePath}/register/options`);
122
+ if (!optionsResponse.ok) throw new PasskeyRequestError(optionsResponse.status);
123
+ const creationOptionsJSON = (await optionsResponse.json()) as PublicKeyCredentialCreationOptionsJSON;
124
+ const publicKey = constructor.parseCreationOptionsFromJSON(creationOptionsJSON);
125
+
126
+ const credential = (await navigator.credentials.create({ publicKey })) as PublicKeyCredential | null;
127
+ if (!credential) throw new Error("Passkey registration was cancelled");
128
+
129
+ const encoded = credential.toJSON() as unknown as PasskeyCredentialJSON;
130
+ return fetchJson<PasskeyRegistrationResult>(`${basePath}/register/verify`, {
131
+ method: "POST",
132
+ headers: { "content-type": "application/json" },
133
+ body: JSON.stringify(encoded),
134
+ });
135
+ };
136
+
137
+ /** 登录成功只代表服务端已写 session;是否设置 app 登录态由调用方决定。 */
138
+ export const authenticatePasskey = async (options: PasskeyClientOptions = {}): Promise<PasskeyAuthenticationResult> => {
139
+ const constructor = requireCredentialConstructor();
140
+ const basePath = resolveBasePath(options);
141
+
142
+ const optionsResponse = await post(`${basePath}/login/options`);
143
+ if (!optionsResponse.ok) throw new PasskeyRequestError(optionsResponse.status);
144
+ const requestOptionsJSON = (await optionsResponse.json()) as PublicKeyCredentialRequestOptionsJSON;
145
+ const publicKey = constructor.parseRequestOptionsFromJSON(requestOptionsJSON);
146
+
147
+ const credential = (await navigator.credentials.get({ publicKey })) as PublicKeyCredential | null;
148
+ if (!credential) throw new Error("Passkey authentication was cancelled");
149
+
150
+ const encoded = credential.toJSON() as unknown as PasskeyCredentialJSON;
151
+ const response = await post(`${basePath}/login/verify`, encoded);
152
+ if (!response.ok) {
153
+ // 只有服务端明确返回未知凭据 404 时才同步密码管理器;注册流程不标记。
154
+ if (response.status === 404) await signalUnknownCredential(publicKey.rpId, encoded.id);
155
+ throw new PasskeyRequestError(response.status);
156
+ }
157
+
158
+ return (await response.json()) as PasskeyAuthenticationResult;
159
+ };
@@ -0,0 +1,56 @@
1
+ import { z } from "zod";
2
+
3
+ const MAX_ATTESTATION_FORMAT_LENGTH = 64;
4
+ const MAX_TRANSPORTS = 16;
5
+ const MAX_TRANSPORT_LENGTH = 64;
6
+
7
+ /**
8
+ * 注册验证后可公开传递的 WebAuthn 凭据元数据。
9
+ * 不包含 attestationObject、clientDataJSON、extensions、origin 等原始或请求上下文数据。
10
+ */
11
+ export interface PasskeyRegistrationMetadata {
12
+ /** Authenticator Attestation GUID;全零 UUID 表示未提供 AAGUID。 */
13
+ aaguid: string;
14
+ /** 实际注册验证返回的 attestation format。 */
15
+ fmt: string;
16
+ /** 注册时 authenticator 报告的 signature counter。 */
17
+ counter: number;
18
+ /** 认证器声明的传输方式;未提供时保持缺省,不转换为空数组。 */
19
+ transports?: string[];
20
+ /** WebAuthn Backup Eligibility(BE)标志。 */
21
+ backup_eligible: boolean;
22
+ /** WebAuthn Backup State(BS)标志。 */
23
+ backed_up: boolean;
24
+ /** SimpleWebAuthn 原始 credentialDeviceType 值。 */
25
+ device_type: "singleDevice" | "multiDevice";
26
+ }
27
+
28
+ /** OpenPGP 注册请求的严格边界校验;只依赖 client-safe 的 zod。 */
29
+ export const passkeyRegistrationMetadataSchema = z
30
+ .strictObject({
31
+ // AAGUID is an arbitrary 128-bit identifier, not necessarily an RFC UUID version.
32
+ aaguid: z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),
33
+ fmt: z.string().min(1).max(MAX_ATTESTATION_FORMAT_LENGTH),
34
+ counter: z.uint32(),
35
+ transports: z.array(z.string().min(1).max(MAX_TRANSPORT_LENGTH)).max(MAX_TRANSPORTS).optional(),
36
+ backup_eligible: z.boolean(),
37
+ backed_up: z.boolean(),
38
+ device_type: z.enum(["singleDevice", "multiDevice"]),
39
+ })
40
+ .superRefine((metadata, context) => {
41
+ const expectedBackupEligible = metadata.device_type === "multiDevice";
42
+ if (metadata.backup_eligible !== expectedBackupEligible) {
43
+ context.addIssue({
44
+ code: "custom",
45
+ path: ["backup_eligible"],
46
+ message: "backup_eligible must match device_type",
47
+ });
48
+ }
49
+ if (!metadata.backup_eligible && metadata.backed_up) {
50
+ context.addIssue({
51
+ code: "custom",
52
+ path: ["backed_up"],
53
+ message: "backed_up requires backup_eligible",
54
+ });
55
+ }
56
+ });
@@ -0,0 +1,183 @@
1
+ import type { ResolvedPubKey } from "./pubkey-types";
2
+
3
+ /**
4
+ * POSIX shell 单引号转义。单引号内不解释任何元字符,
5
+ * 因此只需把 `'` 拆成 `'` + `\'` + `'` 三段拼接。
6
+ */
7
+ export const shellEscape = (value: string): string => `'${value.replaceAll("'", "'\\''")}'`;
8
+
9
+ /**
10
+ * 指纹比较用的规范化:去掉所有空白并转大写。
11
+ * 只用于匹配,不改变调用方展示或存储的原始值。
12
+ */
13
+ export const normalizeFingerprint = (value: string): string => value.replace(/\s+/g, "").toUpperCase();
14
+
15
+ /**
16
+ * 展示用的 Long Key ID:RFC 9580 规定 v6(64 位 hex)取 fingerprint 的前 16 位,
17
+ * v4(40 位 hex)及非标准长度取后 16 位。结果大写并按每 4 位一组用普通空格分隔,
18
+ * 例如 `0123 4567 89AB CDEF`。
19
+ *
20
+ * 只用于展示;身份匹配、`v-model`、命令与验签仍传完整 fingerprint。
21
+ * 空或纯空白输入返回空字符串。
22
+ */
23
+ export const formatPubKeyLongKeyId = (value: string): string => {
24
+ const normalized = normalizeFingerprint(value);
25
+ if (normalized.length === 0) return "";
26
+ const keyId = normalized.length === 64 ? normalized.slice(0, 16) : normalized.slice(-16);
27
+ return keyId.replace(/(.{4})(?=.)/g, "$1 ");
28
+ };
29
+
30
+ /** 签名命令使用的 shell 形态。 */
31
+ export type PubKeyShell = "unix" | "powershell";
32
+
33
+ /** `PubKeyClient` 的布局形态:独立页面或大模态。 */
34
+ export type PubKeyClientVariant = "page" | "modal";
35
+
36
+ export interface PubKeySignCommandOptions {
37
+ /** 被签名原文;按字节原样传给 shell,不做 trim 或补换行。 */
38
+ message: string;
39
+ /** 签名用的 primary key fingerprint。 */
40
+ fingerprint: string;
41
+ }
42
+
43
+ /**
44
+ * 生成 detach-sign 命令。不追加 `!`,让 gpg 按默认规则为所选 primary key
45
+ * 自动挑选签名 subkey;也不带 `--output`,签名写到 stdout 由调用方保存。
46
+ *
47
+ * 普通文本沿用 `echo -n`(各 shell 对 leading `-` 与反斜杠的处理不一致,
48
+ * 这两类消息改用 `printf '%s'`:格式串不含转义,参数按字节输出且不补换行)。
49
+ *
50
+ * 空 message 无法生成有意义的命令,直接抛错而不是产出 `echo -n ''`
51
+ * 这种容易让人以为签了别的内容的提示。
52
+ */
53
+ export const createPubKeySignCommand = ({ message, fingerprint }: PubKeySignCommandOptions): string => {
54
+ if (message.length === 0) throw new RangeError("message must not be empty");
55
+ const key = normalizeFingerprint(fingerprint);
56
+ if (key.length === 0) throw new RangeError("fingerprint must not be empty");
57
+
58
+ // `echo -n -foo` 会被当成选项或输出空行,`echo -n 'a\nb'` 在不同 shell 里
59
+ // 是否展开反斜杠也不一致,因此这两类消息只能走 printf。
60
+ const producer =
61
+ message.startsWith("-") || message.includes("\\")
62
+ ? `printf '%s' ${shellEscape(message)}`
63
+ : `echo -n ${shellEscape(message)}`;
64
+
65
+ return `${producer} | gpg --local-user ${shellEscape(key)} --detach-sign --armor`;
66
+ };
67
+
68
+ /**
69
+ * PowerShell 单引号转义。单引号字符串内不展开 `$`、反引号或变量,
70
+ * 只需把 `'` 写成 `''`。
71
+ */
72
+ export const powershellEscape = (value: string): string => `'${value.replaceAll("'", "''")}'`;
73
+
74
+ /**
75
+ * 生成 PowerShell 的 detach-sign 命令。不能沿用 `echo ... | gpg`:
76
+ * PowerShell 的管道会补 CRLF,Windows PowerShell 5 还会加 BOM,gpg 会签错字节。
77
+ * 因此先把原文按无 BOM UTF-8 写入临时文件,gpg 直接签该文件,再删除临时文件。
78
+ *
79
+ * message 不补换行,换行等字符原样留在单引号字符串里;fingerprint 规范化后
80
+ * 同样按 PowerShell 单引号规则转义。
81
+ */
82
+ export const createPowerShellSignCommand = ({ message, fingerprint }: PubKeySignCommandOptions): string => {
83
+ if (message.length === 0) throw new RangeError("message must not be empty");
84
+ const key = normalizeFingerprint(fingerprint);
85
+ if (key.length === 0) throw new RangeError("fingerprint must not be empty");
86
+
87
+ return `$m=${powershellEscape(message)}; $f=[IO.Path]::GetTempFileName(); [IO.File]::WriteAllText($f,$m,[Text.UTF8Encoding]::new($false)); gpg --local-user ${powershellEscape(key)} --detach-sign --armor --output - $f; Remove-Item $f`;
88
+ };
89
+
90
+ /**
91
+ * 按 userAgent 选择默认命令 tab:Windows → `powershell`,其他 → `unix`。
92
+ * 不传或非字符串(SSR / Node 没有 navigator)时安全回退到 `unix`。
93
+ */
94
+ export const detectPreferredShell = (userAgent?: string | null): PubKeyShell =>
95
+ typeof userAgent === "string" && /windows/i.test(userAgent) ? "powershell" : "unix";
96
+
97
+ export interface PubKeyClientProps {
98
+ /** 被签名原文;只用于生成命令和展示,不会被执行或求值。 */
99
+ message: string;
100
+ /** 已解析的公钥,调用方保证 fingerprint 完整且唯一。 */
101
+ publicKeys: ResolvedPubKey[];
102
+ /** v-model:fingerprint;空值时自动落到第一个公钥。 */
103
+ fingerprint?: string;
104
+ /** 准备阶段折叠时追加的调用方摘要,例如用户名与 Passkey 状态。 */
105
+ contentSummary?: string;
106
+ loading?: boolean;
107
+ disabled?: boolean;
108
+ /** 表单 name / id 前缀,默认 `pubkey`。 */
109
+ name?: string;
110
+ submitLabel?: string;
111
+ loadingLabel?: string;
112
+ /**
113
+ * 布局形态:`page` 用于独立 URL 的整页拦截,`modal` 用于大模态内的签名动作。
114
+ * 默认 `modal`。两种形态共享同一套插槽与提交行为,仅外层布局和滚动方式不同。
115
+ */
116
+ variant?: PubKeyClientVariant;
117
+ /** 使用粗俗的 shell tab 文案(`Normal Shell` / `Fucking PowerShell`),默认 `false`。 */
118
+ vulgar?: boolean;
119
+ }
120
+
121
+ export interface PubKeyClientSubmitPayload {
122
+ fingerprint: string;
123
+ signature: string;
124
+ }
125
+
126
+ export interface PubKeyClientCommandSlotProps {
127
+ /** 无内容或无公钥时为 `null`,不会产出残缺命令。 */
128
+ command: string | null;
129
+ }
130
+
131
+ export interface PubKeyClientKeySlotProps {
132
+ publicKey: ResolvedPubKey;
133
+ fingerprint: string;
134
+ }
135
+
136
+ export interface PubKeyClientDefaultSlotProps {
137
+ publicKey: ResolvedPubKey | null;
138
+ fingerprint: string;
139
+ command: string | null;
140
+ disabled: boolean;
141
+ loading: boolean;
142
+ }
143
+
144
+ export interface PubKeyClientActionSlotProps {
145
+ disabled: boolean;
146
+ loading: boolean;
147
+ }
148
+
149
+ export interface PubKeyClientErrorSlotProps {
150
+ message: string;
151
+ }
152
+
153
+ export interface PubKeyClientSlots {
154
+ /** 签名流程说明;page 可用作全宽页面标题。 */
155
+ guide?: (props: PubKeyClientCommandSlotProps) => unknown;
156
+ /** 两种 variant 都在三阶段表单之后追加全宽内容;名称为兼容保留。 */
157
+ "page-aside"?: () => unknown;
158
+ /** 所选公钥的详情;默认展示 fingerprint 与折叠的 armored key。 */
159
+ key?: (props: PubKeyClientKeySlotProps) => unknown;
160
+ /**
161
+ * 准备阶段的公钥选择之后追加的自定义表单字段,例如 username / Passkey。
162
+ * 与其它准备字段位于同一无内部分卡区域。
163
+ */
164
+ default?: (props: PubKeyClientDefaultSlotProps) => unknown;
165
+ /** 命令展示;默认 `CodeBlock` 只读纯文本,不执行。 */
166
+ command?: (props: PubKeyClientCommandSlotProps) => unknown;
167
+ /**
168
+ * 提交按钮内部内容,fallback 为 `submitLabel` / `loadingLabel`。
169
+ * 原生 submit button 始终保留,不会因为覆盖本插槽而丢失提交语义。
170
+ */
171
+ button?: (props: PubKeyClientActionSlotProps) => unknown;
172
+ /** 整个动作区(包住原生 submit button);需要完全替换按钮时才用。 */
173
+ actions?: (props: PubKeyClientActionSlotProps) => unknown;
174
+ /** 校验错误;默认纯文本 `role="alert"`。 */
175
+ error?: (props: PubKeyClientErrorSlotProps) => unknown;
176
+ }
177
+
178
+ export interface PubKeyClientEmits {
179
+ "update:fingerprint": [fingerprint: string];
180
+ /** 选择变化(含初始)时给出完整公钥,方便调用方同步 username 候选。 */
181
+ select: [publicKey: ResolvedPubKey | null];
182
+ submit: [payload: PubKeyClientSubmitPayload];
183
+ }
@@ -0,0 +1,179 @@
1
+ /**
2
+ * OpenPGP 授权 Passkey 的 proof message 契约。
3
+ * 此模块必须保持 client-safe:不导入 OpenPGP、Hono、Worker 或 Node API。
4
+ */
5
+
6
+ /** 消息时间戳允许的最大回溯窗口。 */
7
+ export const PUBKEY_PROOF_MAX_AGE_MS = 5 * 60_000;
8
+ /** 消息时间戳允许的最大未来偏移。 */
9
+ export const PUBKEY_PROOF_MAX_FUTURE_MS = 60_000;
10
+ export const PUBKEY_PROOF_MESSAGE_MAX_LENGTH = 8192;
11
+ export const PUBKEY_PROOF_USERNAME_MAX_LENGTH = 256;
12
+ /** WebAuthn 允许 credential id 最多 1023 字节,base64url 后约 1364 字符。 */
13
+ export const PUBKEY_PROOF_CREDENTIAL_ID_MAX_LENGTH = 2048;
14
+ export const PUBKEY_PROOF_CREDENTIAL_PUBLIC_KEY_MAX_LENGTH = 4096;
15
+
16
+ /**
17
+ * canonical UUIDv7:固定连字符位置、version 7、RFC 4122 variant。
18
+ * 大小写不敏感,但要求完整的 8-4-4-4-12 形式。
19
+ */
20
+ const UUID_V7_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
21
+
22
+ export interface PubKeyProofCredential {
23
+ id: string;
24
+ public_key: string;
25
+ }
26
+
27
+ /** legacy proof 绑定 username;credential-only proof 只绑定 credential。 */
28
+ export type PubKeyProofMode = "username" | "credential-only";
29
+
30
+ export interface ParsedPubKeyProofMessage {
31
+ uuid: string;
32
+ username: string;
33
+ /** UUIDv7 内嵌的 48 bit 毫秒时间戳。 */
34
+ timestamp: number;
35
+ }
36
+
37
+ /** credential-only proof 不包含也不返回 username。 */
38
+ export interface ParsedPubKeyCredentialProofMessage {
39
+ uuid: string;
40
+ /** UUIDv7 内嵌的 48 bit 毫秒时间戳。 */
41
+ timestamp: number;
42
+ }
43
+
44
+ export type PubKeyProofErrorCode = "invalid-message" | "credential-mismatch" | "outside-time-window";
45
+
46
+ /** 纯业务错误;HTTP 状态由调用方决定。 */
47
+ export class PubKeyProofError extends Error {
48
+ readonly code: PubKeyProofErrorCode;
49
+
50
+ constructor(code: PubKeyProofErrorCode) {
51
+ super("Invalid proof");
52
+ this.name = "PubKeyProofError";
53
+ this.code = code;
54
+ }
55
+ }
56
+
57
+ const fail = (code: PubKeyProofErrorCode): never => {
58
+ throw new PubKeyProofError(code);
59
+ };
60
+
61
+ const parseUuidTimestamp = (uuid: string): number => {
62
+ if (!UUID_V7_PATTERN.test(uuid)) return fail("invalid-message");
63
+ return Number.parseInt(uuid.slice(0, 8) + uuid.slice(9, 13), 16);
64
+ };
65
+
66
+ const assertCredential = (credential: PubKeyProofCredential): void => {
67
+ if (
68
+ credential.id.length === 0 ||
69
+ credential.id.length > PUBKEY_PROOF_CREDENTIAL_ID_MAX_LENGTH ||
70
+ credential.public_key.length === 0 ||
71
+ credential.public_key.length > PUBKEY_PROOF_CREDENTIAL_PUBLIC_KEY_MAX_LENGTH
72
+ ) {
73
+ fail("invalid-message");
74
+ }
75
+ };
76
+
77
+ const assertUsername = (username: string): void => {
78
+ if (username.trim() === "" || username.length > PUBKEY_PROOF_USERNAME_MAX_LENGTH) fail("invalid-message");
79
+ };
80
+
81
+ const assertMessage = (message: string): void => {
82
+ if (
83
+ message.length === 0 ||
84
+ message.length > PUBKEY_PROOF_MESSAGE_MAX_LENGTH ||
85
+ message.includes("\n") ||
86
+ message.includes("\r")
87
+ ) {
88
+ fail("invalid-message");
89
+ }
90
+ };
91
+
92
+ /**
93
+ * 组成 `${uuidv7}:${username}:${credential.id}:${credential.public_key}`。
94
+ * UUID 由 app 生成;这里校验结构与长度,不自行生成 UUID 或读取时钟。
95
+ */
96
+ export const buildPubKeyProofMessage = (uuid: string, username: string, credential: PubKeyProofCredential): string => {
97
+ parseUuidTimestamp(uuid);
98
+ assertUsername(username);
99
+ assertCredential(credential);
100
+
101
+ const message = `${uuid}:${username}:${credential.id}:${credential.public_key}`;
102
+ assertMessage(message);
103
+ return message;
104
+ };
105
+
106
+ interface LeadingProofFields {
107
+ uuid: string;
108
+ timestamp: number;
109
+ remainder: string;
110
+ }
111
+
112
+ /** 校验第一段 canonical UUIDv7 与时间窗,返回剩余待匹配内容。 */
113
+ const parseLeadingProofFields = (message: string, now: number): LeadingProofFields => {
114
+ const separator = message.indexOf(":");
115
+ if (separator <= 0) fail("invalid-message");
116
+
117
+ const uuid = message.slice(0, separator);
118
+ const timestamp = parseUuidTimestamp(uuid);
119
+ if (timestamp < now - PUBKEY_PROOF_MAX_AGE_MS || timestamp > now + PUBKEY_PROOF_MAX_FUTURE_MS) {
120
+ fail("outside-time-window");
121
+ }
122
+
123
+ return { uuid, timestamp, remainder: message.slice(separator + 1) };
124
+ };
125
+
126
+ /**
127
+ * 解析并校验 legacy proof message。username 可能含冒号,因此先用第一个冒号切出
128
+ * UUID,再用固定 credential 后缀反推 username。默认以 Date.now() 判断 5 分钟回溯
129
+ * 与 60 秒未来偏移;测试可注入 now,生产时间语义不变。
130
+ */
131
+ export const parsePubKeyProofMessage = (
132
+ message: string,
133
+ credential: PubKeyProofCredential,
134
+ now: number = Date.now(),
135
+ ): ParsedPubKeyProofMessage => {
136
+ assertMessage(message);
137
+ assertCredential(credential);
138
+
139
+ const { uuid, timestamp, remainder } = parseLeadingProofFields(message, now);
140
+ // 结构上至少要能容纳 username、credential id 与 public key 两处分隔。
141
+ if (remainder.split(":").length < 3) fail("invalid-message");
142
+
143
+ const suffix = `:${credential.id}:${credential.public_key}`;
144
+ if (!remainder.endsWith(suffix)) fail("credential-mismatch");
145
+
146
+ const username = remainder.slice(0, remainder.length - suffix.length);
147
+ assertUsername(username);
148
+ return { uuid, username, timestamp };
149
+ };
150
+
151
+ /**
152
+ * 组成 `${uuidv7}:${credential.id}:${credential.public_key}`。
153
+ * 不包含 username;不能通过空 username 与 legacy 格式互通。
154
+ */
155
+ export const buildPubKeyCredentialProofMessage = (uuid: string, credential: PubKeyProofCredential): string => {
156
+ parseUuidTimestamp(uuid);
157
+ assertCredential(credential);
158
+
159
+ const message = `${uuid}:${credential.id}:${credential.public_key}`;
160
+ assertMessage(message);
161
+ return message;
162
+ };
163
+
164
+ /**
165
+ * 解析并校验 credential-only proof message。UUID 后的内容必须与传入 credential
166
+ * 的 id 和 public key 完全一致,因此 legacy 的 username 段会被拒绝。
167
+ */
168
+ export const parsePubKeyCredentialProofMessage = (
169
+ message: string,
170
+ credential: PubKeyProofCredential,
171
+ now: number = Date.now(),
172
+ ): ParsedPubKeyCredentialProofMessage => {
173
+ assertMessage(message);
174
+ assertCredential(credential);
175
+
176
+ const { uuid, timestamp, remainder } = parseLeadingProofFields(message, now);
177
+ if (remainder !== `${credential.id}:${credential.public_key}`) fail("credential-mismatch");
178
+ return { uuid, timestamp };
179
+ };
@@ -0,0 +1,107 @@
1
+ import type {
2
+ PubKeyPasskeyRegisterRequest,
3
+ PubKeyPasskeyRegisterResponse,
4
+ PubKeyResolverStatus,
5
+ ResolvedPubKey,
6
+ } from "./pubkey-types";
7
+
8
+ const DEFAULT_BASE_PATH = "/api/auth/pubkey";
9
+
10
+ export interface PubKeyPasskeyClientOptions {
11
+ /** Default `/api/auth/pubkey`; use a same-origin path. */
12
+ basePath?: string;
13
+ }
14
+
15
+ /** Array responses remain supported for compatibility and have no resolver status. */
16
+ export interface PubKeyPasskeyKeysResult {
17
+ status?: PubKeyResolverStatus;
18
+ keys: ResolvedPubKey[];
19
+ }
20
+
21
+ export class PubKeyPasskeyRequestError extends Error {
22
+ readonly status: number;
23
+
24
+ constructor(status: number, options?: ErrorOptions) {
25
+ super(`PubKey passkey request failed with status ${status}`, options);
26
+ this.name = "PubKeyPasskeyRequestError";
27
+ this.status = status;
28
+ }
29
+ }
30
+
31
+ interface JsonResult {
32
+ data: unknown;
33
+ status: number;
34
+ }
35
+
36
+ const resolveBasePath = (options: PubKeyPasskeyClientOptions): string =>
37
+ (options.basePath ?? DEFAULT_BASE_PATH).replace(/\/+$/, "");
38
+
39
+ /** Network failures intentionally propagate unchanged, without an HTTP status. */
40
+ const fetchJson = async (url: string, init?: RequestInit): Promise<JsonResult> => {
41
+ const response = await fetch(url, { credentials: "same-origin", ...init });
42
+ if (!response.ok) throw new PubKeyPasskeyRequestError(response.status);
43
+ try {
44
+ return { data: await response.json(), status: response.status };
45
+ } catch (cause) {
46
+ throw new PubKeyPasskeyRequestError(response.status, { cause });
47
+ }
48
+ };
49
+
50
+ const isResolvedKey = (value: unknown): value is ResolvedPubKey => {
51
+ if (!value || typeof value !== "object") return false;
52
+ const candidate = value as Record<string, unknown>;
53
+ return (
54
+ typeof candidate.fingerprint === "string" &&
55
+ candidate.fingerprint.length > 0 &&
56
+ typeof candidate.armoredKey === "string" &&
57
+ Array.isArray(candidate.suggested_usernames) &&
58
+ candidate.suggested_usernames.every((name) => typeof name === "string")
59
+ );
60
+ };
61
+
62
+ const isResolverStatus = (value: unknown): value is PubKeyResolverStatus =>
63
+ value === "loading" || value === "ready" || value === "error";
64
+
65
+ const parseKeysResult = (data: unknown, status: number): PubKeyPasskeyKeysResult => {
66
+ if (Array.isArray(data)) return { keys: data.filter(isResolvedKey) };
67
+ if (!data || typeof data !== "object") throw new PubKeyPasskeyRequestError(status);
68
+
69
+ const candidate = data as Record<string, unknown>;
70
+ if (!isResolverStatus(candidate.status) || !Array.isArray(candidate.keys)) {
71
+ throw new PubKeyPasskeyRequestError(status);
72
+ }
73
+
74
+ return {
75
+ status: candidate.status,
76
+ keys: candidate.keys.filter(isResolvedKey),
77
+ };
78
+ };
79
+
80
+ const requestKeys = async (url: string, init?: RequestInit): Promise<PubKeyPasskeyKeysResult> => {
81
+ const { data, status } = await fetchJson(url, init);
82
+ return parseKeysResult(data, status);
83
+ };
84
+
85
+ export const getPubKeyPasskeyKeys = (options: PubKeyPasskeyClientOptions = {}): Promise<PubKeyPasskeyKeysResult> =>
86
+ requestKeys(`${resolveBasePath(options)}/keys`, { headers: { accept: "application/json" } });
87
+
88
+ export const refreshPubKeyPasskeyKeys = (options: PubKeyPasskeyClientOptions = {}): Promise<PubKeyPasskeyKeysResult> =>
89
+ requestKeys(`${resolveBasePath(options)}/refresh`, { method: "POST" });
90
+
91
+ export const registerPubKeyPasskey = async (
92
+ request: PubKeyPasskeyRegisterRequest,
93
+ options: PubKeyPasskeyClientOptions = {},
94
+ ): Promise<PubKeyPasskeyRegisterResponse> => {
95
+ const { data, status } = await fetchJson(`${resolveBasePath(options)}/register`, {
96
+ method: "POST",
97
+ headers: { "content-type": "application/json" },
98
+ body: JSON.stringify(request),
99
+ });
100
+
101
+ if (!data || typeof data !== "object") throw new PubKeyPasskeyRequestError(status);
102
+ const candidate = data as Record<string, unknown>;
103
+ if (candidate.registered !== true || typeof candidate.id !== "string" || candidate.id.length === 0) {
104
+ throw new PubKeyPasskeyRequestError(status);
105
+ }
106
+ return { registered: true, id: candidate.id };
107
+ };