@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,90 @@
1
+ import * as client from "openid-client";
2
+ import type { AuthIdentity } from "./identity";
3
+
4
+ export type OidcTokenResponse = client.TokenEndpointResponse & client.TokenEndpointResponseHelpers;
5
+
6
+ export interface IdentityInput {
7
+ config: client.Configuration;
8
+ tokens: OidcTokenResponse;
9
+ claims: client.IDToken | undefined;
10
+ accessToken: string;
11
+ }
12
+
13
+ /** 服务端 provider 定义。公开给前端时只取 id / label。 */
14
+ export interface AuthProviderDefinition {
15
+ readonly id: string;
16
+ readonly label: string;
17
+ readonly usesOidc: boolean;
18
+ readonly scopes: readonly string[];
19
+ /** 显式 redirect_uri;未设置时由路由按 publicOrigin / mountPath 推导。 */
20
+ readonly redirectUri?: string;
21
+ readonly getConfiguration: () => Promise<client.Configuration>;
22
+ readonly resolveIdentity: (input: IdentityInput) => Promise<AuthIdentity>;
23
+ }
24
+
25
+ /** 所有 provider 构造函数的公共选项。 */
26
+ export interface ProviderOptions {
27
+ id?: string;
28
+ label?: string;
29
+ clientId: string;
30
+ clientSecret?: string;
31
+ scopes?: readonly string[];
32
+ redirectUri?: string;
33
+ /**
34
+ * 高级 / 测试注入:直接提供已构造的 Configuration,跳过 discovery。
35
+ * 生产环境通常不需要。
36
+ */
37
+ configuration?: client.Configuration;
38
+ }
39
+
40
+ export const readString = (value: unknown): string | undefined =>
41
+ typeof value === "string" && value.length > 0 ? value : undefined;
42
+
43
+ export const readBoolean = (value: unknown): boolean => value === true;
44
+
45
+ /** JSON 请求;失败只抛状态码,避免把上游响应体写进错误消息。 */
46
+ export const fetchJson = async <T>(url: string, init: RequestInit): Promise<T> => {
47
+ const response = await fetch(url, init);
48
+ if (!response.ok) throw new Error(`Provider request failed with status ${response.status}`);
49
+ return (await response.json()) as T;
50
+ };
51
+
52
+ /** discovery 每次只在 isolate 内执行一次;失败后允许下次重试。 */
53
+ export const memoized = <T>(factory: () => Promise<T>): (() => Promise<T>) => {
54
+ let pending: Promise<T> | undefined;
55
+ return () => {
56
+ if (!pending) {
57
+ pending = factory().catch((error: unknown) => {
58
+ pending = undefined;
59
+ throw error;
60
+ });
61
+ }
62
+ return pending;
63
+ };
64
+ };
65
+
66
+ /**
67
+ * 使用 issuer(不是 discovery document URL)做发现,并惰性 memoize。
68
+ */
69
+ export const discoveredConfiguration = (
70
+ issuer: string | URL,
71
+ options: ProviderOptions,
72
+ ): (() => Promise<client.Configuration>) => {
73
+ const injected = options.configuration;
74
+ if (injected) return () => Promise.resolve(injected);
75
+
76
+ const issuerUrl = issuer instanceof URL ? issuer : new URL(issuer);
77
+ return memoized(() => client.discovery(issuerUrl, options.clientId, options.clientSecret));
78
+ };
79
+
80
+ /**
81
+ * 校验代码配置的 key 与 provider.id 一致,避免 URL、事务绑定和 identity.provider 分叉。
82
+ */
83
+ export const defineAuthProviders = <T extends Record<string, AuthProviderDefinition>>(providers: T): T => {
84
+ for (const [key, provider] of Object.entries(providers)) {
85
+ if (key !== provider.id) {
86
+ throw new Error(`Auth provider key "${key}" must match provider id "${provider.id}"`);
87
+ }
88
+ }
89
+ return providers;
90
+ };
@@ -0,0 +1,83 @@
1
+ import type { AuthProviderDefinition, ProviderOptions } from "../provider";
2
+ import { discoveredConfiguration, readBoolean, readString } from "../provider";
3
+
4
+ const normalizeTeamDomain = (teamDomain: string): string => {
5
+ const input = teamDomain.trim();
6
+ if (!input) throw new Error("cloudflare: teamDomain is required");
7
+
8
+ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(input) ? input : `https://${input}`;
9
+ let url: URL;
10
+ try {
11
+ url = new URL(withScheme);
12
+ } catch {
13
+ throw new Error("cloudflare: teamDomain must be a valid Cloudflare Access team domain");
14
+ }
15
+
16
+ if (url.protocol !== "https:") throw new Error("cloudflare: teamDomain must use https");
17
+ if (url.username || url.password) throw new Error("cloudflare: teamDomain must not contain credentials");
18
+ if (url.port) throw new Error("cloudflare: teamDomain must not contain a port");
19
+ if (url.pathname !== "/" && url.pathname !== "") {
20
+ throw new Error("cloudflare: teamDomain must not contain a path");
21
+ }
22
+ if (url.search) throw new Error("cloudflare: teamDomain must not contain a query");
23
+ if (url.hash) throw new Error("cloudflare: teamDomain must not contain a hash");
24
+
25
+ return url.hostname;
26
+ };
27
+
28
+ /**
29
+ * 规范化 Cloudflare Access team domain(`team.cloudflareaccess.com` 或完整 https URL),
30
+ * 并根据 Access SaaS OIDC client 组合精确 issuer。
31
+ */
32
+ export const cloudflareIssuer = (teamDomain: string, clientId: string): string => {
33
+ const normalizedClientId = clientId.trim();
34
+ if (!normalizedClientId) throw new Error("cloudflare: clientId is required");
35
+
36
+ return `https://${normalizeTeamDomain(teamDomain)}/cdn-cgi/access/sso/oidc/${normalizedClientId}`;
37
+ };
38
+
39
+ export interface CloudflareOptions extends ProviderOptions {
40
+ /** `team.cloudflareaccess.com` 或 `https://team.cloudflareaccess.com`。 */
41
+ teamDomain: string;
42
+ }
43
+
44
+ /**
45
+ * Cloudflare Access for SaaS(OIDC)。不是 dashboard self-managed OAuth,
46
+ * 也不读取 `Cf-Access-Jwt-Assertion`。
47
+ *
48
+ * issuer 精确为 `https://<team>.cloudflareaccess.com/cdn-cgi/access/sso/oidc/<clientId>`,
49
+ * 用 discovery 取 endpoints;identity 只来自验签 ID token claims(sub / email 足够,
50
+ * emailVerified / name / picture 可缺省)。默认 scope `openid email profile`。
51
+ */
52
+ export const cloudflare = (options: CloudflareOptions): AuthProviderDefinition => {
53
+ const id = options.id ?? "cloudflare";
54
+ const label = options.label ?? "Cloudflare";
55
+ const scopes = options.scopes ?? ["openid", "email", "profile"];
56
+ const clientId = options.clientId.trim();
57
+ if (!clientId) throw new Error("cloudflare: clientId is required");
58
+
59
+ const issuer = cloudflareIssuer(options.teamDomain, clientId);
60
+ const providerOptions = { ...options, clientId };
61
+
62
+ return {
63
+ id,
64
+ label,
65
+ usesOidc: true,
66
+ scopes,
67
+ redirectUri: options.redirectUri,
68
+ getConfiguration: discoveredConfiguration(issuer, providerOptions),
69
+ async resolveIdentity({ claims }) {
70
+ const subject = readString(claims?.sub);
71
+ if (!subject) throw new Error("Cloudflare ID token did not contain a subject");
72
+
73
+ return {
74
+ provider: id,
75
+ subject,
76
+ email: readString(claims?.email),
77
+ emailVerified: readBoolean(claims?.email_verified),
78
+ name: readString(claims?.name),
79
+ picture: readString(claims?.picture),
80
+ };
81
+ },
82
+ };
83
+ };
@@ -0,0 +1,47 @@
1
+ import * as client from "openid-client";
2
+ import type { AuthProviderDefinition, ProviderOptions } from "../provider";
3
+ import { discoveredConfiguration, readBoolean, readString } from "../provider";
4
+
5
+ export interface CustomOidcOptions extends ProviderOptions {
6
+ /** 同一 app 可配置多个 Custom OIDC,因此 id 必填。 */
7
+ id: string;
8
+ issuer: string;
9
+ }
10
+
11
+ /**
12
+ * 通用 OIDC。discovery + ID token 验签 / iss / aud / exp / nonce;
13
+ * 若 provider 提供 UserInfo endpoint,则调用并强制校验 sub 匹配。
14
+ */
15
+ export const customOidc = (options: CustomOidcOptions): AuthProviderDefinition => {
16
+ const id = options.id;
17
+ const label = options.label ?? id;
18
+ const scopes = options.scopes ?? ["openid", "profile", "email"];
19
+
20
+ return {
21
+ id,
22
+ label,
23
+ usesOidc: true,
24
+ scopes,
25
+ redirectUri: options.redirectUri,
26
+ getConfiguration: discoveredConfiguration(options.issuer, options),
27
+ async resolveIdentity({ config, claims, accessToken }) {
28
+ const subject = readString(claims?.sub);
29
+ if (!subject) throw new Error(`${id} ID token did not contain a subject`);
30
+
31
+ let email = readString(claims?.email);
32
+ let emailVerified = readBoolean(claims?.email_verified);
33
+ let name = readString(claims?.name);
34
+ let picture = readString(claims?.picture);
35
+
36
+ if (config.serverMetadata().userinfo_endpoint) {
37
+ const info = await client.fetchUserInfo(config, accessToken, subject);
38
+ email = readString(info.email) ?? email;
39
+ emailVerified = readBoolean(info.email_verified) || emailVerified;
40
+ name = readString(info.name) ?? name;
41
+ picture = readString(info.picture) ?? picture;
42
+ }
43
+
44
+ return { provider: id, subject, email, emailVerified, name, picture };
45
+ },
46
+ };
47
+ };
@@ -0,0 +1,112 @@
1
+ import * as client from "openid-client";
2
+ import type { AuthProviderDefinition, ProviderOptions } from "../provider";
3
+ import { fetchJson, readBoolean, readString } from "../provider";
4
+
5
+ const GITHUB_ISSUER = "https://github.com";
6
+ const GITHUB_AUTHORIZATION_ENDPOINT = "https://github.com/login/oauth/authorize";
7
+ const GITHUB_TOKEN_ENDPOINT = "https://github.com/login/oauth/access_token";
8
+ const GITHUB_USER_ENDPOINT = "https://api.github.com/user";
9
+ const GITHUB_EMAILS_ENDPOINT = "https://api.github.com/user/emails";
10
+
11
+ const serverMetadata = {
12
+ issuer: GITHUB_ISSUER,
13
+ authorization_endpoint: GITHUB_AUTHORIZATION_ENDPOINT,
14
+ token_endpoint: GITHUB_TOKEN_ENDPOINT,
15
+ response_types_supported: ["code"],
16
+ code_challenge_methods_supported: ["S256"],
17
+ } satisfies client.ServerMetadata;
18
+
19
+ interface GithubUser {
20
+ id?: number;
21
+ login?: string;
22
+ name?: string | null;
23
+ email?: string | null;
24
+ avatar_url?: string | null;
25
+ }
26
+
27
+ export interface GithubEmail {
28
+ email?: string;
29
+ primary?: boolean;
30
+ verified?: boolean;
31
+ }
32
+
33
+ export interface GithubEmailSelection {
34
+ email?: string;
35
+ verified: boolean;
36
+ }
37
+
38
+ const readEmail = (value: unknown): string | undefined => readString(value)?.trim() || undefined;
39
+
40
+ /**
41
+ * 只有 verified 记录自身带非空 email 时才提升为 verified。
42
+ * public profile email 永远不能借 verified 记录的空 email 变成已验证。
43
+ */
44
+ export const selectGithubEmail = (emails: readonly GithubEmail[], publicEmail?: string): GithubEmailSelection => {
45
+ const verifiedRecords = emails.filter((entry) => readBoolean(entry.verified) && Boolean(readEmail(entry.email)));
46
+ const selected = verifiedRecords.find((entry) => readBoolean(entry.primary)) ?? verifiedRecords[0];
47
+ const email = readEmail(selected?.email);
48
+ return email ? { email, verified: true } : { email: readEmail(publicEmail), verified: false };
49
+ };
50
+
51
+ export interface GithubOptions extends ProviderOptions {
52
+ clientSecret: string;
53
+ }
54
+
55
+ /**
56
+ * GitHub OAuth App(不是 OIDC)。没有 id_token,identity 由 `/user` 与
57
+ * `/user/emails`(primary + verified)规范化得到。
58
+ */
59
+ export const github = (options: GithubOptions): AuthProviderDefinition => {
60
+ const id = options.id ?? "github";
61
+ const label = options.label ?? "GitHub";
62
+ const scopes = options.scopes ?? ["read:user", "user:email"];
63
+
64
+ const injected = options.configuration;
65
+ const getConfiguration = injected
66
+ ? () => Promise.resolve(injected)
67
+ : () => Promise.resolve(new client.Configuration(serverMetadata, options.clientId, options.clientSecret));
68
+
69
+ return {
70
+ id,
71
+ label,
72
+ usesOidc: false,
73
+ scopes,
74
+ redirectUri: options.redirectUri,
75
+ getConfiguration,
76
+ async resolveIdentity({ accessToken }) {
77
+ const headers = {
78
+ Authorization: `Bearer ${accessToken}`,
79
+ Accept: "application/vnd.github+json",
80
+ "User-Agent": "acrux-auth",
81
+ };
82
+
83
+ const user = await fetchJson<GithubUser>(GITHUB_USER_ENDPOINT, { headers });
84
+ const subject = typeof user.id === "number" ? String(user.id) : undefined;
85
+ if (!subject) throw new Error("GitHub did not return a user id");
86
+
87
+ const publicEmail = readEmail(user.email);
88
+ let email = publicEmail;
89
+ let emailVerified = false;
90
+
91
+ if (scopes.includes("user:email")) {
92
+ try {
93
+ const emails = await fetchJson<GithubEmail[]>(GITHUB_EMAILS_ENDPOINT, { headers });
94
+ const selection = selectGithubEmail(emails, publicEmail);
95
+ email = selection.email;
96
+ emailVerified = selection.verified;
97
+ } catch {
98
+ // 用户可能拒绝 email scope;保留公开 profile 中的 email(视为未验证)。
99
+ }
100
+ }
101
+
102
+ return {
103
+ provider: id,
104
+ subject,
105
+ email,
106
+ emailVerified,
107
+ name: readString(user.name) ?? readString(user.login),
108
+ picture: readString(user.avatar_url),
109
+ };
110
+ },
111
+ };
112
+ };
@@ -0,0 +1,45 @@
1
+ import * as client from "openid-client";
2
+ import type { AuthProviderDefinition, ProviderOptions } from "../provider";
3
+ import { discoveredConfiguration, readBoolean, readString } from "../provider";
4
+
5
+ const GOOGLE_ISSUER = "https://accounts.google.com";
6
+
7
+ export type GoogleOptions = ProviderOptions;
8
+
9
+ /**
10
+ * Google OIDC。优先使用已验签 ID token 中的 claims;缺少 email 时
11
+ * 再调用 UserInfo,并把 expected subject 绑定到 ID token 的 `sub`。
12
+ */
13
+ export const google = (options: GoogleOptions): AuthProviderDefinition => {
14
+ const id = options.id ?? "google";
15
+ const label = options.label ?? "Google";
16
+ const scopes = options.scopes ?? ["openid", "email", "profile"];
17
+
18
+ return {
19
+ id,
20
+ label,
21
+ usesOidc: true,
22
+ scopes,
23
+ redirectUri: options.redirectUri,
24
+ getConfiguration: discoveredConfiguration(GOOGLE_ISSUER, options),
25
+ async resolveIdentity({ config, claims, accessToken }) {
26
+ const subject = readString(claims?.sub);
27
+ if (!subject) throw new Error("Google ID token did not contain a subject");
28
+
29
+ let email = readString(claims?.email);
30
+ let emailVerified = readBoolean(claims?.email_verified);
31
+ let name = readString(claims?.name);
32
+ let picture = readString(claims?.picture);
33
+
34
+ if (!email && config.serverMetadata().userinfo_endpoint) {
35
+ const info = await client.fetchUserInfo(config, accessToken, subject);
36
+ email = readString(info.email) ?? email;
37
+ emailVerified = readBoolean(info.email_verified) || emailVerified;
38
+ name = readString(info.name) ?? name;
39
+ picture = readString(info.picture) ?? picture;
40
+ }
41
+
42
+ return { provider: id, subject, email, emailVerified, name, picture };
43
+ },
44
+ };
45
+ };
@@ -0,0 +1,4 @@
1
+ export * from "./github";
2
+ export * from "./google";
3
+ export * from "./cloudflare";
4
+ export * from "./custom";
@@ -0,0 +1,32 @@
1
+ /** 公钥解析 / 验签失败的稳定错误码,便于路由层区分处理。 */
2
+ export type PubKeyErrorCode =
3
+ | "invalid-source"
4
+ | "invalid-input"
5
+ | "fetch-failed"
6
+ | "http-error"
7
+ | "timeout"
8
+ | "too-large"
9
+ | "parse-failed"
10
+ | "no-key"
11
+ | "fingerprint-mismatch";
12
+
13
+ export interface PubKeyErrorOptions {
14
+ cause?: unknown;
15
+ status?: number;
16
+ }
17
+
18
+ /**
19
+ * 公钥服务统一错误。验签的“签名不对”不走这里,而是返回 false;
20
+ * 这里只表示来源、网络、解析或调用参数本身有问题。
21
+ */
22
+ export class PubKeyError extends Error {
23
+ readonly code: PubKeyErrorCode;
24
+ readonly status: number | undefined;
25
+
26
+ constructor(code: PubKeyErrorCode, message: string, options: PubKeyErrorOptions = {}) {
27
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
28
+ this.name = "PubKeyError";
29
+ this.code = code;
30
+ this.status = options.status;
31
+ }
32
+ }
@@ -0,0 +1,156 @@
1
+ import * as openpgp from "openpgp";
2
+
3
+ export const MESSAGE = "hello acrux\nsecond line\n";
4
+
5
+ export interface KeyFixture {
6
+ publicKey: string;
7
+ privateKey: openpgp.PrivateKey;
8
+ publicKeyObject: openpgp.Key;
9
+ fingerprint: string;
10
+ keyId: string;
11
+ }
12
+
13
+ export interface SignedFixture {
14
+ keys: KeyFixture;
15
+ signature: string;
16
+ message: string;
17
+ }
18
+
19
+ const encoder = new TextEncoder();
20
+
21
+ const createKey = async (options: openpgp.KeyOptions): Promise<KeyFixture> => {
22
+ const generated = await openpgp.generateKey({ type: "curve25519", ...options, format: "armored" });
23
+ const privateKey = await openpgp.readPrivateKey({ armoredKey: generated.privateKey });
24
+ const publicKeyObject = await openpgp.readKey({ armoredKey: generated.publicKey });
25
+ return {
26
+ publicKey: generated.publicKey,
27
+ privateKey,
28
+ publicKeyObject,
29
+ fingerprint: publicKeyObject.getFingerprint().toUpperCase(),
30
+ keyId: publicKeyObject.getKeyID().toHex().toUpperCase(),
31
+ };
32
+ };
33
+
34
+ export const signDetached = async (fixture: KeyFixture, message: string, date?: Date): Promise<string> =>
35
+ openpgp.sign({
36
+ message: await openpgp.createMessage({ binary: encoder.encode(message) }),
37
+ signingKeys: fixture.privateKey,
38
+ detached: true,
39
+ format: "armored",
40
+ ...(date ? { date } : {}),
41
+ });
42
+
43
+ let alicePromise: Promise<KeyFixture> | undefined;
44
+ export const alice = (): Promise<KeyFixture> =>
45
+ (alicePromise ??= createKey({
46
+ userIDs: [
47
+ { name: "Alice Example", email: "alice@example.com" },
48
+ { name: "Alice Work", email: "alice@corp.example" },
49
+ ],
50
+ subkeys: [{ sign: true }, { sign: false }],
51
+ }));
52
+
53
+ let bobPromise: Promise<KeyFixture> | undefined;
54
+ export const bob = (): Promise<KeyFixture> =>
55
+ (bobPromise ??= createKey({
56
+ userIDs: [{ name: "Bob Builder", email: "bob@example.net" }],
57
+ }));
58
+
59
+ let revokedKeyPromise: Promise<SignedFixture> | undefined;
60
+ export const revokedKey = (): Promise<SignedFixture> =>
61
+ (revokedKeyPromise ??= (async () => {
62
+ const keys = await createKey({ userIDs: [{ name: "Revoked User", email: "revoked@example.com" }] });
63
+ const signature = await signDetached(keys, MESSAGE);
64
+ const revoked = await openpgp.revokeKey({ key: keys.privateKey, format: "armored" });
65
+ return {
66
+ keys: {
67
+ ...keys,
68
+ publicKey: revoked.publicKey,
69
+ publicKeyObject: await openpgp.readKey({ armoredKey: revoked.publicKey }),
70
+ },
71
+ signature,
72
+ message: MESSAGE,
73
+ };
74
+ })());
75
+
76
+ let revokedSubkeyPromise: Promise<SignedFixture> | undefined;
77
+ export const revokedSubkey = (): Promise<SignedFixture> =>
78
+ (revokedSubkeyPromise ??= (async () => {
79
+ const keys = await createKey({
80
+ userIDs: [{ name: "Revoked Subkey", email: "revoked-subkey@example.com" }],
81
+ subkeys: [{ sign: true }],
82
+ });
83
+ const signature = await signDetached(keys, MESSAGE);
84
+
85
+ const primary = keys.privateKey;
86
+ const signingSubkey = primary.getSubkeys()[0];
87
+ if (!signingSubkey) throw new Error("fixture: expected signing subkey");
88
+ const revoked = await signingSubkey.revoke(primary.keyPacket as openpgp.SecretKeyPacket);
89
+ primary.subkeys = primary.subkeys.map((subkey) =>
90
+ subkey.getKeyID().equals(revoked.getKeyID()) ? revoked : subkey,
91
+ );
92
+
93
+ const publicKey = primary.toPublic().armor();
94
+ return {
95
+ keys: {
96
+ ...keys,
97
+ publicKey,
98
+ publicKeyObject: await openpgp.readKey({ armoredKey: publicKey }),
99
+ },
100
+ signature,
101
+ message: MESSAGE,
102
+ };
103
+ })());
104
+
105
+ let expiredKeyPromise: Promise<SignedFixture> | undefined;
106
+ export const expiredKey = (): Promise<SignedFixture> =>
107
+ (expiredKeyPromise ??= (async () => {
108
+ const createdAt = new Date("2020-01-01T00:00:00Z");
109
+ const keys = await createKey({
110
+ userIDs: [{ name: "Expired User", email: "expired@example.com" }],
111
+ date: createdAt,
112
+ keyExpirationTime: 60 * 60 * 24,
113
+ });
114
+ const signature = await signDetached(keys, MESSAGE, new Date(createdAt.getTime() + 1000));
115
+ return { keys, signature, message: MESSAGE };
116
+ })());
117
+
118
+ /** 由 GnuPG 生成的有效 detached signature,覆盖 echo -n + 非 textmode 的精确字节语义(含 CRLF)。 */
119
+ export const GPG_MESSAGE = "gpg exact bytes\nwith crlf\r\nend";
120
+ export const GPG_FINGERPRINT = "DF13A1333A251AE6346A53937A3114C30E8C3CFE";
121
+ export const GPG_KEY = `-----BEGIN PGP PUBLIC KEY BLOCK-----
122
+
123
+ mDMEawu0ShYJKwYBBAHaRw8BAQdAZF2XDoLc4Bc3mbpczudfzTE2wQ1XEMhhth6Q
124
+ sgGDeOS0JUdQRyBGaXh0dXJlIDxncGctZml4dHVyZUBleGFtcGxlLmNvbT6IkAQT
125
+ FgoAOBYhBN8ToTM6JRrmNGpTk3oxFMMOjDz+BQJrC7RKAhsDBQsJCAcCBhUKCQgL
126
+ AgQWAgMBAh4BAheAAAoJEHoxFMMOjDz+xr8A/33eoohYL4LVs6YlwWaHaX6JDpv5
127
+ jGBIMm/+ZBTppLD0AQCvjcwURl8nMK4mHLImbqdC12rXYBUfmoQB6vCwgNEaCA==
128
+ =SXGZ
129
+ -----END PGP PUBLIC KEY BLOCK-----`;
130
+ export const GPG_SIGNATURE = `-----BEGIN PGP SIGNATURE-----
131
+
132
+ iHUEABYKAB0WIQTfE6EzOiUa5jRqU5N6MRTDDow8/gUCawu0SgAKCRB6MRTDDow8
133
+ /gHzAQDHCqi/zpaUGv8vUPmHK7KeLxfzq8vP4xfyff7Mq5usFgD/TYik5jnu8T3F
134
+ c/EdFDv/5HCuZCy013ps4orrEIbhQwg=
135
+ =lJaQ
136
+ -----END PGP SIGNATURE-----`;
137
+
138
+ /** 由 GnuPG 生成:key 不过期,但 detached signature 带 1 天有效期,已于 2020-01-02 过期。 */
139
+ export const EXPIRED_SIGNATURE_MESSAGE = "expired signature payload";
140
+ export const EXPIRED_SIGNATURE_FINGERPRINT = "20DD078B2F900706DDA5BFA9B3FF5EBE60A152AA";
141
+ export const EXPIRED_SIGNATURE_KEY = `-----BEGIN PGP PUBLIC KEY BLOCK-----
142
+
143
+ mDMEXgvhABYJKwYBBAHaRw8BAQdAkIPd9Wa5RwDs7aFhCByL3IkuRMOa61LM30a6
144
+ DUxGLU20JUV4cGlyZWQgU2lnIDxleHBpcmVkLXNpZ0BleGFtcGxlLmNvbT6IkAQT
145
+ FgoAOBYhBCDdB4svkAcG3aW/qbP/Xr5goVKqBQJeC+EAAhsDBQsJCAcCBhUKCQgL
146
+ AgQWAgMBAh4BAheAAAoJELP/Xr5goVKqDQMBAKSWZ4AKIYTcWoKHFjIxFOhLNhAW
147
+ g7UYQfu7zIqi3fakAPkBJ0mh1BpspBlQJ2oK4pgb0TRTaT3cZ4tgf6R/Ew1CDg==
148
+ =IT5X
149
+ -----END PGP PUBLIC KEY BLOCK-----`;
150
+ export const EXPIRED_SIGNATURE = `-----BEGIN PGP SIGNATURE-----
151
+
152
+ iHsEABYKACMWIQQg3QeLL5AHBt2lv6mz/16+YKFSqgUCXgvhAAWDAAFRgAAKCRCz
153
+ /16+YKFSqu5WAQDJ8xheQisMq56rdwu3clnXHOXZWFKwuRIPY5nkO6uAuAD/cpuB
154
+ dMAkNGJUsfB4M6bW2EnIFQoTDSE09wMhwWe9YQQ=
155
+ =q8Cb
156
+ -----END PGP SIGNATURE-----`;
@@ -0,0 +1,91 @@
1
+ import { PubKeyError } from "./errors";
2
+
3
+ export const DEFAULT_TIMEOUT_MS = 5_000;
4
+ export const DEFAULT_MAX_BYTES = 1_048_576;
5
+
6
+ const ACCEPT_HEADER = "application/pgp-keys, application/octet-stream, text/plain;q=0.9, */*;q=0.1";
7
+
8
+ export interface FetchBytesOptions {
9
+ /** 测试可注入;生产使用全局 fetch。 */
10
+ fetch?: typeof fetch;
11
+ timeoutMs?: number;
12
+ maxBytes?: number;
13
+ }
14
+
15
+ const assertHttps = (url: string): void => {
16
+ if (new URL(url).protocol !== "https:") {
17
+ throw new PubKeyError("fetch-failed", `Refusing to fetch a non-HTTPS URL: ${url}`);
18
+ }
19
+ };
20
+
21
+ const readBody = async (response: Response, maxBytes: number): Promise<Uint8Array> => {
22
+ if (!response.body) return new Uint8Array(0);
23
+
24
+ const reader = response.body.getReader();
25
+ const chunks: Uint8Array[] = [];
26
+ let total = 0;
27
+
28
+ for (;;) {
29
+ const { done, value } = await reader.read();
30
+ if (done) break;
31
+ if (!value) continue;
32
+
33
+ total += value.byteLength;
34
+ if (total > maxBytes) {
35
+ await reader.cancel().catch(() => undefined);
36
+ throw new PubKeyError("too-large", `OpenPGP key response exceeds ${maxBytes} bytes`);
37
+ }
38
+ chunks.push(value);
39
+ }
40
+
41
+ const body = new Uint8Array(total);
42
+ let offset = 0;
43
+ for (const chunk of chunks) {
44
+ body.set(chunk, offset);
45
+ offset += chunk.byteLength;
46
+ }
47
+ return body;
48
+ };
49
+
50
+ /**
51
+ * 带 5s 超时与 1MiB 上限的 HTTPS GET。超时覆盖连接与响应体读取,
52
+ * 先看 Content-Length,再按流累计,避免一次读入无界响应。
53
+ */
54
+ export const fetchBytes = async (url: string, options: FetchBytesOptions = {}): Promise<Uint8Array> => {
55
+ assertHttps(url);
56
+
57
+ const fetchImpl = options.fetch ?? fetch;
58
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
59
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
60
+ const controller = new AbortController();
61
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
62
+
63
+ try {
64
+ const response = await fetchImpl(url, {
65
+ signal: controller.signal,
66
+ redirect: "follow",
67
+ headers: { accept: ACCEPT_HEADER },
68
+ });
69
+
70
+ if (!response.ok) {
71
+ throw new PubKeyError("http-error", `HTTP ${response.status} for ${url}`, { status: response.status });
72
+ }
73
+
74
+ assertHttps(response.url || url);
75
+
76
+ const contentLength = Number(response.headers.get("content-length"));
77
+ if (Number.isFinite(contentLength) && contentLength > maxBytes) {
78
+ throw new PubKeyError("too-large", `OpenPGP key response exceeds ${maxBytes} bytes`);
79
+ }
80
+
81
+ return await readBody(response, maxBytes);
82
+ } catch (cause) {
83
+ if (cause instanceof PubKeyError) throw cause;
84
+ if (controller.signal.aborted) {
85
+ throw new PubKeyError("timeout", `Timed out fetching ${url} after ${timeoutMs}ms`, { cause });
86
+ }
87
+ throw new PubKeyError("fetch-failed", `Failed to fetch ${url}`, { cause });
88
+ } finally {
89
+ clearTimeout(timer);
90
+ }
91
+ };
@@ -0,0 +1,10 @@
1
+ export { PubKeyError, type PubKeyErrorCode, type PubKeyErrorOptions } from "./errors";
2
+ export {
3
+ createPubKeyResolver,
4
+ type PubKeyResolver,
5
+ type PubKeyResolverOptions,
6
+ type PubKeyResolverStatus,
7
+ } from "./resolver";
8
+ export { resolvePubKey, type ResolvePubKeyOptions } from "./resolve";
9
+ export { verifyDetachedSignature, type VerifyDetachedSignatureOptions } from "./verify";
10
+ export type { ResolvedPubKey } from "../../pubkey-types";