@tacet-ink/journal-core 0.1.6 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -13,6 +13,42 @@
13
13
  這是 [默·Tacet(tacet.ink)](https://tacet.ink) 的客戶端/伺服端核心原語層,
14
14
  從多個姊妹產品共用的密碼學本體抽取而成,以品牌前綴參數化(前綴契約見下表)。
15
15
 
16
+ ## Quickstart
17
+
18
+ ```sh
19
+ git clone https://github.com/tacet-ink/journal-core.git && cd journal-core
20
+ npm ci
21
+ npm run verify # 429 assertions, all green, run against the real modules (no mocks)
22
+ ```
23
+
24
+ ```ts
25
+ // example.ts
26
+ import { makeHeldKey, generateNoteKey, encryptNote, decryptNote } from './src/index.ts';
27
+ import { makeKeyStore } from './src/client/keys.ts';
28
+
29
+ const cfg = {
30
+ guestKdfPrefix: 'myapp-note-u1',
31
+ recSaltPrefix: 'myapp-note-rec1:',
32
+ cipherGuest: 'jr1g.', // your own brand prefix family (guest era, opt-in)
33
+ cipherBound: 'jr1b.',
34
+ wrap: 'jr1w.',
35
+ store: makeKeyStore({ brand: 'myapp' }),
36
+ };
37
+
38
+ const held = makeHeldKey();
39
+ held.set(await generateNoteKey()); // bound era: random 256-bit noteKey
40
+ const identity = { current: () => 'acct-xxxxxxxxxxxxxxxx' };
41
+
42
+ const cipher = await encryptNote(cfg, held, '今天寫了一點東西。', 'noteId:n1', identity);
43
+ console.log(cipher.slice(0, 5)); // 'jr1b.' — ciphertext; nobody reads it without the key
44
+ console.log(await decryptNote(cfg, held, cipher, 'noteId:n1', identity)); // '今天寫了一點東西。' — roundtrip
45
+ ```
46
+
47
+ run: `node --experimental-strip-types example.ts`
48
+
49
+ 完整 API 見[使用(Usage)](#使用usage)節。Live product: [https://tacet.ink](https://tacet.ink)
50
+ (驗證頁:[https://tacet.ink/verify](https://tacet.ink/verify))。
51
+
16
52
  ## 設計(Design)
17
53
 
18
54
  - **兩時代金鑰模型**:未綁定(guest)時代以 `K_u = SHA-256(guestKdfPrefix ‖ identity)`
@@ -23,24 +59,27 @@
23
59
  前綴全部可配置,AAD(防搬移綁結)由呼叫端傳入。
24
60
  - **extractable 鐵律**:要被 exportKey/wrap 的 key(noteKey 全部產生路徑),
25
61
  import 當下就必須 `extractable=true`;KEK/guest key 恆 nonextractable。
26
- - **opt-in 原語**:選配契約(cipherGuest/wrapDual/wrapShare/pinLock/cipherAttach/cipherLocal)
27
- 未配置即拒絕,各 fork 未選用的原語行為不受影響(cipherGuest 未配置時 bound 路徑不受牽連,
28
- 解密面 guest 家族整面拒絕、不明字串與畸形空字串配置不當明文顯示)。
62
+ - **opt-in 原語**:選配契約(cipherGuest/wrapDual/wrapShare/pinLock/cipherAttach/cipherLocal/
63
+ wrap4/wrapDual4/wrapLocal/wrapRec+recKekHkdf(兩欄一體——同缺同在,部分配置拒寫)/recKekSalt)未配置=回落語意(wrapRec 系照走舊契約面;其他面拒絕或退場),各 fork 未選用的原語行為不受影響(cipherGuest 未配置時 bound 路徑不受牽連,
64
+ 解密面 guest 家族整面拒絕、不明字串與畸形空字串配置不當明文顯示)。wrapLocal 為選配:
65
+ 未配置=寫面功能退場——v1 可用者(借用期部署)升級後需配置 wrapLocal 才保留本機包裹寫入
66
+ (讀取面照走舊形回落,零資料損失面)。
29
67
 
30
68
  ## 模組(Modules)
31
69
 
32
70
  | 模組 | 內容 |
33
71
  | --- | --- |
34
72
  | `src/client/note-crypto.ts` | 兩時代加解密、passphrase/復原套件/本機三路包裹、PIN 第二因子合鑰(jr2w.) |
35
- | `src/client/argon2.ts` | Argon2id 包裹原語(jr3w./jr3d./jr3s.)、PH1 v2 派生、RFC 9106 KAT、雙載體(node:crypto+hash-wasm) |
73
+ | `src/client/argon2.ts` | Argon2id 包裹原語(jr3w./jr3d./jr3s.+密語正規化 v3 世代 jr4w./jr4d.)、PH1 v2/v3 派生、RFC 9106 KAT、雙載體(node:crypto+hash-wasm) |
36
74
  | `src/client/pinlock.ts` | 本機 PIN 鎖定包裹(jr1p.,開啟時鎖定) |
37
75
  | `src/client/bip39.ts` | 復原套件 24 詞 ⇄ hex64 轉寫層(BIP39,零依賴自製) |
38
76
  | `src/client/keys.ts` | 品牌前綴 localStorage 命名空間 |
39
77
  | `src/server/auth.ts` | 零知識 auth 核心:PH1→PH2 login 動線、入庫格式驗證、包裹欄組成對(pair 檢查 pickKeyPackage);PH2 UNIQUE 衝突與 session 撤銷=呼叫端職責 |
78
+ | `src/server/ladder.ts` | 密語正規化 v3 世代 ladder 表原語(ph2_ladder:以舊 ph2 查列/遷移入表 upsert 值主權威)——幽靈守衛的資料承載位(查表接線在 fork route) |
40
79
  | `src/server/ratelimit.ts` | per-IP fixed-window 限流(單句 UPSERT…RETURNING;D1 計數,跨 isolate 有效) |
41
80
  | `src/server/cors.ts`/`hash.ts` | 共用 CORS/雜湊工具(`src/server/env.ts` 為內部 Env 介面,不入 exports) |
42
81
 
43
- ## 前綴契約(家族表:10 個資料前綴+閘對照組 jr1g.)
82
+ ## 前綴契約(家族表:13 個資料前綴+閘對照組 jr1g.)
44
83
 
45
84
  前綴是版本契約:payload 佈局與 KDF 由前綴界定,升級 = 新前綴。
46
85
  Tacet 部署實例(config 傳入):
@@ -51,22 +90,42 @@ Tacet 部署實例(config 傳入):
51
90
  | `jr1b.` | 綁定時代密文 | 隨機 256-bit noteKey | AES-GCM,AAD 綁 noteId |
52
91
  | `jr1c.` | 附件密文(image attachments;選配) | 同筆記金鑰(noteKey/guest key 由呼叫端決定) | AES-GCM,AAD `jr1a:<noteId>:<attachId>` |
53
92
  | `jr1d.` | 本機 IDB stored 密文(notes store;選配) | 同筆記金鑰(呼叫端注入) | AES-GCM,AAD 綁 note_id,payload 自帶 `v` 欄 |
54
- | `jr1w.` | passphrase 包裹+復原套件包裹 | PBKDF2-SHA256 600k | b64(iv[12] ‖ GCM(hex(noteKey))),AAD `notekey` |
93
+ | `jr1l.` | 本機包裹(PWA session 期免重打密語;選配) | deriveGuestKey=K_u 同 guest 面(identity 派生、passphrase-free) | 同 jr1w. 形,AAD `notekey-local` |
94
+ | `jr1r.` | 復原套件包裹(wrappedRec 專用;v0.2.0 批卡⑤,選配,與 recKekHkdf 兩欄一體) | HKDF-SHA256(ikm=recToken, salt=recKekSalt?, info=`journal-kek-rec-v1:`+recKekHkdf)——兩欄齊備才寫 jr1r. 面 | 同 jr1w. 形,AAD `notekey-rec`(部分配置拒寫;舊契約面 jr1w.+PBKDF2+AAD `notekey` 永不變——新世代讀舊寫新雙試) |
95
+ | `jr1w.` | passphrase 包裹+復原套件包裹(未配置世代) | PBKDF2-SHA256 600k(復原套件 KEK=PBKDF2(recToken, recSaltPrefix‖identity)) | b64(iv[12] ‖ GCM(hex(noteKey))),AAD `notekey`(復原套件與 passphrase 同 AAD 慣例=未配置世代借形) |
55
96
  | `jr2w.` | PIN 第二因子合鑰(PBKDF2 版) | PBKDF2 600k(pass)+2M(pin) → HKDF-SHA256 | pinSalt[16] ‖ iv[12] ‖ GCM,108B,AAD `notekey2` |
56
97
  | `jr3w.` | passphrase 包裹(Argon2id 版) | Argon2id m=64MiB t=3 p=1 tag=32B | 同 jr1w. 形,AAD `notekey` |
57
98
  | `jr3d.` | PIN 第二因子合鑰(Argon2id 版) | Argon2id(pass)+Argon2id(pin) → HKDF-SHA256 | 同 jr2w. 形,108B,AAD `notekey2` |
99
+ | `jr4w.` | passphrase 包裹(密語正規化 v3 世代) | Argon2id(normalizePassphrase(pass),NFKC-only) 同上參數 | 同 jr1w./jr3w. 形,AAD `notekey` |
100
+ | `jr4d.` | PIN 第二因子合鑰(密語正規化 v3 世代) | Argon2id(normalizePassphrase(pass))+Argon2id(pin) → HKDF-SHA256 | 同 jr2w./jr3d. 形,108B,AAD `notekey2` |
58
101
  | `jr3s.` | 單篇分享連結包裹 | Argon2id(同上參數) | 同 jr1w. 形,AAD `notekey-share` |
59
102
  | `jr1p.` | 本機 PIN 鎖定(開啟時鎖定) | PBKDF2-SHA256 600k(刻意不用 Argon2id:解鎖要即時) | 同 jr2w. 形,AAD `notekey-pinlock` |
60
103
 
61
104
  guest 密文前綴在閘對照組另驗 `jr1g.`(閘自造前綴,驗證品牌參數化本身;tacet 部署實例 guest 用 `jr1u.`)。
62
105
  跨前綴呼叫一律回 null(前綴守衛+AAD+長度把關),不拋、不降級。
63
106
 
107
+ **世代命名兩軸**(jr4w./jr4d. 起):前綴數字軸=KDF 世代代(jr1w→jr2w→jr3w→jr4w,
108
+ KEK 輸入契約改變即換世代);「v3 家族」文案=PH1 規格代(PH1 v3 用 `derivePh1ArgonV3`)。
109
+ 密語正規化 v3 世代=KEK 吃 `normalizePassphrase`(NFKC-only:不 trim、不分大小寫——
110
+ 大小寫摺疊禁絕=大小寫差恆不同 KEK/ph2)——
111
+ 舊前綴家族(jr1w./jr3w./jr2w./jr3d.)契約面永不變(raw 密語派生,帶內版本化禁原地改語意);
112
+ 跨前綴呼叫恆 null(家族隔離)。同密語寫法差(全形/NFD/NFC)在 v3 世代收容為同一 KEK/PH2,
113
+ 首尾空白與大小寫仍刻意分流(v3 契約只收容寫法差)。
114
+ jr4d. 的 KEK2 HKDF info 域=`'journal-kek2-v1:' + wrapDual4`(自有域——NFKC-effective 密語下
115
+ jr3d/jr4d 兩入參數同輸入,域分離由 info 承載;凍結 KAT 兩 blob 互解 null 為證)。
116
+
64
117
  ## 驗證(Verification)
65
118
 
66
119
  ```sh
67
- npm run verify # 249 斷言對真模組(禁鏡像;限流單句 UPSERT…RETURNING 直載真 SQLite):roundtrip/AAD 防搬移/
120
+ npm run verify # 429 斷言對真模組(禁鏡像;限流單句 UPSERT…RETURNING 直載真 SQLite):roundtrip/AAD 防搬移/
68
121
  # extractable/時代隔離/跨前綴家族隔離/payload 竄改/RFC 9106 KAT/BIP39 @scure 對照 200 組/
69
122
  # server-side(inboundCipher/validWrappedKey/pickKeyPackage/checkRate/timingSafeEq)+ pinlock 全函式
123
+ # + 密語正規化 v3 世代(normalizePassphrase/jr4w./jr4d./PH1 v3 鹽域分離+帶內版本化舊契約向量)
124
+ # + 本機包裹專用前綴(wrapLocal=jr1l. opt-in+讀舊寫新自癒)
125
+ # +復原套件專用前綴與 HKDF 世代 [20](wrapRec=jr1r.+recKekHkdf opt-in+讀舊寫新雙試+KAT)
126
+ # +ladder 表與重取鹽面 [19](ph2_ladder 原語/upsert 值主權威行為面/unwrapNoteKeyDual4WithSalt)
127
+ # +常駐毒化矩陣 [16][18](/tmp 拷貝樹突變重跑=毒化證據隨每執行重建)
128
+ # +KAT 凍結向量 [17](HKDF info 域世代分離+v3/raw 入口契約四 blob)
70
129
  ```
71
130
 
72
131
  - 產品碼**零執行時依賴**(WebCrypto 原語);devDependencies 僅閘用(typescript、@scure/bip39 對照、workers types)。
@@ -96,6 +155,11 @@ const cfg = {
96
155
  cipherGuest: 'jr1g.', // 換成你自己的品牌前綴家族
97
156
  cipherBound: 'jr1b.',
98
157
  wrap: 'jr1w.',
158
+ wrapLocal: 'jr1l.', // 選配:本機包裹專用前綴(未配置 = 讀舊形回落、寫面退場)
159
+ // 復原套件 v0.2.0 世代(選配):wrapRec+jr1r. 專用前綴+recKekHkdf HKDF 派生
160
+ // (info='journal-kek-rec-v1:'+recKekHkdf;recKekSalt 16B hex 鹽域)。兩欄一體:
161
+ // 要開就兩欄一起配(部分配置=ERR_REC_CFG_PARTIAL 拒寫)。兩欄皆缺席 =
162
+ // 行為不變態(jr1w.+PBKDF2+AAD 'notekey' 舊契約面照走,舊 blob 永遠可解)。
99
163
  store: makeKeyStore({ brand: 'myapp' }),
100
164
  // cipherGuest / wrapDual / wrapShare / pinLock / cipherAttach / cipherLocal:選配,未配置即拒絕
101
165
  };
@@ -106,16 +170,26 @@ const cipher = await encryptNote(cfg, held, '今天寫了一點東西。', 'note
106
170
  ```
107
171
 
108
172
  PH1 派生(登入憑證):`derivePh1Argon(pass, saltArg?)` 預設鹽 `PH1_V2_SALT`
109
- (`'tacet-ph1-v1'`,Tacet 實例)。其他產品可自選**固定域鹽**傳入 `saltArg`——
173
+ (`'tacet-ph1-v1'`,Tacet 實例,raw pass)。其他產品可自選**固定域鹽**傳入 `saltArg`——
110
174
  鹽一經選定即 per-product 恆固定(PH2 UNIQUE 約束:同一密語必須恆生同一 PH2;
111
175
  per-user 鹽會摧毀幽靈帳號機制)。改鹽=帶內版本化換鹽尾碼重遷移,禁原地改語意。
112
176
 
177
+ PH1 v3(密語正規化世代):`derivePh1ArgonV3(pass, saltArg?)` 預設鹽 `PH1_V3_SALT`
178
+ (`'tacet-ph1-v2'`,新鹽域=世代 ph2 命名空間分離——同鹽域會讓 v3 'PASS' 與 v2 世代
179
+ raw 'PASS' 撞同一 ph2)。派生輸入吃 `normalizePassphrase`(NFKC-only;大小寫摺疊禁絕=
180
+ 大小寫差恆不同 ph2);v2/legacy 派生面零變更(舊帳戶憑證 raw 契約)。兩代 ph2 可並存查表=
181
+ tacet 遷移層職責(v0.2.0 批卡②)。
182
+ ⚠️ 鹽撞位警告(MINOR-5):`PH1_V3_SALT` 禁當 `derivePh1Argon` 的 `saltArg` 餵入(反之亦然)——
183
+ 把 v3 鹽域值餵 v2 派生(或 fork 把同一 saltArg 帶到兩面)=NFKC-effective 密語與 v2 raw 密語
184
+ 同值撞 ph2,跨世代帳戶空間混合。v3 的 `saltArg` 必須異於本 product 的 v2 鹽域值。
185
+
113
186
  ### 例外契約(錯誤碼語意)
114
187
 
115
188
  - 空 identity(guest 派生):加密面拋 `ERR_NO_IDENTITY`、解密面回 `null`
116
189
  (K_u = SHA-256(prefix ‖ '') 會靜默產出「空帳號金鑰」=誤配炸彈,兩面皆 fail-closed)。
117
- - 空 PIN(`wrapNoteKeyDual`/`wrapNoteKeyDual3`):拋 `ERR_PIN_EMPTY`——與
118
- 「功能未配置」(`ERR_DUAL_NOT_CONFIGURED`/`ERR_JR3W_NOT_CONFIGURED`)語意分離。
190
+ - 空 PIN(`wrapNoteKeyDual`/`wrapNoteKeyDual3`/`wrapNoteKeyDual4`):拋 `ERR_PIN_EMPTY`——與
191
+ 「功能未配置」(`ERR_DUAL_NOT_CONFIGURED`/`ERR_JR3W_NOT_CONFIGURED`/`ERR_JR4W_NOT_CONFIGURED`/
192
+ `ERR_JR4D_NOT_CONFIGURED`)語意分離。
119
193
  - `hexToBytes` fail-closed:非法 hex(奇數長度/非 hex 字元/空字串)拋 `ERR_BAD_HEX`,
120
194
  不再 parseInt 靜默歸零(假金鑰生產器)。unwrap 家族的 try/catch 承接=跨前綴鐵律
121
195
  (回 null 不拋)不變。
@@ -134,7 +208,9 @@ hash-wasm 並以 `setArgonLoader()` 注入(詳 `src/client/argon2.ts` 檔頭
134
208
 
135
209
  ## 授權
136
210
 
137
- MIT。安全問題聯絡 tacetink.csd@gmail.com。
211
+ 版本歷史見 [CHANGELOG.md](./CHANGELOG.md)。
212
+
213
+ MIT。安全問題聯絡 tacetink.csd@gmail.com(安全回報流程見 [SECURITY.md](./SECURITY.md))。
138
214
 
139
215
  ## English Summary
140
216
 
@@ -154,15 +230,23 @@ and salted hashes, and never learns your passphrase or the content of any note.
154
230
  (e.g. `jr1b.` for bound-era ciphertext, `jr3w.` for Argon2id-wrapped note keys). Upgrading KDF
155
231
  parameters always means a new prefix; old prefixes keep decrypting forever (no in-place
156
232
  semantic changes). Cross-prefix calls always return `null` — prefix guard + AAD + length
157
- checks; they never throw or fall back.
233
+ checks; they never throw or fall back. The passphrase-normalization generation follows the
234
+ same rule: `jr4w.`/`jr4d.` wrap with `normalizePassphrase` (NFKC-only — no trim, no
235
+ case-folding); older prefixes keep deriving from the raw passphrase, so every legacy payload
236
+ stays decryptable as-is.
158
237
  - **Tamper-evidence.** Every AES-GCM operation binds additional authenticated data (AAD) —
159
238
  e.g. ciphertext is bound to its note id, so records cannot be shuffled between notes.
160
239
  - **Key hygiene.** Any key that must be exported/wrapped is imported with `extractable=true`;
161
240
  KEK and guest keys are permanently non-extractable.
162
241
 
163
242
  **Opt-in primitives.** Optional contracts (`cipherGuest` / `wrapDual` / `wrapShare` / `pinLock` /
164
- `cipherAttach` / `cipherLocal`) are rejected unless explicitly configured, so forks that don't use
165
- a primitive are unaffected. Unknown or malformed strings never decrypt to plaintext.
243
+ `cipherAttach` / `cipherLocal` / `wrap4` / `wrapDual4` / `wrapLocal` / `wrapRec` (paired with
244
+ `recKekHkdf`: configured together or not at all; partial configuration is rejected on write) /
245
+ `recKekHkdf` / `recKekSalt`): the wrapRec family falls back to the legacy face when unconfigured,
246
+ so forks that don't use a primitive are unaffected. Unknown or malformed strings never
247
+ decrypt to plaintext. `wrapLocal` is opt-in: unconfigured means the write face retires —
248
+ v1-era deployments (borrow-period) must configure `wrapLocal` after upgrading to keep local
249
+ key-wrap writes (the read face still falls back to the legacy blob; no data is lost).
166
250
 
167
251
  **Modules.** Client: two-era crypto (`note-crypto.ts`), Argon2id wrapping (`argon2.ts`, dual
168
252
  carrier: `node:crypto` ≥ Node 24.7 / hash-wasm in browsers, RFC 9106 test vectors), local PIN lock
@@ -172,7 +256,7 @@ PH1→PH2 login flow, inbound cipher/package validation and paired key-package s
172
256
  (`auth.ts`; PH2-UNIQUE conflict and session revocation are caller-owned wiring), per-IP
173
257
  fixed-window rate limiting on D1 (`ratelimit.ts`), shared CORS/hash utilities.
174
258
 
175
- **Verification.** `npm run verify` runs 249 assertions against the real modules (no mocks):
259
+ **Verification.** `npm run verify` runs 429 assertions against the real modules (no mocks):
176
260
  roundtrips, AAD tamper-evidence, extractability rules, era isolation, cross-prefix family
177
261
  isolation, payload tampering, RFC 9106 KAT, and a 200-vector BIP39 cross-check.
178
262
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tacet-ink/journal-core",
3
- "version": "0.1.6",
3
+ "version": "0.2.1",
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": {
@@ -11,6 +11,20 @@
11
11
  "url": "https://github.com/tacet-ink/journal-core/issues"
12
12
  },
13
13
  "type": "module",
14
+ "keywords": [
15
+ "journal",
16
+ "diary",
17
+ "encryption",
18
+ "e2ee",
19
+ "end-to-end-encryption",
20
+ "argon2id",
21
+ "bip39",
22
+ "passphrase",
23
+ "zero-knowledge",
24
+ "webcrypto",
25
+ "privacy",
26
+ "tacet"
27
+ ],
14
28
  "main": "src/index.ts",
15
29
  "types": "src/index.ts",
16
30
  "sideEffects": false,
@@ -26,7 +40,8 @@
26
40
  "./server/ratelimit": "./src/server/ratelimit.ts",
27
41
  "./server/cors": "./src/server/cors.ts",
28
42
  "./server/hash": "./src/server/hash.ts",
29
- "./server/env": "./src/server/env.ts"
43
+ "./server/env": "./src/server/env.ts",
44
+ "./server/ladder": "./src/server/ladder.ts"
30
45
  },
31
46
  "files": [
32
47
  "src",
@@ -44,6 +59,6 @@
44
59
  "devDependencies": {
45
60
  "@cloudflare/workers-types": "^5.20260831.1",
46
61
  "@scure/bip39": "^2.4.0",
47
- "typescript": "~6.0.2"
62
+ "typescript": "~7.0.2"
48
63
  }
49
64
  }
@@ -0,0 +1,49 @@
1
+ #!/usr/bin/env bash
2
+ # open-card-pr.sh — journal-core 同 repo card branch PR 產生器。
3
+ #
4
+ # Usage: open-card-pr.sh <branch> <title> <body-file>
5
+ # branch card branch(head),例:card/<id>
6
+ # title PR 標題
7
+ # body-file PR body 純文字檔(完整讀入)
8
+ #
9
+ # 行為:純 curl POST /repos/tacet-ink/journal-core/pulls
10
+ # (head=<branch>、base=main、Token 取自 /srv/dropbox/csoft/tacet/.env 的
11
+ # GITHUB_TOKEN)。成功時 print PR 編號+URL;僅 print,不做其他事
12
+ # (不 push branch、不合併、不關閉)。
13
+ set -euo pipefail
14
+
15
+ REPO_URL="https://api.github.com/repos/tacet-ink/journal-core/pulls"
16
+ # 位置面:預設為本機絕對路徑(host-specific);其他環境以 ENV_FILE 覆寫
17
+ : "${ENV_FILE:=/srv/dropbox/csoft/tacet/.env}"
18
+
19
+ BRANCH="${1:?usage: open-card-pr.sh <branch> <title> <body-file>}"
20
+ TITLE="${2:?missing PR title}"
21
+ BODY_FILE="${3:?missing body file}"
22
+
23
+ [ -f "$BODY_FILE" ] || { echo "body file not found: $BODY_FILE" >&2; exit 1; }
24
+
25
+ TOKEN="$(grep '^GITHUB_TOKEN=' "$ENV_FILE" | head -1 | cut -d= -f2-)"
26
+ [ -n "$TOKEN" ] || { echo "GITHUB_TOKEN not found in $ENV_FILE" >&2; exit 1; }
27
+
28
+ PAYLOAD="$(jq -n --arg title "$TITLE" --arg head "$BRANCH" --arg base main \
29
+ --rawfile body "$BODY_FILE" \
30
+ '{title: $title, head: $head, base: $base, body: $body}')"
31
+
32
+ RESP="$(curl -sS -X POST \
33
+ -H "Authorization: token ${TOKEN}" \
34
+ -H "Accept: application/vnd.github+json" \
35
+ -H "X-GitHub-Api-Version: 2022-11-28" \
36
+ -d "$PAYLOAD" \
37
+ "$REPO_URL")"
38
+
39
+ NUM="$(printf '%s' "$RESP" | jq -r '.number // empty')"
40
+ if [ -n "$NUM" ]; then
41
+ URL="$(printf '%s' "$RESP" | jq -r '.html_url')"
42
+ echo "PR number: $NUM"
43
+ echo "PR url: $URL"
44
+ else
45
+ # 失敗(422 常見=branch 已有 PR/無 diff):print API 訊息不做事
46
+ printf '%s' "$RESP" | jq -r 'if .message then .message
47
+ else . end' >&2
48
+ exit 1
49
+ fi