@conarium-ai/core 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 (188) hide show
  1. package/CHANGELOG.md +131 -0
  2. package/LICENSE +21 -0
  3. package/README.md +387 -0
  4. package/SECURITY.md +226 -0
  5. package/bin/conarium-anchor-service.mjs +77 -0
  6. package/bin/conarium-anchor-upgrade.mjs +108 -0
  7. package/bin/conarium-coverage.mjs +425 -0
  8. package/bin/conarium-doctor.mjs +480 -0
  9. package/bin/conarium-init.mjs +184 -0
  10. package/bin/conarium-reconcile.mjs +441 -0
  11. package/bin/conarium-stamp.mjs +161 -0
  12. package/bin/conarium-verify.mjs +610 -0
  13. package/conarium.config.json +43 -0
  14. package/deploy/anchor-service/README.md +79 -0
  15. package/deploy/anchor-service/conarium-anchor.service +21 -0
  16. package/deploy/anchor-service/dry-run.mjs +122 -0
  17. package/deploy/anchor-service/ecosystem.config.cjs +21 -0
  18. package/deploy/anchor-service/env.example +11 -0
  19. package/dist/anchor-service.d.ts +39 -0
  20. package/dist/anchor-service.d.ts.map +1 -0
  21. package/dist/anchor-service.js +278 -0
  22. package/dist/anchor-service.js.map +1 -0
  23. package/dist/anchor.d.ts +123 -0
  24. package/dist/anchor.d.ts.map +1 -0
  25. package/dist/anchor.js +246 -0
  26. package/dist/anchor.js.map +1 -0
  27. package/dist/audit-hash.d.ts +4 -0
  28. package/dist/audit-hash.d.ts.map +1 -0
  29. package/dist/audit-hash.js +12 -0
  30. package/dist/audit-hash.js.map +1 -0
  31. package/dist/audit.d.ts +104 -0
  32. package/dist/audit.d.ts.map +1 -0
  33. package/dist/audit.js +391 -0
  34. package/dist/audit.js.map +1 -0
  35. package/dist/config.d.ts +273 -0
  36. package/dist/config.d.ts.map +1 -0
  37. package/dist/config.js +44 -0
  38. package/dist/config.js.map +1 -0
  39. package/dist/connectors/docs.d.ts +23 -0
  40. package/dist/connectors/docs.d.ts.map +1 -0
  41. package/dist/connectors/docs.js +140 -0
  42. package/dist/connectors/docs.js.map +1 -0
  43. package/dist/connectors/index.d.ts +10 -0
  44. package/dist/connectors/index.d.ts.map +1 -0
  45. package/dist/connectors/index.js +37 -0
  46. package/dist/connectors/index.js.map +1 -0
  47. package/dist/connectors/jira.d.ts +16 -0
  48. package/dist/connectors/jira.d.ts.map +1 -0
  49. package/dist/connectors/jira.js +67 -0
  50. package/dist/connectors/jira.js.map +1 -0
  51. package/dist/connectors/openapi.d.ts +28 -0
  52. package/dist/connectors/openapi.d.ts.map +1 -0
  53. package/dist/connectors/openapi.js +447 -0
  54. package/dist/connectors/openapi.js.map +1 -0
  55. package/dist/connectors/postgres.d.ts +17 -0
  56. package/dist/connectors/postgres.d.ts.map +1 -0
  57. package/dist/connectors/postgres.js +131 -0
  58. package/dist/connectors/postgres.js.map +1 -0
  59. package/dist/connectors/slack.d.ts +16 -0
  60. package/dist/connectors/slack.d.ts.map +1 -0
  61. package/dist/connectors/slack.js +65 -0
  62. package/dist/connectors/slack.js.map +1 -0
  63. package/dist/connectors/supabase_rest.d.ts +35 -0
  64. package/dist/connectors/supabase_rest.d.ts.map +1 -0
  65. package/dist/connectors/supabase_rest.js +153 -0
  66. package/dist/connectors/supabase_rest.js.map +1 -0
  67. package/dist/connectors/zion.d.ts +24 -0
  68. package/dist/connectors/zion.d.ts.map +1 -0
  69. package/dist/connectors/zion.js +76 -0
  70. package/dist/connectors/zion.js.map +1 -0
  71. package/dist/console.d.ts +30 -0
  72. package/dist/console.d.ts.map +1 -0
  73. package/dist/console.js +257 -0
  74. package/dist/console.js.map +1 -0
  75. package/dist/coverage.d.ts +100 -0
  76. package/dist/coverage.d.ts.map +1 -0
  77. package/dist/coverage.js +175 -0
  78. package/dist/coverage.js.map +1 -0
  79. package/dist/executor.d.ts +12 -0
  80. package/dist/executor.d.ts.map +1 -0
  81. package/dist/executor.js +77 -0
  82. package/dist/executor.js.map +1 -0
  83. package/dist/governance.d.ts +124 -0
  84. package/dist/governance.d.ts.map +1 -0
  85. package/dist/governance.js +977 -0
  86. package/dist/governance.js.map +1 -0
  87. package/dist/http.d.ts +48 -0
  88. package/dist/http.d.ts.map +1 -0
  89. package/dist/http.js +221 -0
  90. package/dist/http.js.map +1 -0
  91. package/dist/index.d.ts +3 -0
  92. package/dist/index.d.ts.map +1 -0
  93. package/dist/index.js +25 -0
  94. package/dist/index.js.map +1 -0
  95. package/dist/keys.d.ts +51 -0
  96. package/dist/keys.d.ts.map +1 -0
  97. package/dist/keys.js +174 -0
  98. package/dist/keys.js.map +1 -0
  99. package/dist/license.d.ts +35 -0
  100. package/dist/license.d.ts.map +1 -0
  101. package/dist/license.js +122 -0
  102. package/dist/license.js.map +1 -0
  103. package/dist/llm-gate.d.ts +17 -0
  104. package/dist/llm-gate.d.ts.map +1 -0
  105. package/dist/llm-gate.js +19 -0
  106. package/dist/llm-gate.js.map +1 -0
  107. package/dist/openapi_connector.d.ts +6 -0
  108. package/dist/openapi_connector.d.ts.map +1 -0
  109. package/dist/openapi_connector.js +145 -0
  110. package/dist/openapi_connector.js.map +1 -0
  111. package/dist/pseudonymize.d.ts +19 -0
  112. package/dist/pseudonymize.d.ts.map +1 -0
  113. package/dist/pseudonymize.js +25 -0
  114. package/dist/pseudonymize.js.map +1 -0
  115. package/dist/rate_limit.d.ts +41 -0
  116. package/dist/rate_limit.d.ts.map +1 -0
  117. package/dist/rate_limit.js +66 -0
  118. package/dist/rate_limit.js.map +1 -0
  119. package/dist/receipt.d.ts +161 -0
  120. package/dist/receipt.d.ts.map +1 -0
  121. package/dist/receipt.js +210 -0
  122. package/dist/receipt.js.map +1 -0
  123. package/dist/scripts/discover_schema.d.ts +2 -0
  124. package/dist/scripts/discover_schema.d.ts.map +1 -0
  125. package/dist/scripts/discover_schema.js +75 -0
  126. package/dist/scripts/discover_schema.js.map +1 -0
  127. package/dist/scripts/dogfood_prove.d.ts +2 -0
  128. package/dist/scripts/dogfood_prove.d.ts.map +1 -0
  129. package/dist/scripts/dogfood_prove.js +41 -0
  130. package/dist/scripts/dogfood_prove.js.map +1 -0
  131. package/dist/search_policy.d.ts +23 -0
  132. package/dist/search_policy.d.ts.map +1 -0
  133. package/dist/search_policy.js +79 -0
  134. package/dist/search_policy.js.map +1 -0
  135. package/dist/server.d.ts +29 -0
  136. package/dist/server.d.ts.map +1 -0
  137. package/dist/server.js +379 -0
  138. package/dist/server.js.map +1 -0
  139. package/dist/tokens.d.ts +14 -0
  140. package/dist/tokens.d.ts.map +1 -0
  141. package/dist/tokens.js +58 -0
  142. package/dist/tokens.js.map +1 -0
  143. package/dist/types.d.ts +132 -0
  144. package/dist/types.d.ts.map +1 -0
  145. package/dist/types.js +2 -0
  146. package/dist/types.js.map +1 -0
  147. package/docs/ARCHITECTURE.md +42 -0
  148. package/docs/CONSENT-BINDING-SPEC.md +136 -0
  149. package/docs/CONSENT-BINDING-SPEC.md.anchors.jsonl +1 -0
  150. package/docs/PRIOR-ART.md +213 -0
  151. package/docs/PRIOR-ART.md.anchors.jsonl +3 -0
  152. package/docs/RECEIPT-SPEC.md +301 -0
  153. package/docs/RECEIPT-SPEC.md.anchors.jsonl +1 -0
  154. package/docs/dogfood/2026-07-31-anchor.anchors.jsonl +1 -0
  155. package/docs/dogfood/2026-08-06-reconcile.md +140 -0
  156. package/docs/plans/2026-07-02-redteam-harness.md +416 -0
  157. package/docs/specs/2026-07-02-redteam-harness-design.md +90 -0
  158. package/docs/superpowers/TODO-gate1-f4.md +23 -0
  159. package/docs/superpowers/plans/2026-07-29-conarium-receipt-plan.md +200 -0
  160. package/docs/superpowers/plans/2026-07-29-katman0-kapanis-plan.md +231 -0
  161. package/docs/superpowers/plans/2026-07-31-per-user-identity.md +667 -0
  162. package/docs/superpowers/specs/2026-07-29-conarium-receipt-design.md +202 -0
  163. package/docs/superpowers/specs/2026-07-31-per-user-identity-design.md +144 -0
  164. package/docs/superpowers/specs/2026-08-01-coverage-proof-design.md +139 -0
  165. package/docs/superpowers/specs/2026-08-05-receipt-meta-provenance-design.md +116 -0
  166. package/examples/claude-desktop-config.json +9 -0
  167. package/examples/cursor-mcp-settings.json +10 -0
  168. package/package.json +99 -0
  169. package/scripts/audit-chain-check.mjs +119 -0
  170. package/scripts/conarium_sabah_brief.mjs +107 -0
  171. package/scripts/gen-test-vectors.mjs +193 -0
  172. package/scripts/pg-snapshot.sql +27 -0
  173. package/scripts/start-mcp-c1.mjs +70 -0
  174. package/test-vectors/001-single-receipt/receipts.jsonl +1 -0
  175. package/test-vectors/002-chain-of-three/receipts.jsonl +3 -0
  176. package/test-vectors/003-tampered-field/receipts.jsonl +1 -0
  177. package/test-vectors/004-prevhash-break/receipts.jsonl +2 -0
  178. package/test-vectors/005-seq-gap/receipts.jsonl +2 -0
  179. package/test-vectors/006-bad-signature/receipts.jsonl +1 -0
  180. package/test-vectors/007-schema-invalid/receipts.jsonl +1 -0
  181. package/test-vectors/008-unsigned-no-pubkey/receipts.jsonl +1 -0
  182. package/test-vectors/009-unsigned-but-pubkey-given/receipts.jsonl +1 -0
  183. package/test-vectors/README.md +92 -0
  184. package/test-vectors/expected-hashes.json +24 -0
  185. package/test-vectors/keys/vector-key.SECRET-TEST-ONLY.pem +6 -0
  186. package/test-vectors/keys/vector-key.pub.pem +3 -0
  187. package/test-vectors/keys/vector-key.pub.pem.keyid +1 -0
  188. package/test-vectors/manifest.json +95 -0
@@ -0,0 +1,610 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * conarium-verify — independent offline verifier for Conarium Receipt v0.1.
4
+ *
5
+ * ZERO imports from src/. Canonicalization is duplicated here on purpose:
6
+ * a third party must be able to run this single file without the Conarium package.
7
+ *
8
+ * Usage:
9
+ * conarium-verify <file|dir> --pubkey <path> [--pubkey <path2> ...]
10
+ * [--anchor-check] [--expect-seq-from N] [--json]
11
+ *
12
+ * Exit codes (design §5):
13
+ * 0 chain intact, signatures valid
14
+ * 10 hash mismatch (tampered)
15
+ * 11 prevHash break (deleted / inserted)
16
+ * 12 seq gap or non-increasing
17
+ * 13 signature invalid / no pubkey
18
+ * 14 anchor proof failed / missing under --anchor-check
19
+ * 15 anchor COULD NOT BE CHECKED (calendar unreachable, verifier not installed)
20
+ * — deliberately distinct from 14: "I could not verify" is not "this is invalid"
21
+ * 20 schema invalid
22
+ */
23
+ import { createHash, createPublicKey, verify as cryptoVerify } from 'crypto'
24
+ import { readFileSync, existsSync, statSync, readdirSync } from 'fs'
25
+ import { join, extname } from 'path'
26
+ import { createRequire } from 'module'
27
+
28
+ const require = createRequire(import.meta.url)
29
+
30
+ const RECEIPT_V1 = 'conarium-receipt/0.1'
31
+ const RECEIPT_V2 = 'conarium-receipt/0.2'
32
+ const RECEIPT_V3 = 'conarium-receipt/0.3'
33
+ const SURUMLER = [RECEIPT_V1, RECEIPT_V2, RECEIPT_V3]
34
+ // v0.3 meta kaynaklari. Bilinmeyen bir kaynak sema hatasidir: "protocol" yazip
35
+ // olcmemis olmak, dogrulayanin makbuza fazladan guvenmesi demek olurdu.
36
+ const META_KAYNAKLARI = ['protocol', 'operator-declared', 'undeclared']
37
+ const GENESIS = 'sha256:0000000000000000000000000000000000000000000000000000000000000000'
38
+
39
+ // ─── JCS subset (must match src/receipt.ts canonicalize) ─────────────────────
40
+
41
+ function canonicalize(obj) {
42
+ return canonValue(obj)
43
+ }
44
+
45
+ function canonValue(v) {
46
+ if (v === null) return 'null'
47
+ if (v === undefined) {
48
+ throw new Error('canonicalize: undefined is not allowed (omit the field)')
49
+ }
50
+ if (typeof v === 'boolean') return v ? 'true' : 'false'
51
+ if (typeof v === 'number') {
52
+ if (!Number.isFinite(v)) throw new Error('canonicalize: non-finite number')
53
+ return JSON.stringify(v)
54
+ }
55
+ if (typeof v === 'string') return JSON.stringify(v)
56
+ if (Array.isArray(v)) {
57
+ return '[' + v.map(canonValue).join(',') + ']'
58
+ }
59
+ if (typeof v === 'object') {
60
+ const keys = Object.keys(v)
61
+ .filter((k) => v[k] !== undefined)
62
+ .sort()
63
+ const parts = []
64
+ for (const k of keys) {
65
+ parts.push(JSON.stringify(k) + ':' + canonValue(v[k]))
66
+ }
67
+ return '{' + parts.join(',') + '}'
68
+ }
69
+ throw new Error(`canonicalize: unsupported type ${typeof v}`)
70
+ }
71
+
72
+ function receiptHash(r) {
73
+ const copy = { ...r }
74
+ delete copy.hash
75
+ delete copy.sig
76
+ delete copy.anchor
77
+ if (copy.chain && typeof copy.chain === 'object') {
78
+ const chain = { ...copy.chain }
79
+ delete chain.hash
80
+ copy.chain = chain
81
+ }
82
+ const digest = createHash('sha256').update(canonicalize(copy)).digest('hex')
83
+ return `sha256:${digest}`
84
+ }
85
+
86
+ // Exported for cross-check tests (dynamic import of this file).
87
+ export { canonicalize, receiptHash }
88
+
89
+ // ─── CLI ─────────────────────────────────────────────────────────────────────
90
+
91
+ function usage(msg) {
92
+ if (msg) console.error(msg)
93
+ console.error(
94
+ 'Usage: conarium-verify <file|dir> --pubkey <path> [--pubkey <path2> ...] [--anchor-check] [--anchors <path>] [--expect-seq-from N] [--json]',
95
+ )
96
+ }
97
+
98
+ function parseArgs(argv) {
99
+ const out = {
100
+ target: null,
101
+ pubkeys: [],
102
+ anchorCheck: false,
103
+ anchorsPath: null,
104
+ expectSeqFrom: null,
105
+ json: false,
106
+ }
107
+ const args = [...argv]
108
+ while (args.length) {
109
+ const a = args.shift()
110
+ if (a === '--pubkey') {
111
+ const p = args.shift()
112
+ if (!p) throw new Error('--pubkey requires a path')
113
+ out.pubkeys.push(p)
114
+ } else if (a === '--anchor-check') {
115
+ out.anchorCheck = true
116
+ } else if (a === '--anchors') {
117
+ const p = args.shift()
118
+ if (!p) throw new Error('--anchors requires a path')
119
+ out.anchorsPath = p
120
+ } else if (a === '--expect-seq-from') {
121
+ const n = args.shift()
122
+ if (n === undefined || !/^\d+$/.test(n)) throw new Error('--expect-seq-from requires an integer')
123
+ out.expectSeqFrom = Number(n)
124
+ } else if (a === '--json') {
125
+ out.json = true
126
+ } else if (a === '--help' || a === '-h') {
127
+ usage()
128
+ process.exit(0)
129
+ } else if (a.startsWith('-')) {
130
+ throw new Error(`unknown flag: ${a}`)
131
+ } else if (!out.target) {
132
+ out.target = a
133
+ } else {
134
+ throw new Error(`unexpected argument: ${a}`)
135
+ }
136
+ }
137
+ return out
138
+ }
139
+
140
+ function hashPrefixToBuffer(hash) {
141
+ const hex = typeof hash === 'string' && hash.startsWith('sha256:') ? hash.slice(7) : hash
142
+ if (typeof hex !== 'string' || !/^[0-9a-fA-F]{64}$/.test(hex)) {
143
+ throw new Error('anchor hash must be sha256:<64 hex>')
144
+ }
145
+ const buf = Buffer.from(hex, 'hex')
146
+ if (buf.length !== 32) throw new Error('anchor hash must decode to 32 bytes')
147
+ return buf
148
+ }
149
+
150
+ function loadAnchorSidecar(path) {
151
+ if (!existsSync(path)) return []
152
+ const raw = readFileSync(path, 'utf-8').trim()
153
+ if (!raw) return []
154
+ return raw.split('\n').filter(Boolean).map((l) => JSON.parse(l))
155
+ }
156
+
157
+ function findAnchorRecord(rows, ref) {
158
+ for (let i = rows.length - 1; i >= 0; i--) {
159
+ if (rows[i].hash === ref) return rows[i]
160
+ }
161
+ return null
162
+ }
163
+
164
+ /**
165
+ * "Kontrol edemedim" ile "kanıt geçersiz" ayrımı.
166
+ *
167
+ * Yalnızca KESİN ulaşılamama durumları buraya girer. Tanımadığımız bir hata
168
+ * `unknown` sayılmaz, 14 (kanıt başarısız) tarafında kalır: belirsizliği
169
+ * "sorun yok" yönüne yuvarlamak, bu ayrımı yapmanın amacını yok ederdi.
170
+ */
171
+ const AG_HATA_KODLARI = new Set([
172
+ 'ESOCKETTIMEDOUT', 'ETIMEDOUT', 'ECONNREFUSED', 'ECONNRESET', 'ENOTFOUND',
173
+ 'EAI_AGAIN', 'ENETUNREACH', 'EHOSTUNREACH', 'ECONNABORTED', 'EPIPE',
174
+ ])
175
+ const AG_HATA_DESENI = /socket hang up|socket timed? ?out|network (is )?unreachable|getaddrinfo|request-promise|ESOCKETTIMEDOUT|ETIMEDOUT|ECONNREFUSED|ECONNRESET|ENOTFOUND|EAI_AGAIN/i
176
+
177
+ function ulasilamadiMi(err) {
178
+ if (!err) return false
179
+ if (err.code && AG_HATA_KODLARI.has(String(err.code))) return true
180
+ if (err.cause && err.cause.code && AG_HATA_KODLARI.has(String(err.cause.code))) return true
181
+ return AG_HATA_DESENI.test(String(err.message || err))
182
+ }
183
+
184
+ async function verifyOtsProof(otsBase64, hash) {
185
+ let OpenTimestamps
186
+ try {
187
+ OpenTimestamps = require('javascript-opentimestamps')
188
+ if (OpenTimestamps && OpenTimestamps.default) OpenTimestamps = OpenTimestamps.default
189
+ } catch {
190
+ // "Kontrol edemedim", "kanıt geçersiz" DEĞİL. Paket 2026-08-12'den beri
191
+ // opsiyonel bir bağımlılık (bagimlilik agacindaki kritik aciklar nedeniyle),
192
+ // dolayısıyla bu durum artık istisna değil, sıradan bir kurulum hâli.
193
+ return { unknown: true, detail: 'javascript-opentimestamps not installed — anchor not checked' }
194
+ }
195
+ try {
196
+ const hashBuf = hashPrefixToBuffer(hash)
197
+ const detached = OpenTimestamps.DetachedTimestampFile.fromHash(
198
+ new OpenTimestamps.Ops.OpSHA256(),
199
+ hashBuf,
200
+ )
201
+ const detachedOts = OpenTimestamps.DetachedTimestampFile.deserialize(Buffer.from(otsBase64, 'base64'))
202
+ // Digest mismatch (proof for another hash) → fail closed before calendar I/O when possible
203
+ if (typeof detachedOts.fileDigest === 'function') {
204
+ const fileDigest = Buffer.from(detachedOts.fileDigest())
205
+ if (!fileDigest.equals(hashBuf)) {
206
+ return { ok: false, pending: false, detail: 'ots proof digest does not match chain hash' }
207
+ }
208
+ }
209
+ const verified = await OpenTimestamps.verify(detachedOts, detached, {
210
+ ignoreBitcoinNode: true,
211
+ timeout: 15000,
212
+ })
213
+ if (!verified || Object.keys(verified).length === 0) {
214
+ return { ok: true, pending: true }
215
+ }
216
+ return { ok: true, pending: !verified.bitcoin }
217
+ } catch (err) {
218
+ // Takvime/blok gezginine ulaşılamaması bir KANIT BAŞARISIZLIĞI değildir.
219
+ // Bu projenin bütün iddiası "kaydedilmedi ≠ olmadı" ayrımını yapmak; kendi
220
+ // doğrulayıcısı içeride bu ayrımı yapmazsa iddia kendi kodunda çürür.
221
+ // Dijest karşılaştırması zaten yukarıda ÇEVRİMDIŞI yapıldı, yani yerel
222
+ // gerçek kaybolmuyor — kaybolan yalnızca zaman kanıtının teyidi.
223
+ if (ulasilamadiMi(err)) {
224
+ return { unknown: true, detail: `anchor calendar unreachable: ${err.message || String(err)}` }
225
+ }
226
+ return { ok: false, pending: false, detail: err.message || String(err) }
227
+ }
228
+ }
229
+
230
+ function loadVerifyKeys(paths) {
231
+ if (paths.length === 0) {
232
+ return { error: 'no --pubkey given (refusing to skip signature checks)', code: 13 }
233
+ }
234
+ const keys = new Map()
235
+ for (const path of paths) {
236
+ if (!existsSync(path)) {
237
+ return { error: `public key not found: ${path}`, code: 13 }
238
+ }
239
+ let pem
240
+ try {
241
+ pem = readFileSync(path, 'utf-8')
242
+ } catch (err) {
243
+ return { error: `cannot read public key ${path}: ${err.message}`, code: 13 }
244
+ }
245
+ let publicKey
246
+ try {
247
+ publicKey = createPublicKey(pem)
248
+ } catch (err) {
249
+ return { error: `invalid public PEM ${path}: ${err.message}`, code: 13 }
250
+ }
251
+ if (publicKey.asymmetricKeyType !== 'ed25519') {
252
+ return { error: `expected Ed25519 at ${path}, got ${publicKey.asymmetricKeyType}`, code: 13 }
253
+ }
254
+ const sidecar = `${path}.keyid`
255
+ if (!existsSync(sidecar)) {
256
+ return { error: `missing keyId sidecar: ${sidecar}`, code: 13 }
257
+ }
258
+ const keyId = readFileSync(sidecar, 'utf-8').trim()
259
+ if (!keyId) {
260
+ return { error: `empty keyId sidecar: ${sidecar}`, code: 13 }
261
+ }
262
+ keys.set(keyId, publicKey)
263
+ }
264
+ return { keys }
265
+ }
266
+
267
+ function loadReceipts(target) {
268
+ if (!existsSync(target)) {
269
+ return { error: `path not found: ${target}`, code: 20 }
270
+ }
271
+ const st = statSync(target)
272
+ let files = []
273
+ if (st.isDirectory()) {
274
+ files = readdirSync(target)
275
+ .filter((f) => ['.json', '.jsonl', '.receipt'].includes(extname(f)))
276
+ .map((f) => join(target, f))
277
+ .sort()
278
+ } else {
279
+ files = [target]
280
+ }
281
+
282
+ const receipts = []
283
+ for (const file of files) {
284
+ const raw = readFileSync(file, 'utf-8').trim()
285
+ if (!raw) continue
286
+ const lines = raw.includes('\n') && !raw.trimStart().startsWith('[')
287
+ ? raw.split('\n').filter(Boolean)
288
+ : [raw]
289
+ for (let i = 0; i < lines.length; i++) {
290
+ let obj
291
+ try {
292
+ obj = JSON.parse(lines[i])
293
+ } catch (err) {
294
+ return { error: `invalid JSON in ${file}:${i + 1}: ${err.message}`, code: 20 }
295
+ }
296
+ if (Array.isArray(obj)) {
297
+ for (const item of obj) receipts.push({ file, receipt: item })
298
+ } else {
299
+ receipts.push({ file, receipt: obj })
300
+ }
301
+ }
302
+ }
303
+ return { receipts }
304
+ }
305
+
306
+ function schemaOk(r) {
307
+ if (!r || typeof r !== 'object') return 'not an object'
308
+ if (!SURUMLER.includes(r.v)) return `unsupported version ${r.v}`
309
+ if (typeof r.id !== 'string' || !r.id) return 'missing id'
310
+ if (typeof r.ts !== 'string') return 'missing ts'
311
+ if (!r.chain || typeof r.chain !== 'object') return 'missing chain'
312
+ if (!Number.isInteger(r.chain.seq)) return 'chain.seq not integer'
313
+ if (typeof r.chain.prevHash !== 'string') return 'missing chain.prevHash'
314
+ if (typeof r.chain.hash !== 'string') return 'missing chain.hash'
315
+ // Her iki surumde de null olmali; undefined sema kaymasi sayilir -> 20.
316
+ // (Riza baglama gelecek bir surumun isi, v0.2'nin degil.)
317
+ if (r.consentRef !== null && r.consentRef !== undefined) {
318
+ return 'consentRef must be null'
319
+ }
320
+ if (!('consentRef' in r)) return 'missing consentRef (must be null)'
321
+ if (!('anchor' in r)) return 'missing anchor field'
322
+ // Govde alanlari da semaya dahildir. Bunlar olmadan da hash zaten tutmaz ve
323
+ // exit 10 doner — ama "kurcalanmis" TESHISI yanlis olur: eksik alanli bir
324
+ // kayit degistirilmis bir makbuz degil, hic makbuz degildir. Teshis dogru
325
+ // olsun diye burada yakalaniyor (test-vectors/007 bunu kilitliyor).
326
+ for (const alan of ['period', 'request', 'dataRefs', 'policy', 'flags', 'masking', 'outcome']) {
327
+ if (!(alan in r) || r[alan] === null || r[alan] === undefined) return `missing ${alan}`
328
+ }
329
+ if (!Array.isArray(r.dataRefs)) return 'dataRefs must be an array'
330
+ if (!Array.isArray(r.flags)) return 'flags must be an array'
331
+ if (typeof r.policy !== 'object' || typeof r.policy.decision !== 'string') {
332
+ return 'policy.decision is required'
333
+ }
334
+ // v0.1: aktör "service" olmak zorunda (degismedi — eski makbuzlar aynen dogrulanir)
335
+ if (r.v === RECEIPT_V1) {
336
+ if (!r.actor || r.actor.type !== 'service') return 'actor.type must be "service" in v0.1'
337
+ } else {
338
+ if (!r.actor || (r.actor.type !== 'service' && r.actor.type !== 'user')) {
339
+ return 'actor.type must be "service" or "user" in v0.2'
340
+ }
341
+ if (typeof r.actor.assurance !== 'string' || !r.actor.assurance) {
342
+ return 'actor.assurance is required in v0.2'
343
+ }
344
+ if (r.actor.type === 'user' && r.actor.assurance === 'shared-token') {
345
+ return 'actor.type "user" cannot carry assurance "shared-token"'
346
+ }
347
+ }
348
+ // v0.3: model/client artik DEGERI ile birlikte KAYNAGINI da tasir.
349
+ // "undeclared" gecerli bir makbuzdur — eksik degil, durustce bos.
350
+ if (r.v === RECEIPT_V3) {
351
+ for (const alan of ['model', 'client']) {
352
+ const m = r[alan]
353
+ if (!m || typeof m !== 'object') return `missing ${alan}`
354
+ if (!META_KAYNAKLARI.includes(m.source)) {
355
+ return `${alan}.source must be one of ${META_KAYNAKLARI.join('|')} in v0.3`
356
+ }
357
+ // Bildirilmedi denip deger tasimak celiskidir: makbuz ya bilmiyordur ya bilir.
358
+ if (m.source === 'undeclared') {
359
+ const dolu = alan === 'model'
360
+ ? [m.provider, m.name, m.version].some((x) => x !== null)
361
+ : [m.name, m.version].some((x) => x !== null)
362
+ if (dolu) return `${alan}.source is "undeclared" but carries values`
363
+ }
364
+ }
365
+ }
366
+ return null
367
+ }
368
+
369
+ function verifySig(keys, receipt) {
370
+ if (!receipt.sig || typeof receipt.sig !== 'object') {
371
+ return 'missing sig'
372
+ }
373
+ if (receipt.sig.alg !== 'Ed25519') return `unsupported sig.alg ${receipt.sig.alg}`
374
+ const pk = keys.get(receipt.sig.keyId)
375
+ if (!pk) return `unknown keyId ${receipt.sig.keyId}`
376
+ try {
377
+ const ok = cryptoVerify(
378
+ null,
379
+ Buffer.from(receipt.chain.hash, 'utf-8'),
380
+ pk,
381
+ Buffer.from(receipt.sig.value, 'base64'),
382
+ )
383
+ return ok ? null : 'signature cryptographically invalid'
384
+ } catch (err) {
385
+ return `signature verify error: ${err.message}`
386
+ }
387
+ }
388
+
389
+ function fail(code, message, jsonMode, extra = {}) {
390
+ const payload = { ok: false, code, message, ...extra }
391
+ console.error(message)
392
+ if (jsonMode) console.log(JSON.stringify(payload))
393
+ process.exit(code)
394
+ }
395
+
396
+ async function main(argv = process.argv.slice(2)) {
397
+ let opts
398
+ try {
399
+ opts = parseArgs(argv)
400
+ } catch (err) {
401
+ usage(err.message)
402
+ process.exit(20)
403
+ }
404
+ if (!opts.target) {
405
+ usage('missing <file|dir>')
406
+ process.exit(20)
407
+ }
408
+
409
+ const keyResult = loadVerifyKeys(opts.pubkeys)
410
+ if (keyResult.error) {
411
+ fail(keyResult.code, keyResult.error, opts.json)
412
+ }
413
+ const { keys } = keyResult
414
+
415
+ const loaded = loadReceipts(opts.target)
416
+ if (loaded.error) {
417
+ fail(loaded.code, loaded.error, opts.json)
418
+ }
419
+ const { receipts } = loaded
420
+
421
+ let anchorRows = []
422
+ if (opts.anchorCheck) {
423
+ const defaultAnchors =
424
+ opts.anchorsPath ||
425
+ (existsSync(opts.target) && statSync(opts.target).isFile()
426
+ ? `${opts.target}.anchors.jsonl`
427
+ : null)
428
+ if (defaultAnchors && existsSync(defaultAnchors)) {
429
+ anchorRows = loadAnchorSidecar(defaultAnchors)
430
+ }
431
+ }
432
+
433
+ if (receipts.length === 0) {
434
+ console.error('warning: empty chain (0 receipts)')
435
+ if (opts.json) console.log(JSON.stringify({ ok: true, code: 0, warning: 'empty', count: 0 }))
436
+ process.exit(0)
437
+ }
438
+ if (receipts.length === 1) {
439
+ console.error('warning: single-receipt chain')
440
+ }
441
+
442
+ let prevHash = GENESIS
443
+ let prevSeq = opts.expectSeqFrom !== null ? opts.expectSeqFrom - 1 : null
444
+ let pendingAnchorWarned = false
445
+
446
+ for (let i = 0; i < receipts.length; i++) {
447
+ const { file, receipt } = receipts[i]
448
+ const where = `${file}#${i}`
449
+
450
+ const schemaErr = schemaOk(receipt)
451
+ if (schemaErr) {
452
+ fail(20, `schema invalid at ${where}: ${schemaErr}`, opts.json, { index: i, file })
453
+ }
454
+
455
+ const expected = receiptHash(receipt)
456
+ if (receipt.chain.hash !== expected) {
457
+ fail(10, `hash mismatch at ${where}: recomputed ${expected}, stored ${receipt.chain.hash}`, opts.json, {
458
+ index: i,
459
+ file,
460
+ })
461
+ }
462
+
463
+ if (receipt.chain.prevHash !== prevHash) {
464
+ fail(
465
+ 11,
466
+ `prevHash break at ${where}: expected ${prevHash}, got ${receipt.chain.prevHash}`,
467
+ opts.json,
468
+ { index: i, file },
469
+ )
470
+ }
471
+
472
+ if (prevSeq !== null) {
473
+ if (receipt.chain.seq !== prevSeq + 1) {
474
+ fail(
475
+ 12,
476
+ `seq gap at ${where}: expected ${prevSeq + 1}, got ${receipt.chain.seq}`,
477
+ opts.json,
478
+ { index: i, file },
479
+ )
480
+ }
481
+ } else if (i > 0) {
482
+ // After first receipt, seq must increase by exactly 1
483
+ // (first receipt establishes the baseline)
484
+ }
485
+ if (i > 0) {
486
+ const prev = receipts[i - 1].receipt
487
+ if (receipt.chain.seq <= prev.chain.seq) {
488
+ fail(
489
+ 12,
490
+ `seq non-increasing at ${where}: ${prev.chain.seq} → ${receipt.chain.seq}`,
491
+ opts.json,
492
+ { index: i, file },
493
+ )
494
+ }
495
+ if (receipt.chain.seq !== prev.chain.seq + 1) {
496
+ fail(
497
+ 12,
498
+ `seq gap at ${where}: expected ${prev.chain.seq + 1}, got ${receipt.chain.seq}`,
499
+ opts.json,
500
+ { index: i, file },
501
+ )
502
+ }
503
+ }
504
+ if (opts.expectSeqFrom !== null && i === 0 && receipt.chain.seq !== opts.expectSeqFrom) {
505
+ fail(
506
+ 12,
507
+ `seq start mismatch at ${where}: expected ${opts.expectSeqFrom}, got ${receipt.chain.seq}`,
508
+ opts.json,
509
+ { index: i, file },
510
+ )
511
+ }
512
+
513
+ const sigErr = verifySig(keys, receipt)
514
+ if (sigErr) {
515
+ fail(13, `signature invalid at ${where}: ${sigErr}`, opts.json, { index: i, file })
516
+ }
517
+
518
+ if (opts.anchorCheck) {
519
+ if (receipt.anchor === null || receipt.anchor === undefined) {
520
+ fail(14, `anchor missing at ${where} (--anchor-check)`, opts.json, { index: i, file })
521
+ }
522
+ if (typeof receipt.anchor !== 'object' || typeof receipt.anchor.log !== 'string') {
523
+ fail(14, `anchor proof invalid at ${where}`, opts.json, { index: i, file })
524
+ }
525
+ const ref = receipt.anchor.ref || receipt.chain.hash
526
+ const row = findAnchorRecord(anchorRows, ref)
527
+ if (!row) {
528
+ fail(14, `anchor sidecar record missing for ref ${ref} at ${where}`, opts.json, {
529
+ index: i,
530
+ file,
531
+ })
532
+ }
533
+ if (!row.ots) {
534
+ fail(14, `anchor ots missing in sidecar for ref ${ref} at ${where}`, opts.json, {
535
+ index: i,
536
+ file,
537
+ })
538
+ }
539
+ const otsResult = await verifyOtsProof(row.ots, receipt.chain.hash)
540
+ // 15 ÖNCE gelir: "kontrol edemedim" ile "kanıt tutmuyor" farklı cevaplardır
541
+ // ve ikincisi birincisini yutarsa doğrulayıcı bilmediği bir şeyi iddia eder.
542
+ // Sessizce 0 dönmek de aynı ölçüde yanlış olurdu — çağıran, çıpanın
543
+ // doğrulanmadığını BİLMELİ, sadece doğrulanamadığını.
544
+ if (otsResult.unknown) {
545
+ fail(
546
+ 15,
547
+ `anchor could not be checked at ${where}: ${otsResult.detail}`,
548
+ opts.json,
549
+ { index: i, file },
550
+ )
551
+ }
552
+ if (!otsResult.ok) {
553
+ fail(
554
+ 14,
555
+ `anchor proof failed at ${where}: ${otsResult.detail || 'verify failed'}`,
556
+ opts.json,
557
+ { index: i, file },
558
+ )
559
+ }
560
+ if (otsResult.pending || row.state === 'pending') {
561
+ if (!pendingAnchorWarned) {
562
+ console.error(
563
+ 'warning: anchor pending (calendar only, not yet Bitcoin-attested)',
564
+ )
565
+ pendingAnchorWarned = true
566
+ }
567
+ }
568
+ }
569
+
570
+ prevHash = receipt.chain.hash
571
+ prevSeq = receipt.chain.seq
572
+ }
573
+
574
+ // Bildirilmemis meta BASARISIZLIK DEGILDIR — ama sessizce de gecmez. Denetci
575
+ // "N makbuz dogrulandi" cumlesini okurken, kacinin model kimligi tasimadigini
576
+ // gormeli; aksi halde dogrulama, olcmedigi bir seyi onaylamis gibi okunur.
577
+ // NOT: receipts elemanlari {file, receipt} sarmalidir — dogrudan r.model okumak
578
+ // sessizce hep 0 verir (bu tam olarak bir kez yasandi, e2e kosusu yakaladi).
579
+ const modelBildirilmemis = receipts.filter((r) => r.receipt?.model?.source === 'undeclared').length
580
+ const clientBildirilmemis = receipts.filter((r) => r.receipt?.client?.source === 'undeclared').length
581
+ const notlar = []
582
+ if (modelBildirilmemis) notlar.push(`${modelBildirilmemis} with undeclared model`)
583
+ if (clientBildirilmemis) notlar.push(`${clientBildirilmemis} with undeclared client`)
584
+
585
+ if (opts.json) {
586
+ console.log(JSON.stringify({
587
+ ok: true,
588
+ code: 0,
589
+ count: receipts.length,
590
+ undeclaredModel: modelBildirilmemis,
591
+ undeclaredClient: clientBildirilmemis,
592
+ }))
593
+ } else {
594
+ const ek = notlar.length ? ` (${notlar.join(', ')})` : ''
595
+ console.log(`ok: ${receipts.length} receipt(s) verified${ek}`)
596
+ }
597
+ process.exit(0)
598
+ }
599
+
600
+ const isDirect =
601
+ process.argv[1] &&
602
+ (process.argv[1].endsWith('conarium-verify.mjs') ||
603
+ process.argv[1].endsWith('conarium-verify'))
604
+
605
+ if (isDirect) {
606
+ main().catch((err) => {
607
+ console.error(err)
608
+ process.exit(20)
609
+ })
610
+ }
@@ -0,0 +1,43 @@
1
+ {
2
+ "serverName": "Conarium",
3
+ "consumer": "ai-assistant",
4
+ "connectors": [
5
+ {
6
+ "type": "postgres",
7
+ "name": "maindb",
8
+ "description": "Application Postgres database (read-only, governed access)",
9
+ "config": {
10
+ "url": "env:DATABASE_READONLY_DSN"
11
+ }
12
+ }
13
+ ],
14
+ "policy": {
15
+ "allowConnectors": [
16
+ "maindb"
17
+ ],
18
+ "allowTables": [
19
+ "public.customers",
20
+ "public.orders",
21
+ "public.products"
22
+ ],
23
+ "denyTables": [
24
+ "public.secrets",
25
+ "public.admin_users",
26
+ "public.credit_cards",
27
+ "public.salaries"
28
+ ],
29
+ "maskColumns": [
30
+ "public.customers.email",
31
+ "public.customers.phone",
32
+ "public.customers.national_id",
33
+ "public.customers.address",
34
+ "public.orders.card_number",
35
+ "public.orders.notes"
36
+ ],
37
+ "maxRows": 50
38
+ },
39
+ "audit": {
40
+ "sink": "conarium-audit.jsonl",
41
+ "failClosed": true
42
+ }
43
+ }