@conarium-ai/core 0.2.1 → 0.2.3

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.
@@ -0,0 +1,63 @@
1
+ # Per-user identity — local pack (Hetzner stays untouched)
2
+
3
+ Today a shared token writes `assurance: shared-token` and names nobody.
4
+ The code for `policy.profiles` / `policy.actorProfiles` is already in
5
+ `src/governance.ts`. This directory is the operator kit to turn it on
6
+ **locally**, prove it, and roll it back. Copying to `/opt/conarium-mcp`
7
+ is a separate patron decision.
8
+
9
+ ## 1. Mint tokens (hash only on disk)
10
+
11
+ ```bash
12
+ node examples/per-user-identity/mint-token.mjs --id emekcan --file ./conarium.tokens.json
13
+ node examples/per-user-identity/mint-token.mjs --id copilot --file ./conarium.tokens.json
14
+ ```
15
+
16
+ Stdout prints the raw token **once**. The file stores `{ sha256, id }` only.
17
+ POSIX mode `0600`. Point the gateway at it:
18
+
19
+ ```bash
20
+ export CONARIUM_TOKENS_FILE=$PWD/conarium.tokens.json
21
+ ```
22
+
23
+ Do not commit `conarium.tokens.json` or the raw tokens.
24
+
25
+ ## 2. Config overlay (c2)
26
+
27
+ Merge `policy.overlay.json` under `policy` of the live c2
28
+ config. Do **not** replace `allowTables` / connectors.
29
+
30
+ - Base (AI / unlisted actor): names stay masked.
31
+ - `emekcan` → profile `patron`: name columns visible; email / TCKN / IBAN
32
+ scanners still run (a profile cannot switch those off).
33
+
34
+ Backup first:
35
+
36
+ ```bash
37
+ cp conarium.config.c2.json conarium.config.c2.json.bak
38
+ ```
39
+
40
+ ## 3. Local proof (this machine, not Hetzner)
41
+
42
+ ```bash
43
+ npm run build
44
+ node examples/per-user-identity/prove-identity.mjs
45
+ ```
46
+
47
+ Same row, two tokens: patron sees the name, the other sees `[MASKED_PII]`.
48
+ Both receipts carry `assurance: per-user-token`. The patron receipt's
49
+ `policy.id` is `conarium.policy/patron`; the other stays `conarium.policy`.
50
+ `conarium-verify` must exit 0.
51
+
52
+ ## 4. Rollback (one command)
53
+
54
+ ```bash
55
+ # POSIX
56
+ cp conarium.config.c2.json.bak conarium.config.c2.json && unset CONARIUM_TOKENS_FILE
57
+
58
+ # Windows PowerShell
59
+ Copy-Item conarium.config.c2.json.bak conarium.config.c2.json -Force; Remove-Item Env:CONARIUM_TOKENS_FILE -ErrorAction SilentlyContinue
60
+ ```
61
+
62
+ Leave the tokens file in place or delete it; without `CONARIUM_TOKENS_FILE`
63
+ every caller is `shared-token` again. No Hetzner restart is part of this pack.
@@ -0,0 +1,92 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Mint a per-user token into conarium.tokens.json.
4
+ *
5
+ * The file stores SHA-256 only. The raw token is printed once, to stdout,
6
+ * and is never written. 0600 on POSIX.
7
+ *
8
+ * node mint-token.mjs --id emekcan [--file ./conarium.tokens.json]
9
+ *
10
+ * Exit: 0 wrote · 1 refused · 2 could not run
11
+ */
12
+ import { createHash, randomBytes } from 'node:crypto'
13
+ import { existsSync, readFileSync, writeFileSync, chmodSync, mkdirSync } from 'node:fs'
14
+ import { dirname, resolve } from 'node:path'
15
+ import { platform } from 'node:os'
16
+
17
+ const ARGS = process.argv.slice(2)
18
+ const has = (f) => ARGS.includes(f)
19
+ const valueOf = (f, fallback) => {
20
+ const i = ARGS.indexOf(f)
21
+ return i >= 0 && ARGS[i + 1] ? ARGS[i + 1] : fallback
22
+ }
23
+
24
+ if (has('--help') || has('-h')) {
25
+ console.log(`conarium mint-token — append a hashed per-user token
26
+
27
+ --id <actor> person id written on the receipt (required)
28
+ --file <path> tokens file (default: ./conarium.tokens.json)
29
+ --bytes <n> raw token length (default: 32)
30
+
31
+ The raw token is printed once. It is not stored.`)
32
+ process.exit(0)
33
+ }
34
+
35
+ const id = valueOf('--id', '')
36
+ if (!id || id.startsWith('--')) {
37
+ console.error('refusing: --id <actor> is required')
38
+ process.exit(1)
39
+ }
40
+
41
+ const file = resolve(process.cwd(), valueOf('--file', './conarium.tokens.json'))
42
+ const bytes = Number(valueOf('--bytes', '32'))
43
+ if (!Number.isInteger(bytes) || bytes < 24 || bytes > 64) {
44
+ console.error('refusing: --bytes must be an integer 24–64')
45
+ process.exit(1)
46
+ }
47
+
48
+ const raw = randomBytes(bytes).toString('base64url')
49
+ const sha256 = createHash('sha256').update(raw).digest('hex')
50
+
51
+ let doc = { tokens: [] }
52
+ if (existsSync(file)) {
53
+ try {
54
+ doc = JSON.parse(readFileSync(file, 'utf8'))
55
+ } catch (e) {
56
+ console.error(`cannot read ${file}: ${e.message}`)
57
+ process.exit(2)
58
+ }
59
+ if (!Array.isArray(doc.tokens)) doc.tokens = []
60
+ }
61
+
62
+ if (doc.tokens.some((t) => t && t.sha256 === sha256)) {
63
+ console.error('refusing: hash collision (rerun)')
64
+ process.exit(1)
65
+ }
66
+
67
+ doc.tokens.push({ sha256, id })
68
+
69
+ try {
70
+ mkdirSync(dirname(file), { recursive: true })
71
+ writeFileSync(file, JSON.stringify(doc, null, 2) + '\n', { encoding: 'utf8' })
72
+ if (platform() !== 'win32') {
73
+ try { chmodSync(file, 0o600) } catch { /* doctor still accepts */ }
74
+ }
75
+ } catch (e) {
76
+ console.error(`cannot write ${file}: ${e.message}`)
77
+ process.exit(2)
78
+ }
79
+
80
+ const stored = readFileSync(file, 'utf8')
81
+ if (stored.includes(raw)) {
82
+ console.error('refusing: raw token leaked into the file — not printing it')
83
+ process.exit(2)
84
+ }
85
+
86
+ console.log(`id ${id}`)
87
+ console.log(`sha256 ${sha256}`)
88
+ console.log(`file ${file}`)
89
+ console.log(`token ${raw}`)
90
+ console.log('')
91
+ console.log('The token line is the only copy. Put it in the client env, not in git.')
92
+ process.exit(0)
@@ -0,0 +1,15 @@
1
+ {
2
+ "_comment": "Overlay for a live conarium.config.c2.json. Merge under policy. Do not replace allowTables/denyTables/connectors. Base policy (AI) keeps names masked; the patron profile unmasks name columns only. Email/TCKN/IBAN scanners still run.",
3
+ "policy": {
4
+ "maskColumns": ["*.customer_name", "*.email", "*.phone", "*.tckn", "*.iban"],
5
+ "profiles": {
6
+ "patron": {
7
+ "maskColumns": ["*.email", "*.phone", "*.tckn", "*.iban"],
8
+ "maskLabelledNames": false
9
+ }
10
+ },
11
+ "actorProfiles": {
12
+ "emekcan": "patron"
13
+ }
14
+ }
15
+ }
@@ -0,0 +1,138 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Local proof: same row, two tokens, two receipts.
4
+ * Does not talk to Hetzner. Needs a built dist/ (npm run build).
5
+ */
6
+ import { createHash, randomBytes } from 'node:crypto'
7
+ import { mkdtempSync, writeFileSync, readFileSync, mkdirSync } from 'node:fs'
8
+ import { join, dirname, resolve } from 'node:path'
9
+ import { tmpdir } from 'node:os'
10
+ import { spawnSync } from 'node:child_process'
11
+ import { fileURLToPath, pathToFileURL } from 'node:url'
12
+
13
+ const here = dirname(fileURLToPath(import.meta.url))
14
+ const root = resolve(here, '..', '..')
15
+ const distGov = join(root, 'dist', 'governance.js')
16
+ const distAudit = join(root, 'dist', 'audit.js')
17
+ const distTokens = join(root, 'dist', 'tokens.js')
18
+ const distKeys = join(root, 'dist', 'keys.js')
19
+ const verifyJs = join(root, 'bin', 'conarium-verify.mjs')
20
+
21
+ function fail(msg) {
22
+ console.error(`FAIL ${msg}`)
23
+ process.exit(1)
24
+ }
25
+
26
+ const { Governance } = await import(pathToFileURL(distGov).href)
27
+ const { Audit } = await import(pathToFileURL(distAudit).href)
28
+ const { loadTokenStore, resolveActor } = await import(pathToFileURL(distTokens).href)
29
+ const { writeKeyPairFiles } = await import(pathToFileURL(distKeys).href)
30
+
31
+ const dir = mkdtempSync(join(tmpdir(), 'cnr-identity-'))
32
+ const tokensFile = join(dir, 'conarium.tokens.json')
33
+ const receiptSink = join(dir, 'receipts.jsonl')
34
+ const auditSink = join(dir, 'audit.jsonl')
35
+ mkdirSync(dir, { recursive: true })
36
+
37
+ const patronRaw = randomBytes(32).toString('base64url')
38
+ const aiRaw = randomBytes(32).toString('base64url')
39
+ writeFileSync(tokensFile, JSON.stringify({
40
+ tokens: [
41
+ { sha256: createHash('sha256').update(patronRaw).digest('hex'), id: 'emekcan' },
42
+ { sha256: createHash('sha256').update(aiRaw).digest('hex'), id: 'copilot' },
43
+ ],
44
+ }) + '\n')
45
+
46
+ const keyFiles = writeKeyPairFiles(join(dir, 'audit-ed25519'), 'cnr-identity-demo')
47
+ process.env.CONARIUM_AUDIT_SIGNING_KEY = keyFiles.privatePath
48
+ process.env.CONARIUM_AUDIT_TRUST_PUBKEYS = keyFiles.publicPath
49
+ delete process.env.CONARIUM_AUDIT_UNSIGNED
50
+
51
+ const policy = {
52
+ allowTables: ['public.customers'],
53
+ maskColumns: ['*.customer_name', '*.email', '*.phone', '*.tckn', '*.iban'],
54
+ profiles: {
55
+ patron: {
56
+ maskColumns: ['*.email', '*.phone', '*.tckn', '*.iban'],
57
+ maskLabelledNames: false,
58
+ },
59
+ },
60
+ actorProfiles: { emekcan: 'patron' },
61
+ }
62
+
63
+ const store = loadTokenStore(tokensFile)
64
+ const patron = resolveActor(patronRaw, store, 'conarium_c2')
65
+ const ai = resolveActor(aiRaw, store, 'conarium_c2')
66
+ if (patron.assurance !== 'per-user-token' || patron.id !== 'emekcan') fail(`patron resolve: ${JSON.stringify(patron)}`)
67
+ if (ai.assurance !== 'per-user-token' || ai.id !== 'copilot') fail(`ai resolve: ${JSON.stringify(ai)}`)
68
+
69
+ const row = { _table: 'public.customers', customer_name: 'Ayşe Yılmaz', email: 'a@b.com', city: 'İzmir' }
70
+ const base = new Governance(policy)
71
+ const asPatron = base.forActor(patron)
72
+ const asAi = base.forActor(ai)
73
+
74
+ const patronOut = asPatron.redact({ rows: [row], rowCount: 1, fields: Object.keys(row) })
75
+ const aiOut = asAi.redact({ rows: [row], rowCount: 1, fields: Object.keys(row) })
76
+ const pName = patronOut.rows[0].customer_name
77
+ const aName = aiOut.rows[0].customer_name
78
+
79
+ console.log(`patron name ${pName}`)
80
+ console.log(`ai name ${aName}`)
81
+ console.log(`patron email ${patronOut.rows[0].email}`)
82
+ console.log(`ai email ${aiOut.rows[0].email}`)
83
+
84
+ if (pName !== 'Ayşe Yılmaz') fail(`patron should see the name, got ${pName}`)
85
+ if (aName !== '[MASKED_PII]') fail(`ai should see [MASKED_PII], got ${aName}`)
86
+ if (patronOut.rows[0].email !== '[MASKED_PII]' || aiOut.rows[0].email !== '[MASKED_PII]') {
87
+ fail('email must stay masked for both (content scanner / remaining maskColumns)')
88
+ }
89
+
90
+ const audit = new Audit({ sink: auditSink, receiptSink, consumer: 'conarium_c2', failClosed: true })
91
+ audit.log({
92
+ tool: 'query',
93
+ target: 'public.customers',
94
+ denied: false,
95
+ actor: patron.id,
96
+ actorAssurance: patron.assurance,
97
+ policyProfile: asPatron.appliedProfile() || undefined,
98
+ rowsReturned: 1,
99
+ source: 'postgres',
100
+ })
101
+ audit.log({
102
+ tool: 'query',
103
+ target: 'public.customers',
104
+ denied: false,
105
+ actor: ai.id,
106
+ actorAssurance: ai.assurance,
107
+ policyProfile: asAi.appliedProfile() || undefined,
108
+ rowsReturned: 1,
109
+ source: 'postgres',
110
+ })
111
+
112
+ const receipts = readFileSync(receiptSink, 'utf8').trim().split('\n').map((l) => JSON.parse(l))
113
+ if (receipts.length !== 2) fail(`expected 2 receipts, got ${receipts.length}`)
114
+
115
+ const [rPatron, rAi] = receipts
116
+ console.log(`patron policy.id ${rPatron.policy.id}`)
117
+ console.log(`patron assurance ${rPatron.actor.assurance} actor.id=${rPatron.actor.id}`)
118
+ console.log(`ai policy.id ${rAi.policy.id}`)
119
+ console.log(`ai assurance ${rAi.actor.assurance} actor.id=${rAi.actor.id}`)
120
+
121
+ if (rPatron.policy.id !== 'conarium.policy/patron') fail(`patron policy.id ${rPatron.policy.id}`)
122
+ if (rAi.policy.id !== 'conarium.policy') fail(`ai (no profile) policy.id ${rAi.policy.id}`)
123
+ if (rPatron.actor.assurance !== 'per-user-token' || rAi.actor.assurance !== 'per-user-token') {
124
+ fail('both receipts must carry per-user-token')
125
+ }
126
+
127
+ const v = spawnSync(process.execPath, [verifyJs, receiptSink, '--pubkey', keyFiles.publicPath], {
128
+ encoding: 'utf8',
129
+ env: process.env,
130
+ })
131
+ process.stdout.write(v.stdout || '')
132
+ process.stderr.write(v.stderr || '')
133
+ if (v.status !== 0) fail(`conarium-verify exit ${v.status}`)
134
+ if (!String(v.stdout || v.stderr || '').includes('verified')) fail('verify output missing verified')
135
+
136
+ console.log('PASS same query, two tokens, two receipts, verify EXIT 0')
137
+ console.log(`artefacts in ${dir} (temp; not Hetzner)`)
138
+ process.exit(0)
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ # Restore c2 policy to the backup taken before the identity overlay.
3
+ # Does not touch Hetzner. Run from the directory that holds the config.
4
+ set -euo pipefail
5
+ test -f conarium.config.c2.json.bak || { echo "missing conarium.config.c2.json.bak"; exit 1; }
6
+ cp conarium.config.c2.json.bak conarium.config.c2.json
7
+ unset CONARIUM_TOKENS_FILE || true
8
+ echo "restored conarium.config.c2.json from .bak; CONARIUM_TOKENS_FILE unset"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@conarium-ai/core",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "//files-artefakt": "examples/ altindaki uretilmis dosyalar (ozel anahtar, makbuz/denetim JSONL) ELENIR. .gitignore npm'i baglamaz: izin listesinde 'examples' oldugu icin demoyu kosturmus bir makinede 'npm publish' _keys/audit-ed25519.pem'i (OZEL ANAHTAR) ve makbuzlari yayinliyordu. test/pack_artefakt.mjs bunu kilitler. Elemeler examples/ ile SINIRLI: test-vectors/ altindaki receipts.jsonl ve .pub.pem YAYINLANMAK ZORUNDA, yoksa ucuncu taraf konformans vektorlerini kosturamaz.",
5
5
  "//files": "Pakete NE gireceginin izin listesi. Liste olmadan npm her seyi gonderiyordu: 296 dosya / 1.5 MB — CI workflowlari, gitleaks ayari, 137 KB pazarlama gorseli, sitenin api/chat.js dosyasi. Bir bankanin guvenlik ekibi tarball'i acip bunlari gorur. scripts/ BILEREK var: conarium-reconcile calisirken scripts/pg-snapshot.sql'e atif yapiyor, olmazsa kullanici destek maili yazar.",
6
6
  "files": [
@@ -13,10 +13,13 @@
13
13
  "!examples/**/_keys",
14
14
  "!examples/**/*.jsonl",
15
15
  "!examples/**/*.keyid",
16
+ "!examples/**/conarium.tokens.json",
16
17
  "test-vectors",
17
18
  "!**/*.pem",
18
19
  "test-vectors/keys/vector-key.pub.pem",
19
20
  "deploy",
21
+ "!deploy/hetzner",
22
+ "!deploy/hetzner/**",
20
23
  "conarium.config.json",
21
24
  "README.md",
22
25
  "LICENSE",
@@ -66,7 +69,7 @@
66
69
  "build": "tsc",
67
70
  "test": "vitest run",
68
71
  "test:anchor-verify": "npm run build && node test/anchor_verify.mjs",
69
- "test:checks": "npm run build && node test/doctor.mjs && node test/console_cli.mjs && node test/console_policy.mjs && node test/init.mjs && node test/demo_bank_seed.mjs && node test/pack_artefakt.mjs && node test/connectors.mjs && node test/governance_lineage_adversarial.mjs && node test/governance_security_regression.mjs && node test/security_hardening_14.mjs && node test/anchor_verify.mjs && node test/spec_exitcode_drift.mjs && node test/vectors_run.mjs",
72
+ "test:checks": "npm run build && node test/doctor.mjs && node test/console_cli.mjs && node test/console_policy.mjs && node test/init.mjs && node test/demo_bank_seed.mjs && node test/pack_artefakt.mjs && node test/connectors.mjs && node test/governance_lineage_adversarial.mjs && node test/governance_security_regression.mjs && node test/security_hardening_14.mjs && node test/anchor_verify.mjs && node test/spec_exitcode_drift.mjs && node test/vectors_run.mjs && node test/http_gateway.e2e.mjs",
70
73
  "test:all": "npm run lint && npm run test && npm run test:checks",
71
74
  "dev": "tsx watch src/index.ts",
72
75
  "start": "node dist/index.js",