@tacet-ink/journal-core 0.1.5 → 0.2.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.
package/README.md CHANGED
@@ -8,37 +8,40 @@
8
8
  零知識日記核心:端對端加密、密語即身份的 auth、傳輸與限流原語。
9
9
  伺服器看不到任何一個字:passphrase 永不過線,密鑰包裹與密文都在客戶端完成。
10
10
 
11
+ > **English**: Zero-knowledge journaling core — E2E-encrypted notes, passphrase-as-identity auth, transport & rate-limiting primitives. The server never sees a single word: the passphrase never crosses the wire, and all key wrapping and encryption happen client-side. See the [English summary](#english-summary) below.
12
+
11
13
  這是 [默·Tacet(tacet.ink)](https://tacet.ink) 的客戶端/伺服端核心原語層,
12
14
  從多個姊妹產品共用的密碼學本體抽取而成,以品牌前綴參數化(前綴契約見下表)。
13
15
 
14
- ## 設計
16
+ ## 設計(Design)
15
17
 
16
18
  - **兩時代金鑰模型**:未綁定(guest)時代以 `K_u = SHA-256(guestKdfPrefix ‖ identity)`
17
19
  純客戶端派生(混淆級);綁定後改用隨機 256-bit noteKey 加密,
18
20
  noteKey 再以 passphrase(KEK)與復原套件(KEK_rec)雙重包裹上傳。
19
21
  此後 passphrase 不再過線:線上只送 PH1(雜湊形),伺服器存 PH2 = SHA-256(PH1)。
20
22
  - **帶內版本化**:升級 KDF 參數 = 換新前綴(舊前綴照解、原地改語意是禁手)。
21
- 前綴全部可配置,AAD(防搬移繫結)由呼叫端傳入。
23
+ 前綴全部可配置,AAD(防搬移綁結)由呼叫端傳入。
22
24
  - **extractable 鐵律**:要被 exportKey/wrap 的 key(noteKey 全部產生路徑),
23
25
  import 當下就必須 `extractable=true`;KEK/guest key 恆 nonextractable。
24
- - **opt-in 原語**:選配契約(cipherGuest/wrapDual/wrapShare/pinLock/cipherAttach/cipherLocal)
25
- 未配置即拒絕,各 fork 未選用的原語行為不受影響(cipherGuest 未配置時 bound 路徑不受牽連,
26
+ - **opt-in 原語**:選配契約(cipherGuest/wrapDual/wrapShare/pinLock/cipherAttach/cipherLocal/
27
+ wrap4/wrapDual4/wrapLocal)未配置即拒絕,各 fork 未選用的原語行為不受影響(cipherGuest 未配置時 bound 路徑不受牽連,
26
28
  解密面 guest 家族整面拒絕、不明字串與畸形空字串配置不當明文顯示)。
27
29
 
28
- ## 模組
30
+ ## 模組(Modules)
29
31
 
30
32
  | 模組 | 內容 |
31
33
  | --- | --- |
32
34
  | `src/client/note-crypto.ts` | 兩時代加解密、passphrase/復原套件/本機三路包裹、PIN 第二因子合鑰(jr2w.) |
33
- | `src/client/argon2.ts` | Argon2id 包裹原語(jr3w./jr3d./jr3s.)、PH1 v2 派生、RFC 9106 KAT、雙載體(node:crypto+hash-wasm) |
35
+ | `src/client/argon2.ts` | Argon2id 包裹原語(jr3w./jr3d./jr3s.+密語正規化 v3 世代 jr4w./jr4d.)、PH1 v2/v3 派生、RFC 9106 KAT、雙載體(node:crypto+hash-wasm) |
34
36
  | `src/client/pinlock.ts` | 本機 PIN 鎖定包裹(jr1p.,開啟時鎖定) |
35
37
  | `src/client/bip39.ts` | 復原套件 24 詞 ⇄ hex64 轉寫層(BIP39,零依賴自製) |
36
38
  | `src/client/keys.ts` | 品牌前綴 localStorage 命名空間 |
37
- | `src/server/auth.ts` | 零知識 auth 核心:PH1/PH2 hash-ladder、PH2 UNIQUE、session 撤銷、包裹欄組成對契約 |
38
- | `src/server/ratelimit.ts` | per-IP 滑動視窗限流(D1 計數,併發安全版) |
39
+ | `src/server/auth.ts` | 零知識 auth 核心:PH1→PH2 login 動線、入庫格式驗證、包裹欄組成對(pair 檢查 pickKeyPackage);PH2 UNIQUE 衝突與 session 撤銷=呼叫端職責 |
40
+ | `src/server/ladder.ts` | 密語正規化 v3 世代 ladder 表原語(ph2_ladder:以舊 ph2 查列/遷移入表 upsert 值主權威)——幽靈守衛的資料承载位(查表接線在 fork route) |
41
+ | `src/server/ratelimit.ts` | per-IP fixed-window 限流(單句 UPSERT…RETURNING;D1 計數,跨 isolate 有效) |
39
42
  | `src/server/cors.ts`/`hash.ts` | 共用 CORS/雜湊工具(`src/server/env.ts` 為內部 Env 介面,不入 exports) |
40
43
 
41
- ## 前綴契約(家族表:10 個資料前綴+閘對照組 jr1g.)
44
+ ## 前綴契約(家族表:13 個資料前綴+閘對照組 jr1g.)
42
45
 
43
46
  前綴是版本契約:payload 佈局與 KDF 由前綴界定,升級 = 新前綴。
44
47
  Tacet 部署實例(config 傳入):
@@ -49,29 +52,48 @@ Tacet 部署實例(config 傳入):
49
52
  | `jr1b.` | 綁定時代密文 | 隨機 256-bit noteKey | AES-GCM,AAD 綁 noteId |
50
53
  | `jr1c.` | 附件密文(image attachments;選配) | 同筆記金鑰(noteKey/guest key 由呼叫端決定) | AES-GCM,AAD `jr1a:<noteId>:<attachId>` |
51
54
  | `jr1d.` | 本機 IDB stored 密文(notes store;選配) | 同筆記金鑰(呼叫端注入) | AES-GCM,AAD 綁 note_id,payload 自帶 `v` 欄 |
55
+ | `jr1l.` | 本機包裹(PWA session 期免重打密語;選配) | deriveGuestKey=K_u 同 guest 面(identity 派生、passphrase-free) | 同 jr1w. 形,AAD `notekey-local` |
52
56
  | `jr1w.` | passphrase 包裹+復原套件包裹 | PBKDF2-SHA256 600k | b64(iv[12] ‖ GCM(hex(noteKey))),AAD `notekey` |
53
57
  | `jr2w.` | PIN 第二因子合鑰(PBKDF2 版) | PBKDF2 600k(pass)+2M(pin) → HKDF-SHA256 | pinSalt[16] ‖ iv[12] ‖ GCM,108B,AAD `notekey2` |
54
58
  | `jr3w.` | passphrase 包裹(Argon2id 版) | Argon2id m=64MiB t=3 p=1 tag=32B | 同 jr1w. 形,AAD `notekey` |
55
59
  | `jr3d.` | PIN 第二因子合鑰(Argon2id 版) | Argon2id(pass)+Argon2id(pin) → HKDF-SHA256 | 同 jr2w. 形,108B,AAD `notekey2` |
60
+ | `jr4w.` | passphrase 包裹(密語正規化 v3 世代) | Argon2id(normalizePassphrase(pass),NFKC-only) 同上參數 | 同 jr1w./jr3w. 形,AAD `notekey` |
61
+ | `jr4d.` | PIN 第二因子合鑰(密語正規化 v3 世代) | Argon2id(normalizePassphrase(pass))+Argon2id(pin) → HKDF-SHA256 | 同 jr2w./jr3d. 形,108B,AAD `notekey2` |
56
62
  | `jr3s.` | 單篇分享連結包裹 | Argon2id(同上參數) | 同 jr1w. 形,AAD `notekey-share` |
57
63
  | `jr1p.` | 本機 PIN 鎖定(開啟時鎖定) | PBKDF2-SHA256 600k(刻意不用 Argon2id:解鎖要即時) | 同 jr2w. 形,AAD `notekey-pinlock` |
58
64
 
59
65
  guest 密文前綴在閘對照組另驗 `jr1g.`(閘自造前綴,驗證品牌參數化本身;tacet 部署實例 guest 用 `jr1u.`)。
60
66
  跨前綴呼叫一律回 null(前綴守衛+AAD+長度把關),不拋、不降級。
61
67
 
62
- ## 驗證
68
+ **世代命名兩軸**(jr4w./jr4d. 起):前綴數字軸=KDF 世代代(jr1w→jr2w→jr3w→jr4w,
69
+ KEK 輸入契約改變即換世代);「v3 家族」文案=PH1 規格代(PH1 v3 用 `derivePh1ArgonV3`)。
70
+ 密語正規化 v3 世代=KEK 吃 `normalizePassphrase`(NFKC-only:不 trim、不分大小寫——
71
+ 大小寫摺疊禁絕=大小寫差恆不同 KEK/ph2)——
72
+ 舊前綴家族(jr1w./jr3w./jr2w./jr3d.)契約面永不變(raw 密語派生,帶內版本化禁原地改語意);
73
+ 跨前綴呼叫恆 null(家族隔離)。同密語寫法差(全形/NFD/NFC)在 v3 世代收容為同一 KEK/PH2,
74
+ 首尾空白與大小寫仍刻意分流(v3 契約只收容寫法差)。
75
+ jr4d. 的 KEK2 HKDF info 域=`'journal-kek2-v1:' + wrapDual4`(自有域——NFKC-effective 密語下
76
+ jr3d/jr4d 兩入參數同輸入,域分離由 info 承載;凍結 KAT 兩 blob 互解 null 為證)。
77
+
78
+ ## 驗證(Verification)
63
79
 
64
80
  ```sh
65
- npm run verify # 127 斷言對真模組(禁鏡像):roundtrip/AAD 防搬移/extractable/時代隔離/
66
- # 跨前綴家族隔離/payload 竄改/RFC 9106 KAT/BIP39 @scure 對照 200 組
81
+ npm run verify # 384 斷言對真模組(禁鏡像;限流單句 UPSERT…RETURNING 直載真 SQLite):roundtrip/AAD 防搬移/
82
+ # extractable/時代隔離/跨前綴家族隔離/payload 竄改/RFC 9106 KAT/BIP39 @scure 對照 200 組/
83
+ # server-side(inboundCipher/validWrappedKey/pickKeyPackage/checkRate/timingSafeEq)+ pinlock 全函式
84
+ # + 密語正規化 v3 世代(normalizePassphrase/jr4w./jr4d./PH1 v3 鹽域分離+帶內版本化舊契約向量)
85
+ # + 本機包裹專用前綴(wrapLocal=jr1l. opt-in+讀舊寫新自癒)
86
+ # +ladder 表與重取鹽面 [19](ph2_ladder 原語/upsert 值主權威行為面/unwrapNoteKeyDual4WithSalt)
87
+ # +常駐毒化矩陣 [16][18](/tmp 拷貝樹突變重跑=毒化證據隨每執行重建)
88
+ # +KAT 凍結向量 [17](HKDF info 域世代分離+v3/raw 入口契約四 blob)
67
89
  ```
68
90
 
69
91
  - 產品碼**零執行時依賴**(WebCrypto 原語);devDependencies 僅閘用(typescript、@scure/bip39 對照、workers types)。
70
- - Argon2id 雙載體:node 走 `node:crypto`(Node 26+ 原生)、瀏覽器走 hash-wasm(wasm 內嵌),
92
+ - Argon2id 雙載體:node 走 `node:crypto`(Node 24.7+ 原生)、瀏覽器走 hash-wasm(wasm 內嵌),
71
93
  RFC 9106 標準向量逐位元一致;無載體即 throw(禁 fallback 鐵律)。
72
94
  - BIP39 原語自製零依賴,與 @scure/bip39 參照 200 組雙向對照(僅 entropy↔words 轉寫層,禁用其 seed 派生)。
73
95
 
74
- ## 使用
96
+ ## 使用(Usage)
75
97
 
76
98
  TypeScript 原始碼發行(exports 直指 .ts)。**注意**:Node 的 strip-types 不適用於
77
99
  node_modules 內的檔案,npm 安裝的消費者請走打包器;源碼 clone 可直接 node --experimental-strip-types。
@@ -85,6 +107,7 @@ import { makeKeyStore, makeHeldKey, generateNoteKey, encryptNote, decryptNote }
85
107
  import { generateNoteKey, encryptNote, decryptNote, makeHeldKey,
86
108
  wrapNoteKey, unwrapNoteKey } from '@tacet-ink/journal-core/client/note-crypto';
87
109
  import { makeKeyStore } from '@tacet-ink/journal-core/client/keys';
110
+ import { derivePh1Argon } from '@tacet-ink/journal-core/client/argon2';
88
111
 
89
112
  const cfg = {
90
113
  guestKdfPrefix: 'myapp-note-u1',
@@ -92,6 +115,7 @@ const cfg = {
92
115
  cipherGuest: 'jr1g.', // 換成你自己的品牌前綴家族
93
116
  cipherBound: 'jr1b.',
94
117
  wrap: 'jr1w.',
118
+ wrapLocal: 'jr1l.', // 選配:本機包裹專用前綴(未配置 = 讀舊形回落、寫面退場)
95
119
  store: makeKeyStore({ brand: 'myapp' }),
96
120
  // cipherGuest / wrapDual / wrapShare / pinLock / cipherAttach / cipherLocal:選配,未配置即拒絕
97
121
  };
@@ -101,6 +125,33 @@ const identity = { current: () => 'acct-xxxxxxxxxxxxxxxx' };
101
125
  const cipher = await encryptNote(cfg, held, '今天寫了一點東西。', 'noteId:n1', identity);
102
126
  ```
103
127
 
128
+ PH1 派生(登入憑證):`derivePh1Argon(pass, saltArg?)` 預設鹽 `PH1_V2_SALT`
129
+ (`'tacet-ph1-v1'`,Tacet 實例,raw pass)。其他產品可自選**固定域鹽**傳入 `saltArg`——
130
+ 鹽一經選定即 per-product 恆固定(PH2 UNIQUE 約束:同一密語必須恆生同一 PH2;
131
+ per-user 鹽會摧毀幽靈帳號機制)。改鹽=帶內版本化換鹽尾碼重遷移,禁原地改語意。
132
+
133
+ PH1 v3(密語正規化世代):`derivePh1ArgonV3(pass, saltArg?)` 預設鹽 `PH1_V3_SALT`
134
+ (`'tacet-ph1-v2'`,新鹽域=世代 ph2 命名空間分離——同鹽域會讓 v3 'PASS' 與 v2 世代
135
+ raw 'PASS' 撞同一 ph2)。派生輸入吃 `normalizePassphrase`(NFKC-only;大小寫摺疊禁絕=
136
+ 大小寫差恆不同 ph2);v2/legacy 派生面零變更(舊帳戶憑證 raw 契約)。兩代 ph2 可並存查表=
137
+ tacet 遷移層職責(v0.2.0 批卡②)。
138
+ ⚠️ 鹽撞位警告(MINOR-5):`PH1_V3_SALT` 禁當 `derivePh1Argon` 的 `saltArg` 餵入(反之亦然)——
139
+ 把 v3 鹽域值餵 v2 派生(或 fork 把同一 saltArg 帶到兩面)=NFKC-effective 密語與 v2 raw 密語
140
+ 同值撞 ph2,跨世代帳戶空間混合。v3 的 `saltArg` 必須異於本 product 的 v2 鹽域值。
141
+
142
+ ### 例外契約(錯誤碼語意)
143
+
144
+ - 空 identity(guest 派生):加密面拋 `ERR_NO_IDENTITY`、解密面回 `null`
145
+ (K_u = SHA-256(prefix ‖ '') 會靜默產出「空帳號金鑰」=誤配炸彈,兩面皆 fail-closed)。
146
+ - 空 PIN(`wrapNoteKeyDual`/`wrapNoteKeyDual3`/`wrapNoteKeyDual4`):拋 `ERR_PIN_EMPTY`——與
147
+ 「功能未配置」(`ERR_DUAL_NOT_CONFIGURED`/`ERR_JR3W_NOT_CONFIGURED`/`ERR_JR4W_NOT_CONFIGURED`/
148
+ `ERR_JR4D_NOT_CONFIGURED`)語意分離。
149
+ - `hexToBytes` fail-closed:非法 hex(奇數長度/非 hex 字元/空字串)拋 `ERR_BAD_HEX`,
150
+ 不再 parseInt 靜默歸零(假金鑰生產器)。unwrap 家族的 try/catch 承接=跨前綴鐵律
151
+ (回 null 不拋)不變。
152
+ - `PinLockConfig`:解包輸出的 noteKey 恆 `extractable=true`(鐵律,非可調選項)——
153
+ config 只帶三個前綴欄(pinLock/pinLockSaltPrefix/pinLockAad),缺任一即拒。
154
+
104
155
  打包器(vite/esbuild)可直接 alias 到源碼目錄使用;Argon2id 瀏覽器載體需另裝
105
156
  hash-wasm 並以 `setArgonLoader()` 注入(詳 `src/client/argon2.ts` 檔頭)。
106
157
 
@@ -114,3 +165,61 @@ hash-wasm 並以 `setArgonLoader()` 注入(詳 `src/client/argon2.ts` 檔頭
114
165
  ## 授權
115
166
 
116
167
  MIT。安全問題聯絡 tacetink.csd@gmail.com。
168
+
169
+ ## English Summary
170
+
171
+ **What this is.** `@tacet-ink/journal-core` is the cryptographic and server-primitive layer powering
172
+ [默·Tacet (tacet.ink)](https://tacet.ink), a zero-knowledge journal: the server stores only ciphertext
173
+ and salted hashes, and never learns your passphrase or the content of any note.
174
+
175
+ **Security model.**
176
+
177
+ - **Two key eras.** Before binding an account, notes are encrypted with a client-derived key
178
+ `K_u = SHA-256(guestKdfPrefix ‖ identity)` (obfuscation-grade, not true E2E). After binding,
179
+ notes are encrypted with a random 256-bit noteKey. The noteKey is wrapped twice — with the
180
+ passphrase (KEK) and with a recovery package (KEK_rec) — before upload. From that point the
181
+ passphrase never crosses the wire: only PH1 (a client-side hash form) is transmitted, and the
182
+ server stores only `PH2 = SHA-256(PH1)`.
183
+ - **In-band versioning.** Payload layout and KDF are defined by configurable cipher prefixes
184
+ (e.g. `jr1b.` for bound-era ciphertext, `jr3w.` for Argon2id-wrapped note keys). Upgrading KDF
185
+ parameters always means a new prefix; old prefixes keep decrypting forever (no in-place
186
+ semantic changes). Cross-prefix calls always return `null` — prefix guard + AAD + length
187
+ checks; they never throw or fall back. The passphrase-normalization generation follows the
188
+ same rule: `jr4w.`/`jr4d.` wrap with `normalizePassphrase` (NFKC-only — no trim, no
189
+ case-folding); older prefixes keep deriving from the raw passphrase, so every legacy payload
190
+ stays decryptable as-is.
191
+ - **Tamper-evidence.** Every AES-GCM operation binds additional authenticated data (AAD) —
192
+ e.g. ciphertext is bound to its note id, so records cannot be shuffled between notes.
193
+ - **Key hygiene.** Any key that must be exported/wrapped is imported with `extractable=true`;
194
+ KEK and guest keys are permanently non-extractable.
195
+
196
+ **Opt-in primitives.** Optional contracts (`cipherGuest` / `wrapDual` / `wrapShare` / `pinLock` /
197
+ `cipherAttach` / `cipherLocal` / `wrap4` / `wrapDual4` / `wrapLocal`) are rejected unless explicitly
198
+ configured, so forks that don't use a primitive are unaffected. Unknown or malformed strings never
199
+ decrypt to plaintext.
200
+
201
+ **Modules.** Client: two-era crypto (`note-crypto.ts`), Argon2id wrapping (`argon2.ts`, dual
202
+ carrier: `node:crypto` ≥ Node 24.7 / hash-wasm in browsers, RFC 9106 test vectors), local PIN lock
203
+ (`pinlock.ts`), recovery-package BIP39 codec (`bip39.ts`, zero-dependency, cross-checked against
204
+ @scure/bip39), brand-namespaced key storage (`keys.ts`). Server: zero-knowledge auth core with a
205
+ PH1→PH2 login flow, inbound cipher/package validation and paired key-package selection
206
+ (`auth.ts`; PH2-UNIQUE conflict and session revocation are caller-owned wiring), per-IP
207
+ fixed-window rate limiting on D1 (`ratelimit.ts`), shared CORS/hash utilities.
208
+
209
+ **Verification.** `npm run verify` runs 384 assertions against the real modules (no mocks):
210
+ roundtrips, AAD tamper-evidence, extractability rules, era isolation, cross-prefix family
211
+ isolation, payload tampering, RFC 9106 KAT, and a 200-vector BIP39 cross-check.
212
+
213
+ **Usage.** TypeScript source is published (exports point at `.ts`). If you install from npm you
214
+ must bundle it (vite/esbuild etc.); Node's strip-types does not apply inside `node_modules`.
215
+ See the code sample in the 使用 section above.
216
+
217
+ **Honest limits.** The guest era is obfuscation-grade, not E2E. PH1 derivation is defined by each
218
+ product (fast hash or Argon2id); this layer only validates its hex64 form. Product concerns
219
+ (routing, quotas, subscriptions, GC, webhooks) live in the product forks. No third-party audit
220
+ yet. A lost passphrase is unrecoverable by design — that is the price of server-side zero
221
+ knowledge.
222
+
223
+ ## License
224
+
225
+ MIT. Security contact: tacetink.csd@gmail.com.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tacet-ink/journal-core",
3
- "version": "0.1.5",
3
+ "version": "0.2.0",
4
4
  "description": "Zero-knowledge journal core — e2e crypto, passphrase-only auth, transport, ratelimit. The server never sees plaintext.",
5
5
  "homepage": "https://tacet.ink",
6
6
  "repository": {
@@ -13,6 +13,7 @@
13
13
  "type": "module",
14
14
  "main": "src/index.ts",
15
15
  "types": "src/index.ts",
16
+ "sideEffects": false,
16
17
  "exports": {
17
18
  ".": "./src/index.ts",
18
19
  "./client/note-crypto": "./src/client/note-crypto.ts",
@@ -25,7 +26,8 @@
25
26
  "./server/ratelimit": "./src/server/ratelimit.ts",
26
27
  "./server/cors": "./src/server/cors.ts",
27
28
  "./server/hash": "./src/server/hash.ts",
28
- "./server/env": "./src/server/env.ts"
29
+ "./server/env": "./src/server/env.ts",
30
+ "./server/ladder": "./src/server/ladder.ts"
29
31
  },
30
32
  "files": [
31
33
  "src",
@@ -34,10 +36,11 @@
34
36
  "LICENSE"
35
37
  ],
36
38
  "engines": {
37
- "node": ">=22"
39
+ "node": ">=24.7.0"
38
40
  },
39
41
  "scripts": {
40
- "verify": "node --experimental-strip-types scripts/verify-core-crypto.ts"
42
+ "verify": "node --experimental-strip-types scripts/verify-core-crypto.ts",
43
+ "typecheck": "tsc -p ."
41
44
  },
42
45
  "devDependencies": {
43
46
  "@cloudflare/workers-types": "^5.20260831.1",