@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.
- package/LICENSE +21 -0
- package/README.md +796 -2
- package/package.json +59 -3
- package/src/components/AuthError.vue +45 -0
- package/src/components/AuthLogin.vue +201 -0
- package/src/components/PubKeyClient.vue +477 -0
- package/src/index.ts +82 -0
- package/src/next.ts +22 -0
- package/src/passkey-client.ts +159 -0
- package/src/passkey-metadata.ts +56 -0
- package/src/pubkey-client.ts +183 -0
- package/src/pubkey-proof.ts +179 -0
- package/src/pubkey-transport.ts +107 -0
- package/src/pubkey-types.ts +41 -0
- package/src/server/http.ts +27 -0
- package/src/server/identity.ts +22 -0
- package/src/server/index.ts +10 -0
- package/src/server/passkey/challenge.ts +70 -0
- package/src/server/passkey/config.ts +97 -0
- package/src/server/passkey/index.ts +10 -0
- package/src/server/passkey/routes.ts +310 -0
- package/src/server/passkey/store.ts +84 -0
- package/src/server/provider.ts +90 -0
- package/src/server/providers/cloudflare.ts +83 -0
- package/src/server/providers/custom.ts +47 -0
- package/src/server/providers/github.ts +112 -0
- package/src/server/providers/google.ts +45 -0
- package/src/server/providers/index.ts +4 -0
- package/src/server/pubkey/errors.ts +32 -0
- package/src/server/pubkey/fixtures.ts +156 -0
- package/src/server/pubkey/http.ts +91 -0
- package/src/server/pubkey/index.ts +10 -0
- package/src/server/pubkey/keys.ts +166 -0
- package/src/server/pubkey/resolve.ts +189 -0
- package/src/server/pubkey/resolver.ts +111 -0
- package/src/server/pubkey/verify.ts +119 -0
- package/src/server/pubkey/wkd.ts +78 -0
- package/src/server/pubkey-passkey/index.ts +14 -0
- package/src/server/pubkey-passkey/routes.ts +260 -0
- package/src/server/routes.ts +340 -0
- package/src/server/session.ts +86 -0
- package/src/server/userpass.ts +104 -0
- package/src/types.ts +82 -0
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { PasskeyRegistrationMetadata } from "./passkey-metadata";
|
|
2
|
+
import type { PubKeyProofCredential } from "./pubkey-proof";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* 已解析的 OpenPGP 公钥。此文件必须保持 client-safe:只含纯类型,不导入
|
|
6
|
+
* openpgp、Node 内置模块或任何服务端代码。
|
|
7
|
+
*/
|
|
8
|
+
export interface ResolvedPubKey {
|
|
9
|
+
/** primary key fingerprint,无空格大写 hex(v4 为 40 位,v6 为 64 位)。 */
|
|
10
|
+
fingerprint: string;
|
|
11
|
+
/** 单把公钥的 ASCII armor,可直接交给 openpgp.readKey。 */
|
|
12
|
+
armoredKey: string;
|
|
13
|
+
/** 由所有 UID 的 name / email local-part 及来源账号汇总的去重候选用户名。 */
|
|
14
|
+
suggested_usernames: string[];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export type PubKeyResolverStatus = "loading" | "ready" | "error";
|
|
18
|
+
|
|
19
|
+
export type PubKeyPasskeyCredential = PubKeyProofCredential;
|
|
20
|
+
|
|
21
|
+
/** `POST /register` 请求体;字段名与浏览器端 PGP proof 一致。 */
|
|
22
|
+
export interface PubKeyPasskeyRegisterRequest {
|
|
23
|
+
fingerprint: string;
|
|
24
|
+
message: string;
|
|
25
|
+
signature: string;
|
|
26
|
+
credential: PubKeyPasskeyCredential;
|
|
27
|
+
/** 可选注册元数据;不进入 proof message,也不参与验签或凭据存储。 */
|
|
28
|
+
metadata?: PasskeyRegistrationMetadata;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface PubKeyPasskeyKeysResponse {
|
|
32
|
+
status: PubKeyResolverStatus;
|
|
33
|
+
keys: ResolvedPubKey[];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export type PubKeyPasskeyRefreshResponse = PubKeyPasskeyKeysResponse;
|
|
37
|
+
|
|
38
|
+
export interface PubKeyPasskeyRegisterResponse {
|
|
39
|
+
registered: true;
|
|
40
|
+
id: string;
|
|
41
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { Context } from "hono";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 解析反向代理后的公开 origin。非法值在启动时抛错,与 userpass 的既有行为一致。
|
|
5
|
+
*/
|
|
6
|
+
export const parsePublicOrigin = (value?: string): string | undefined => (value ? new URL(value).origin : undefined);
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* 带 Origin 时要求与公开 origin(未配置则当前请求 origin)严格同源。
|
|
10
|
+
* 没有 Origin 的请求放行,便于 curl 等非浏览器客户端。
|
|
11
|
+
*/
|
|
12
|
+
export const hasSameOrigin = (c: Context, publicOrigin?: string): boolean => {
|
|
13
|
+
const origin = c.req.header("origin");
|
|
14
|
+
if (!origin) return true;
|
|
15
|
+
try {
|
|
16
|
+
return new URL(origin).origin === (publicOrigin ?? new URL(c.req.url).origin);
|
|
17
|
+
} catch {
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
/** 允许带 charset 的 `application/json`,其他 Content-Type 一律拒绝。 */
|
|
23
|
+
export const hasJsonContentType = (c: Context): boolean => {
|
|
24
|
+
const contentType = c.req.header("content-type");
|
|
25
|
+
if (!contentType) return false;
|
|
26
|
+
return contentType.split(";")[0]?.trim().toLowerCase() === "application/json";
|
|
27
|
+
};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 统一身份。身份键是 `provider + subject`,不要按 email 自动合并账号。
|
|
3
|
+
*/
|
|
4
|
+
export interface AuthIdentity {
|
|
5
|
+
provider: string;
|
|
6
|
+
subject: string;
|
|
7
|
+
email?: string;
|
|
8
|
+
emailVerified?: boolean;
|
|
9
|
+
name?: string;
|
|
10
|
+
picture?: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** 可以安全下发给前端的 provider 信息。 */
|
|
14
|
+
export interface AuthProviderPublic {
|
|
15
|
+
id: string;
|
|
16
|
+
label: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export const publicProvider = (provider: AuthProviderPublic): AuthProviderPublic => ({
|
|
20
|
+
id: provider.id,
|
|
21
|
+
label: provider.label,
|
|
22
|
+
});
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export * from "../next";
|
|
2
|
+
export * from "./identity";
|
|
3
|
+
export * from "./passkey";
|
|
4
|
+
export * from "./pubkey";
|
|
5
|
+
export * from "./pubkey-passkey";
|
|
6
|
+
export * from "./provider";
|
|
7
|
+
export * from "./providers";
|
|
8
|
+
export * from "./routes";
|
|
9
|
+
export * from "./session";
|
|
10
|
+
export * from "./userpass";
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
export const PASSKEY_CHALLENGE_PREFIX = "pk1.";
|
|
2
|
+
export const PASSKEY_CHALLENGE_COOKIE = "__Host-acrux_passkey";
|
|
3
|
+
export const PASSKEY_CHALLENGE_MAX_AGE_SECONDS = 300;
|
|
4
|
+
export const PASSKEY_CHALLENGE_MAX_AGE_MS = PASSKEY_CHALLENGE_MAX_AGE_SECONDS * 1000;
|
|
5
|
+
const PASSKEY_CHALLENGE_CLOCK_SKEW_MS = 60_000;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* 匿名 attestation 注册挑战的固定用途身份。
|
|
9
|
+
*
|
|
10
|
+
* 匿名挑战同时带 `anonymous: true`,与 session 注册挑战互斥;
|
|
11
|
+
* 即使应用写入了同名字符串的 session identity 也不能互换。
|
|
12
|
+
*/
|
|
13
|
+
export const PASSKEY_ANONYMOUS_REGISTRATION_IDENTITY = "!passkey-anonymous-attestation";
|
|
14
|
+
|
|
15
|
+
export type PasskeyChallengeMode = "registration" | "authentication";
|
|
16
|
+
|
|
17
|
+
export interface PasskeyChallenge {
|
|
18
|
+
mode: PasskeyChallengeMode;
|
|
19
|
+
challenge: string;
|
|
20
|
+
iat: number;
|
|
21
|
+
rpID: string;
|
|
22
|
+
origin: string;
|
|
23
|
+
/** 注册挑战绑定发起时的 opaque session identity;匿名注册是固定用途身份。 */
|
|
24
|
+
identity?: string;
|
|
25
|
+
/** 匿名 attestation 注册挑战;不允许携带 session identity。 */
|
|
26
|
+
anonymous?: true;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null;
|
|
30
|
+
|
|
31
|
+
export const serializePasskeyChallenge = (challenge: PasskeyChallenge): string =>
|
|
32
|
+
`${PASSKEY_CHALLENGE_PREFIX}${JSON.stringify(challenge)}`;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* 解析并校验服务端签名 cookie 中的挑战。用途前缀、mode 与有效期都在这里收口。
|
|
36
|
+
*/
|
|
37
|
+
export const parsePasskeyChallenge = (
|
|
38
|
+
raw: string | false | undefined,
|
|
39
|
+
expectedMode: PasskeyChallengeMode,
|
|
40
|
+
now: number = Date.now(),
|
|
41
|
+
): PasskeyChallenge | undefined => {
|
|
42
|
+
if (typeof raw !== "string" || !raw.startsWith(PASSKEY_CHALLENGE_PREFIX)) return undefined;
|
|
43
|
+
|
|
44
|
+
let parsed: unknown;
|
|
45
|
+
try {
|
|
46
|
+
parsed = JSON.parse(raw.slice(PASSKEY_CHALLENGE_PREFIX.length));
|
|
47
|
+
} catch {
|
|
48
|
+
return undefined;
|
|
49
|
+
}
|
|
50
|
+
if (!isRecord(parsed)) return undefined;
|
|
51
|
+
|
|
52
|
+
const { mode, challenge, iat, rpID, origin, identity, anonymous } = parsed;
|
|
53
|
+
if (typeof mode !== "string" || mode !== expectedMode) return undefined;
|
|
54
|
+
if (typeof challenge !== "string" || challenge.length === 0) return undefined;
|
|
55
|
+
if (typeof iat !== "number" || !Number.isFinite(iat)) return undefined;
|
|
56
|
+
if (typeof rpID !== "string" || rpID.length === 0) return undefined;
|
|
57
|
+
if (typeof origin !== "string" || origin.length === 0) return undefined;
|
|
58
|
+
if (identity !== undefined && typeof identity !== "string") return undefined;
|
|
59
|
+
if (anonymous !== undefined && anonymous !== true) return undefined;
|
|
60
|
+
// 匿名注册必须是固定用途身份且只出现在 registration 挑战里。
|
|
61
|
+
if (anonymous === true) {
|
|
62
|
+
if (mode !== "registration") return undefined;
|
|
63
|
+
if (identity !== PASSKEY_ANONYMOUS_REGISTRATION_IDENTITY) return undefined;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const age = now - iat;
|
|
67
|
+
if (age > PASSKEY_CHALLENGE_MAX_AGE_MS || age < -PASSKEY_CHALLENGE_CLOCK_SKEW_MS) return undefined;
|
|
68
|
+
|
|
69
|
+
return { mode, challenge, iat, rpID, origin, identity, ...(anonymous === true ? { anonymous: true as const } : {}) };
|
|
70
|
+
};
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { cose, decodeCredentialPublicKey, isoBase64URL } from "@simplewebauthn/server/helpers";
|
|
2
|
+
|
|
3
|
+
/** 单凭据配置:`id` 是凭据 ID,`publicKey` 是未填充 base64url 的 COSE 公钥。 */
|
|
4
|
+
export interface PasskeyCredentialConfig {
|
|
5
|
+
id: string;
|
|
6
|
+
publicKey: string;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface ResolvedPasskeyCredential {
|
|
10
|
+
id: string;
|
|
11
|
+
publicKey: ReturnType<typeof isoBase64URL.toBuffer>;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface PasskeyRelyingParty {
|
|
15
|
+
/** 完整 origin(含端口),作为 `expectedOrigin`。 */
|
|
16
|
+
origin: string;
|
|
17
|
+
/** RP ID 必须是 origin 的 hostname,不含端口。 */
|
|
18
|
+
rpID: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export const resolvePasskeyRelyingParty = (
|
|
22
|
+
publicOrigin: string | undefined,
|
|
23
|
+
requestUrl: string,
|
|
24
|
+
): PasskeyRelyingParty => {
|
|
25
|
+
const origin = publicOrigin ?? new URL(requestUrl).origin;
|
|
26
|
+
return { origin, rpID: new URL(origin).hostname };
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 非空、未填充、可逆的 canonical base64url;长度模 4 余 1 不可能解码。
|
|
31
|
+
*/
|
|
32
|
+
const isCanonicalBase64Url = (value: string): boolean => {
|
|
33
|
+
if (!value || value.length % 4 === 1) return false;
|
|
34
|
+
if (!isoBase64URL.isBase64URL(value) || value !== isoBase64URL.trimPadding(value)) return false;
|
|
35
|
+
return isoBase64URL.fromBuffer(isoBase64URL.toBuffer(value)) === value;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/** 用库的 COSE key 类型守卫确认 kty / alg / 必需字段,避免接受不完整配置。 */
|
|
39
|
+
const isUsableCosePublicKey = (coseKey: ReturnType<typeof decodeCredentialPublicKey>): boolean => {
|
|
40
|
+
if (!cose.isCOSEKty(coseKey.get(cose.COSEKEYS.kty)) || !cose.isCOSEAlg(coseKey.get(cose.COSEKEYS.alg))) {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (cose.isCOSEPublicKeyEC2(coseKey)) {
|
|
45
|
+
return (
|
|
46
|
+
cose.isCOSECrv(coseKey.get(cose.COSEKEYS.crv)) &&
|
|
47
|
+
Boolean(coseKey.get(cose.COSEKEYS.x)) &&
|
|
48
|
+
Boolean(coseKey.get(cose.COSEKEYS.y))
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
if (cose.isCOSEPublicKeyOKP(coseKey)) {
|
|
52
|
+
return cose.isCOSECrv(coseKey.get(cose.COSEKEYS.crv)) && Boolean(coseKey.get(cose.COSEKEYS.x));
|
|
53
|
+
}
|
|
54
|
+
if (cose.isCOSEPublicKeyRSA(coseKey)) {
|
|
55
|
+
return Boolean(coseKey.get(cose.COSEKEYS.n)) && Boolean(coseKey.get(cose.COSEKEYS.e));
|
|
56
|
+
}
|
|
57
|
+
if (cose.isCOSEPublicKeyAKP(coseKey)) {
|
|
58
|
+
return Boolean(coseKey.get(cose.COSEKEYS.pub));
|
|
59
|
+
}
|
|
60
|
+
return false;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const assertCosePublicKey = (publicKey: ReturnType<typeof isoBase64URL.toBuffer>): void => {
|
|
64
|
+
let decoded: unknown;
|
|
65
|
+
try {
|
|
66
|
+
decoded = decodeCredentialPublicKey(publicKey);
|
|
67
|
+
} catch {
|
|
68
|
+
throw new Error("createPasskeyRoutes: credential.publicKey must be a valid COSE public key");
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (!(decoded instanceof Map) || !isUsableCosePublicKey(decoded as ReturnType<typeof decodeCredentialPublicKey>)) {
|
|
72
|
+
throw new Error("createPasskeyRoutes: credential.publicKey must be a valid COSE public key");
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* 启动时校验并解码凭据。要求 canonical 未填充 base64url,publicKey 还要能解码为 COSE。
|
|
78
|
+
*/
|
|
79
|
+
export const parsePasskeyCredential = (credential?: PasskeyCredentialConfig): ResolvedPasskeyCredential | undefined => {
|
|
80
|
+
if (!credential) return undefined;
|
|
81
|
+
|
|
82
|
+
const { id, publicKey } = credential;
|
|
83
|
+
if (!isCanonicalBase64Url(id)) {
|
|
84
|
+
throw new Error("createPasskeyRoutes: credential.id must be a canonical unpadded base64url string");
|
|
85
|
+
}
|
|
86
|
+
if (!isCanonicalBase64Url(publicKey)) {
|
|
87
|
+
throw new Error("createPasskeyRoutes: credential.publicKey must be a canonical unpadded base64url string");
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const decoded = isoBase64URL.toBuffer(publicKey);
|
|
91
|
+
assertCosePublicKey(decoded);
|
|
92
|
+
|
|
93
|
+
return { id, publicKey: decoded };
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
export const encodeCredentialPublicKey = (publicKey: ReturnType<typeof isoBase64URL.toBuffer>): string =>
|
|
97
|
+
isoBase64URL.fromBuffer(publicKey);
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export { createPasskeyRoutes, type PasskeyRoutes, type PasskeyRoutesOptions, type PasskeyVerifier } from "./routes";
|
|
2
|
+
export type { PasskeyCredentialConfig } from "./config";
|
|
3
|
+
export {
|
|
4
|
+
createPasskeyCredentialCollection,
|
|
5
|
+
createPasskeyCredentialStore,
|
|
6
|
+
PasskeyCredentialConflictError,
|
|
7
|
+
type PasskeyCredentialCollection,
|
|
8
|
+
type PasskeyCredentialRecord,
|
|
9
|
+
type PasskeyCredentialStore,
|
|
10
|
+
} from "./store";
|
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
import {
|
|
2
|
+
generateAuthenticationOptions,
|
|
3
|
+
generateRegistrationOptions,
|
|
4
|
+
verifyAuthenticationResponse,
|
|
5
|
+
verifyRegistrationResponse,
|
|
6
|
+
type AuthenticationResponseJSON,
|
|
7
|
+
type RegistrationResponseJSON,
|
|
8
|
+
} from "@simplewebauthn/server";
|
|
9
|
+
import { Hono, type Context } from "hono";
|
|
10
|
+
import { deleteCookie, getSignedCookie, setSignedCookie } from "hono/cookie";
|
|
11
|
+
import { z } from "zod";
|
|
12
|
+
import type { PasskeyRegistrationMetadata } from "../../passkey-metadata";
|
|
13
|
+
import { hasJsonContentType, hasSameOrigin, parsePublicOrigin } from "../http";
|
|
14
|
+
import type { AuthSession } from "../session";
|
|
15
|
+
import {
|
|
16
|
+
PASSKEY_ANONYMOUS_REGISTRATION_IDENTITY,
|
|
17
|
+
PASSKEY_CHALLENGE_COOKIE,
|
|
18
|
+
PASSKEY_CHALLENGE_MAX_AGE_SECONDS,
|
|
19
|
+
parsePasskeyChallenge,
|
|
20
|
+
serializePasskeyChallenge,
|
|
21
|
+
type PasskeyChallengeMode,
|
|
22
|
+
} from "./challenge";
|
|
23
|
+
import {
|
|
24
|
+
encodeCredentialPublicKey,
|
|
25
|
+
resolvePasskeyRelyingParty,
|
|
26
|
+
type PasskeyCredentialConfig,
|
|
27
|
+
type PasskeyRelyingParty,
|
|
28
|
+
} from "./config";
|
|
29
|
+
import { createPasskeyCredentialStore, type PasskeyCredentialStore } from "./store";
|
|
30
|
+
|
|
31
|
+
/** 生产默认直接使用 SimpleWebAuthn;仅测试可以注入替身验证实现。 */
|
|
32
|
+
export interface PasskeyVerifier {
|
|
33
|
+
verifyRegistration: typeof verifyRegistrationResponse;
|
|
34
|
+
verifyAuthentication: typeof verifyAuthenticationResponse;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const defaultVerifier: PasskeyVerifier = {
|
|
38
|
+
verifyRegistration: verifyRegistrationResponse,
|
|
39
|
+
verifyAuthentication: verifyAuthenticationResponse,
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
export interface PasskeyRoutesOptions {
|
|
43
|
+
/** 用户可见的 RP 名称,例如站点名。 */
|
|
44
|
+
rpName: string;
|
|
45
|
+
/** WebAuthn user.name;与 userDisplayName 都必须非空。 */
|
|
46
|
+
username: string;
|
|
47
|
+
userDisplayName?: string;
|
|
48
|
+
/** 登录成功写入的 opaque session identity;默认 `passkey:${username}`。 */
|
|
49
|
+
sessionIdentity?: string;
|
|
50
|
+
session: AuthSession;
|
|
51
|
+
/** 挑战 cookie 的 HMAC 密钥;与 session / OIDC 共用 secret 时靠 `pk1.` 前缀隔离。 */
|
|
52
|
+
secret: string;
|
|
53
|
+
/** 反向代理后的公开 origin;未配置时使用请求 origin。 */
|
|
54
|
+
publicOrigin?: string;
|
|
55
|
+
/** 静态凭据;与 `store` 同时使用时作为 seed 加入 store。store 为空且未提供时登录不可用,注册仍可用。 */
|
|
56
|
+
credential?: PasskeyCredentialConfig;
|
|
57
|
+
/**
|
|
58
|
+
* per-isolate 内存凭据集合。应用可传入以 env 静态凭据为 seed 的 store,
|
|
59
|
+
* 之后运行时 `add` 的凭据对所有 options / verify 立即生效。
|
|
60
|
+
*/
|
|
61
|
+
store?: PasskeyCredentialStore;
|
|
62
|
+
/**
|
|
63
|
+
* 显式允许无 session 的匿名 attestation 注册;默认 false。
|
|
64
|
+
*
|
|
65
|
+
* 开启后 `register/options` 与 `register/verify` 可匿名运行,但匿名 verify
|
|
66
|
+
* 只返回 `{ id, public_key, metadata }`,不写 session、不自动加入 store。
|
|
67
|
+
*/
|
|
68
|
+
allowAnonymousRegistration?: boolean;
|
|
69
|
+
/** 覆盖挑战 cookie 名,主要用于测试。 */
|
|
70
|
+
challengeCookieName?: string;
|
|
71
|
+
/** 仅供测试注入;生产不要传。 */
|
|
72
|
+
verifier?: PasskeyVerifier;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const challengeCookieOptions = {
|
|
76
|
+
httpOnly: true,
|
|
77
|
+
secure: true,
|
|
78
|
+
sameSite: "Lax",
|
|
79
|
+
path: "/",
|
|
80
|
+
} as const;
|
|
81
|
+
|
|
82
|
+
const credentialResponseSchema = z.looseObject({
|
|
83
|
+
id: z.string().min(1),
|
|
84
|
+
rawId: z.string().min(1),
|
|
85
|
+
type: z.string().min(1),
|
|
86
|
+
response: z.looseObject({}),
|
|
87
|
+
clientExtensionResults: z.record(z.string(), z.unknown()).optional(),
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
const nonEmpty = (value: string, field: string): string => {
|
|
91
|
+
const trimmed = value.trim();
|
|
92
|
+
if (!trimmed) throw new Error(`createPasskeyRoutes: ${field} must not be empty`);
|
|
93
|
+
return trimmed;
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
const unauthorized = (c: Context) => c.json({ error: "Unauthorized" }, 401);
|
|
97
|
+
const forbidden = (c: Context) => c.json({ error: "Forbidden" }, 403);
|
|
98
|
+
const notFound = (c: Context) => c.json({ error: "Not Found" }, 404);
|
|
99
|
+
const unsupportedMediaType = (c: Context) => c.json({ error: "Unsupported Media Type" }, 415);
|
|
100
|
+
const unavailable = (c: Context) => c.json({ error: "Service Unavailable" }, 503);
|
|
101
|
+
|
|
102
|
+
const parseResponseBody = async (c: Context): Promise<z.infer<typeof credentialResponseSchema> | undefined> => {
|
|
103
|
+
const parsed = credentialResponseSchema.safeParse(await c.req.json().catch(() => undefined));
|
|
104
|
+
return parsed.success ? parsed.data : undefined;
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
interface ChallengeContext {
|
|
108
|
+
mode: PasskeyChallengeMode;
|
|
109
|
+
challenge: string;
|
|
110
|
+
relyingParty: PasskeyRelyingParty;
|
|
111
|
+
identity?: string;
|
|
112
|
+
anonymous?: boolean;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Passkey 路由:`GET /status`、`POST /register/options|verify`、`POST /login/options|verify`。
|
|
117
|
+
*
|
|
118
|
+
* 凭据来自 per-isolate 内存 store:启动静态 seed + 运行时 add。登录每次读取当前列表,
|
|
119
|
+
* 成功后写入配置的 sessionIdentity(默认 `passkey:<username>`)。counter 固定 0,本流程不提供克隆检测。
|
|
120
|
+
*
|
|
121
|
+
* 注册默认要求已登录;显式 `allowAnonymousRegistration` 后,无 session 的匿名
|
|
122
|
+
* attestation 也能拿到 `{ id, public_key, metadata }`,用于后续外部授权(如 PGP proof)决定是否注册。
|
|
123
|
+
*/
|
|
124
|
+
export const createPasskeyRoutes = (options: PasskeyRoutesOptions) => {
|
|
125
|
+
if (!options.secret) throw new Error("createPasskeyRoutes: secret is required");
|
|
126
|
+
|
|
127
|
+
const publicOrigin = parsePublicOrigin(options.publicOrigin);
|
|
128
|
+
const credentialStore = options.store ?? createPasskeyCredentialStore();
|
|
129
|
+
if (options.credential) credentialStore.add(options.credential);
|
|
130
|
+
const allowAnonymousRegistration = options.allowAnonymousRegistration === true;
|
|
131
|
+
const challengeCookieName = options.challengeCookieName ?? PASSKEY_CHALLENGE_COOKIE;
|
|
132
|
+
const verifier = options.verifier ?? defaultVerifier;
|
|
133
|
+
const rpName = nonEmpty(options.rpName, "rpName");
|
|
134
|
+
const username = nonEmpty(options.username, "username");
|
|
135
|
+
const userDisplayName = nonEmpty(options.userDisplayName ?? username, "userDisplayName");
|
|
136
|
+
const sessionIdentity = nonEmpty(options.sessionIdentity ?? `passkey:${username}`, "sessionIdentity");
|
|
137
|
+
|
|
138
|
+
const writeChallenge = async (c: Context, context: ChallengeContext): Promise<void> => {
|
|
139
|
+
await setSignedCookie(
|
|
140
|
+
c,
|
|
141
|
+
challengeCookieName,
|
|
142
|
+
serializePasskeyChallenge({
|
|
143
|
+
mode: context.mode,
|
|
144
|
+
challenge: context.challenge,
|
|
145
|
+
iat: Date.now(),
|
|
146
|
+
rpID: context.relyingParty.rpID,
|
|
147
|
+
origin: context.relyingParty.origin,
|
|
148
|
+
identity: context.identity,
|
|
149
|
+
...(context.anonymous ? { anonymous: true as const } : {}),
|
|
150
|
+
}),
|
|
151
|
+
options.secret,
|
|
152
|
+
{ ...challengeCookieOptions, maxAge: PASSKEY_CHALLENGE_MAX_AGE_SECONDS },
|
|
153
|
+
);
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
/** 单次使用:读取后立即删除,无论后续校验是否通过。 */
|
|
157
|
+
const consumeChallenge = async (
|
|
158
|
+
c: Context,
|
|
159
|
+
mode: PasskeyChallengeMode,
|
|
160
|
+
): Promise<ReturnType<typeof parsePasskeyChallenge>> => {
|
|
161
|
+
let raw: string | false | undefined;
|
|
162
|
+
try {
|
|
163
|
+
raw = await getSignedCookie(c, options.secret, challengeCookieName);
|
|
164
|
+
} catch {
|
|
165
|
+
raw = undefined;
|
|
166
|
+
}
|
|
167
|
+
deleteCookie(c, challengeCookieName, challengeCookieOptions);
|
|
168
|
+
return parsePasskeyChallenge(raw, mode);
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
return new Hono()
|
|
172
|
+
.get("/status", (c) => c.json({ enabled: credentialStore.list().length > 0 }))
|
|
173
|
+
.post("/register/options", async (c) => {
|
|
174
|
+
if (!hasSameOrigin(c, publicOrigin)) return forbidden(c);
|
|
175
|
+
|
|
176
|
+
const identity = await options.session.get(c);
|
|
177
|
+
if (!identity && !allowAnonymousRegistration) return unauthorized(c);
|
|
178
|
+
|
|
179
|
+
const credentials = credentialStore.list();
|
|
180
|
+
const relyingParty = resolvePasskeyRelyingParty(publicOrigin, c.req.url);
|
|
181
|
+
const registrationOptions = await generateRegistrationOptions({
|
|
182
|
+
rpName,
|
|
183
|
+
rpID: relyingParty.rpID,
|
|
184
|
+
userName: username,
|
|
185
|
+
userDisplayName,
|
|
186
|
+
attestationType: "none",
|
|
187
|
+
excludeCredentials: credentials.length ? credentials.map((credential) => ({ id: credential.id })) : undefined,
|
|
188
|
+
authenticatorSelection: { residentKey: "discouraged", userVerification: "required" },
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
await writeChallenge(c, {
|
|
192
|
+
mode: "registration",
|
|
193
|
+
challenge: registrationOptions.challenge,
|
|
194
|
+
relyingParty,
|
|
195
|
+
identity: identity ?? PASSKEY_ANONYMOUS_REGISTRATION_IDENTITY,
|
|
196
|
+
anonymous: !identity,
|
|
197
|
+
});
|
|
198
|
+
return c.json(registrationOptions);
|
|
199
|
+
})
|
|
200
|
+
.post("/register/verify", async (c) => {
|
|
201
|
+
if (!hasSameOrigin(c, publicOrigin)) return forbidden(c);
|
|
202
|
+
if (!hasJsonContentType(c)) return unsupportedMediaType(c);
|
|
203
|
+
|
|
204
|
+
const identity = await options.session.get(c);
|
|
205
|
+
// 未开启匿名且无 session 时保持旧行为:直接 401,不消费挑战。
|
|
206
|
+
if (!identity && !allowAnonymousRegistration) return unauthorized(c);
|
|
207
|
+
|
|
208
|
+
const challenge = await consumeChallenge(c, "registration");
|
|
209
|
+
if (!challenge) return unauthorized(c);
|
|
210
|
+
|
|
211
|
+
if (challenge.anonymous) {
|
|
212
|
+
// 匿名挑战只能在无 session 时使用,防止把已有登录身份借给匿名流程。
|
|
213
|
+
if (identity) return unauthorized(c);
|
|
214
|
+
if (challenge.identity !== PASSKEY_ANONYMOUS_REGISTRATION_IDENTITY) return unauthorized(c);
|
|
215
|
+
} else if (!identity || !challenge.identity || challenge.identity !== identity) {
|
|
216
|
+
return unauthorized(c);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const body = await parseResponseBody(c);
|
|
220
|
+
if (!body) return unauthorized(c);
|
|
221
|
+
|
|
222
|
+
try {
|
|
223
|
+
const result = await verifier.verifyRegistration({
|
|
224
|
+
response: body as unknown as RegistrationResponseJSON,
|
|
225
|
+
expectedChallenge: challenge.challenge,
|
|
226
|
+
expectedOrigin: challenge.origin,
|
|
227
|
+
expectedRPID: challenge.rpID,
|
|
228
|
+
requireUserPresence: true,
|
|
229
|
+
requireUserVerification: true,
|
|
230
|
+
});
|
|
231
|
+
if (!result.verified) return unauthorized(c);
|
|
232
|
+
|
|
233
|
+
// 匿名路径只回传 attestation 结果,不写 session、不加入 store;是否注册由应用决定。
|
|
234
|
+
const registrationInfo = result.registrationInfo;
|
|
235
|
+
const registered = registrationInfo.credential;
|
|
236
|
+
const metadata: PasskeyRegistrationMetadata = {
|
|
237
|
+
aaguid: registrationInfo.aaguid,
|
|
238
|
+
fmt: registrationInfo.fmt,
|
|
239
|
+
counter: registered.counter,
|
|
240
|
+
...(registered.transports === undefined ? {} : { transports: registered.transports }),
|
|
241
|
+
backup_eligible: registrationInfo.credentialDeviceType === "multiDevice",
|
|
242
|
+
backed_up: registrationInfo.credentialBackedUp,
|
|
243
|
+
device_type: registrationInfo.credentialDeviceType,
|
|
244
|
+
};
|
|
245
|
+
return c.json({
|
|
246
|
+
id: registered.id,
|
|
247
|
+
public_key: encodeCredentialPublicKey(registered.publicKey),
|
|
248
|
+
metadata,
|
|
249
|
+
});
|
|
250
|
+
} catch {
|
|
251
|
+
return unauthorized(c);
|
|
252
|
+
}
|
|
253
|
+
})
|
|
254
|
+
.post("/login/options", async (c) => {
|
|
255
|
+
if (!hasSameOrigin(c, publicOrigin)) return forbidden(c);
|
|
256
|
+
|
|
257
|
+
const credentials = credentialStore.list();
|
|
258
|
+
if (credentials.length === 0) return unavailable(c);
|
|
259
|
+
|
|
260
|
+
const relyingParty = resolvePasskeyRelyingParty(publicOrigin, c.req.url);
|
|
261
|
+
const authenticationOptions = await generateAuthenticationOptions({
|
|
262
|
+
rpID: relyingParty.rpID,
|
|
263
|
+
allowCredentials: credentials.map((credential) => ({ id: credential.id })),
|
|
264
|
+
userVerification: "required",
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
await writeChallenge(c, {
|
|
268
|
+
mode: "authentication",
|
|
269
|
+
challenge: authenticationOptions.challenge,
|
|
270
|
+
relyingParty,
|
|
271
|
+
});
|
|
272
|
+
return c.json(authenticationOptions);
|
|
273
|
+
})
|
|
274
|
+
.post("/login/verify", async (c) => {
|
|
275
|
+
if (!hasSameOrigin(c, publicOrigin)) return forbidden(c);
|
|
276
|
+
|
|
277
|
+
const credentials = credentialStore.list();
|
|
278
|
+
if (credentials.length === 0) return unavailable(c);
|
|
279
|
+
if (!hasJsonContentType(c)) return unsupportedMediaType(c);
|
|
280
|
+
|
|
281
|
+
const challenge = await consumeChallenge(c, "authentication");
|
|
282
|
+
if (!challenge) return unauthorized(c);
|
|
283
|
+
|
|
284
|
+
const body = await parseResponseBody(c);
|
|
285
|
+
if (!body) return unauthorized(c);
|
|
286
|
+
|
|
287
|
+
const credential = credentials.find((candidate) => candidate.id === body.id);
|
|
288
|
+
// 未知凭据明确 404,客户端可据此调用 Signal API。
|
|
289
|
+
if (!credential) return notFound(c);
|
|
290
|
+
|
|
291
|
+
try {
|
|
292
|
+
const result = await verifier.verifyAuthentication({
|
|
293
|
+
response: body as unknown as AuthenticationResponseJSON,
|
|
294
|
+
expectedChallenge: challenge.challenge,
|
|
295
|
+
expectedOrigin: challenge.origin,
|
|
296
|
+
expectedRPID: challenge.rpID,
|
|
297
|
+
credential: { id: credential.id, publicKey: credential.publicKey, counter: credential.counter },
|
|
298
|
+
requireUserVerification: true,
|
|
299
|
+
});
|
|
300
|
+
if (!result.verified) return unauthorized(c);
|
|
301
|
+
} catch {
|
|
302
|
+
return unauthorized(c);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
await options.session.set(c, sessionIdentity);
|
|
306
|
+
return c.json({ authenticated: true });
|
|
307
|
+
});
|
|
308
|
+
};
|
|
309
|
+
|
|
310
|
+
export type PasskeyRoutes = ReturnType<typeof createPasskeyRoutes>;
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { parsePasskeyCredential, type PasskeyCredentialConfig, type ResolvedPasskeyCredential } from "./config";
|
|
2
|
+
|
|
3
|
+
/** 内存凭据记录:只保留协议需要的字段,不保存 username 或账户关系。 */
|
|
4
|
+
export interface PasskeyCredentialRecord extends ResolvedPasskeyCredential {
|
|
5
|
+
/** 固定 0;当前流程不做克隆检测。 */
|
|
6
|
+
counter: number;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* per-isolate 内存凭据集合。
|
|
11
|
+
*
|
|
12
|
+
* 启动时可传入静态凭据作为 seed,之后由应用(例如 PGP proof 路由)运行时 `add`。
|
|
13
|
+
* 进程结束后失效;不持久化,也不与账户绑定。
|
|
14
|
+
*/
|
|
15
|
+
export interface PasskeyCredentialStore {
|
|
16
|
+
/** 当前快照,按插入顺序;返回副本,调用方不能改到内部状态。 */
|
|
17
|
+
list(): PasskeyCredentialRecord[];
|
|
18
|
+
/** 校验并加入凭据;同 id 同 publicKey 幂等返回已有记录,同 id 不同 publicKey 抛 Conflict。 */
|
|
19
|
+
add(credential: PasskeyCredentialConfig): PasskeyCredentialRecord;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export type PasskeyCredentialCollection = PasskeyCredentialStore;
|
|
23
|
+
|
|
24
|
+
/** 同一 credential id 携带了不同 publicKey。 */
|
|
25
|
+
export class PasskeyCredentialConflictError extends Error {
|
|
26
|
+
readonly code = "PASSKEY_CREDENTIAL_CONFLICT";
|
|
27
|
+
readonly id: string;
|
|
28
|
+
|
|
29
|
+
constructor(id: string) {
|
|
30
|
+
super(`Passkey credential conflict: "${id}" already exists with a different public key`);
|
|
31
|
+
this.name = "PasskeyCredentialConflictError";
|
|
32
|
+
this.id = id;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const cloneRecord = (record: PasskeyCredentialRecord): PasskeyCredentialRecord => ({
|
|
37
|
+
id: record.id,
|
|
38
|
+
publicKey: record.publicKey.slice(),
|
|
39
|
+
counter: record.counter,
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
const samePublicKey = (a: ResolvedPasskeyCredential, b: ResolvedPasskeyCredential): boolean =>
|
|
43
|
+
a.publicKey.length === b.publicKey.length && a.publicKey.every((byte, index) => byte === b.publicKey[index]);
|
|
44
|
+
|
|
45
|
+
const toRecord = (credential: PasskeyCredentialConfig): PasskeyCredentialRecord => {
|
|
46
|
+
const parsed = parsePasskeyCredential(credential);
|
|
47
|
+
if (!parsed) throw new Error("createPasskeyCredentialStore: credential is required");
|
|
48
|
+
return { ...parsed, counter: 0 };
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* 创建 per-isolate 内存凭据集合,可接收 0..n 个静态凭据作为 seed。
|
|
53
|
+
*
|
|
54
|
+
* `undefined` 会跳过,便于直接传入可选的 env 配置;静态 seed 与运行时 `add`
|
|
55
|
+
* 走同一套 canonical base64url / COSE 校验,非法配置在构造时抛出。
|
|
56
|
+
*/
|
|
57
|
+
export const createPasskeyCredentialStore = (
|
|
58
|
+
...credentials: (PasskeyCredentialConfig | undefined)[]
|
|
59
|
+
): PasskeyCredentialStore => {
|
|
60
|
+
const records = new Map<string, PasskeyCredentialRecord>();
|
|
61
|
+
|
|
62
|
+
const store: PasskeyCredentialStore = {
|
|
63
|
+
list: () => [...records.values()].map(cloneRecord),
|
|
64
|
+
add: (credential) => {
|
|
65
|
+
const record = toRecord(credential);
|
|
66
|
+
const existing = records.get(record.id);
|
|
67
|
+
if (existing) {
|
|
68
|
+
if (!samePublicKey(existing, record)) throw new PasskeyCredentialConflictError(record.id);
|
|
69
|
+
return cloneRecord(existing);
|
|
70
|
+
}
|
|
71
|
+
records.set(record.id, record);
|
|
72
|
+
return cloneRecord(record);
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
for (const credential of credentials) {
|
|
77
|
+
if (credential) store.add(credential);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
return store;
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
/** `createPasskeyCredentialStore` 的同义名,对齐领域里的「凭据集合」。 */
|
|
84
|
+
export const createPasskeyCredentialCollection = createPasskeyCredentialStore;
|