@conarium-ai/core 0.2.12 → 0.2.14

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 (107) hide show
  1. package/CHANGELOG.md +170 -1
  2. package/LICENSE +21 -21
  3. package/LIMITATIONS.md +23 -2
  4. package/LIMITATIONS.tr.md +13 -2
  5. package/bin/conarium-coverage.mjs +89 -6
  6. package/bin/conarium-doctor.mjs +44 -0
  7. package/bin/conarium-verify.mjs +110 -51
  8. package/dist/anchor.d.ts +11 -0
  9. package/dist/anchor.d.ts.map +1 -1
  10. package/dist/anchor.js +27 -0
  11. package/dist/anchor.js.map +1 -1
  12. package/dist/audit.d.ts +4 -0
  13. package/dist/audit.d.ts.map +1 -1
  14. package/dist/audit.js +126 -30
  15. package/dist/audit.js.map +1 -1
  16. package/dist/config.d.ts +14 -0
  17. package/dist/config.d.ts.map +1 -1
  18. package/dist/config.js +35 -0
  19. package/dist/config.js.map +1 -1
  20. package/dist/connectors/openapi.d.ts +14 -1
  21. package/dist/connectors/openapi.d.ts.map +1 -1
  22. package/dist/connectors/openapi.js +78 -5
  23. package/dist/connectors/openapi.js.map +1 -1
  24. package/dist/connectors/postgres.js +8 -8
  25. package/dist/console-receipts.d.ts +12 -1
  26. package/dist/console-receipts.d.ts.map +1 -1
  27. package/dist/console-receipts.js +14 -2
  28. package/dist/console-receipts.js.map +1 -1
  29. package/dist/console-shortcut.d.ts.map +1 -1
  30. package/dist/console-shortcut.js +5 -1
  31. package/dist/console-shortcut.js.map +1 -1
  32. package/dist/console.d.ts.map +1 -1
  33. package/dist/console.js +15 -4
  34. package/dist/console.js.map +1 -1
  35. package/dist/coverage.d.ts +17 -1
  36. package/dist/coverage.d.ts.map +1 -1
  37. package/dist/coverage.js +30 -3
  38. package/dist/coverage.js.map +1 -1
  39. package/dist/digit_pii.d.ts.map +1 -1
  40. package/dist/digit_pii.js +64 -12
  41. package/dist/digit_pii.js.map +1 -1
  42. package/dist/governance.d.ts +2 -0
  43. package/dist/governance.d.ts.map +1 -1
  44. package/dist/governance.js +23 -8
  45. package/dist/governance.js.map +1 -1
  46. package/dist/http.d.ts +11 -1
  47. package/dist/http.d.ts.map +1 -1
  48. package/dist/http.js +87 -7
  49. package/dist/http.js.map +1 -1
  50. package/dist/iban.d.ts.map +1 -1
  51. package/dist/iban.js +6 -3
  52. package/dist/iban.js.map +1 -1
  53. package/dist/index.js +1 -0
  54. package/dist/index.js.map +1 -1
  55. package/dist/keys.d.ts +5 -0
  56. package/dist/keys.d.ts.map +1 -1
  57. package/dist/keys.js +22 -7
  58. package/dist/keys.js.map +1 -1
  59. package/dist/mask-text.d.ts +11 -0
  60. package/dist/mask-text.d.ts.map +1 -0
  61. package/dist/mask-text.js +42 -0
  62. package/dist/mask-text.js.map +1 -0
  63. package/dist/receipt-view.d.ts +13 -0
  64. package/dist/receipt-view.d.ts.map +1 -1
  65. package/dist/receipt-view.js +28 -5
  66. package/dist/receipt-view.js.map +1 -1
  67. package/dist/server.d.ts.map +1 -1
  68. package/dist/server.js +31 -15
  69. package/dist/server.js.map +1 -1
  70. package/dist/sql-gate/mssql.d.ts.map +1 -1
  71. package/dist/sql-gate/mssql.js +36 -2
  72. package/dist/sql-gate/mssql.js.map +1 -1
  73. package/dist/sql-gate/oracle.d.ts.map +1 -1
  74. package/dist/sql-gate/oracle.js +24 -3
  75. package/dist/sql-gate/oracle.js.map +1 -1
  76. package/dist/sql-gate/rules.d.ts +19 -1
  77. package/dist/sql-gate/rules.d.ts.map +1 -1
  78. package/dist/sql-gate/rules.js +116 -7
  79. package/dist/sql-gate/rules.js.map +1 -1
  80. package/dist/types.d.ts +6 -0
  81. package/dist/types.d.ts.map +1 -1
  82. package/docs/API-STABILITY.md +2 -2
  83. package/docs/ARCHITECTURE.md +42 -42
  84. package/docs/RECEIPT-SPEC.md +17 -11
  85. package/docs/plans/2026-07-02-redteam-harness.md +416 -416
  86. package/docs/specs/2026-07-02-redteam-harness-design.md +90 -90
  87. package/docs/superpowers/TODO-gate1-f4.md +23 -23
  88. package/docs/superpowers/plans/2026-07-29-conarium-receipt-plan.md +200 -200
  89. package/docs/superpowers/specs/2026-07-29-conarium-receipt-design.md +202 -202
  90. package/examples/claude-desktop-config.json +9 -9
  91. package/examples/cursor-mcp-settings.json +10 -10
  92. package/examples/proof-service/README.md +50 -0
  93. package/package.json +9 -2
  94. package/public/app.js +378 -378
  95. package/public/index.html +160 -160
  96. package/public/style.css +504 -504
  97. package/scripts/conarium_sabah_brief.mjs +107 -107
  98. package/scripts/start-mcp-c1.mjs +93 -93
  99. package/test-vectors/sql-gate/LAST-RUN.json +1 -2
  100. package/test-vectors/sql-gate/README.md +3 -1
  101. package/test-vectors/sql-gate/vectors.json +28 -0
  102. package/dist/openapi_connector.d.ts +0 -6
  103. package/dist/openapi_connector.d.ts.map +0 -1
  104. package/dist/openapi_connector.js +0 -145
  105. package/dist/openapi_connector.js.map +0 -1
  106. package/docs/audit/2026-08-14-security-scan.md +0 -48
  107. package/docs/audit/2026-08-14-surface-sync.md +0 -34
package/CHANGELOG.md CHANGED
@@ -1,6 +1,175 @@
1
1
  # Changelog
2
2
 
3
- ## Unreleased
3
+ ## 0.2.14 — 2026-08-15
4
+
5
+ Follow-up to the 0.2.13 hardening: the detector rule that 0.2.13 half-fixed,
6
+ plus the findings CodeQL raised on the new code.
7
+
8
+ - **Behavior change:** what a digit run proves now decides whether letters
9
+ around it can hide it, instead of how long the tail is. A Luhn card, a
10
+ checksum-valid TCKN and a TR mobile number are masked under any letter tail
11
+ (`4111…xyz`, `0532…xyz`). A run that is merely ten or eleven digits keeps the
12
+ bounded rule, because relaxing that one would mask the digits inside a token
13
+ and leave `ghp_[MASKED_PII]abcd` where the secret detector can no longer
14
+ recognise it. Vector values that fail the TCKN checksum on purpose are
15
+ unchanged.
16
+
17
+ - **Launcher paths are quoted for sh.** The macOS launcher wrapped both paths
18
+ in double quotes and escaped only `"`, so `$(…)`, backticks and `\` in a path
19
+ this code does not choose stayed live shell. Single quotes with the `'\''`
20
+ idiom make a path a path.
21
+
22
+ - **The audit sink lock is 0600.** It was written with the default mode, next
23
+ to data that is not world-readable. `wx` already refused a planted symlink.
24
+
25
+ - **CodeQL scope excludes tests** (`.github/codeql/codeql-config.yml`). A ReDoS
26
+ pattern the loader must reject and a hostile URL the verifier must refuse are
27
+ fixtures, not defects; reporting them buried the product findings. `src/` and
28
+ `api/` are unchanged in scope.
29
+
30
+ - **Docs:** `examples/proof-service/` said the `/proof` service existed only on
31
+ the box and invited someone to copy it here. Its sources are versioned in the
32
+ site repo; the page now records the one thing that matters to this package —
33
+ the service resolves the receipt view from `CONARIUM_ROOT` but keeps its own
34
+ copies of `governance.js` and `audit-hash.js`, so a masking or audit-hash
35
+ change does not reach `/proof` until those are recopied and it restarts.
36
+
37
+ - **Behavior change (A1):** A single trailing letter no longer hides a
38
+ card or TR phone (`4111…x`, `0532…x`). A longer alphanumeric tail
39
+ (`ghp_1234…abcd`) stays a token so the secret detector still fires.
40
+
41
+ - **A2:** Dev-only `vitest` 2.1.9 → 4.1.10 (closes the vite/esbuild
42
+ Dependabot chain). Production dependencies unchanged.
43
+
44
+ - **A3:** `LAST-RUN.json` no longer carries a `when` timestamp, so a
45
+ green generator run does not dirty the tree.
46
+
47
+ - **A4:** `examples/proof-service/README.md` is the repo seat for the
48
+ box-only `/proof` process. `.gitignore` now covers `*.bak-*`.
49
+
50
+ ## 0.2.13 — 2026-08-15
51
+
52
+ Security hardening release. Two independent external reviews and one code
53
+ audit produced the findings below; each was reproduced against running code
54
+ before it was fixed. Several defaults change — the entries marked
55
+ **Behavior change** are the ones to read before upgrading.
56
+
57
+ - **Dialect scalar functions.** The function allow-list carries Postgres
58
+ names, so routing the MSSQL and Oracle gates through it denied ordinary
59
+ calls (`GETDATE`, `ISNULL`, `DATEADD`, `NVL`, `TO_CHAR`). Safe scalars are
60
+ now listed per dialect and consulted only for an unqualified name, so
61
+ `app.pkg.nvl` stays a user package. One dialect's list never applies to
62
+ another's gate, and row-collapsing, `DBMS_*` and `UTL_*` families remain
63
+ denied.
64
+
65
+ - **npm Trusted Publishing (OIDC).** The publish workflow no longer expects a
66
+ long-lived `NPM_TOKEN`; npmjs.com recognises the repository and workflow as
67
+ the authorised publisher and provenance is attached to the release. No
68
+ publish token lives in the repository. See `docs/security/NPM-PROVENANCE.md`.
69
+
70
+ - **G20:** Write-token scan ignores SQL string literals
71
+ (`SELECT 'DELETE ' FROM t` is a read). OpenAPI fetch caps the body at
72
+ 50KB before `JSON.parse`. Audit sink hash stays `JSON.stringify`
73
+ (JCS would break existing files — LIMITATIONS).
74
+
75
+ - **G12:** `conarium-doctor` warns when HTTP is on and
76
+ `CONARIUM_MCP_RATE_PER_MIN` is 0; a positive limit is an info line.
77
+ The default remains 0 (production profile fills 60).
78
+
79
+ - **G11:** Unpinned `conarium-verify` still exits 0, but stderr says the
80
+ tail was not seen and `--json` carries `tailPinned`. `--strict` requires
81
+ a tail pin (exit 11) and pins seq from 1. The console verify command
82
+ embeds `--expect-count` and `--expect-last-hash` for the current chain.
83
+
84
+ - **Behavior change (G10):** OpenAPI fetch uses `redirect: manual` and
85
+ re-checks every hop (max 5). The approved DNS address is pinned via
86
+ an undici Agent lookup; TLS SNI stays the original hostname. undici
87
+ is not added to package.json.
88
+
89
+ - **Behavior change (G9):** Private key files that are not 0600 fail
90
+ boot. Escape hatch `CONARIUM_ALLOW_LOOSE_KEY_PERMS=1` restores the
91
+ old warning. win32 skips the check (POSIX mode is meaningless).
92
+
93
+ - **Behavior change (G6):** HTTP sessions idle out after
94
+ `CONARIUM_SESSION_IDLE_MS` (default 30 minutes; 0 = off). Owner-binding
95
+ is unchanged. Sweeper uses `unref()`.
96
+
97
+ - **Behavior change (G7):** `CONARIUM_MAX_SESSIONS` defaults to 100
98
+ (0 = unlimited). A new initialize at the cap is JSON-RPC rejected.
99
+
100
+ - **G8:** Token file reloads on mtime change. Broken JSON keeps the
101
+ previous store and logs; it does not fall back to an empty map.
102
+
103
+ - **G5:** Audit sink takes an advisory `<sink>.lock` (`wx`, PID + start).
104
+ A second OS process is rejected; a stale lock (dead PID) is stolen.
105
+ Same-process re-entry stays allowed (console / validateChain boot).
106
+ The lock does not stop a writer outside Conarium.
107
+
108
+ - **G4:** `profile: "production"` (or `CONARIUM_PROFILE=production`) refuses
109
+ boot without Ed25519 AND HMAC, turns G3 strict signatures and OpenTimestamps
110
+ anchoring on, and defaults HTTP rate-limit to 60/min unless explicitly 0.
111
+ `conarium-doctor` reports the profile as one block.
112
+
113
+ - **Behavior change (G21):** `conarium-coverage --receipts` re-verifies each
114
+ receipt Ed25519 signature; a broken sig is not COMPLETE and names the
115
+ receipt. The declaration carries `windowStartPinned` — an unpinned
116
+ prefix-truncated window is no longer a silent complete. Output says
117
+ "access NOT RECORDED", never "no access occurred". `--expect-seq-from`
118
+ pins the window start.
119
+
120
+ - **Behavior change (G17):** Receipt HTML never prints raw `anchor.state`
121
+ as a trust signal — forged `state: bitcoin` renders as `doğrulanmadı`
122
+ until the OTS sidecar verifies. `--anchor-check` skips `anchor:null`
123
+ (periodic anchoring) and fails only on a claimed-but-unverified
124
+ anchor; the run ends with `N/M anchored, head anchored: yes/no`.
125
+ `--require-head-anchor` exits 14 when the chain head is unanchored.
126
+
127
+ - **G3:** `CONARIUM_AUDIT_REQUIRE_SIG=1` is opt-in strict boot — any
128
+ unsigned line is rejected when a signing key is configured. Default
129
+ unchanged (legacy unsigned chains still open).
130
+
131
+ - **Behavior change (G18):** Flat query rows apply the same column-name
132
+ secret/PII heuristic as nested JSON (`api_key` / `password` →
133
+ `[MASKED_SECRET]`). One function, two call sites.
134
+
135
+ - **Behavior change (G19):** Console `/api/config` redacts `key`,
136
+ `anonKey`, `headers`, and `authorization`, and also redacts JWT /
137
+ `sk-` / `AKIA` shaped values under innocent names.
138
+
139
+ - **Behavior change (G16):** Audit `reason`, `target`, and `governance`
140
+ go through the same mask pipeline as `args`. A DB error that carries
141
+ a cell value can no longer land unmasked on the signed sink.
142
+
143
+ - **Audit chain atomicity (G1):** `lastHash` and `sinkSize` advance
144
+ only after a successful sink append — same order as `writeReceipt()`.
145
+ A failed write no longer orphans the in-memory chain.
146
+
147
+ - **Audit self-heal (G2):** After a failed append, the next successful
148
+ `log()` chains from the last hash that is actually on disk. A fresh
149
+ `Audit({sink})` boot `validateChain` stays clean. `failClosed=true`
150
+ also leaves state unmoved.
151
+
152
+ - **Behavior change (G15):** Content detectors treat `.` / `/` as group
153
+ separators and use token boundaries (a glued letter or `_` no longer
154
+ hides a card/phone/IBAN). Zero-padded `&#064;` emails are masked.
155
+ Hyphenated US SSN is masked; bare 9-digit SSN stays a documented
156
+ limitation.
157
+
158
+ - **Behavior change (G14):** MSSQL and Oracle gates use the same function
159
+ allow-list as Postgres (`isSafeBuiltinFunction` / `isBlockedDumpFunction`).
160
+ `STRING_AGG` / `LISTAGG` and user/package functions are denied. MSSQL
161
+ locking hints (`WITH (UPDLOCK)` and kin) are denied. Oracle row-cap
162
+ wrapper strips comments so a trailing `--` cannot swallow `FETCH FIRST`.
163
+
164
+ - **Behavior change (G13):** Connector/DB error text is masked before it
165
+ reaches the model. Failed `query` / `search` / `describe_table` paths
166
+ that previously skipped the audit trail now write a `denied` line.
167
+ Already-logged denies (policy, missing table, 50KB) are not written twice.
168
+
169
+ ## 0.2.8 – 0.2.12 — 2026-08-14
170
+
171
+ These shipped across 0.2.8, 0.2.9, 0.2.10, 0.2.11 and 0.2.12 and were kept in
172
+ one list at the time; the tags are the authority on which release carries which.
4
173
 
5
174
  - **Table existence oracle closed.** Assistant `describe_table` / `search` /
6
175
  `query` errors no longer distinguish denied from missing. The audit log
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Emek Can Doğru (Conarium)
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Emek Can Doğru (Conarium)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/LIMITATIONS.md CHANGED
@@ -19,6 +19,12 @@ Oracle does not resolve synonyms: an allow-listed name is the name the parser se
19
19
  There is no MSSQL or Oracle connector. An operator can attach their own executor (`connectors[].type: custom-sql`) that receives only gated SQL. That path requires an explicit `policy.dialect` — the omitted-dialect postgres default does not apply. The gate speaks three dialects; the connection is the operator's.
20
20
  Parsers: Postgres `pgsql-ast-parser` · MSSQL `node-sql-parser` (transactsql) · Oracle `@guanmingchiu/sqlparser-ts`.
21
21
 
22
+ ## Bare 9-digit US SSN is not a content detector
23
+
24
+ `XXX-XX-XXXX` (hyphenated) is masked. A bare 9-digit run is not: it
25
+ collides with order IDs and other identifiers. This is a measured
26
+ limitation, not an oversight.
27
+
22
28
  ## Names in free text are not guaranteed
23
29
 
24
30
  Structured columns: deterministic (`maskColumns`).
@@ -49,8 +55,23 @@ of this gateway.
49
55
  ## Two processes, one audit file
50
56
 
51
57
  `Audit.log()` is synchronous. One process can write many concurrent queries
52
- without breaking `prevHash`. Two OS processes appending the same sink have
53
- no lock. That install is unsupported until a lock is an explicit decision.
58
+ without breaking `prevHash`. A second OS process that opens the same sink
59
+ is rejected (`<sink>.lock`, advisory `wx`). The lock does not stop a writer
60
+ outside Conarium that ignores the lock file.
61
+
62
+ ## Strict signature mode is opt-in
63
+
64
+ `CONARIUM_AUDIT_REQUIRE_SIG=1` refuses boot if a signing key is set and
65
+ any audit line is unsigned. The default still accepts a fully unsigned
66
+ legacy chain when an HMAC key is later added (08-05 compatibility).
67
+
68
+ ## Audit sink hash is not JCS
69
+
70
+ Receipts hash with RFC 8785 JCS (`canonicalize`). The audit JSONL hasher
71
+ (`src/audit-hash.ts`) uses `JSON.stringify` of insertion order. The two
72
+ disagree when keys are unsorted (`{"b":1,"a":2}` vs `{"a":2,"b":1}`).
73
+ Switching the sink to JCS would invalidate every existing audit file.
74
+ Independent re-hash of an old sink must use `JSON.stringify`, not JCS.
54
75
 
55
76
  ## Cryptography is not independently audited
56
77
 
package/LIMITATIONS.tr.md CHANGED
@@ -19,6 +19,11 @@ Oracle synonym hedefini çözmez: allow-list’teki ad, parser’ın gördüğü
19
19
  MSSQL veya Oracle konnektörü yok. Operatör kendi çalıştırıcısını takabilir (`connectors[].type: custom-sql`); çalıştırıcıya yalnız kapıdan geçmiş SQL gider. Bu yolda `policy.dialect` zorunludur — yoksa postgres varsayılanı uygulanmaz. Kapı üç lehçeyi yönetir; bağlantıyı operatör getirir.
20
20
  Ayrıştırıcılar: Postgres `pgsql-ast-parser` · MSSQL `node-sql-parser` (transactsql) · Oracle `@guanmingchiu/sqlparser-ts`.
21
21
 
22
+ ## Çıplak 9 haneli ABD SSN içerik dedektörü değil
23
+
24
+ `XXX-XX-XXXX` (tireli) maskelenir. Çıplak 9 haneli koşu maskelenmez:
25
+ sipariş numarası ve benzeri kimliklerle çakışır. Ölçülmüş sınır, unutkanlık değil.
26
+
22
27
  ## Serbest metinde isim garantisi yok
23
28
 
24
29
  Yapılandırılmış kolonlar: deterministik (`maskColumns`).
@@ -48,8 +53,14 @@ atlayabilir. Operatörün kendi süreci bu kapının denetim konusu değildir.
48
53
  ## İki süreç, tek denetim dosyası
49
54
 
50
55
  `Audit.log()` senkrondur. Tek süreçte eşzamanlı sorgular `prevHash` kırmadan
51
- yazar. İki OS süreci aynı sink’e kilit olmadan ekler. Kilit ayrı karar;
52
- o kurulum desteklenmez.
56
+ yazar. Aynı sink’i açan ikinci OS süreci reddedilir (`<sink>.lock`,
57
+ advisory `wx`). Kilit, Conarium dışından dosyaya yazan süreci durdurmaz.
58
+
59
+ ## Sıkı imza kipi opt-in
60
+
61
+ `CONARIUM_AUDIT_REQUIRE_SIG=1` imza anahtarı varken imzasız tek satırda
62
+ boot'u reddeder. Varsayılan, HMAC sonradan eklenince tamamen imzasız
63
+ eski zinciri hâlâ açar (08-05 uyumu).
53
64
 
54
65
  ## Denetlenmemiş kriptografi
55
66
 
@@ -64,6 +64,20 @@ function coverageHash(d) {
64
64
  return `sha256:${digest}`
65
65
  }
66
66
 
67
+ function receiptHash(r) {
68
+ const copy = { ...r }
69
+ delete copy.hash
70
+ delete copy.sig
71
+ delete copy.anchor
72
+ if (copy.chain && typeof copy.chain === 'object') {
73
+ const chain = { ...copy.chain }
74
+ delete chain.hash
75
+ copy.chain = chain
76
+ }
77
+ const digest = createHash('sha256').update(canonicalize(copy)).digest('hex')
78
+ return `sha256:${digest}`
79
+ }
80
+
67
81
  // Exported for cross-check tests (dynamic import of this file).
68
82
  export { canonicalize, coverageHash }
69
83
 
@@ -72,12 +86,12 @@ export { canonicalize, coverageHash }
72
86
  function usage(msg) {
73
87
  if (msg) console.error(msg)
74
88
  console.error(
75
- 'Usage: conarium-coverage <declaration.json> --pubkey <path> [--receipts <receipts.jsonl>] [--allow-gaps] [--json]',
89
+ 'Usage: conarium-coverage <declaration.json> --pubkey <path> [--receipts <receipts.jsonl>] [--expect-seq-from N] [--allow-gaps] [--json]',
76
90
  )
77
91
  }
78
92
 
79
93
  function parseArgs(argv) {
80
- const out = { target: null, pubkeys: [], receiptsPath: null, json: false, allowGaps: false }
94
+ const out = { target: null, pubkeys: [], receiptsPath: null, json: false, allowGaps: false, expectSeqFrom: null }
81
95
  const args = [...argv]
82
96
  while (args.length) {
83
97
  const a = args.shift()
@@ -93,6 +107,10 @@ function parseArgs(argv) {
93
107
  out.json = true
94
108
  } else if (a === '--allow-gaps') {
95
109
  out.allowGaps = true
110
+ } else if (a === '--expect-seq-from') {
111
+ const n = args.shift()
112
+ if (n === undefined || !/^\d+$/.test(n)) throw new Error('--expect-seq-from requires an integer')
113
+ out.expectSeqFrom = Number(n)
96
114
  } else if (a === '--help' || a === '-h') {
97
115
  usage()
98
116
  process.exit(0)
@@ -206,6 +224,30 @@ function schemaOk(d) {
206
224
  return null
207
225
  }
208
226
 
227
+ function verifyReceiptSig(keys, receipt) {
228
+ const id = receipt.id || `seq:${receipt.chain?.seq}`
229
+ if (!receipt.sig || typeof receipt.sig !== 'object') {
230
+ return { id, error: 'missing sig' }
231
+ }
232
+ if (receipt.sig.alg !== 'Ed25519') return { id, error: `unsupported sig.alg ${receipt.sig.alg}` }
233
+ const pk = keys.get(receipt.sig.keyId)
234
+ if (!pk) return { id, error: `unknown keyId ${receipt.sig.keyId}` }
235
+ try {
236
+ if (receipt.chain?.hash && receiptHash(receipt) !== receipt.chain.hash) {
237
+ return { id, error: 'hash mismatch' }
238
+ }
239
+ const ok = cryptoVerify(
240
+ null,
241
+ Buffer.from(receipt.chain.hash, 'utf-8'),
242
+ pk,
243
+ Buffer.from(receipt.sig.value, 'base64'),
244
+ )
245
+ return ok ? null : { id, error: 'signature cryptographically invalid' }
246
+ } catch (err) {
247
+ return { id, error: `signature verify error: ${err.message}` }
248
+ }
249
+ }
250
+
209
251
  function verifySig(keys, d) {
210
252
  const pk = keys.get(d.sig.keyId)
211
253
  if (!pk) return `unknown keyId ${d.sig.keyId}`
@@ -370,10 +412,32 @@ async function main(argv = process.argv.slice(2)) {
370
412
  if (recResult.error) {
371
413
  fail(recResult.code, recResult.error, opts.json)
372
414
  }
415
+ for (const receipt of recResult.receipts) {
416
+ const sigFail = verifyReceiptSig(keys, receipt)
417
+ if (sigFail) {
418
+ fail(
419
+ 13,
420
+ `receipt signature invalid at ${sigFail.id}: ${sigFail.error} — coverage is not COMPLETE`,
421
+ opts.json,
422
+ { receiptId: sigFail.id },
423
+ )
424
+ }
425
+ }
373
426
  const crossErr = crossCheck(d, recResult.receipts)
374
427
  if (crossErr) {
375
428
  fail(30, `inconsistent with receipts: ${crossErr}`, opts.json)
376
429
  }
430
+ if (opts.expectSeqFrom !== null && recResult.receipts.length) {
431
+ const seqs = recResult.receipts.map((r) => r.chain.seq).sort((a, b) => a - b)
432
+ if (seqs[0] !== opts.expectSeqFrom) {
433
+ fail(
434
+ 12,
435
+ `window start mismatch: expected seq ${opts.expectSeqFrom}, receipts start at ${seqs[0]} — coverage is not COMPLETE`,
436
+ opts.json,
437
+ { expectedFirstSeq: opts.expectSeqFrom, firstSeq: seqs[0] },
438
+ )
439
+ }
440
+ }
377
441
  }
378
442
 
379
443
  // Zincir kesintisizliği: CI'da sorulan soru "kapsamam eksiksiz mi?" (b).
@@ -391,20 +455,39 @@ async function main(argv = process.argv.slice(2)) {
391
455
  fail(12, msg, opts.json, { gaps: d.chain.gaps })
392
456
  }
393
457
 
458
+ const windowStartPinned = d.chain.windowStartPinned === true || opts.expectSeqFrom !== null
459
+ const complete = d.chain.contiguous === true && windowStartPinned
460
+ const pinNote = windowStartPinned
461
+ ? 'window start pinned'
462
+ : 'window start not pinned (başlangıç sabitlenmedi)'
463
+
394
464
  if (opts.json) {
395
- console.log(JSON.stringify({ ok: true, code: 0, declaration: d.id, version: d.v }))
465
+ console.log(JSON.stringify({
466
+ ok: true,
467
+ code: 0,
468
+ declaration: d.id,
469
+ version: d.v,
470
+ complete,
471
+ windowStartPinned,
472
+ pinNote,
473
+ }))
396
474
  } else {
397
475
  const unassigned = d.v === COVERAGE_V ? d.coverage.unassignedReceiptCount : 0
398
476
  console.log(
399
477
  `ok: coverage declaration ${d.id} verified (version ${d.v}, ${d.chain.count} receipts, ` +
400
- `contiguous=${d.chain.contiguous}, accessed=${d.coverage.accessed}, ` +
401
- `notRecorded=${d.coverage.notRecorded})`,
478
+ `contiguous=${d.chain.contiguous}, ${pinNote}, accessed=${d.coverage.accessed}, ` +
479
+ `notRecorded=${d.coverage.notRecorded} (access NOT RECORDED))`,
402
480
  )
481
+ if (!windowStartPinned) {
482
+ console.warn(
483
+ 'warning: window start not pinned — prefix truncation is invisible; pass --expect-seq-from N',
484
+ )
485
+ }
403
486
  // Belirsizlik uyarısı: notRecorded listesi ancak unassigned=0 iken "kesin" sayılabilir.
404
487
  // "erişilmedi"/"not accessed" ifadesi YASAK — kaydın yokluğu belirsizdir, erişim yokluğu değil.
405
488
  if (unassigned > 0) {
406
489
  console.warn(
407
- `warning: notRecorded=${d.coverage.notRecorded} (${unassigned} receipt(s) could not be attributed ` +
490
+ `warning: notRecorded=${d.coverage.notRecorded} (access NOT RECORDED; ${unassigned} receipt(s) could not be attributed ` +
408
491
  `to a specific object; this list is NOT definitive)`,
409
492
  )
410
493
  }
@@ -446,6 +446,50 @@ if (config) {
446
446
  }
447
447
  }
448
448
 
449
+ // 7b. Production proof profile — one block
450
+ {
451
+ const production =
452
+ (process.env.CONARIUM_PROFILE || '').toLowerCase() === 'production' ||
453
+ config?.profile === 'production'
454
+ if (production) {
455
+ const missing = []
456
+ if (!envSet('CONARIUM_AUDIT_SIGNING_KEY')) missing.push('Ed25519 (CONARIUM_AUDIT_SIGNING_KEY)')
457
+ if (!envSet('CONARIUM_AUDIT_HMAC_KEY')) missing.push('HMAC (CONARIUM_AUDIT_HMAC_KEY)')
458
+ const rateRaw = process.env.CONARIUM_MCP_RATE_PER_MIN
459
+ const rate = rateRaw === undefined || rateRaw === '' ? 60 : Number(rateRaw)
460
+ if (missing.length) {
461
+ fail(
462
+ 'Production profile',
463
+ `refuses boot without ${missing.join(' and ')}`,
464
+ 'Production requires Ed25519 AND HMAC, G3 strict signatures, and an anchor sink. Rate limit defaults to 60/min unless CONARIUM_MCP_RATE_PER_MIN=0.',
465
+ )
466
+ } else {
467
+ ok(
468
+ 'Production profile',
469
+ `Ed25519 + HMAC required; G3 on; anchor on; rate ${Number.isFinite(rate) ? rate : 60}/min`,
470
+ )
471
+ }
472
+ }
473
+ }
474
+
475
+ // 7c. HTTP rate limit — default 0 is intentional; say so when HTTP is on
476
+ {
477
+ const httpMode = Boolean(envSet('CONARIUM_MCP_TOKEN'))
478
+ if (httpMode) {
479
+ const rateRaw = process.env.CONARIUM_MCP_RATE_PER_MIN
480
+ const rate = rateRaw === undefined || rateRaw === '' ? 0 : Number(rateRaw)
481
+ if (!Number.isFinite(rate) || rate === 0) {
482
+ warn(
483
+ 'HTTP rate limit',
484
+ 'CONARIUM_MCP_RATE_PER_MIN is 0 (off)',
485
+ 'Public HTTP should set a limit. Production profile defaults to 60/min unless explicitly 0.',
486
+ )
487
+ } else {
488
+ ok('HTTP rate limit', `${rate}/min`)
489
+ }
490
+ }
491
+ }
492
+
449
493
  // 8. Signing key material — never printed, only described
450
494
  {
451
495
  const keyPath = envSet('CONARIUM_AUDIT_SIGNING_KEY')