@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,480 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * conarium-doctor — pre-flight diagnosis for a Conarium install.
4
+ *
5
+ * WHY THIS EXISTS
6
+ * Conarium is meant to be installed once, by the operator, without us in the
7
+ * loop. Every misconfiguration that produces a vague stack trace — or worse, a
8
+ * process that starts happily and governs nothing — becomes a support email
9
+ * from a timezone we cannot answer quickly. This tool converts those into a
10
+ * checklist the operator can act on alone.
11
+ *
12
+ * TWO SILENT FAILURES IT EXISTS FOR (both real, both in the current code):
13
+ * 1. `loadConfig()` returns an EMPTY config when the config file is missing
14
+ * (src/server.ts). A typo in the path yields a server that runs, logs one
15
+ * stderr line, and enforces nothing. Nothing crashes.
16
+ * 2. Connector `connect()` failures are caught and logged, not thrown
17
+ * (src/server.ts). The gateway stays up with zero connectors.
18
+ *
19
+ * DESIGN RULES
20
+ * - NO imports from src/ or dist/. The doctor must run when the build is
21
+ * broken, because that is exactly when it is needed. Node builtins only.
22
+ * - NEVER print a secret. Operators paste this output into support email and
23
+ * CI logs. Passwords, tokens and key material are reported as shape only
24
+ * (set / not set, length, host — never the value).
25
+ * - Exit codes stay OUT of the receipt exit-code namespace (10..50, see
26
+ * docs/RECEIPT-SPEC.md). The doctor is not part of the receipt protocol:
27
+ * 0 = no failures (warnings allowed)
28
+ * 1 = at least one failure
29
+ * 2 = the doctor itself could not run
30
+ */
31
+ import { existsSync, readFileSync, statSync, accessSync, constants } from 'node:fs'
32
+ import { resolve, dirname, join } from 'node:path'
33
+ import { fileURLToPath } from 'node:url'
34
+ import net from 'node:net'
35
+ import { createPublicKey, createPrivateKey } from 'node:crypto'
36
+
37
+ const ARGS = process.argv.slice(2)
38
+ const has = (f) => ARGS.includes(f)
39
+ const valueOf = (f, fallback) => {
40
+ const i = ARGS.indexOf(f)
41
+ return i >= 0 && ARGS[i + 1] ? ARGS[i + 1] : fallback
42
+ }
43
+
44
+ if (has('--help') || has('-h')) {
45
+ console.log(`conarium-doctor — check a Conarium install before it goes wrong
46
+
47
+ --config <path> config file (default: conarium.config.json in cwd)
48
+ --no-net skip the TCP reachability probe AND the npm version check
49
+ --help this text
50
+
51
+ Exit: 0 clean · 1 problems found · 2 doctor could not run
52
+ Secrets are never printed — values are reported as shape only.`)
53
+ process.exit(0)
54
+ }
55
+
56
+ const CONFIG_PATH = resolve(process.cwd(), valueOf('--config', 'conarium.config.json'))
57
+ const SKIP_NET = has('--no-net')
58
+
59
+ const results = []
60
+ const ok = (label, detail) => results.push({ level: 'ok', label, detail })
61
+ const warn = (label, detail, fix) => results.push({ level: 'warn', label, detail, fix })
62
+ const fail = (label, detail, fix) => results.push({ level: 'fail', label, detail, fix })
63
+
64
+ /* ---------------------------------------------------------------- helpers */
65
+
66
+ /** A DSN carries a password. Report only its shape. */
67
+ function describeDsn(raw) {
68
+ try {
69
+ const u = new URL(raw)
70
+ const db = u.pathname.replace(/^\//, '') || '(none)'
71
+ return {
72
+ scheme: u.protocol.replace(':', ''),
73
+ host: u.hostname,
74
+ port: u.port || (u.protocol === 'postgres:' || u.protocol === 'postgresql:' ? '5432' : ''),
75
+ user: u.username || '(none)',
76
+ hasPassword: Boolean(u.password),
77
+ db,
78
+ text: `${u.protocol}//${u.username || '(no user)'}@${u.hostname}${u.port ? ':' + u.port : ''}/${db}`,
79
+ }
80
+ } catch {
81
+ return null
82
+ }
83
+ }
84
+
85
+ function tcpProbe(host, port, timeoutMs = 4000) {
86
+ return new Promise((done) => {
87
+ const sock = new net.Socket()
88
+ let settled = false
89
+ const finish = (r) => {
90
+ if (settled) return
91
+ settled = true
92
+ sock.destroy()
93
+ done(r)
94
+ }
95
+ sock.setTimeout(timeoutMs)
96
+ sock.once('connect', () => finish({ reachable: true }))
97
+ sock.once('timeout', () => finish({ reachable: false, why: `no answer in ${timeoutMs}ms` }))
98
+ sock.once('error', (e) => finish({ reachable: false, why: e.code || e.message }))
99
+ sock.connect(Number(port), host)
100
+ })
101
+ }
102
+
103
+ function envSet(name) {
104
+ const v = process.env[name]
105
+ return typeof v === 'string' && v.trim() !== '' ? v : null
106
+ }
107
+
108
+ function cmpSemver(a, b) {
109
+ const pa = String(a).split('.').map((n) => parseInt(n, 10) || 0)
110
+ const pb = String(b).split('.').map((n) => parseInt(n, 10) || 0)
111
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
112
+ const da = pa[i] || 0
113
+ const db = pb[i] || 0
114
+ if (da > db) return 1
115
+ if (da < db) return -1
116
+ }
117
+ return 0
118
+ }
119
+
120
+ /* ------------------------------------------------------------- the checks */
121
+
122
+ // 1. Runtime
123
+ {
124
+ const major = Number(process.versions.node.split('.')[0])
125
+ if (Number.isNaN(major)) warn('Node runtime', `unrecognised version ${process.version}`, 'Conarium expects Node >= 18.')
126
+ else if (major < 18) fail('Node runtime', `${process.version} is below the supported floor`, 'Install Node 18 or newer.')
127
+ else ok('Node runtime', process.version)
128
+ }
129
+
130
+ // 1b. Installed version vs npm registry.
131
+ // Telemetry none: this is a GET for a version number. No install id, no
132
+ // hostname, no config, no license is sent. A bank reading this file should
133
+ // see that the only bytes leaving the box are an HTTP request for
134
+ // @conarium-ai/core's `latest` document. `--no-net` makes zero requests.
135
+ {
136
+ const pkgPath = join(dirname(fileURLToPath(import.meta.url)), '..', 'package.json')
137
+ let installed = null
138
+ try {
139
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'))
140
+ if (typeof pkg.version === 'string' && pkg.version) installed = pkg.version
141
+ } catch {
142
+ installed = null
143
+ }
144
+ if (!installed) {
145
+ warn('Version', `could not read ${pkgPath}`, 'Reinstall the package so package.json sits next to bin/.')
146
+ } else if (SKIP_NET) {
147
+ ok('Version', `${installed} (registry not queried: --no-net)`)
148
+ } else {
149
+ const url = envSet('CONARIUM_NPM_REGISTRY') || 'https://registry.npmjs.org/@conarium-ai/core/latest'
150
+ try {
151
+ const ac = new AbortController()
152
+ const timer = setTimeout(() => ac.abort(), 2000)
153
+ let latest
154
+ try {
155
+ const res = await fetch(url, { signal: ac.signal, headers: { accept: 'application/json' } })
156
+ if (!res.ok) throw new Error(`HTTP ${res.status}`)
157
+ const body = await res.json()
158
+ latest = body && typeof body.version === 'string' ? body.version : null
159
+ if (!latest) throw new Error('no version field')
160
+ } finally {
161
+ clearTimeout(timer)
162
+ }
163
+ if (latest === installed) {
164
+ ok('Version', `${installed} (matches npm latest)`)
165
+ } else if (cmpSemver(latest, installed) > 0) {
166
+ warn(
167
+ 'Version',
168
+ `${installed} installed; ${latest} is on npm`,
169
+ `npm i @conarium-ai/core@${latest}`,
170
+ )
171
+ } else {
172
+ ok('Version', `${installed} installed; npm latest is ${latest}`)
173
+ }
174
+ } catch (e) {
175
+ warn(
176
+ 'Version',
177
+ `${installed} installed; registry unreachable (${e.name === 'AbortError' ? 'timeout' : e.message})`,
178
+ 'Air-gapped is fine. Rerun without --no-net when you next have a network, or pin the version yourself.',
179
+ )
180
+ }
181
+ }
182
+ }
183
+
184
+ // 2. Config file — the silent one
185
+ let config = null
186
+ if (!existsSync(CONFIG_PATH)) {
187
+ fail(
188
+ 'Config file',
189
+ `not found at ${CONFIG_PATH}`,
190
+ 'Conarium does NOT fail on a missing config — it starts with zero connectors and governs nothing. ' +
191
+ 'Create the file, or pass --config <path> to both the doctor and the gateway.',
192
+ )
193
+ } else {
194
+ let raw
195
+ try {
196
+ raw = readFileSync(CONFIG_PATH, 'utf-8')
197
+ } catch (e) {
198
+ fail('Config file', `cannot read ${CONFIG_PATH}: ${e.code || e.message}`, 'Check file permissions.')
199
+ }
200
+ if (raw !== undefined) {
201
+ try {
202
+ config = JSON.parse(raw)
203
+ ok('Config file', CONFIG_PATH)
204
+ } catch (e) {
205
+ fail('Config file', `invalid JSON: ${e.message}`, 'Fix the syntax; the gateway will refuse to start until you do.')
206
+ }
207
+ }
208
+ }
209
+
210
+ // 3. Connectors + the fail-closed allow list
211
+ if (config) {
212
+ const connectors = Array.isArray(config.connectors) ? config.connectors : []
213
+ const allow = config.policy?.allowConnectors
214
+ if (connectors.length === 0) {
215
+ warn('Connectors', 'none configured', 'The gateway will start and expose no data. Add at least one connector.')
216
+ } else {
217
+ ok('Connectors', connectors.map((c) => `${c.name} (${c.type})`).join(', '))
218
+ if (!Array.isArray(allow) || allow.length === 0) {
219
+ fail(
220
+ 'policy.allowConnectors',
221
+ `${connectors.length} connector(s) configured but the allow list is empty`,
222
+ `Connectors are fail-closed: an empty list permits nothing. Add policy.allowConnectors: ${JSON.stringify(connectors.map((c) => c.name))}.`,
223
+ )
224
+ } else {
225
+ const unknown = allow.filter((n) => !connectors.some((c) => c.name === n))
226
+ const uncovered = connectors.filter((c) => !allow.includes(c.name)).map((c) => c.name)
227
+ if (unknown.length) warn('policy.allowConnectors', `names with no connector: ${unknown.join(', ')}`, 'Typo, or a connector was removed.')
228
+ if (uncovered.length) warn('policy.allowConnectors', `configured but not permitted: ${uncovered.join(', ')}`, 'These connectors will be refused at runtime.')
229
+ if (!unknown.length && !uncovered.length) ok('policy.allowConnectors', allow.join(', '))
230
+ }
231
+ }
232
+
233
+ // 4. Is anything actually being protected?
234
+ const pol = config.policy || {}
235
+ const hasMask = Array.isArray(pol.maskColumns) && pol.maskColumns.length > 0
236
+ const hasDeny = Array.isArray(pol.denyTables) && pol.denyTables.length > 0
237
+ const hasAllowTables = Array.isArray(pol.allowTables) && pol.allowTables.length > 0
238
+ if (!hasMask && !hasDeny && !hasAllowTables) {
239
+ warn(
240
+ 'Policy surface',
241
+ 'no maskColumns, no denyTables, no allowTables',
242
+ 'Content detectors (email / national id / card / secrets) still run, but no column or table rule is set. ' +
243
+ 'That is a valid choice — make sure it is a choice.',
244
+ )
245
+ } else {
246
+ ok('Policy surface', [hasAllowTables && 'allowTables', hasDeny && 'denyTables', hasMask && 'maskColumns'].filter(Boolean).join(' + '))
247
+ }
248
+
249
+ // 5. Per-person profiles need per-user credentials
250
+ const profiles = pol.profiles || pol.actorProfiles
251
+ if (profiles && Object.keys(profiles).length > 0) {
252
+ if (envSet('CONARIUM_MCP_TOKEN')) {
253
+ warn(
254
+ 'Masking profiles',
255
+ 'profiles are configured while a shared token is in use',
256
+ 'A profile only applies to a per-user credential. With a shared token every caller falls back to the base policy — ' +
257
+ 'the profiles are silently ignored.',
258
+ )
259
+ } else {
260
+ ok('Masking profiles', `${Object.keys(profiles).length} profile(s)`)
261
+ }
262
+ }
263
+
264
+ // 6. Receipts need an Ed25519 key
265
+ const receiptSink = config.audit?.receiptSink
266
+ const signingKeyPath = envSet('CONARIUM_AUDIT_SIGNING_KEY')
267
+ if (receiptSink && !signingKeyPath) {
268
+ fail(
269
+ 'Receipt signing key',
270
+ 'audit.receiptSink is configured but CONARIUM_AUDIT_SIGNING_KEY is not set',
271
+ 'Receipts require Ed25519 (HMAC is not sufficient). Set the key, or remove receiptSink.',
272
+ )
273
+ }
274
+
275
+ // 7. Audit sink writability
276
+ const sink = config.audit?.sink
277
+ if (sink) {
278
+ const sinkPath = resolve(process.cwd(), sink)
279
+ const dir = dirname(sinkPath)
280
+ if (!existsSync(dir)) {
281
+ fail('Audit sink', `directory does not exist: ${dir}`, 'Create it, or point audit.sink somewhere that exists.')
282
+ } else {
283
+ try {
284
+ accessSync(dir, constants.W_OK)
285
+ ok('Audit sink', sinkPath + (existsSync(sinkPath) ? ` (${statSync(sinkPath).size} bytes)` : ' (will be created)'))
286
+ } catch {
287
+ fail('Audit sink', `directory is not writable: ${dir}`, 'The gateway is fail-closed on audit: it will refuse to serve.')
288
+ }
289
+ }
290
+ }
291
+ }
292
+
293
+ // 8. Signing key material — never printed, only described
294
+ {
295
+ const keyPath = envSet('CONARIUM_AUDIT_SIGNING_KEY')
296
+ const hmac = envSet('CONARIUM_AUDIT_HMAC_KEY')
297
+ const unsigned = envSet('CONARIUM_AUDIT_UNSIGNED')
298
+ if (!keyPath && !hmac && !unsigned) {
299
+ warn(
300
+ 'Audit signing',
301
+ 'no CONARIUM_AUDIT_SIGNING_KEY, no CONARIUM_AUDIT_HMAC_KEY, no CONARIUM_AUDIT_UNSIGNED',
302
+ 'The audit writer refuses to write unsigned entries. Set one of the three before first use.',
303
+ )
304
+ }
305
+ if (keyPath) {
306
+ const resolved = resolve(process.cwd(), keyPath)
307
+ if (!existsSync(resolved)) {
308
+ fail('Signing key', `CONARIUM_AUDIT_SIGNING_KEY points at a missing file: ${resolved}`, 'Check the path. The value is read as a FILE path, not as key material.')
309
+ } else {
310
+ try {
311
+ const pem = readFileSync(resolved, 'utf-8')
312
+ const key = createPrivateKey(pem)
313
+ if (key.asymmetricKeyType !== 'ed25519') {
314
+ fail('Signing key', `expected Ed25519, found ${key.asymmetricKeyType}`, 'Generate an Ed25519 key pair.')
315
+ } else {
316
+ ok('Signing key', `Ed25519 private key at ${resolved}`)
317
+ }
318
+ } catch (e) {
319
+ fail('Signing key', `unreadable or not a private key: ${e.message}`, 'The file must be a PEM-encoded Ed25519 private key.')
320
+ }
321
+ }
322
+ }
323
+ }
324
+
325
+ // 9. Public keys used for verification need their .keyid sidecar.
326
+ // Without it the verifier returns 13 for EVERY receipt — and the operator
327
+ // blames the receipts, not the missing file.
328
+ {
329
+ const trust = envSet('CONARIUM_AUDIT_TRUST_PUBKEYS')
330
+ if (trust) {
331
+ for (const p of trust.split(',').map((s) => s.trim()).filter(Boolean)) {
332
+ const pubPath = resolve(process.cwd(), p)
333
+ if (!existsSync(pubPath)) {
334
+ fail('Trusted public key', `missing file: ${pubPath}`, 'Check CONARIUM_AUDIT_TRUST_PUBKEYS.')
335
+ continue
336
+ }
337
+ try {
338
+ const k = createPublicKey(readFileSync(pubPath, 'utf-8'))
339
+ if (k.asymmetricKeyType !== 'ed25519') {
340
+ fail('Trusted public key', `expected Ed25519 at ${pubPath}, got ${k.asymmetricKeyType}`, 'Use the matching Ed25519 public key.')
341
+ continue
342
+ }
343
+ } catch (e) {
344
+ fail('Trusted public key', `invalid PEM at ${pubPath}: ${e.message}`, 'Re-export the public key.')
345
+ continue
346
+ }
347
+ const sidecar = `${pubPath}.keyid`
348
+ if (!existsSync(sidecar)) {
349
+ fail(
350
+ 'keyId sidecar',
351
+ `missing: ${sidecar}`,
352
+ 'The verifier requires <pubkey>.keyid next to every trusted public key. Without it EVERY receipt fails with exit 13, ' +
353
+ 'which reads like tampering and is not.',
354
+ )
355
+ } else if (readFileSync(sidecar, 'utf-8').trim() === '') {
356
+ fail('keyId sidecar', `empty: ${sidecar}`, 'It must contain the key id used when the receipts were signed.')
357
+ } else {
358
+ ok('Trusted public key', `${pubPath} (+ keyid sidecar)`)
359
+ }
360
+ }
361
+ }
362
+ }
363
+
364
+ // 10. Anchoring is an optional peer dependency since 0.1.0.
365
+ {
366
+ const anchoring = Boolean(envSet('CONARIUM_ANCHOR_BASE_URL') || envSet('CONARIUM_ANCHOR_STORE') || config?.audit?.anchor)
367
+ if (anchoring) {
368
+ let present = false
369
+ try {
370
+ await import('javascript-opentimestamps')
371
+ present = true
372
+ } catch {
373
+ present = false
374
+ }
375
+ if (present) ok('Anchoring', 'configured, javascript-opentimestamps present')
376
+ else
377
+ fail(
378
+ 'Anchoring',
379
+ 'configured, but javascript-opentimestamps is not installed',
380
+ 'It is an OPTIONAL peer dependency (its transitive tree carried known vulnerabilities, so it is not installed by default). ' +
381
+ 'Run: npm install javascript-opentimestamps — or turn anchoring off. Until then the verifier reports exit 15 (could not check).',
382
+ )
383
+ }
384
+ }
385
+
386
+ // 11. Connector endpoints — described always, probed only when networking is on.
387
+ // `--no-net` must silence the network, not the diagnosis: an operator on an
388
+ // air-gapped box still needs to see which endpoint the config points at.
389
+ if (config) {
390
+ const targets = []
391
+ for (const c of Array.isArray(config.connectors) ? config.connectors : []) {
392
+ const url = c?.config?.url
393
+ if (typeof url !== 'string') continue
394
+ const raw = url.startsWith('env:') ? process.env[url.slice(4)] : url
395
+ if (!raw) {
396
+ fail('Connector DSN', `${c.name}: config points at env ${url.slice(4)} which is not set`, 'Export the variable before starting the gateway.')
397
+ continue
398
+ }
399
+ const d = describeDsn(raw)
400
+ if (!d) {
401
+ fail('Connector DSN', `${c.name}: value is not a parseable URL`, 'Expected e.g. postgresql://user:pass@host:5432/db')
402
+ continue
403
+ }
404
+ // Always show WHICH endpoint was checked — an operator debugging a wrong
405
+ // environment needs to see it, and it is the only line where a DSN is
406
+ // rendered at all, so the redaction is exercised on every run (and by the
407
+ // test suite) instead of only in the no-password branch.
408
+ if (!d.hasPassword && d.user !== '(none)') {
409
+ warn('Connector DSN', `${c.name}: ${d.text} — no password in the DSN`, 'Fine if you authenticate another way; surprising otherwise.')
410
+ } else {
411
+ ok('Connector DSN', `${c.name}: ${d.text}${d.hasPassword ? ' (password set, not shown)' : ''}`)
412
+ }
413
+ if (d.host && d.port) targets.push({ name: c.name, ...d })
414
+ }
415
+ for (const t of SKIP_NET ? [] : targets) {
416
+ const r = await tcpProbe(t.host, t.port)
417
+ if (r.reachable) ok('Reachability', `${t.name}: ${t.host}:${t.port} answers`)
418
+ else
419
+ fail(
420
+ 'Reachability',
421
+ `${t.name}: ${t.host}:${t.port} unreachable (${r.why})`,
422
+ 'The gateway logs connector failures and keeps running with zero connectors — it will look healthy and serve nothing.',
423
+ )
424
+ }
425
+ }
426
+
427
+ // 12. License pack — offline, never fail-closed. A broken license file must
428
+ // not lock the MIT core. Missing file = community.
429
+ {
430
+ const licensePath = envSet('CONARIUM_LICENSE_FILE') || join(process.cwd(), 'conarium.license.json')
431
+ const pubPath = envSet('CONARIUM_LICENSE_PUBKEY')
432
+ if (!existsSync(licensePath)) {
433
+ ok('License', 'community (no license file)')
434
+ } else {
435
+ let verifier = null
436
+ try {
437
+ verifier = await import('../dist/license.js')
438
+ } catch {
439
+ verifier = null
440
+ }
441
+ if (!verifier?.verifyLicense) {
442
+ warn(
443
+ 'License',
444
+ `file present at ${licensePath} but the verifier is not built`,
445
+ 'Run npm run build, or ignore this — the MIT core stays community either way.',
446
+ )
447
+ } else if (!pubPath) {
448
+ warn(
449
+ 'License',
450
+ `file present at ${licensePath} but CONARIUM_LICENSE_PUBKEY is not set — treating as community`,
451
+ 'Set the pubkey path to verify offline. Until then the MIT core stays community.',
452
+ )
453
+ } else if (!existsSync(pubPath)) {
454
+ warn('License', `CONARIUM_LICENSE_PUBKEY points at a missing file — treating as community`, 'Check the path.')
455
+ } else {
456
+ const r = verifier.verifyLicense(readFileSync(licensePath, 'utf-8'), readFileSync(pubPath, 'utf-8'))
457
+ if (r.valid) ok('License', `${r.tier}${r.customer ? ` · ${r.customer}` : ''}${r.expiresAt ? ` · expires ${r.expiresAt}` : ''}`)
458
+ else ok('License', `community (${r.reason})`)
459
+ }
460
+ }
461
+ }
462
+
463
+ /* ------------------------------------------------------------------ report */
464
+
465
+ const ICON = { ok: ' ok ', warn: ' warn ', fail: ' FAIL ' }
466
+ console.log('')
467
+ console.log('conarium doctor')
468
+ console.log('─'.repeat(66))
469
+ for (const r of results) {
470
+ console.log(`[${ICON[r.level]}] ${r.label}: ${r.detail}`)
471
+ if (r.fix && r.level !== 'ok') console.log(` → ${r.fix}`)
472
+ }
473
+ const fails = results.filter((r) => r.level === 'fail').length
474
+ const warns = results.filter((r) => r.level === 'warn').length
475
+ console.log('─'.repeat(66))
476
+ console.log(`${results.length} checks · ${fails} failed · ${warns} warning(s)`)
477
+ if (fails === 0 && warns === 0) console.log('This install is ready.')
478
+ if (fails > 0) console.log('Fix the FAIL lines above; the gateway will not govern correctly until you do.')
479
+ console.log('')
480
+ process.exit(fails > 0 ? 1 : 0)
@@ -0,0 +1,184 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * conarium-init — write a fail-closed skeleton so the operator does not
4
+ * copy config, MCP JSON and a key pair by hand (and forget the .keyid sidecar).
5
+ *
6
+ * Standalone: Node builtins only. No imports from src/ or dist/.
7
+ *
8
+ * Exit: 0 wrote · 1 refused (exists / cannot write) · 2 could not run
9
+ * Secrets never go to stdout — paths only, never PEM bodies.
10
+ */
11
+ import {
12
+ existsSync,
13
+ mkdirSync,
14
+ writeFileSync,
15
+ chmodSync,
16
+ } from 'node:fs'
17
+ import { resolve, join, dirname } from 'node:path'
18
+ import { generateKeyPairSync, createHash } from 'node:crypto'
19
+ import { platform } from 'node:os'
20
+ import { fileURLToPath } from 'node:url'
21
+
22
+ const ARGS = process.argv.slice(2)
23
+ const has = (f) => ARGS.includes(f)
24
+ const valueOf = (f, fallback) => {
25
+ const i = ARGS.indexOf(f)
26
+ return i >= 0 && ARGS[i + 1] ? ARGS[i + 1] : fallback
27
+ }
28
+
29
+ if (has('--help') || has('-h')) {
30
+ console.log(`conarium-init — write a fail-closed Conarium skeleton
31
+
32
+ --out <dir> destination (default: current directory)
33
+ --force overwrite existing files
34
+ --no-keys skip the Ed25519 key pair
35
+ --help this text
36
+
37
+ Exit: 0 wrote · 1 refused · 2 could not run
38
+ Signing-key material is never printed — only its path.`)
39
+ process.exit(0)
40
+ }
41
+
42
+ const OUT = resolve(process.cwd(), valueOf('--out', '.'))
43
+ const FORCE = has('--force')
44
+ const NO_KEYS = has('--no-keys')
45
+
46
+ const CONFIG_NAME = 'conarium.config.json'
47
+ const KEY_BASE = 'audit-ed25519'
48
+ const SIGNING_NAME = `${KEY_BASE}.pem`
49
+ const PUBLIC_NAME = `${KEY_BASE}.pub.pem`
50
+
51
+ function die(code, msg) {
52
+ console.error(msg)
53
+ process.exit(code)
54
+ }
55
+
56
+ function keyIdFromPublicPem(publicPem) {
57
+ return createHash('sha256').update(publicPem.trim(), 'utf8').digest('hex').slice(0, 16)
58
+ }
59
+
60
+ const SKELETON = {
61
+ serverName: 'Conarium',
62
+ consumer: 'ai-assistant',
63
+ connectors: [
64
+ {
65
+ type: 'postgres',
66
+ name: 'maindb',
67
+ description: 'Replace the URL with your read-only DSN before going live.',
68
+ config: {
69
+ url: 'postgresql://app:changeme@127.0.0.1:5432/yourdb',
70
+ },
71
+ },
72
+ ],
73
+ policy: {
74
+ allowConnectors: ['maindb'],
75
+ allowTables: [],
76
+ denyTables: ['public.secrets', 'public.credit_cards'],
77
+ maskColumns: ['*.email', '*.phone', '*.tckn', '*.iban', '*.ssn', '*.national_id'],
78
+ maxRows: 50,
79
+ },
80
+ audit: {
81
+ sink: 'conarium-audit.jsonl',
82
+ failClosed: true,
83
+ },
84
+ }
85
+
86
+ try {
87
+ mkdirSync(OUT, { recursive: true })
88
+ } catch (e) {
89
+ die(2, `cannot create ${OUT}: ${e.message}`)
90
+ }
91
+
92
+ const configPath = join(OUT, CONFIG_NAME)
93
+ const signingKeyPath = join(OUT, SIGNING_NAME)
94
+ const publicPath = join(OUT, PUBLIC_NAME)
95
+ const signingKeyIdPath = `${signingKeyPath}.keyid`
96
+ const publicKeyIdPath = `${publicPath}.keyid`
97
+
98
+ const planned = [configPath]
99
+ if (!NO_KEYS) planned.push(signingKeyPath, publicPath, signingKeyIdPath, publicKeyIdPath)
100
+
101
+ if (!FORCE) {
102
+ const clashes = planned.filter((p) => existsSync(p))
103
+ if (clashes.length) {
104
+ die(1, `refusing to overwrite (pass --force):\n ${clashes.join('\n ')}`)
105
+ }
106
+ }
107
+
108
+ const writeOpts = FORCE ? { encoding: 'utf-8' } : { encoding: 'utf-8', flag: 'wx' }
109
+
110
+ const config = structuredClone(SKELETON)
111
+ if (!NO_KEYS) {
112
+ // Receipts need Ed25519. Writing receiptSink without a key makes the doctor
113
+ // FAIL (not warn) — so this field only appears when we also write the pair.
114
+ config.audit.receiptSink = 'conarium-receipts.jsonl'
115
+ }
116
+
117
+ try {
118
+ writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n', writeOpts)
119
+ } catch (e) {
120
+ die(1, `cannot write ${configPath}: ${e.code || e.message}`)
121
+ }
122
+
123
+ let keyId = null
124
+ if (!NO_KEYS) {
125
+ const pair = generateKeyPairSync('ed25519')
126
+ const signingPem = pair.privateKey.export({ type: 'pkcs8', format: 'pem' }).toString()
127
+ const publicPem = pair.publicKey.export({ type: 'spki', format: 'pem' }).toString()
128
+ keyId = keyIdFromPublicPem(publicPem)
129
+ try {
130
+ writeFileSync(signingKeyPath, signingPem, writeOpts)
131
+ writeFileSync(publicPath, publicPem, writeOpts)
132
+ writeFileSync(signingKeyIdPath, keyId + '\n', writeOpts)
133
+ writeFileSync(publicKeyIdPath, keyId + '\n', writeOpts)
134
+ } catch (e) {
135
+ die(1, `cannot write key files: ${e.code || e.message}`)
136
+ }
137
+ if (platform() !== 'win32') {
138
+ try {
139
+ chmodSync(signingKeyPath, 0o600)
140
+ } catch {
141
+ // best-effort; doctor will still accept the key
142
+ }
143
+ }
144
+ }
145
+
146
+ const pkgRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')
147
+ const gatewayJs = join(pkgRoot, 'dist', 'index.js')
148
+
149
+ console.log('')
150
+ console.log('conarium init')
151
+ console.log('─'.repeat(66))
152
+ console.log(`wrote ${configPath}`)
153
+ console.log(' allowTables is empty on purpose — add schema-qualified')
154
+ console.log(' names (public.customers) or the gateway will deny every table.')
155
+ console.log(' maskColumns and denyTables are already set. Replace the')
156
+ console.log(' postgres URL before going live (placeholder DSN).')
157
+ if (!NO_KEYS) {
158
+ console.log(`wrote ${signingKeyPath} (Ed25519, mode 0600 where supported)`)
159
+ console.log(`wrote ${publicPath}`)
160
+ console.log(`wrote ${publicKeyIdPath} (keyId ${keyId})`)
161
+ console.log(`wrote ${signingKeyIdPath}`)
162
+ }
163
+ console.log('')
164
+ console.log('Next:')
165
+ if (!NO_KEYS) {
166
+ console.log(` export CONARIUM_AUDIT_SIGNING_KEY=${signingKeyPath}`)
167
+ console.log(` export CONARIUM_AUDIT_TRUST_PUBKEYS=${publicPath}`)
168
+ }
169
+ console.log(' conarium-doctor --no-net')
170
+ console.log('')
171
+ console.log('MCP client block (Cursor / Claude Code) — paste into mcp.json:')
172
+ console.log(JSON.stringify({
173
+ mcpServers: {
174
+ conarium: {
175
+ command: 'node',
176
+ args: [gatewayJs],
177
+ env: NO_KEYS
178
+ ? {}
179
+ : { CONARIUM_AUDIT_SIGNING_KEY: signingKeyPath },
180
+ },
181
+ },
182
+ }, null, 2))
183
+ console.log('')
184
+ process.exit(0)