@tacet-ink/journal-core 0.2.5 → 0.3.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 (49) hide show
  1. package/README.md +38 -15
  2. package/dist/client/argon-auto.d.ts +47 -0
  3. package/dist/client/argon-auto.js +226 -0
  4. package/dist/client/argon-worker.d.ts +31 -0
  5. package/dist/client/argon-worker.js +147 -0
  6. package/dist/client/argon2.d.ts +167 -0
  7. package/dist/client/argon2.js +410 -0
  8. package/dist/client/bip39.d.ts +11 -0
  9. package/dist/client/bip39.js +139 -0
  10. package/dist/client/keys.d.ts +15 -0
  11. package/dist/client/keys.js +30 -0
  12. package/dist/client/note-crypto.d.ts +203 -0
  13. package/dist/client/note-crypto.js +600 -0
  14. package/dist/client/pinlock.d.ts +38 -0
  15. package/dist/client/pinlock.js +84 -0
  16. package/dist/client/vault-error.d.ts +44 -0
  17. package/dist/client/vault-error.js +19 -0
  18. package/dist/client/vault.d.ts +107 -0
  19. package/dist/client/vault.js +391 -0
  20. package/dist/client/vendor/hash-wasm-argon2.d.ts +14 -0
  21. package/dist/client/vendor/hash-wasm-argon2.js +160 -0
  22. package/dist/client/wordlist.d.ts +7 -0
  23. package/dist/client/wordlist.js +264 -0
  24. package/dist/index.d.ts +18 -0
  25. package/dist/index.js +17 -0
  26. package/dist/server/auth.d.ts +99 -0
  27. package/dist/server/auth.js +158 -0
  28. package/dist/server/cors.d.ts +10 -0
  29. package/dist/server/cors.js +21 -0
  30. package/dist/server/env.d.ts +6 -0
  31. package/dist/server/env.js +1 -0
  32. package/dist/server/hash.d.ts +11 -0
  33. package/dist/server/hash.js +26 -0
  34. package/dist/server/ladder.d.ts +49 -0
  35. package/dist/server/ladder.js +50 -0
  36. package/dist/server/ratelimit.d.ts +32 -0
  37. package/dist/server/ratelimit.js +63 -0
  38. package/docs/format-spec.md +369 -0
  39. package/docs/vectors/bip39.json +1063 -0
  40. package/docs/vectors/families.json +594 -0
  41. package/docs/vectors/kat.json +145 -0
  42. package/package.json +68 -17
  43. package/scripts/verify-core-crypto.ts +406 -11
  44. package/src/client/argon-auto.ts +224 -0
  45. package/src/client/argon-worker.ts +147 -0
  46. package/src/client/argon2.ts +7 -2
  47. package/src/client/vault-error.ts +51 -0
  48. package/src/client/vault.ts +486 -0
  49. package/src/client/vendor/hash-wasm-argon2.ts +27 -0
package/README.md CHANGED
@@ -18,7 +18,7 @@
18
18
  ```sh
19
19
  git clone https://github.com/tacet-ink/journal-core.git && cd journal-core
20
20
  npm ci --ignore-scripts
21
- npm run verify # 491 assertions, all green, run against the real modules (no mocks)
21
+ npm run verify # 506 assertions, all green, run against the real modules (no mocks)
22
22
  ```
23
23
 
24
24
  ```ts
@@ -80,9 +80,14 @@ run: `node --experimental-strip-types example.ts`
80
80
  | `src/server/ratelimit.ts` | per-IP fixed-window 限流(單句 UPSERT…RETURNING;D1 計數,跨 isolate 有效) |
81
81
  | `src/server/cors.ts`/`hash.ts` | 共用 CORS/雜湊工具(`src/server/env.ts` 為內部 Env 介面,不入 exports) |
82
82
 
83
+ 發行形(0.3.0 起):`dist/`=tsc 原生 emit 的 ESM `.js`+`.d.ts`,`exports` 全部子路徑指向 dist;
84
+ `src/` 同包隨附(稽核/閱讀用,import 恆走 dist)。
85
+
83
86
  ## 前綴契約(家族表:13 個資料前綴+閘對照組 jr1g.)
84
87
 
85
88
  前綴是版本契約:payload 佈局與 KDF 由前綴界定,升級 = 新前綴。
89
+ 逐位元組布局、KDF 參數、AAD 與世代契約的完整規格見 [docs/format-spec.md](./docs/format-spec.md),
90
+ 測試向量見 [docs/vectors/](./docs/vectors/)(真原語產生的凍結證據;閘 [26] 檢存在性與 shape)。
86
91
  Tacet 部署實例(config 傳入):
87
92
 
88
93
  | 前綴 | 語意 | KDF | payload |
@@ -119,7 +124,7 @@ jr3d/jr4d 兩入參數同輸入,域分離由 info 承載;凍結 KAT 兩 blob
119
124
 
120
125
  ```sh
121
126
  npm ci --ignore-scripts
122
- npm run verify # 491 斷言對真模組(禁鏡像;限流單句 UPSERT…RETURNING 直載真 SQLite):roundtrip/AAD 防搬移/
127
+ npm run verify # 506 斷言對真模組(禁鏡像;限流單句 UPSERT…RETURNING 直載真 SQLite):roundtrip/AAD 防搬移/
123
128
  # extractable/時代隔離/跨前綴家族隔離/payload 竄改/RFC 9106 KAT/BIP39 @scure 對照 200 組/
124
129
  # server-side(inboundCipher/validWrappedKey/pickKeyPackage/checkRate/timingSafeEq)+ pinlock 全函式
125
130
  # + 密語正規化 v3 世代(normalizePassphrase/jr4w./jr4d./PH1 v3 鹽域分離+帶內版本化舊契約向量)
@@ -131,8 +136,10 @@ npm run verify # 491 斷言對真模組(禁鏡像;限流單句 UPSERT…RE
131
136
  # +KAT 凍結向量 [17](HKDF info 域世代分離+v3/raw 入口契約四 blob)
132
137
  # +包裹前綴快檢 [13-2](錯前綴試探免付 KDF:五入口行為+計時帽+計數錨)
133
138
  # +CI 供應鏈面 [21](npm ci --ignore-scripts+dependabot runner fromJSON 分流+腳本摘除+NIT-1 錨+r2 MINOR-1 URL 直傳;
134
- # 491 帳=repo 樹——發行包內無 .github=[21] 四條 workflow 錨收斂為 1 顯性 SKIP 行→480,SKIP 顯形非靜默)
139
+ # 506 帳=repo 樹——發行包內無 .github=[21] 四條 workflow 錨收斂為 1 顯性 SKIP 行→503,SKIP 顯形非靜默)
135
140
  # +發行 tarball 治理面 [22](pack 白名單零 open-card-pr.sh)
141
+ # +格式規格+測試向量 [26](docs/format-spec.md+docs/vectors 存在性/位元組 shape/欄位名對規格/凍結 KAT 逐字對閘)
142
+ # +高階 Vault API [27](roundtrip 三形/新舊前綴解鎖/upgrade/換密語/復原/VaultError 毒化/載體覆寫+Worker 回退鏈/vendor 孿生)
136
143
  ```
137
144
 
138
145
  - 產品碼**零執行時依賴**(WebCrypto 原語);devDependencies 僅閘用(typescript、@scure/bip39 對照、workers types)。
@@ -146,8 +153,9 @@ npm run verify # 491 斷言對真模組(禁鏡像;限流單句 UPSERT…RE
146
153
 
147
154
  ## 使用(Usage)
148
155
 
149
- TypeScript 原始碼發行(exports 直指 .ts)。**注意**:Node 的 strip-types 不適用於
150
- node_modules 內的檔案,npm 安裝的消費者請走打包器;源碼 clone 可直接 node --experimental-strip-types。
156
+ 0.3.0 起發行 `dist/`(ESM `.js`+`.d.ts`):npm 安裝後瀏覽器、Node、Deno、Bun、Workers
157
+ 皆可直接 import,不需打包器、不需 strip-types(0.2.x 的「npm 安裝必走打包器」限制已退役)。
158
+ 源碼 clone 仍可直接 `node --experimental-strip-types` 跑 `src/`。
151
159
 
152
160
  ```ts
153
161
  import { makeKeyStore, makeHeldKey, generateNoteKey, encryptNote, decryptNote } from '@tacet-ink/journal-core';
@@ -241,8 +249,8 @@ catch)+套用 `migrations/0011-ph2-ladder.sql`(+0012 索引修正);
241
249
  - `PinLockConfig`:解包輸出的 noteKey 恆 `extractable=true`(鐵律,非可調選項)——
242
250
  config 只帶三個前綴欄(pinLock/pinLockSaltPrefix/pinLockAad),缺任一即拒。
243
251
 
244
- 打包器(vite/esbuild)可直接 alias 到源碼目錄使用;Argon2id 瀏覽器載體需另裝
245
- hash-wasm 並以 `setArgonLoader()` 注入(詳 `src/client/argon2.ts` 檔頭)。
252
+ Argon2id 瀏覽器載體需另裝 hash-wasm 並以 `setArgonLoader()` 注入(詳 `src/client/argon2.ts` 檔頭);
253
+ Node ≥ 24.7 走內建 `node:crypto` 免注入。
246
254
 
247
255
  ## 界限(誠實面)
248
256
 
@@ -309,16 +317,31 @@ carrier: `node:crypto` ≥ Node 24.7 / hash-wasm in browsers, RFC 9106 test vect
309
317
  @scure/bip39), brand-namespaced key storage (`keys.ts`). Server: zero-knowledge auth core with a
310
318
  PH1→PH2 login flow, inbound cipher/package validation and paired key-package selection
311
319
  (`auth.ts`; PH2-UNIQUE conflict and session revocation are caller-owned wiring), per-IP
312
- fixed-window rate limiting on D1 (`ratelimit.ts`), shared CORS/hash utilities.
313
-
314
- **Verification.** `npm run verify` runs 491 assertions against the real modules (no mocks):
320
+ fixed-window rate limiting on D1 (`ratelimit.ts`), shared CORS/hash utilities. Since 0.3.0 the
321
+ package ships `dist/` (tsc-emitted ESM `.js` + `.d.ts`); every `exports` subpath resolves to dist,
322
+ and `src/` is included for reading and auditing only.
323
+
324
+ **Format spec & test vectors.** The byte-level wire format of every prefix family — payload layout
325
+ and field lengths, KDF parameters, AAD strings, and the in-band versioning contract — is specified
326
+ in [docs/format-spec.md](./docs/format-spec.md) (Chinese; transcribed from the source, not a new
327
+ contract). JSON test vectors live in [docs/vectors/](./docs/vectors/): one wrap/encrypt sample per
328
+ prefix family (`families.json`), known-answer vectors (RFC 9106 Argon2id, the gate's frozen
329
+ `jr2w.`/`jr3w.`/`jr3d.`/`jr4w.`/`jr4d.`/`jr1r.`/`jr1w.` blobs, and PH1/PH2 credential samples in
330
+ `kat.json`), and 34 BIP39 samples (`bip39.json`). They were generated once by
331
+ `scripts/generate-vectors.ts` against the real primitives and committed as frozen evidence; the
332
+ verify gate checks their presence and shape (section [26]) and does not regenerate them.
333
+
334
+ **Verification.** `npm run verify` runs 506 assertions against the real modules (no mocks):
315
335
  roundtrips, AAD tamper-evidence, extractability rules, era isolation, cross-prefix family
316
336
  isolation, payload tampering, RFC 9106 KAT, a 200-vector BIP39 cross-check, and the
317
- login ladder-guard behavior suite (external audit #8).
318
-
319
- **Usage.** TypeScript source is published (exports point at `.ts`). If you install from npm you
320
- must bundle it (vite/esbuild etc.); Node's strip-types does not apply inside `node_modules`.
321
- See the code sample in the 使用 section above.
337
+ login ladder-guard behavior suite (external audit #8), and presence/shape checks for the format
338
+ spec and test vectors.
339
+
340
+ **Usage.** Since 0.3.0 the npm package ships compiled ESM in `dist/`, so browsers, Node, Deno, Bun
341
+ and Workers can import it directly — no bundler and no strip-types needed (the 0.2.x "must bundle"
342
+ requirement is retired). A source checkout can still run `src/` with `node --experimental-strip-types`.
343
+ In browsers, inject the hash-wasm Argon2id carrier via `setArgonLoader()`; Node ≥ 24.7 uses the
344
+ built-in `node:crypto`. See the code sample in the 使用 section above.
322
345
 
323
346
  **Honest limits.** The guest era is obfuscation-grade, not E2E. PH1 derivation is defined by each
324
347
  product (fast hash or Argon2id); this layer only validates its hex64 form. Product concerns
@@ -0,0 +1,47 @@
1
+ /**
2
+ * argon-auto.ts — Argon2id 載體平台預設。
3
+ *
4
+ * 優先序(向後相容鐵律:setArgonLoader 照舊優先):
5
+ * 1. 呼叫端已 setArgonLoader 注入(非本模組自裝)='injected'——本模組零介入。
6
+ * 2. 回退鏈 chain(可覆寫;預設 ['node','worker','inline'])逐項取第一個可用者:
7
+ * - 'node':node:crypto.argon2 在場(argon2.ts 原生腿;本模組不注入)。
8
+ * - 'worker':Web Worker(argon-worker.ts 內嵌 blob 形);執行期失效=若 chain 於其後含
9
+ * 'inline' 則回退 inline(onFallback 通知+currentArgonCarrier 翻 'inline'=行為顯形),否則 throw。
10
+ * - 'inline':同執行緒 vendor hash-wasm(WebAssembly 在場即可)。
11
+ * 3. 皆不可用=ERR_VAULT_KDF_UNSUPPORTED(zero-fallback:禁 PBKDF2/zeros 兜底)。
12
+ * 裝載即 KAT:每個載體首用前跑 RFC 9106 KAT(verifyArgonKat)——錯值載體=拒用,不只是缺席才拒。
13
+ *
14
+ * 'worker'/'inline' 經 setArgonLoader 全域注入(argon2.ts 派生本體唯一入口):同頁其他 argon2.ts
15
+ * 呼叫端共享此載體;呼叫端之後自行 setArgonLoader 即覆寫(下次 ensure 判 'injected')。
16
+ * resetArgonCarrier() 撤除本模組自裝載體(不動呼叫端注入)並終止 Worker。
17
+ */
18
+ import { type ArgonWorkerLike } from './argon-worker.ts';
19
+ export type ArgonCarrierKind = 'injected' | 'node' | 'worker' | 'inline';
20
+ export type ArgonCarrierChoice = 'node' | 'worker' | 'inline';
21
+ export type { ArgonWorkerLike };
22
+ export interface ArgonFallbackEvent {
23
+ from: 'worker';
24
+ to: 'inline';
25
+ error: unknown;
26
+ }
27
+ export interface ArgonCarrierOptions {
28
+ /** 回退鏈(預設 ['node','worker','inline'])。例:['worker']=只准 Worker(失效即拒,不回退)。 */
29
+ chain?: readonly ArgonCarrierChoice[];
30
+ /** Worker 工廠覆寫(預設瀏覽器 blob Worker;測試/特殊宿主注入轉接層)。 */
31
+ createWorker?: () => ArgonWorkerLike;
32
+ /** Worker → inline 回退通知(行為顯形;不提供=靜默回退但 currentArgonCarrier 仍翻 'inline')。 */
33
+ onFallback?: (ev: ArgonFallbackEvent) => void;
34
+ }
35
+ export declare const DEFAULT_ARGON_CHAIN: readonly ArgonCarrierChoice[];
36
+ /** 載體終端失效累計(拋出派生本體的失效才計;回退成功不計)。vault 以前後差分辨
37
+ * 「解包 null=密語錯」與「載體失效」(低階 unwrap 吞錯回 null,邊界還原真因)。 */
38
+ export declare function argonCarrierFailures(): number;
39
+ /** 現行載體(未 ensure 過且無注入、非 node=null)。 */
40
+ export declare function currentArgonCarrier(): ArgonCarrierKind | null;
41
+ /** 撤除本模組自裝載體(呼叫端 setArgonLoader 注入不動)+終止 Worker。 */
42
+ export declare function resetArgonCarrier(): void;
43
+ /**
44
+ * 確保 Argon2id 載體可用並回報種類。冪等:同選項重呼沿用既裝載體(Worker 不重建);
45
+ * 選項(chain/createWorker/onFallback)改變=撤除重裝。首用載體必過 RFC 9106 KAT。
46
+ */
47
+ export declare function ensureArgonCarrier(opts?: ArgonCarrierOptions): Promise<ArgonCarrierKind>;
@@ -0,0 +1,226 @@
1
+ /**
2
+ * argon-auto.ts — Argon2id 載體平台預設。
3
+ *
4
+ * 優先序(向後相容鐵律:setArgonLoader 照舊優先):
5
+ * 1. 呼叫端已 setArgonLoader 注入(非本模組自裝)='injected'——本模組零介入。
6
+ * 2. 回退鏈 chain(可覆寫;預設 ['node','worker','inline'])逐項取第一個可用者:
7
+ * - 'node':node:crypto.argon2 在場(argon2.ts 原生腿;本模組不注入)。
8
+ * - 'worker':Web Worker(argon-worker.ts 內嵌 blob 形);執行期失效=若 chain 於其後含
9
+ * 'inline' 則回退 inline(onFallback 通知+currentArgonCarrier 翻 'inline'=行為顯形),否則 throw。
10
+ * - 'inline':同執行緒 vendor hash-wasm(WebAssembly 在場即可)。
11
+ * 3. 皆不可用=ERR_VAULT_KDF_UNSUPPORTED(zero-fallback:禁 PBKDF2/zeros 兜底)。
12
+ * 裝載即 KAT:每個載體首用前跑 RFC 9106 KAT(verifyArgonKat)——錯值載體=拒用,不只是缺席才拒。
13
+ *
14
+ * 'worker'/'inline' 經 setArgonLoader 全域注入(argon2.ts 派生本體唯一入口):同頁其他 argon2.ts
15
+ * 呼叫端共享此載體;呼叫端之後自行 setArgonLoader 即覆寫(下次 ensure 判 'injected')。
16
+ * resetArgonCarrier() 撤除本模組自裝載體(不動呼叫端注入)並終止 Worker。
17
+ */
18
+ import { getArgonLoader, setArgonLoader, verifyArgonKat } from './argon2.js';
19
+ import { makeWorkerArgon2id, createBlobArgonWorker } from './argon-worker.js';
20
+ import { hashWasmArgon2Factory } from './vendor/hash-wasm-argon2.js';
21
+ import { VaultError } from './vault-error.js';
22
+ export const DEFAULT_ARGON_CHAIN = ['node', 'worker', 'inline'];
23
+ function nodeArgonAvailable() {
24
+ const nodeCrypto = globalThis.process?.getBuiltinModule?.('node:crypto');
25
+ return typeof nodeCrypto?.argon2 === 'function';
26
+ }
27
+ function workerAvailable(opts) {
28
+ if (opts.createWorker)
29
+ return true;
30
+ const g = globalThis;
31
+ return typeof g.Worker === 'function' && typeof g.Blob === 'function' && typeof g.URL?.createObjectURL === 'function';
32
+ }
33
+ function wasmAvailable() {
34
+ return typeof globalThis.WebAssembly === 'object';
35
+ }
36
+ let auto = null;
37
+ let nodeVerified = false;
38
+ const verified = new WeakSet();
39
+ let failures = 0;
40
+ /** 載體終端失效累計(拋出派生本體的失效才計;回退成功不計)。vault 以前後差分辨
41
+ * 「解包 null=密語錯」與「載體失效」(低階 unwrap 吞錯回 null,邊界還原真因)。 */
42
+ export function argonCarrierFailures() {
43
+ return failures;
44
+ }
45
+ /** 現行載體(未 ensure 過且無注入、非 node=null)。 */
46
+ export function currentArgonCarrier() {
47
+ const cur = getArgonLoader();
48
+ if (cur)
49
+ return auto && cur === auto.loader ? auto.kind : 'injected';
50
+ return nodeArgonAvailable() ? 'node' : null;
51
+ }
52
+ /** 撤除本模組自裝載體(呼叫端 setArgonLoader 注入不動)+終止 Worker。 */
53
+ export function resetArgonCarrier() {
54
+ if (!auto)
55
+ return;
56
+ const a = auto;
57
+ auto = null;
58
+ if (getArgonLoader() === a.loader)
59
+ setArgonLoader(null);
60
+ a.dispose();
61
+ }
62
+ // ── inline 載體(同執行緒 vendor hash-wasm;串行) ────────────────────────────
63
+ function makeInlineArgon2id() {
64
+ let mod = null;
65
+ let queue = Promise.resolve();
66
+ return (params) => {
67
+ const job = queue.then(() => {
68
+ if (!mod)
69
+ mod = hashWasmArgon2Factory();
70
+ return mod.argon2id(params);
71
+ });
72
+ queue = job.catch(() => undefined);
73
+ return job;
74
+ };
75
+ }
76
+ function terminal(e, what) {
77
+ failures++;
78
+ return new VaultError('ERR_VAULT_KDF_UNSUPPORTED', what, { cause: e });
79
+ }
80
+ function installInline(chainKey, opts) {
81
+ const inline = makeInlineArgon2id();
82
+ const argon2id = async (params) => {
83
+ try {
84
+ return await inline(params);
85
+ }
86
+ catch (e) {
87
+ throw terminal(e, 'inline carrier failed');
88
+ }
89
+ };
90
+ const mod = { argon2id };
91
+ const st = {
92
+ loader: () => Promise.resolve(mod),
93
+ kind: 'inline',
94
+ chainKey,
95
+ createWorker: opts.createWorker,
96
+ onFallback: opts.onFallback,
97
+ dispose: () => { },
98
+ };
99
+ return st;
100
+ }
101
+ function installWorker(chainKey, opts, fallbackInline) {
102
+ const w = makeWorkerArgon2id(opts.createWorker ?? createBlobArgonWorker);
103
+ let inline = null;
104
+ const st = {
105
+ loader: () => Promise.resolve(mod),
106
+ kind: 'worker',
107
+ chainKey,
108
+ createWorker: opts.createWorker,
109
+ onFallback: opts.onFallback,
110
+ dispose: () => w.terminate(),
111
+ };
112
+ const argon2id = async (params) => {
113
+ if (st.kind === 'worker') {
114
+ try {
115
+ return await w.argon2id(params);
116
+ }
117
+ catch (e) {
118
+ if (!fallbackInline)
119
+ throw terminal(e, 'worker carrier failed (chain has no inline fallback)');
120
+ // 回退:整載體翻 inline(不再試 Worker)——顯形:kind 翻面+onFallback 通知。
121
+ if (st.kind === 'worker') {
122
+ st.kind = 'inline';
123
+ w.terminate();
124
+ try {
125
+ opts.onFallback?.({ from: 'worker', to: 'inline', error: e });
126
+ }
127
+ catch { /* 通知面不影響派生 */ }
128
+ }
129
+ }
130
+ }
131
+ inline ??= makeInlineArgon2id();
132
+ try {
133
+ return await inline(params);
134
+ }
135
+ catch (e) {
136
+ throw terminal(e, 'inline carrier failed');
137
+ }
138
+ };
139
+ const mod = { argon2id };
140
+ return st;
141
+ }
142
+ async function katOrThrow() {
143
+ let ok = false;
144
+ try {
145
+ ok = await verifyArgonKat();
146
+ }
147
+ catch (e) {
148
+ if (e instanceof VaultError)
149
+ throw e;
150
+ throw terminal(e, 'carrier KAT threw');
151
+ }
152
+ if (!ok)
153
+ throw terminal(null, 'carrier KAT mismatch (RFC 9106)');
154
+ }
155
+ /**
156
+ * 確保 Argon2id 載體可用並回報種類。冪等:同選項重呼沿用既裝載體(Worker 不重建);
157
+ * 選項(chain/createWorker/onFallback)改變=撤除重裝。首用載體必過 RFC 9106 KAT。
158
+ */
159
+ export async function ensureArgonCarrier(opts = {}) {
160
+ const cur = getArgonLoader();
161
+ if (cur && (!auto || cur !== auto.loader)) {
162
+ // 呼叫端覆寫優先:自裝殘留(若有)撤除但不碰全域注入。
163
+ if (auto) {
164
+ const a = auto;
165
+ auto = null;
166
+ a.dispose();
167
+ }
168
+ if (!verified.has(cur)) {
169
+ await katOrThrow();
170
+ verified.add(cur);
171
+ }
172
+ return 'injected';
173
+ }
174
+ const chain = opts.chain ?? DEFAULT_ARGON_CHAIN;
175
+ if (!Array.isArray(chain) || chain.length === 0 || !chain.every((c) => c === 'node' || c === 'worker' || c === 'inline')) {
176
+ throw new VaultError('ERR_VAULT_CONFIG', 'carrier.chain');
177
+ }
178
+ const chainKey = chain.join(',');
179
+ if (auto && cur === auto.loader && auto.chainKey === chainKey && auto.createWorker === opts.createWorker && auto.onFallback === opts.onFallback) {
180
+ return auto.kind;
181
+ }
182
+ resetArgonCarrier();
183
+ for (let i = 0; i < chain.length; i++) {
184
+ const choice = chain[i];
185
+ if (choice === 'node') {
186
+ if (!nodeArgonAvailable())
187
+ continue;
188
+ if (!nodeVerified) {
189
+ await katOrThrow();
190
+ nodeVerified = true;
191
+ }
192
+ return 'node';
193
+ }
194
+ if (choice === 'worker') {
195
+ if (!workerAvailable(opts))
196
+ continue;
197
+ const st = installWorker(chainKey, opts, chain.slice(i + 1).includes('inline') && wasmAvailable());
198
+ auto = st;
199
+ setArgonLoader(st.loader);
200
+ try {
201
+ await katOrThrow();
202
+ }
203
+ catch (e) {
204
+ resetArgonCarrier();
205
+ throw e;
206
+ }
207
+ return st.kind;
208
+ }
209
+ if (choice === 'inline') {
210
+ if (!wasmAvailable())
211
+ continue;
212
+ const st = installInline(chainKey, opts);
213
+ auto = st;
214
+ setArgonLoader(st.loader);
215
+ try {
216
+ await katOrThrow();
217
+ }
218
+ catch (e) {
219
+ resetArgonCarrier();
220
+ throw e;
221
+ }
222
+ return st.kind;
223
+ }
224
+ }
225
+ throw new VaultError('ERR_VAULT_KDF_UNSUPPORTED', 'no Argon2id carrier in chain [' + chainKey + ']');
226
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * argon-worker.ts — Argon2id Web Worker 載體:登入不卡畫面。
3
+ *
4
+ * Worker 本體=內嵌 blob 形(免 bundle 步):vendor 工廠 hashWasmArgon2Factory 的原文
5
+ *(Function#toString)+訊息膠水組成 Worker 源碼字串 → Blob → object URL → new Worker。
6
+ * 協定:main → { id, password, salt, iterations, parallelism, memorySize, hashLength };
7
+ * worker → { id, ok: true, out: Uint8Array } | { id, ok: false, error }。
8
+ * 串行:main 端單一佇列(hash-wasm Argon2 禁並行——argon2.ts deriveKek2Argon 註同理),
9
+ * worker 端亦以 promise 鏈串行(雙防線)。
10
+ * 失敗態:建構拋出/error 事件/ok:false 回應=本載體失效(dead),佇列內與後續請求一律 reject——
11
+ * 回退與否由 argon-auto.ts 回退鏈決定(本檔不自帶回退,行為顯形)。
12
+ */
13
+ import type { HashWasmArgon2id } from './argon2.ts';
14
+ /** Worker 最小介面(瀏覽器 Worker 直接相容;node worker_threads 等可包轉接層注入)。 */
15
+ export interface ArgonWorkerLike {
16
+ postMessage(message: unknown, transfer?: Transferable[]): void;
17
+ terminate(): void;
18
+ onmessage: ((ev: {
19
+ data: unknown;
20
+ }) => void) | null;
21
+ onerror: ((ev: unknown) => void) | null;
22
+ }
23
+ /** Worker 源碼字串(self.onmessage 形;瀏覽器 DedicatedWorkerGlobalScope 語意)。 */
24
+ export declare function argonWorkerSource(): string;
25
+ /** 瀏覽器預設 Worker 工廠:blob URL(CSP 需 worker-src blob:;不允許時建構拋出或 error 事件→回退鏈接手)。 */
26
+ export declare function createBlobArgonWorker(): ArgonWorkerLike;
27
+ /** Worker 載體:回 hash-wasm 同形 argon2id(argon2.ts ArgonLoader 契約)+terminate。 */
28
+ export declare function makeWorkerArgon2id(createWorker: () => ArgonWorkerLike): {
29
+ argon2id: HashWasmArgon2id;
30
+ terminate(): void;
31
+ };
@@ -0,0 +1,147 @@
1
+ /**
2
+ * argon-worker.ts — Argon2id Web Worker 載體:登入不卡畫面。
3
+ *
4
+ * Worker 本體=內嵌 blob 形(免 bundle 步):vendor 工廠 hashWasmArgon2Factory 的原文
5
+ *(Function#toString)+訊息膠水組成 Worker 源碼字串 → Blob → object URL → new Worker。
6
+ * 協定:main → { id, password, salt, iterations, parallelism, memorySize, hashLength };
7
+ * worker → { id, ok: true, out: Uint8Array } | { id, ok: false, error }。
8
+ * 串行:main 端單一佇列(hash-wasm Argon2 禁並行——argon2.ts deriveKek2Argon 註同理),
9
+ * worker 端亦以 promise 鏈串行(雙防線)。
10
+ * 失敗態:建構拋出/error 事件/ok:false 回應=本載體失效(dead),佇列內與後續請求一律 reject——
11
+ * 回退與否由 argon-auto.ts 回退鏈決定(本檔不自帶回退,行為顯形)。
12
+ */
13
+ import { hashWasmArgon2Factory } from './vendor/hash-wasm-argon2.js';
14
+ /** Worker 源碼字串(self.onmessage 形;瀏覽器 DedicatedWorkerGlobalScope 語意)。 */
15
+ export function argonWorkerSource() {
16
+ return [
17
+ "'use strict';",
18
+ 'const factory = (' + hashWasmArgon2Factory.toString() + ');',
19
+ 'let mod = null;',
20
+ 'let q = Promise.resolve();',
21
+ 'self.onmessage = (ev) => {',
22
+ ' const m = ev.data;',
23
+ ' q = q.then(async () => {',
24
+ ' try {',
25
+ ' if (!mod) mod = factory();',
26
+ " const r = await mod.argon2id({ password: m.password, salt: m.salt, iterations: m.iterations, parallelism: m.parallelism, memorySize: m.memorySize, hashLength: m.hashLength, outputType: 'binary' });",
27
+ ' const out = new Uint8Array(r);',
28
+ ' self.postMessage({ id: m.id, ok: true, out }, [out.buffer]);',
29
+ ' } catch (e) {',
30
+ ' self.postMessage({ id: m.id, ok: false, error: String((e && e.message) || e) });',
31
+ ' }',
32
+ ' });',
33
+ '};',
34
+ '',
35
+ ].join('\n');
36
+ }
37
+ /** 瀏覽器預設 Worker 工廠:blob URL(CSP 需 worker-src blob:;不允許時建構拋出或 error 事件→回退鏈接手)。 */
38
+ export function createBlobArgonWorker() {
39
+ const url = URL.createObjectURL(new Blob([argonWorkerSource()], { type: 'text/javascript' }));
40
+ let w;
41
+ try {
42
+ w = new Worker(url);
43
+ }
44
+ catch (e) {
45
+ URL.revokeObjectURL(url);
46
+ throw e;
47
+ }
48
+ const like = {
49
+ postMessage: (m, t) => w.postMessage(m, t ?? []),
50
+ terminate: () => { w.terminate(); URL.revokeObjectURL(url); },
51
+ onmessage: null,
52
+ onerror: null,
53
+ };
54
+ w.onmessage = (ev) => like.onmessage?.({ data: ev.data });
55
+ w.onerror = (ev) => like.onerror?.(ev);
56
+ w.onmessageerror = (ev) => like.onerror?.(ev);
57
+ return like;
58
+ }
59
+ /** Worker 載體:回 hash-wasm 同形 argon2id(argon2.ts ArgonLoader 契約)+terminate。 */
60
+ export function makeWorkerArgon2id(createWorker) {
61
+ let worker = null;
62
+ let dead = null;
63
+ let seq = 0;
64
+ const pending = new Map();
65
+ let queue = Promise.resolve();
66
+ const die = (e) => {
67
+ if (!dead)
68
+ dead = e ?? new Error('ERR_ARGON_WORKER_DEAD');
69
+ for (const p of pending.values())
70
+ p.reject(dead);
71
+ pending.clear();
72
+ if (worker) {
73
+ try {
74
+ worker.terminate();
75
+ }
76
+ catch { /* 已終止 */ }
77
+ }
78
+ worker = null;
79
+ };
80
+ const boot = () => {
81
+ if (worker)
82
+ return worker;
83
+ const w = createWorker();
84
+ w.onmessage = (ev) => {
85
+ const d = ev.data;
86
+ const p = d && typeof d.id === 'number' ? pending.get(d.id) : undefined;
87
+ if (!p || !d)
88
+ return;
89
+ pending.delete(d.id);
90
+ if (d.ok && d.out instanceof Uint8Array)
91
+ p.resolve(d.out);
92
+ else {
93
+ const err = new Error('ERR_ARGON_WORKER: ' + (d.error ?? 'bad response'));
94
+ p.reject(err);
95
+ die(err); // ok:false=worker 內 wasm 失效(CSP wasm-eval/記憶體)——整載體 dead,交回退鏈
96
+ }
97
+ };
98
+ w.onerror = (ev) => die(new Error('ERR_ARGON_WORKER_ERROR', { cause: ev }));
99
+ worker = w;
100
+ return w;
101
+ };
102
+ const run = (params) => new Promise((resolve, reject) => {
103
+ if (dead) {
104
+ reject(dead);
105
+ return;
106
+ }
107
+ let w;
108
+ try {
109
+ w = boot();
110
+ }
111
+ catch (e) {
112
+ die(e);
113
+ reject(dead);
114
+ return;
115
+ }
116
+ const id = ++seq;
117
+ pending.set(id, { resolve, reject });
118
+ try {
119
+ w.postMessage({
120
+ id,
121
+ password: params.password,
122
+ salt: params.salt,
123
+ iterations: params.iterations,
124
+ parallelism: params.parallelism,
125
+ memorySize: params.memorySize,
126
+ hashLength: params.hashLength,
127
+ });
128
+ }
129
+ catch (e) {
130
+ pending.delete(id);
131
+ die(e);
132
+ reject(dead);
133
+ }
134
+ });
135
+ const argon2id = (params) => {
136
+ const job = queue.then(() => run(params));
137
+ queue = job.catch(() => undefined);
138
+ return job.then((out) => {
139
+ if (params.outputType === 'binary')
140
+ return out;
141
+ if (params.outputType === 'hex')
142
+ return Array.from(out).map((b) => b.toString(16).padStart(2, '0')).join('');
143
+ throw new Error('ERR_ARGON_WORKER_OUTPUT_TYPE');
144
+ });
145
+ };
146
+ return { argon2id, terminate: () => die(new Error('ERR_ARGON_WORKER_TERMINATED')) };
147
+ }