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

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,166 @@
1
+ import * as openpgp from "openpgp";
2
+ import type { ResolvedPubKey } from "../../pubkey-types";
3
+ import { PubKeyError } from "./errors";
4
+
5
+ /** 去掉所有空白并转大写;OpenPGP 的 fingerprint 与 key ID 都按此形式比较。 */
6
+ export const normalizeFingerprint = (value: string): string => value.replace(/\s+/g, "").toUpperCase();
7
+
8
+ const HEX = /^[0-9A-F]+$/;
9
+
10
+ /** 校验并规范化完整 fingerprint;非法输入直接抛明确错误。 */
11
+ export const normalizeFullFingerprint = (value: string): string => {
12
+ const normalized = normalizeFingerprint(value);
13
+ if (!(normalized.length === 40 || normalized.length === 64) || !HEX.test(normalized)) {
14
+ throw new PubKeyError("invalid-input", `Invalid OpenPGP fingerprint: ${value}`);
15
+ }
16
+ return normalized;
17
+ };
18
+
19
+ /** key ID 只接受 16 位 long ID 或完整 40/64 位 fingerprint;去掉可选的 `0x` 前缀。 */
20
+ export const normalizeKeyId = (value: string): string => {
21
+ const normalized = normalizeFingerprint(value).replace(/^0X/, "");
22
+ if (![16, 40, 64].includes(normalized.length) || !HEX.test(normalized)) {
23
+ throw new PubKeyError("invalid-input", `Invalid OpenPGP key ID: ${value}`);
24
+ }
25
+ return normalized;
26
+ };
27
+
28
+ export const isFullFingerprint = (value: string): boolean => value.length === 40 || value.length === 64;
29
+
30
+ /** 判断一段文本是否至少包含一个 PGP PUBLIC KEY BLOCK。 */
31
+ export const containsPublicKeyArmor = (value: string): boolean =>
32
+ value.includes("-----BEGIN PGP PUBLIC KEY BLOCK-----");
33
+
34
+ const parseArmoredKeys = async (armoredKeys: string): Promise<openpgp.Key[]> => {
35
+ const blocks = [
36
+ ...armoredKeys.matchAll(/-----BEGIN PGP PUBLIC KEY BLOCK-----[\s\S]*?-----END PGP PUBLIC KEY BLOCK-----/g),
37
+ ].map((match) => match[0]);
38
+ if (blocks.length === 0) {
39
+ throw new PubKeyError("parse-failed", "No armored OpenPGP public key block found");
40
+ }
41
+
42
+ try {
43
+ const keys: openpgp.Key[] = [];
44
+ for (const block of blocks) {
45
+ keys.push(...(await openpgp.readKeys({ armoredKeys: block })));
46
+ }
47
+ return keys;
48
+ } catch (cause) {
49
+ throw new PubKeyError("parse-failed", "Failed to parse armored OpenPGP public key", { cause });
50
+ }
51
+ };
52
+
53
+ const parseBinaryKeys = async (binaryKeys: Uint8Array): Promise<openpgp.Key[]> => {
54
+ try {
55
+ return await openpgp.readKeys({ binaryKeys });
56
+ } catch (cause) {
57
+ throw new PubKeyError("parse-failed", "Failed to parse binary OpenPGP public key", { cause });
58
+ }
59
+ };
60
+
61
+ const assertPublicKeys = (keys: openpgp.Key[]): openpgp.Key[] => {
62
+ if (keys.length === 0) throw new PubKeyError("no-key", "No OpenPGP public key found");
63
+ if (keys.some((key) => key.isPrivate())) {
64
+ throw new PubKeyError("invalid-input", "Expected an OpenPGP public key, got a private key");
65
+ }
66
+ return keys;
67
+ };
68
+
69
+ export const parsePublicKeyInput = async (input: string | Uint8Array): Promise<openpgp.Key[]> =>
70
+ assertPublicKeys(typeof input === "string" ? await parseArmoredKeys(input) : await parseBinaryKeys(input));
71
+
72
+ const decoder = new TextDecoder();
73
+
74
+ const isArmoredBody = (body: Uint8Array): boolean =>
75
+ containsPublicKeyArmor(decoder.decode(body.subarray(0, 256)).trimStart());
76
+
77
+ /** GitHub 对未上传 GPG key 的账号返回带明确 Note 的空 armor 占位。 */
78
+ const NO_KEY_PLACEHOLDER = /Note:\s*This user hasn't uploaded any GPG keys\./i;
79
+
80
+ /** 远程响应可能是 armored 或 binary;空响应与明确占位明确报 no-key。 */
81
+ export const parsePublicKeyBody = async (body: Uint8Array): Promise<openpgp.Key[]> => {
82
+ if (body.byteLength === 0) throw new PubKeyError("no-key", "Empty OpenPGP key response");
83
+ if (isArmoredBody(body)) {
84
+ const text = decoder.decode(body);
85
+ if (NO_KEY_PLACEHOLDER.test(text)) {
86
+ throw new PubKeyError("no-key", "OpenPGP key response is an explicit no-key placeholder");
87
+ }
88
+ return parsePublicKeyInput(text);
89
+ }
90
+ return parsePublicKeyInput(body);
91
+ };
92
+
93
+ const asciiLower = (value: string): string => value.replace(/[A-Z]/g, (character) => character.toLowerCase());
94
+
95
+ const emailLocalPart = (email: string | undefined): string | undefined => {
96
+ if (!email) return undefined;
97
+ const at = email.lastIndexOf("@");
98
+ return at > 0 ? email.slice(0, at) : undefined;
99
+ };
100
+
101
+ export interface PubKeySuggestionOptions {
102
+ /** 仅汇总该 email 对应 UID 的 local-part / name(WKD 用)。 */
103
+ email?: string;
104
+ }
105
+
106
+ /**
107
+ * 汇总 UID 的 email local-part 与 name;来源账号(github/gitlab)作为额外候选。
108
+ * 每个 UID 内 local-part 在前、name 在后,UID 之间保持原始顺序。
109
+ * 传入 email 时只取匹配该地址的 UID。按小写去重,保留第一次出现的顺序。
110
+ */
111
+ export const collectSuggestedUsernames = (
112
+ key: openpgp.Key,
113
+ extra: readonly string[] = [],
114
+ options: PubKeySuggestionOptions = {},
115
+ ): string[] => {
116
+ const seen = new Set<string>();
117
+ const usernames: string[] = [];
118
+ const expectedEmail = options.email?.trim().toLowerCase();
119
+ const add = (value: string | undefined): void => {
120
+ const trimmed = value?.trim();
121
+ if (!trimmed) return;
122
+ const canonical = asciiLower(trimmed);
123
+ if (seen.has(canonical)) return;
124
+ seen.add(canonical);
125
+ usernames.push(trimmed);
126
+ };
127
+
128
+ for (const user of key.users) {
129
+ const userID = user.userID;
130
+ if (!userID) continue;
131
+ if (expectedEmail && userID.email?.trim().toLowerCase() !== expectedEmail) continue;
132
+ add(emailLocalPart(userID.email));
133
+ add(userID.name);
134
+ }
135
+ for (const name of extra) add(name);
136
+
137
+ return usernames;
138
+ };
139
+
140
+ export const resolvedPubKeyFromKey = (
141
+ key: openpgp.Key,
142
+ extra: readonly string[] = [],
143
+ options: PubKeySuggestionOptions = {},
144
+ ): ResolvedPubKey => ({
145
+ fingerprint: normalizeFingerprint(key.getFingerprint()),
146
+ armoredKey: key.armor(),
147
+ suggested_usernames: collectSuggestedUsernames(key, extra, options),
148
+ });
149
+
150
+ export const keyHasEmail = (key: openpgp.Key, email: string): boolean => {
151
+ const expected = email.trim().toLowerCase();
152
+ return key.users.some((user) => user.userID?.email?.trim().toLowerCase() === expected);
153
+ };
154
+
155
+ /**
156
+ * fingerprint 精确匹配 primary 或任一 subkey;16 位 long ID 按 RFC 9580 匹配:
157
+ * v6(64 位 hex)fingerprint 取前 16 位,v4(40 位 hex)取后 16 位。
158
+ * 8 位短 ID 已在 normalizeKeyId 阶段拒绝。
159
+ */
160
+ export const keyMatchesKeyId = (key: openpgp.Key, keyId: string): boolean => {
161
+ const fingerprints = [key, ...key.getSubkeys()].map((candidate) => normalizeFingerprint(candidate.getFingerprint()));
162
+ return fingerprints.some((fingerprint) => {
163
+ if (isFullFingerprint(keyId)) return fingerprint === keyId;
164
+ return fingerprint.length === 64 ? fingerprint.startsWith(keyId) : fingerprint.endsWith(keyId);
165
+ });
166
+ };
@@ -0,0 +1,189 @@
1
+ import type * as openpgp from "openpgp";
2
+ import type { ResolvedPubKey } from "../../pubkey-types";
3
+ import { PubKeyError } from "./errors";
4
+ import { fetchBytes, type FetchBytesOptions } from "./http";
5
+ import {
6
+ containsPublicKeyArmor,
7
+ isFullFingerprint,
8
+ keyHasEmail,
9
+ keyMatchesKeyId,
10
+ normalizeKeyId,
11
+ parsePublicKeyBody,
12
+ parsePublicKeyInput,
13
+ resolvedPubKeyFromKey,
14
+ } from "./keys";
15
+ import { wkdUrls } from "./wkd";
16
+
17
+ export type ResolvePubKeyOptions = FetchBytesOptions;
18
+
19
+ interface LoadedKeys {
20
+ keys: openpgp.Key[];
21
+ /** github/gitlab 账号名等额外候选用户名。 */
22
+ usernames: string[];
23
+ /** WKD 只汇总匹配请求 email 的 UID 建议名。 */
24
+ suggestionEmail?: string;
25
+ }
26
+
27
+ type ParsedSource =
28
+ | { type: "inline"; armoredKeys: string }
29
+ | { type: "https"; url: string; usernames: string[] }
30
+ | { type: "wkd"; email: string }
31
+ | { type: "keyserver"; host: "ubuntu" | "openpgp"; id: string };
32
+
33
+ const unsupportedAccountSuffix = /\.(?:keys|pgp)$/i;
34
+
35
+ const parseAccountUrl = (host: "github" | "gitlab", value: string, source: string): ParsedSource => {
36
+ const account = value.trim();
37
+ if (!account) throw new PubKeyError("invalid-source", `Missing ${host} account in source: ${source}`);
38
+ if (unsupportedAccountSuffix.test(account)) {
39
+ throw new PubKeyError(
40
+ "invalid-source",
41
+ `${host} source must be a plain account name; .keys and .pgp suffixes are not supported`,
42
+ );
43
+ }
44
+
45
+ return {
46
+ type: "https",
47
+ url: `https://${host}.com/${encodeURIComponent(account)}.gpg`,
48
+ usernames: [account],
49
+ };
50
+ };
51
+
52
+ const parseSource = (source: string): ParsedSource => {
53
+ const value = source.trim();
54
+ if (!value) throw new PubKeyError("invalid-source", "Empty OpenPGP key source");
55
+
56
+ if (containsPublicKeyArmor(value)) return { type: "inline", armoredKeys: value };
57
+
58
+ if (/^https:\/\//i.test(value)) {
59
+ let url: URL;
60
+ try {
61
+ url = new URL(value);
62
+ } catch (cause) {
63
+ throw new PubKeyError("invalid-source", `Invalid HTTPS URL: ${value}`, { cause });
64
+ }
65
+ if (url.username || url.password) {
66
+ throw new PubKeyError("invalid-source", "HTTPS key URLs must not contain credentials");
67
+ }
68
+ return { type: "https", url: url.toString(), usernames: [] };
69
+ }
70
+
71
+ if (/^http:\/\//i.test(value)) {
72
+ throw new PubKeyError("invalid-source", "Only HTTPS URLs are supported for OpenPGP keys");
73
+ }
74
+
75
+ const schemeMatch = /^([A-Za-z][A-Za-z0-9+.-]*):(.*)$/s.exec(value);
76
+ if (schemeMatch) {
77
+ const scheme = (schemeMatch[1] ?? "").toLowerCase();
78
+ const rest = schemeMatch[2] ?? "";
79
+
80
+ if (scheme === "github" || scheme === "gitlab") return parseAccountUrl(scheme, rest, value);
81
+ if (scheme === "ubuntu" || scheme === "openpgp") {
82
+ const id = normalizeKeyId(rest);
83
+ return { type: "keyserver", host: scheme, id };
84
+ }
85
+
86
+ throw new PubKeyError("invalid-source", `Unsupported OpenPGP key source scheme: ${scheme}`);
87
+ }
88
+
89
+ if (value.includes("@")) return { type: "wkd", email: value };
90
+
91
+ throw new PubKeyError(
92
+ "invalid-source",
93
+ "Unsupported OpenPGP key source: use inline armor, github:, gitlab:, ubuntu:, openpgp:, an HTTPS URL, or an email",
94
+ );
95
+ };
96
+
97
+ const keyserverUrl = (host: "ubuntu" | "openpgp", id: string): string =>
98
+ host === "ubuntu"
99
+ ? `https://keyserver.ubuntu.com/pks/lookup?op=get&search=${encodeURIComponent(`0x${id}`)}`
100
+ : isFullFingerprint(id)
101
+ ? `https://keys.openpgp.org/vks/v1/by-fingerprint/${id}`
102
+ : `https://keys.openpgp.org/vks/v1/by-keyid/${id}`;
103
+
104
+ const loadKeyserver = async (
105
+ host: "ubuntu" | "openpgp",
106
+ id: string,
107
+ options: ResolvePubKeyOptions,
108
+ ): Promise<LoadedKeys> => {
109
+ const keys = await parsePublicKeyBody(await fetchBytes(keyserverUrl(host, id), options));
110
+ const selected = keys.filter((key) => keyMatchesKeyId(key, id));
111
+
112
+ if (selected.length === 0) {
113
+ throw new PubKeyError("fingerprint-mismatch", `Key server response does not contain ${id}`);
114
+ }
115
+ return { keys: selected, usernames: [] };
116
+ };
117
+
118
+ /** advanced 子域不存在(DNS 失败或 404/410)时才按规范回退 direct;超时与 5xx 不回退。 */
119
+ const shouldFallbackToDirect = (error: unknown): boolean =>
120
+ error instanceof PubKeyError &&
121
+ (error.code === "fetch-failed" || (error.code === "http-error" && (error.status === 404 || error.status === 410)));
122
+
123
+ const loadWkd = async (email: string, options: ResolvePubKeyOptions): Promise<LoadedKeys> => {
124
+ const lookup = await wkdUrls(email);
125
+
126
+ let body: Uint8Array;
127
+ try {
128
+ body = await fetchBytes(lookup.advancedUrl, options);
129
+ } catch (error) {
130
+ if (!shouldFallbackToDirect(error)) throw error;
131
+ body = await fetchBytes(lookup.directUrl, options);
132
+ }
133
+
134
+ const keys = await parsePublicKeyBody(body);
135
+ const matching = keys.filter((key) => keyHasEmail(key, lookup.address));
136
+ if (matching.length === 0) {
137
+ throw new PubKeyError("no-key", `WKD response does not contain a key with UID ${lookup.address}`);
138
+ }
139
+ return { keys: matching, usernames: [], suggestionEmail: lookup.address };
140
+ };
141
+
142
+ const loadSource = async (source: string, options: ResolvePubKeyOptions): Promise<LoadedKeys> => {
143
+ const parsed = parseSource(source);
144
+
145
+ switch (parsed.type) {
146
+ case "inline":
147
+ return { keys: await parsePublicKeyInput(parsed.armoredKeys), usernames: [] };
148
+ case "https":
149
+ return {
150
+ keys: await parsePublicKeyBody(await fetchBytes(parsed.url, options)),
151
+ usernames: parsed.usernames,
152
+ };
153
+ case "wkd":
154
+ return loadWkd(parsed.email, options);
155
+ case "keyserver":
156
+ return loadKeyserver(parsed.host, parsed.id, options);
157
+ }
158
+ };
159
+
160
+ /**
161
+ * 解析一个公钥来源,返回每把 key 一条记录。支持内联(可多段)armor、
162
+ * github:/gitlab:/ubuntu:/openpgp:、HTTPS armor 或 binary、以及裸 email 的 WKD。
163
+ * 无 key 时统一抛 `PubKeyError("no-key" | "invalid-source")`,不返回空数组。
164
+ */
165
+ export const resolvePubKey = async (source: string, options: ResolvePubKeyOptions = {}): Promise<ResolvedPubKey[]> => {
166
+ const loaded = await loadSource(source, options);
167
+ const resolved = new Map<string, ResolvedPubKey>();
168
+
169
+ for (const key of loaded.keys) {
170
+ const item = resolvedPubKeyFromKey(key, loaded.usernames, { email: loaded.suggestionEmail });
171
+ const existing = resolved.get(item.fingerprint);
172
+ if (!existing) {
173
+ resolved.set(item.fingerprint, item);
174
+ continue;
175
+ }
176
+
177
+ const seen = new Set(existing.suggested_usernames.map((name) => name.toLowerCase()));
178
+ for (const name of item.suggested_usernames) {
179
+ const canonical = name.toLowerCase();
180
+ if (seen.has(canonical)) continue;
181
+ seen.add(canonical);
182
+ existing.suggested_usernames.push(name);
183
+ }
184
+ }
185
+
186
+ const keys = [...resolved.values()];
187
+ if (keys.length === 0) throw new PubKeyError("no-key", "No OpenPGP public key found");
188
+ return keys;
189
+ };
@@ -0,0 +1,111 @@
1
+ import type { PubKeyResolverStatus, ResolvedPubKey } from "../../pubkey-types";
2
+ import { normalizeFullFingerprint } from "./keys";
3
+ import { resolvePubKey, type ResolvePubKeyOptions } from "./resolve";
4
+
5
+ export type { PubKeyResolverStatus } from "../../pubkey-types";
6
+
7
+ export interface PubKeyResolverOptions extends ResolvePubKeyOptions {
8
+ /** 构造时是否立即启动解析;默认 true。Workers 禁止 module global fetch 时可设 false。 */
9
+ autoStart?: boolean;
10
+ }
11
+
12
+ export interface PubKeyResolver {
13
+ /** 当前解析状态;构造后默认进入 loading。 */
14
+ readonly status: PubKeyResolverStatus;
15
+ /** 最近一次失败;成功后清空。 */
16
+ readonly error: Error | undefined;
17
+ /** 当前成功缓存的 key 快照;失败不会清掉旧值。 */
18
+ list(): ResolvedPubKey[];
19
+ /** 按 primary fingerprint 精确查找;找不到返回 undefined。 */
20
+ get(fingerprint: string): ResolvedPubKey | undefined;
21
+ /**
22
+ * 首次调用触发一次后台解析并记录已启动;之后不再主动重复。
23
+ * 与手动 refresh 共享在途 Promise,失败后需要手动 refresh 才会重试。
24
+ */
25
+ ensureStarted(): void;
26
+ /** 手动重新解析;在途调用共享同一个 Promise(singleflight)。 */
27
+ refresh(): Promise<ResolvedPubKey[]>;
28
+ }
29
+
30
+ const copyKey = (key: ResolvedPubKey): ResolvedPubKey => ({
31
+ ...key,
32
+ suggested_usernames: [...key.suggested_usernames],
33
+ });
34
+
35
+ /**
36
+ * per-isolate 公钥缓存控制器。autoStart(默认 true)时构造即发起一次解析;
37
+ * autoStart:false 时绝不在构造期 fetch,由首次 ensureStarted 启动。启动失败
38
+ * 被吞掉但状态可读;成功后缓存到实例销毁;refresh 成功时原子替换,失败时
39
+ * 保留旧成功缓存。所有状态都在闭包内,不存在跨实例共享。
40
+ */
41
+ export const createPubKeyResolver = (source: string, options: PubKeyResolverOptions = {}): PubKeyResolver => {
42
+ const { autoStart = true, ...resolveOptions } = options;
43
+ let status: PubKeyResolverStatus = "loading";
44
+ let lastError: Error | undefined;
45
+ let keys: readonly ResolvedPubKey[] = [];
46
+ let inFlight: Promise<ResolvedPubKey[]> | undefined;
47
+ let started = false;
48
+
49
+ const run = async (): Promise<ResolvedPubKey[]> => {
50
+ status = "loading";
51
+ lastError = undefined;
52
+
53
+ try {
54
+ const resolved = await resolvePubKey(source, resolveOptions);
55
+ keys = resolved;
56
+ status = "ready";
57
+ return keys.map(copyKey);
58
+ } catch (cause) {
59
+ lastError = cause instanceof Error ? cause : new Error(String(cause));
60
+ status = "error";
61
+ throw lastError;
62
+ }
63
+ };
64
+
65
+ const refresh = (): Promise<ResolvedPubKey[]> => {
66
+ if (inFlight) return inFlight;
67
+
68
+ const pending = run();
69
+ inFlight = pending;
70
+ void pending
71
+ .finally(() => {
72
+ if (inFlight === pending) inFlight = undefined;
73
+ })
74
+ .catch(() => {
75
+ // 初始调用没有 await;这里确保失败不会变成 unhandled rejection。
76
+ });
77
+ return pending;
78
+ };
79
+
80
+ const ensureStarted = (): void => {
81
+ if (started) return;
82
+ started = true;
83
+ void refresh().catch(() => {
84
+ // 启动尝试失败只记录在 status / error 中;之后由手动 refresh 重试。
85
+ });
86
+ };
87
+
88
+ if (autoStart) ensureStarted();
89
+
90
+ return {
91
+ get status() {
92
+ return status;
93
+ },
94
+ get error() {
95
+ return lastError;
96
+ },
97
+ list: () => keys.map(copyKey),
98
+ get: (fingerprint) => {
99
+ let normalized: string;
100
+ try {
101
+ normalized = normalizeFullFingerprint(fingerprint);
102
+ } catch {
103
+ return undefined;
104
+ }
105
+ const found = keys.find((key) => key.fingerprint === normalized);
106
+ return found ? copyKey(found) : undefined;
107
+ },
108
+ ensureStarted,
109
+ refresh,
110
+ };
111
+ };
@@ -0,0 +1,119 @@
1
+ import * as openpgp from "openpgp";
2
+ import type { ResolvedPubKey } from "../../pubkey-types";
3
+ import { PubKeyError } from "./errors";
4
+ import { normalizeFingerprint, normalizeFullFingerprint, parsePublicKeyInput } from "./keys";
5
+
6
+ export interface VerifyDetachedSignatureOptions {
7
+ /** 候选公钥集合;只会使用 primary fingerprint 完全匹配的那一把。 */
8
+ keys: readonly ResolvedPubKey[];
9
+ /** 期望的 primary key fingerprint;大小写与空格会被规范化。 */
10
+ fingerprint: string;
11
+ /** 被签名的原始消息。string 另有 Windows PowerShell 兼容候选;Uint8Array 严格按原字节。 */
12
+ message: string | Uint8Array;
13
+ /** armored detached signature。 */
14
+ signature: string;
15
+ }
16
+
17
+ /** 允许消息层 UUID 的 +60s 未来时间窗,但 key/subkey 当前有效性仍按真实 now 判断。 */
18
+ const VERIFY_CLOCK_SKEW_MS = 60_000;
19
+
20
+ const readCandidateKeys = async (armoredKey: string): Promise<openpgp.Key[]> => {
21
+ try {
22
+ return await parsePublicKeyInput(armoredKey);
23
+ } catch {
24
+ return [];
25
+ }
26
+ };
27
+
28
+ /**
29
+ * 验证 armored detached signature。只使用 fingerprint 指向的 primary key,
30
+ * 并只接受它自己的合法 signing subkey。签名不匹配、key/subkey 过期或撤销、
31
+ * 签名过期等情况返回 false;fingerprint 或 signature 本身格式非法则抛
32
+ * `PubKeyError("invalid-input")`。哈希算法与最小 key 强度沿用 openpgp 默认。
33
+ * string message 先尝试原始 UTF-8 bytes,失败后仅额外尝试 Windows PowerShell
34
+ * 管道产生的 EF BB BF + 原始 bytes + 0D 0A;Uint8Array 不增加候选。
35
+ */
36
+ export const verifyDetachedSignature = async ({
37
+ keys,
38
+ fingerprint,
39
+ message,
40
+ signature,
41
+ }: VerifyDetachedSignatureOptions): Promise<boolean> => {
42
+ const expectedFingerprint = normalizeFullFingerprint(fingerprint);
43
+
44
+ if (typeof message !== "string" && !(message instanceof Uint8Array)) {
45
+ throw new PubKeyError("invalid-input", "message must be a string or Uint8Array");
46
+ }
47
+ if (typeof signature !== "string" || signature.trim() === "") {
48
+ throw new PubKeyError("invalid-input", "signature must be a non-empty armored string");
49
+ }
50
+
51
+ let signingKey: openpgp.Key | undefined;
52
+ for (const candidate of keys) {
53
+ const key = (await readCandidateKeys(candidate.armoredKey)).find(
54
+ (item) => normalizeFingerprint(item.getFingerprint()) === expectedFingerprint,
55
+ );
56
+ if (!key) continue;
57
+ signingKey = key;
58
+ break;
59
+ }
60
+ if (!signingKey) return false;
61
+
62
+ let detachedSignature: openpgp.Signature;
63
+ try {
64
+ detachedSignature = await openpgp.readSignature({ armoredSignature: signature });
65
+ } catch (cause) {
66
+ throw new PubKeyError("invalid-input", "Invalid armored detached signature", { cause });
67
+ }
68
+
69
+ const now = new Date();
70
+ const verifyDate = new Date(now.getTime() + VERIFY_CLOCK_SKEW_MS);
71
+ const binary = typeof message === "string" ? new TextEncoder().encode(message) : message;
72
+ const binaryCandidates = [binary];
73
+ if (typeof message === "string") {
74
+ // Windows PowerShell 管道可能给原始 UTF-8 bytes 加 BOM,并在末尾追加 CRLF。
75
+ // 只兼容这一种完整 byte sequence,不做 trim、换行归一化或独立 BOM 去除。
76
+ const powershellBinary = new Uint8Array(binary.byteLength + 5);
77
+ powershellBinary.set([0xef, 0xbb, 0xbf]);
78
+ powershellBinary.set(binary, 3);
79
+ powershellBinary.set([0x0d, 0x0a], binary.byteLength + 3);
80
+ binaryCandidates.push(powershellBinary);
81
+ }
82
+
83
+ try {
84
+ // 当前状态必须有效:OpenPGP.js 的验签主要检查签名时刻的 key 有效性,
85
+ // 这里额外拒绝“签名之后才过期/撤销”的 key。
86
+ await signingKey.verifyPrimaryKey(now);
87
+
88
+ for (const candidateBinary of binaryCandidates) {
89
+ const result = await openpgp.verify({
90
+ message: await openpgp.createMessage({ binary: candidateBinary }),
91
+ signature: detachedSignature,
92
+ verificationKeys: signingKey,
93
+ date: verifyDate,
94
+ });
95
+
96
+ let verified = false;
97
+ for (const candidate of result.signatures) {
98
+ try {
99
+ await candidate.verified;
100
+
101
+ // gpg --detach-sign 非 textmode 才是 binary;text 签名会引入换行归一化,
102
+ // 不作为有效候选。
103
+ const signaturePacket = (await candidate.signature).packets[0];
104
+ if (signaturePacket?.signatureType !== openpgp.enums.signature.binary) continue;
105
+
106
+ // 实际使用的 primary key 或 signing subkey 也必须当前有效。
107
+ await signingKey.getSigningKey(candidate.keyID, now);
108
+ verified = true;
109
+ } catch {
110
+ // 多签名 armor 中其它 key 的失败 packet 不影响合法候选。
111
+ }
112
+ }
113
+ if (verified) return true;
114
+ }
115
+ return false;
116
+ } catch {
117
+ return false;
118
+ }
119
+ };
@@ -0,0 +1,78 @@
1
+ import { PubKeyError } from "./errors";
2
+
3
+ /** RFC 6189 §5.1.6 的 z-base-32 alphabet。 */
4
+ const ZBASE32_ALPHABET = "ybndrfg8ejkmcpqxot1uwisza345h769";
5
+
6
+ /** 按 RFC 6189 的 5-bit 分组(MSB first)编码。 */
7
+ export const zbase32Encode = (bytes: Uint8Array): string => {
8
+ let buffer = 0;
9
+ let bits = 0;
10
+ let encoded = "";
11
+
12
+ for (const byte of bytes) {
13
+ buffer = (buffer << 8) | byte;
14
+ bits += 8;
15
+ while (bits >= 5) {
16
+ encoded += ZBASE32_ALPHABET[(buffer >>> (bits - 5)) & 31];
17
+ bits -= 5;
18
+ }
19
+ }
20
+
21
+ if (bits > 0) encoded += ZBASE32_ALPHABET[(buffer << (5 - bits)) & 31];
22
+ return encoded;
23
+ };
24
+
25
+ /** WKD 只把 ASCII 大写字母转小写,非 ASCII 字符保持原样。 */
26
+ const asciiLower = (value: string): string => value.replace(/[A-Z]/g, (character) => character.toLowerCase());
27
+
28
+ export interface WkdEmail {
29
+ /** 原始本地部分 + 小写域名,用于 UID 比较。 */
30
+ address: string;
31
+ /** 原始本地部分;`l` 查询参数保留其大小写。 */
32
+ localPart: string;
33
+ domain: string;
34
+ }
35
+
36
+ export interface WkdLookup extends WkdEmail {
37
+ hash: string;
38
+ advancedUrl: string;
39
+ directUrl: string;
40
+ }
41
+
42
+ export const parseWkdEmail = (value: string): WkdEmail => {
43
+ const email = value.trim();
44
+ const at = email.lastIndexOf("@");
45
+ if (at <= 0 || at === email.length - 1 || /\s/.test(email)) {
46
+ throw new PubKeyError("invalid-source", `Invalid email for WKD lookup: ${value}`);
47
+ }
48
+
49
+ const localPart = email.slice(0, at);
50
+ const domain = email.slice(at + 1).toLowerCase();
51
+ if (/[/:?#]/.test(domain)) throw new PubKeyError("invalid-source", `Invalid WKD domain: ${domain}`);
52
+
53
+ return { address: `${localPart}@${domain}`, localPart, domain };
54
+ };
55
+
56
+ /** `SHA1(asciiLower(local-part))` 的 z-base-32 编码,固定 32 字符。 */
57
+ export const wkdHash = async (email: string): Promise<string> => {
58
+ const { localPart } = parseWkdEmail(email);
59
+ const digest = await crypto.subtle.digest("SHA-1", new TextEncoder().encode(asciiLower(localPart)));
60
+ return zbase32Encode(new Uint8Array(digest));
61
+ };
62
+
63
+ /**
64
+ * 生成 advanced 与 direct 两个规范 URL。advanced 优先;`l` 参数保留原始
65
+ * local-part 并做 percent escaping。
66
+ */
67
+ export const wkdUrls = async (email: string): Promise<WkdLookup> => {
68
+ const parsed = parseWkdEmail(email);
69
+ const hash = await wkdHash(parsed.address);
70
+ const localPart = encodeURIComponent(parsed.localPart);
71
+
72
+ return {
73
+ ...parsed,
74
+ hash,
75
+ advancedUrl: `https://openpgpkey.${parsed.domain}/.well-known/openpgpkey/${parsed.domain}/hu/${hash}?l=${localPart}`,
76
+ directUrl: `https://${parsed.domain}/.well-known/openpgpkey/hu/${hash}?l=${localPart}`,
77
+ };
78
+ };
@@ -0,0 +1,14 @@
1
+ export {
2
+ createPubKeyPasskeyRoutes,
3
+ type PubKeyPasskeyCompleteRegistration,
4
+ type PubKeyPasskeyCompletionInput,
5
+ type PubKeyPasskeyCompletionResult,
6
+ type PubKeyPasskeyCredential,
7
+ type PubKeyPasskeyErrorResponse,
8
+ type PubKeyPasskeyKeysResponse,
9
+ type PubKeyPasskeyRefreshResponse,
10
+ type PubKeyPasskeyRegisterRequest,
11
+ type PubKeyPasskeyRegisterResponse,
12
+ type PubKeyPasskeyRoutes,
13
+ type PubKeyPasskeyRoutesOptions,
14
+ } from "./routes";