@conarium-ai/core 0.1.2 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,192 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Prove the demo through the real MCP gateway: query → masked rows →
4
+ * signed receipt → independent verify. Importing Governance here would
5
+ * prove the class, not the product.
6
+ *
7
+ * Needs: Postgres on the DSN in conarium.config.json, and
8
+ * CONARIUM_AUDIT_SIGNING_KEY pointing at the Ed25519 private PEM
9
+ * (conarium-init --out ./_keys). The key path is never passed on argv.
10
+ */
11
+ import { existsSync, readFileSync } from 'node:fs'
12
+ import { spawnSync } from 'node:child_process'
13
+ import { dirname, join, resolve } from 'node:path'
14
+ import { fileURLToPath } from 'node:url'
15
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js'
16
+ import { StdioClientTransport, getDefaultEnvironment } from '@modelcontextprotocol/sdk/client/stdio.js'
17
+
18
+ const here = dirname(fileURLToPath(import.meta.url))
19
+ const pkgRoot = resolve(here, '..', '..')
20
+ const gatewayJs = join(pkgRoot, 'dist/index.js')
21
+ const verifyJs = join(pkgRoot, 'bin', 'conarium-verify.mjs')
22
+ const configPath = join(here, 'conarium.config.json')
23
+ const receiptPath = join(here, 'conarium-receipts.jsonl')
24
+ const auditPath = join(here, 'conarium-audit.jsonl')
25
+
26
+ function fail(msg) {
27
+ console.error(`FAIL ${msg}`)
28
+ process.exitCode = 1
29
+ }
30
+
31
+ function pass(msg) {
32
+ console.log(`PASS ${msg}`)
33
+ }
34
+
35
+ function countLines(p) {
36
+ if (!existsSync(p)) return 0
37
+ const t = readFileSync(p, 'utf8').trim()
38
+ return t ? t.split('\n').filter(Boolean).length : 0
39
+ }
40
+
41
+ function lastJsonl(p) {
42
+ const lines = readFileSync(p, 'utf8').trim().split('\n').filter(Boolean)
43
+ return JSON.parse(lines[lines.length - 1])
44
+ }
45
+
46
+ function textOf(result) {
47
+ const parts = result?.content ?? []
48
+ return parts.map((c) => (c && c.type === 'text' ? c.text : '')).join('\n')
49
+ }
50
+
51
+ function pubFromPriv(priv) {
52
+ if (priv.endsWith('.pem') && !priv.endsWith('.pub.pem')) return `${priv.slice(0, -4)}.pub.pem`
53
+ return `${priv}.pub.pem`
54
+ }
55
+
56
+ if (!existsSync(gatewayJs)) {
57
+ fail(`gateway missing (${gatewayJs}) — npm run build, or install the package`)
58
+ process.exit(1)
59
+ }
60
+
61
+ const signingKey = process.env.CONARIUM_AUDIT_SIGNING_KEY?.trim()
62
+ if (!signingKey) {
63
+ fail('CONARIUM_AUDIT_SIGNING_KEY is not set')
64
+ console.error(' → npx conarium-init --out ./_keys')
65
+ console.error(' → export CONARIUM_AUDIT_SIGNING_KEY="$PWD/_keys/audit-ed25519.pem"')
66
+ process.exit(1)
67
+ }
68
+ if (!existsSync(signingKey)) {
69
+ fail(`signing key file not found (path only; contents not printed)`)
70
+ process.exit(1)
71
+ }
72
+
73
+ const pubkey = pubFromPriv(signingKey)
74
+ if (!existsSync(pubkey) || !existsSync(`${pubkey}.keyid`)) {
75
+ fail(`verifier needs ${pubkey} and ${pubkey}.keyid — conarium-init writes both; do not delete them`)
76
+ process.exit(1)
77
+ }
78
+
79
+ const cfg = JSON.parse(readFileSync(configPath, 'utf8'))
80
+ const url = cfg.connectors?.[0]?.config?.url ?? ''
81
+ if (!url.includes('127.0.0.1') || !url.includes('54329')) {
82
+ fail('demo DSN is not the local compose port — refusing to start the gateway')
83
+ process.exit(1)
84
+ }
85
+
86
+ const beforeReceipts = countLines(receiptPath)
87
+
88
+ const env = { ...getDefaultEnvironment(), CONARIUM_AUDIT_SIGNING_KEY: signingKey }
89
+ const transport = new StdioClientTransport({
90
+ command: process.execPath,
91
+ args: [gatewayJs, '--config', configPath],
92
+ cwd: here,
93
+ env,
94
+ stderr: 'pipe',
95
+ })
96
+
97
+ const client = new Client({ name: 'demo-bank-prove', version: '0.0.0' })
98
+
99
+ try {
100
+ await client.connect(transport)
101
+
102
+ const allowed = await client.callTool({
103
+ name: 'query',
104
+ arguments: {
105
+ sql: 'SELECT holder_name, tckn, iban, balance_try FROM public.accounts LIMIT 5',
106
+ },
107
+ })
108
+ if (allowed.isError) {
109
+ fail(`accounts query was denied: ${textOf(allowed)}`)
110
+ } else {
111
+ const body = JSON.parse(textOf(allowed))
112
+ const row = body.rows?.[0]
113
+ if (!row) fail('accounts query returned no rows — is Postgres up on 54329?')
114
+ else if (row.tckn !== '[MASKED_PII]' || row.iban !== '[MASKED_PII]') {
115
+ fail(`tckn/iban not masked: ${JSON.stringify({ tckn: row.tckn, iban: row.iban })}`)
116
+ } else if (row.balance_try === undefined || row.balance_try === '[MASKED_PII]') {
117
+ fail('balance_try should remain visible')
118
+ } else {
119
+ pass('query public.accounts → tckn/iban [MASKED_PII], balance_try visible')
120
+ }
121
+ }
122
+
123
+ const afterQuery = countLines(receiptPath)
124
+ if (afterQuery !== beforeReceipts + 1) {
125
+ fail(`receipt file did not grow by 1 (before=${beforeReceipts} after=${afterQuery}) — gateway did not emit a receipt`)
126
+ } else {
127
+ pass(`receipt file grew ${beforeReceipts} → ${afterQuery}`)
128
+ }
129
+
130
+ if (afterQuery > 0) {
131
+ const rec = lastJsonl(receiptPath)
132
+ const objects = (rec.dataRefs ?? []).map((d) => d.object)
133
+ if (!objects.includes('public.accounts')) {
134
+ fail(`last receipt object is not public.accounts (got ${JSON.stringify(objects)})`)
135
+ } else if (!rec.policy || typeof rec.policy !== 'object' || !rec.policy.id) {
136
+ fail('last receipt has an empty policy field')
137
+ } else {
138
+ pass(`last receipt object=public.accounts policy.id=${rec.policy.id}`)
139
+ }
140
+ }
141
+
142
+ const verified = spawnSync(process.execPath, [verifyJs, receiptPath, '--pubkey', pubkey], {
143
+ cwd: here,
144
+ encoding: 'utf8',
145
+ })
146
+ const vout = `${verified.stdout || ''}${verified.stderr || ''}`
147
+ if (verified.status !== 0 || !/receipt\(s\) verified/.test(vout)) {
148
+ fail(`conarium-verify exit ${verified.status}: ${vout.trim().slice(0, 800)}`)
149
+ } else {
150
+ pass('conarium-verify EXIT 0 · receipt(s) verified')
151
+ }
152
+
153
+ let denied = false
154
+ let denyText = ''
155
+ try {
156
+ const blocked = await client.callTool({
157
+ name: 'query',
158
+ arguments: { sql: 'SELECT pan FROM public.card_vault' },
159
+ })
160
+ denyText = textOf(blocked)
161
+ denied = Boolean(blocked.isError) || /not permitted|denied|card_vault/i.test(denyText)
162
+ } catch (e) {
163
+ denied = true
164
+ denyText = e.message
165
+ }
166
+ if (!denied) fail(`card_vault was not denied: ${denyText}`)
167
+ else {
168
+ const audit = existsSync(auditPath) ? readFileSync(auditPath, 'utf8') : ''
169
+ const logged = audit.split('\n').filter(Boolean).some((line) => {
170
+ try {
171
+ const e = JSON.parse(line)
172
+ return e.denied === true && /card_vault/i.test(JSON.stringify(e.args ?? e.reason ?? e.target ?? ''))
173
+ } catch {
174
+ return false
175
+ }
176
+ })
177
+ if (!logged) fail('card_vault deny did not land in the audit log')
178
+ else pass('public.card_vault denied and logged')
179
+ }
180
+ } catch (e) {
181
+ fail(e.message)
182
+ } finally {
183
+ try {
184
+ await client.close()
185
+ } catch {
186
+ /* gateway already gone */
187
+ }
188
+ }
189
+
190
+ if (process.exitCode === 1) {
191
+ console.error('prove-receipt failed — the gateway, not a helper class, must produce the receipt')
192
+ }
@@ -0,0 +1,55 @@
1
+ -- Demo bank schema. Every identifier is fake on purpose.
2
+ -- TCKN values are 11 digits starting with 1 and do NOT satisfy the checksum.
3
+ -- IBANs are TR00 + zeros. Names are stock "deneme" labels, not people.
4
+
5
+ CREATE TABLE accounts (
6
+ id serial PRIMARY KEY,
7
+ holder_name text NOT NULL,
8
+ tckn text NOT NULL,
9
+ iban text NOT NULL,
10
+ balance_try numeric(14, 2) NOT NULL
11
+ );
12
+
13
+ CREATE TABLE transactions (
14
+ id serial PRIMARY KEY,
15
+ account_id int NOT NULL REFERENCES accounts (id),
16
+ amount_try numeric(14, 2) NOT NULL,
17
+ memo text NOT NULL
18
+ );
19
+
20
+ CREATE TABLE card_vault (
21
+ id serial PRIMARY KEY,
22
+ account_id int NOT NULL REFERENCES accounts (id),
23
+ pan text NOT NULL,
24
+ cvv text NOT NULL
25
+ );
26
+
27
+ INSERT INTO accounts (holder_name, tckn, iban, balance_try)
28
+ SELECT
29
+ (ARRAY[
30
+ 'Ali Deneme',
31
+ 'Ayse Ornek',
32
+ 'Mehmet Sahte',
33
+ 'Fatma Test',
34
+ 'Can Yok',
35
+ 'Zeynep Demo',
36
+ 'Hasan Ornek'
37
+ ])[1 + ((g - 1) % 7)],
38
+ '1' || lpad((g * 17)::text, 10, '0'),
39
+ 'TR00' || lpad(g::text, 22, '0'),
40
+ (1000 + g)::numeric(14, 2)
41
+ FROM generate_series(1, 250) AS g;
42
+
43
+ INSERT INTO transactions (account_id, amount_try, memo)
44
+ SELECT
45
+ 1 + ((g - 1) % 250),
46
+ ((g % 97) + 1)::numeric(14, 2),
47
+ (ARRAY['EFT deneme', 'Havale ornek', 'POS sahte', 'Maas test'])[1 + ((g - 1) % 4)]
48
+ FROM generate_series(1, 400) AS g;
49
+
50
+ INSERT INTO card_vault (account_id, pan, cvv)
51
+ SELECT
52
+ g,
53
+ '0000-0000-0000-' || lpad(g::text, 4, '0'),
54
+ '000'
55
+ FROM generate_series(1, 250) AS g;
package/package.json CHANGED
@@ -1,14 +1,21 @@
1
1
  {
2
2
  "name": "@conarium-ai/core",
3
- "version": "0.1.2",
3
+ "version": "0.2.1",
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.",
4
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.",
5
6
  "files": [
6
7
  "dist",
7
8
  "bin",
8
9
  "scripts",
9
10
  "docs",
11
+ "public",
10
12
  "examples",
13
+ "!examples/**/_keys",
14
+ "!examples/**/*.jsonl",
15
+ "!examples/**/*.keyid",
11
16
  "test-vectors",
17
+ "!**/*.pem",
18
+ "test-vectors/keys/vector-key.pub.pem",
12
19
  "deploy",
13
20
  "conarium.config.json",
14
21
  "README.md",
@@ -52,13 +59,14 @@
52
59
  "conarium-coverage": "bin/conarium-coverage.mjs",
53
60
  "conarium-reconcile": "bin/conarium-reconcile.mjs",
54
61
  "conarium-stamp": "bin/conarium-stamp.mjs",
55
- "conarium-anchor-upgrade": "bin/conarium-anchor-upgrade.mjs"
62
+ "conarium-anchor-upgrade": "bin/conarium-anchor-upgrade.mjs",
63
+ "conarium-console": "bin/conarium-console.mjs"
56
64
  },
57
65
  "scripts": {
58
66
  "build": "tsc",
59
67
  "test": "vitest run",
60
68
  "test:anchor-verify": "npm run build && node test/anchor_verify.mjs",
61
- "test:checks": "npm run build && node test/doctor.mjs && node test/init.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",
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",
62
70
  "test:all": "npm run lint && npm run test && npm run test:checks",
63
71
  "dev": "tsx watch src/index.ts",
64
72
  "start": "node dist/index.js",
package/public/app.js ADDED
@@ -0,0 +1,289 @@
1
+ document.addEventListener('DOMContentLoaded', () => {
2
+
3
+ // Tab Switching Logic
4
+ const tabs = document.querySelectorAll('.nav-item');
5
+ const contents = document.querySelectorAll('.tab-content');
6
+
7
+ tabs.forEach(tab => {
8
+ tab.addEventListener('click', (e) => {
9
+ e.preventDefault();
10
+ const targetId = `tab-${tab.dataset.tab}`;
11
+
12
+ tabs.forEach(t => t.classList.remove('active'));
13
+ contents.forEach(c => c.classList.remove('active'));
14
+
15
+ tab.classList.add('active');
16
+ document.getElementById(targetId).classList.add('active');
17
+ });
18
+ });
19
+
20
+ function authHeaders(extra) {
21
+ const params = new URLSearchParams(location.search)
22
+ let token = params.get('token') || sessionStorage.getItem('conarium-console-token') || ''
23
+ if (token) sessionStorage.setItem('conarium-console-token', token)
24
+ const headers = { ...(extra || {}) }
25
+ if (token) {
26
+ headers['Authorization'] = 'Bearer ' + token
27
+ headers['x-csrf-token'] = token
28
+ }
29
+ return headers
30
+ }
31
+
32
+ function policyOf(data) {
33
+ if (data && typeof data.policy === 'object' && data.policy) return data.policy
34
+ return data || {}
35
+ }
36
+
37
+ function parseList(raw) {
38
+ return String(raw || '')
39
+ .split(/[\n,]+/)
40
+ .map(s => s.trim())
41
+ .filter(Boolean)
42
+ }
43
+
44
+ function fillList(id, arr) {
45
+ const el = document.getElementById(id)
46
+ el.value = Array.isArray(arr) ? arr.join('\n') : ''
47
+ }
48
+
49
+ function setAllowTablesWarn(empty) {
50
+ const w = document.getElementById('allowTables-warn')
51
+ if (!w) return
52
+ w.hidden = !empty
53
+ }
54
+
55
+ // Load Config
56
+ async function loadConfig() {
57
+ try {
58
+ const res = await fetch('/api/config', { headers: authHeaders() })
59
+ if (!res.ok) {
60
+ showToast('Could not load policy (' + res.status + '). Pass ?token=…')
61
+ return
62
+ }
63
+ const data = await res.json()
64
+ const pol = policyOf(data)
65
+ const maxEl = document.getElementById('maxRows')
66
+ maxEl.value = pol.maxRows == null ? '' : String(pol.maxRows)
67
+ fillList('allowTables', pol.allowTables)
68
+ fillList('denyTables', pol.denyTables)
69
+ fillList('maskColumns', pol.maskColumns)
70
+ document.getElementById('allowTools').value = Array.isArray(pol.allowTools) ? pol.allowTools.join(', ') : ''
71
+ document.getElementById('denyTools').value = Array.isArray(pol.denyTools) ? pol.denyTools.join(', ') : ''
72
+ setAllowTablesWarn(!Array.isArray(pol.allowTables) || pol.allowTables.length === 0)
73
+ } catch (e) {
74
+ console.error('Failed to load config', e)
75
+ }
76
+ }
77
+
78
+ // Save Config — only the fields this form edits. connectors/audit/profiles stay on the server.
79
+ document.getElementById('config-form').addEventListener('submit', async (e) => {
80
+ e.preventDefault()
81
+
82
+ const maxRaw = document.getElementById('maxRows').value
83
+ const body = {
84
+ allowTables: parseList(document.getElementById('allowTables').value),
85
+ denyTables: parseList(document.getElementById('denyTables').value),
86
+ maskColumns: parseList(document.getElementById('maskColumns').value),
87
+ allowTools: parseList(document.getElementById('allowTools').value),
88
+ denyTools: parseList(document.getElementById('denyTools').value),
89
+ }
90
+ if (maxRaw !== '') body.maxRows = parseInt(maxRaw, 10)
91
+
92
+ setAllowTablesWarn(body.allowTables.length === 0)
93
+
94
+ try {
95
+ const res = await fetch('/api/config', {
96
+ method: 'POST',
97
+ headers: authHeaders({ 'Content-Type': 'application/json' }),
98
+ body: JSON.stringify(body)
99
+ })
100
+ if (res.ok) {
101
+ const out = await res.json().catch(() => ({}))
102
+ if (out.allowTablesEmpty) setAllowTablesWarn(true)
103
+ showToast('Governance Policy Saved')
104
+ } else {
105
+ showToast('Save failed (' + res.status + ')')
106
+ }
107
+ } catch (e) {
108
+ console.error('Failed to save config', e)
109
+ }
110
+ })
111
+
112
+ // Load Audit Logs
113
+ async function loadAudit() {
114
+ try {
115
+ const res = await fetch('/api/audit', { headers: authHeaders() });
116
+ const data = await res.json();
117
+
118
+ const tbody = document.getElementById('audit-body');
119
+ tbody.innerHTML = '';
120
+
121
+ if (data.length === 0) {
122
+ tbody.innerHTML = `<tr><td colspan="8" class="text-center">No audit logs found.</td></tr>`;
123
+ return;
124
+ }
125
+
126
+ data.forEach(log => {
127
+ const tr = document.createElement('tr');
128
+ const isDenied = Boolean(log.denied);
129
+ const statusClass = isDenied ? 'status-rejected' : 'status-success';
130
+ const statusText = isDenied ? 'Denied' : 'Allowed';
131
+ const sqlText = String(log.args && log.args.sql ? log.args.sql : (log.query || '-'));
132
+ const hashValue = String(log.hash || '');
133
+ const hashText = hashValue ? hashValue.substring(0, 8) + '...' : '-';
134
+
135
+ function tdText(value) {
136
+ const td = document.createElement('td');
137
+ td.textContent = String(value);
138
+ return td;
139
+ }
140
+ function tdCode(value) {
141
+ const td = document.createElement('td');
142
+ const code = document.createElement('code');
143
+ code.textContent = String(value);
144
+ td.appendChild(code);
145
+ return td;
146
+ }
147
+
148
+ tr.appendChild(tdText(new Date(log.timestamp).toLocaleString()));
149
+ tr.appendChild(tdText(log.actor || 'unknown'));
150
+ tr.appendChild(tdCode(log.tool || '-'));
151
+
152
+ const sqlTd = document.createElement('td');
153
+ sqlTd.title = sqlText;
154
+ const sqlCode = document.createElement('code');
155
+ sqlCode.textContent = sqlText.length > 40 ? sqlText.substring(0, 40) + '...' : sqlText;
156
+ sqlTd.appendChild(sqlCode);
157
+ tr.appendChild(sqlTd);
158
+
159
+ tr.appendChild(tdText(log.rowsReturned || 0));
160
+ tr.appendChild(tdText(`${log.maskedCount || 0} PII`));
161
+
162
+ const statusTd = document.createElement('td');
163
+ const status = document.createElement('span');
164
+ status.className = `status-badge-sm ${statusClass}`;
165
+ status.textContent = statusText;
166
+ statusTd.appendChild(status);
167
+ tr.appendChild(statusTd);
168
+
169
+ const hashTd = document.createElement('td');
170
+ hashTd.title = hashValue;
171
+ const hashCode = document.createElement('code');
172
+ hashCode.style.fontSize = '0.75rem';
173
+ hashCode.style.color = 'var(--text-secondary)';
174
+ hashCode.textContent = hashText;
175
+ hashTd.appendChild(hashCode);
176
+ tr.appendChild(hashTd);
177
+
178
+ tbody.appendChild(tr);
179
+ });
180
+ } catch (e) {
181
+ console.error('Failed to load audit logs', e);
182
+ }
183
+ }
184
+
185
+ document.getElementById('refresh-audit').addEventListener('click', loadAudit);
186
+
187
+ // Load Connectors
188
+ async function loadConnectors() {
189
+ try {
190
+ const res = await fetch('/api/connectors', { headers: authHeaders() });
191
+ const data = await res.json();
192
+
193
+ const list = document.getElementById('connector-list');
194
+ list.innerHTML = '';
195
+
196
+ data.forEach(conn => {
197
+ const statusColor = conn.status === 'connected' ? 'var(--success)' : 'var(--danger)';
198
+ const el = document.createElement('div');
199
+ el.className = 'connector-item';
200
+ el.innerHTML = `
201
+ <div class="connector-info">
202
+ <h4>${conn.id}</h4>
203
+ <span>${conn.type}</span>
204
+ </div>
205
+ <div style="text-align: right">
206
+ <div style="color: ${statusColor}; font-weight: 600; font-size: 0.875rem;">
207
+ ● ${conn.status}
208
+ </div>
209
+ <span style="font-size: 0.75rem; color: var(--text-secondary)">${conn.latency}</span>
210
+ </div>
211
+ `;
212
+ list.appendChild(el);
213
+ });
214
+ } catch (e) {
215
+ console.error('Failed to load connectors', e);
216
+ }
217
+ }
218
+
219
+ // --- Live Playground ---
220
+ const pgQuery = document.getElementById('pg-query');
221
+ document.querySelectorAll('.pg-samples .chip').forEach(chip => {
222
+ chip.addEventListener('click', () => { pgQuery.value = chip.dataset.q; });
223
+ });
224
+
225
+ function renderRows(rows) {
226
+ return rows.map(r => {
227
+ const lines = Object.entries(r).map(([k, v]) => {
228
+ const masked = v === '[MASKED_PII]';
229
+ return ` <span class="jk">"${k}"</span>: <span class="${masked ? 'jmask' : 'jv'}">${JSON.stringify(v)}</span>`;
230
+ }).join(',\n');
231
+ return `{\n${lines}\n}`;
232
+ }).join(',\n');
233
+ }
234
+
235
+ const pgRun = document.getElementById('pg-run');
236
+ if (pgRun) pgRun.addEventListener('click', async () => {
237
+ const query = pgQuery.value.trim();
238
+ const out = document.getElementById('pg-result');
239
+ out.innerHTML = '<div class="loader">Running through Conarium…</div>';
240
+ try {
241
+ const res = await fetch('/api/playground', {
242
+ method: 'POST', headers: authHeaders({ 'Content-Type': 'application/json' }),
243
+ body: JSON.stringify({ query })
244
+ });
245
+ const d = await res.json();
246
+ if (d.decision === 'deny') {
247
+ out.innerHTML = `
248
+ <div class="pg-blocked">
249
+ <div class="pg-blocked-icon">🛑</div>
250
+ <div>
251
+ <h4>BLOCKED by Conarium</h4>
252
+ <p>${d.reason}</p>
253
+ <span class="pg-logged">✓ Logged to audit · decision: <code>deny</code></span>
254
+ </div>
255
+ </div>`;
256
+ } else {
257
+ out.innerHTML = `
258
+ <div class="pg-compare">
259
+ <div class="pg-col pg-raw">
260
+ <div class="pg-col-head">🔴 RAW — direct DB access</div>
261
+ <pre>${renderRows(d.raw)}</pre>
262
+ </div>
263
+ <div class="pg-arrow">▸</div>
264
+ <div class="pg-col pg-gov">
265
+ <div class="pg-col-head">🟢 GOVERNED — through Conarium</div>
266
+ <pre>${renderRows(d.governed)}</pre>
267
+ </div>
268
+ </div>
269
+ <div class="pg-logged">✓ <strong>${d.maskedCount}</strong> PII field(s) masked · ${d.governed.length} row(s) · logged to audit</div>`;
270
+ }
271
+ loadAudit();
272
+ } catch (e) {
273
+ out.innerHTML = `<div class="pg-blocked"><p>Error: ${e.message}</p></div>`;
274
+ }
275
+ });
276
+
277
+ // Toast Utility
278
+ function showToast(msg) {
279
+ const toast = document.getElementById('toast');
280
+ toast.textContent = msg;
281
+ toast.classList.add('show');
282
+ setTimeout(() => toast.classList.remove('show'), 3000);
283
+ }
284
+
285
+ // Initialize
286
+ loadConfig();
287
+ loadAudit();
288
+ loadConnectors();
289
+ });