@sanctuary-framework/mcp-server 0.3.0 → 0.3.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.
package/dist/index.cjs CHANGED
@@ -298,8 +298,13 @@ async function loadConfig(configPath) {
298
298
  try {
299
299
  const raw = await promises.readFile(path$1, "utf-8");
300
300
  const fileConfig = JSON.parse(raw);
301
- return deepMerge(config, fileConfig);
302
- } catch {
301
+ const merged = deepMerge(config, fileConfig);
302
+ validateConfig(merged);
303
+ return merged;
304
+ } catch (err) {
305
+ if (err instanceof Error && err.message.includes("unimplemented features")) {
306
+ throw err;
307
+ }
303
308
  return config;
304
309
  }
305
310
  }
@@ -307,6 +312,33 @@ async function saveConfig(config, configPath) {
307
312
  const path$1 = path.join(config.storage_path, "sanctuary.json");
308
313
  await promises.writeFile(path$1, JSON.stringify(config, null, 2), { mode: 384 });
309
314
  }
315
+ function validateConfig(config) {
316
+ const errors = [];
317
+ const implementedKeyProtection = /* @__PURE__ */ new Set(["passphrase", "none"]);
318
+ if (!implementedKeyProtection.has(config.state.key_protection)) {
319
+ errors.push(
320
+ `Unimplemented config value: state.key_protection = "${config.state.key_protection}". Only ${[...implementedKeyProtection].map((v) => `"${v}"`).join(", ")} are currently implemented. Using an unimplemented key protection mode would silently degrade security.`
321
+ );
322
+ }
323
+ const implementedEnvironment = /* @__PURE__ */ new Set(["local-process", "docker"]);
324
+ if (!implementedEnvironment.has(config.execution.environment)) {
325
+ errors.push(
326
+ `Unimplemented config value: execution.environment = "${config.execution.environment}". Only ${[...implementedEnvironment].map((v) => `"${v}"`).join(", ")} are currently implemented. Using an unimplemented environment would silently degrade security.`
327
+ );
328
+ }
329
+ const implementedProofSystem = /* @__PURE__ */ new Set(["commitment-only"]);
330
+ if (!implementedProofSystem.has(config.disclosure.proof_system)) {
331
+ errors.push(
332
+ `Unimplemented config value: disclosure.proof_system = "${config.disclosure.proof_system}". Only ${[...implementedProofSystem].map((v) => `"${v}"`).join(", ")} is currently implemented. Using an unimplemented proof system would silently degrade security.`
333
+ );
334
+ }
335
+ if (errors.length > 0) {
336
+ throw new Error(
337
+ `Sanctuary configuration references unimplemented features:
338
+ ${errors.join("\n")}`
339
+ );
340
+ }
341
+ }
310
342
  function deepMerge(base, override) {
311
343
  const result = { ...base };
312
344
  for (const [key, value] of Object.entries(override)) {
@@ -650,7 +682,11 @@ var RESERVED_NAMESPACE_PREFIXES = [
650
682
  "_commitments",
651
683
  "_reputation",
652
684
  "_escrow",
653
- "_guarantees"
685
+ "_guarantees",
686
+ "_bridge",
687
+ "_federation",
688
+ "_handshake",
689
+ "_shr"
654
690
  ];
655
691
  var StateStore = class {
656
692
  storage;
@@ -917,12 +953,14 @@ var StateStore = class {
917
953
  /**
918
954
  * Import a previously exported state bundle.
919
955
  */
920
- async import(bundleBase64, conflictResolution = "skip") {
956
+ async import(bundleBase64, conflictResolution = "skip", publicKeyResolver) {
921
957
  const bundleBytes = fromBase64url(bundleBase64);
922
958
  const bundleJson = bytesToString(bundleBytes);
923
959
  const bundle = JSON.parse(bundleJson);
924
960
  let importedKeys = 0;
925
961
  let skippedKeys = 0;
962
+ let skippedInvalidSig = 0;
963
+ let skippedUnknownKid = 0;
926
964
  let conflicts = 0;
927
965
  const namespaces = [];
928
966
  for (const [ns, entries] of Object.entries(
@@ -936,6 +974,26 @@ var StateStore = class {
936
974
  }
937
975
  namespaces.push(ns);
938
976
  for (const { key, entry } of entries) {
977
+ const signerPublicKey = publicKeyResolver(entry.kid);
978
+ if (!signerPublicKey) {
979
+ skippedUnknownKid++;
980
+ skippedKeys++;
981
+ continue;
982
+ }
983
+ try {
984
+ const ciphertextBytes = fromBase64url(entry.payload.ct);
985
+ const signatureBytes = fromBase64url(entry.sig);
986
+ const sigValid = verify(ciphertextBytes, signatureBytes, signerPublicKey);
987
+ if (!sigValid) {
988
+ skippedInvalidSig++;
989
+ skippedKeys++;
990
+ continue;
991
+ }
992
+ } catch {
993
+ skippedInvalidSig++;
994
+ skippedKeys++;
995
+ continue;
996
+ }
939
997
  const exists = await this.storage.exists(ns, key);
940
998
  if (exists) {
941
999
  conflicts++;
@@ -971,6 +1029,8 @@ var StateStore = class {
971
1029
  return {
972
1030
  imported_keys: importedKeys,
973
1031
  skipped_keys: skippedKeys,
1032
+ skipped_invalid_sig: skippedInvalidSig,
1033
+ skipped_unknown_kid: skippedUnknownKid,
974
1034
  conflicts,
975
1035
  namespaces,
976
1036
  imported_at: (/* @__PURE__ */ new Date()).toISOString()
@@ -1159,7 +1219,11 @@ var RESERVED_NAMESPACE_PREFIXES2 = [
1159
1219
  "_commitments",
1160
1220
  "_reputation",
1161
1221
  "_escrow",
1162
- "_guarantees"
1222
+ "_guarantees",
1223
+ "_bridge",
1224
+ "_federation",
1225
+ "_handshake",
1226
+ "_shr"
1163
1227
  ];
1164
1228
  function getReservedNamespaceViolation(namespace) {
1165
1229
  for (const prefix of RESERVED_NAMESPACE_PREFIXES2) {
@@ -1496,6 +1560,13 @@ function createL1Tools(stateStore, storage, masterKey, keyProtection, auditLog)
1496
1560
  required: ["namespace", "key"]
1497
1561
  },
1498
1562
  handler: async (args) => {
1563
+ const reservedViolation = getReservedNamespaceViolation(args.namespace);
1564
+ if (reservedViolation) {
1565
+ return toolResult({
1566
+ error: "namespace_reserved",
1567
+ message: `Namespace "${args.namespace}" is reserved for internal use (prefix: ${reservedViolation}). Cannot read from reserved namespaces.`
1568
+ });
1569
+ }
1499
1570
  const result = await stateStore.read(
1500
1571
  args.namespace,
1501
1572
  args.key,
@@ -1532,6 +1603,13 @@ function createL1Tools(stateStore, storage, masterKey, keyProtection, auditLog)
1532
1603
  required: ["namespace"]
1533
1604
  },
1534
1605
  handler: async (args) => {
1606
+ const reservedViolation = getReservedNamespaceViolation(args.namespace);
1607
+ if (reservedViolation) {
1608
+ return toolResult({
1609
+ error: "namespace_reserved",
1610
+ message: `Namespace "${args.namespace}" is reserved for internal use (prefix: ${reservedViolation}). Cannot list reserved namespaces.`
1611
+ });
1612
+ }
1535
1613
  const result = await stateStore.list(
1536
1614
  args.namespace,
1537
1615
  args.prefix,
@@ -1610,9 +1688,15 @@ function createL1Tools(stateStore, storage, masterKey, keyProtection, auditLog)
1610
1688
  required: ["bundle"]
1611
1689
  },
1612
1690
  handler: async (args) => {
1691
+ const publicKeyResolver = (kid) => {
1692
+ const identity = identityMgr.get(kid);
1693
+ if (!identity) return null;
1694
+ return fromBase64url(identity.public_key);
1695
+ };
1613
1696
  const result = await stateStore.import(
1614
1697
  args.bundle,
1615
- args.conflict_resolution ?? "skip"
1698
+ args.conflict_resolution ?? "skip",
1699
+ publicKeyResolver
1616
1700
  );
1617
1701
  auditLog?.append("l1", "state_import", "principal", {
1618
1702
  imported_keys: result.imported_keys
@@ -2057,7 +2141,7 @@ function createRangeProof(value, blindingFactor, commitment, min, max) {
2057
2141
  bitProofs.push(bitProof);
2058
2142
  }
2059
2143
  const sumBlinding = bitBlindings.reduce(
2060
- (acc, bi, i) => mod(acc + mod(BigInt(1 << i)) * bi),
2144
+ (acc, bi, i) => mod(acc + mod(BigInt(1) << BigInt(i)) * bi),
2061
2145
  0n
2062
2146
  );
2063
2147
  const blindingDiff = mod(b - sumBlinding);
@@ -2099,7 +2183,7 @@ function verifyRangeProof(proof) {
2099
2183
  let reconstructed = ed25519.RistrettoPoint.ZERO;
2100
2184
  for (let i = 0; i < numBits; i++) {
2101
2185
  const C_i = ed25519.RistrettoPoint.fromHex(fromBase64url(proof.bit_commitments[i]));
2102
- const weight = mod(BigInt(1 << i));
2186
+ const weight = mod(BigInt(1) << BigInt(i));
2103
2187
  reconstructed = reconstructed.add(safeMultiply(C_i, weight));
2104
2188
  }
2105
2189
  const diff = C.subtract(safeMultiply(G, mod(BigInt(proof.min)))).subtract(reconstructed);
@@ -3154,7 +3238,9 @@ function createL4Tools(storage, masterKey, identityManager, auditLog, handshakeR
3154
3238
  contexts: summary.contexts
3155
3239
  });
3156
3240
  return toolResult({
3157
- summary
3241
+ summary,
3242
+ // SEC-ADD-03: Tag response as containing counterparty-generated attestation data
3243
+ _content_trust: "external"
3158
3244
  });
3159
3245
  }
3160
3246
  },
@@ -3475,14 +3561,16 @@ var DEFAULT_TIER2 = {
3475
3561
  };
3476
3562
  var DEFAULT_CHANNEL = {
3477
3563
  type: "stderr",
3478
- timeout_seconds: 300,
3479
- auto_deny: true
3564
+ timeout_seconds: 300
3565
+ // SEC-002: auto_deny is not configurable. Timeout always denies.
3566
+ // Field omitted intentionally — all channels hardcode deny on timeout.
3480
3567
  };
3481
3568
  var DEFAULT_POLICY = {
3482
3569
  version: 1,
3483
3570
  tier1_always_approve: [
3484
3571
  "state_export",
3485
3572
  "state_import",
3573
+ "state_delete",
3486
3574
  "identity_rotate",
3487
3575
  "reputation_import",
3488
3576
  "bootstrap_provide_guarantee"
@@ -3492,7 +3580,6 @@ var DEFAULT_POLICY = {
3492
3580
  "state_read",
3493
3581
  "state_write",
3494
3582
  "state_list",
3495
- "state_delete",
3496
3583
  "identity_create",
3497
3584
  "identity_list",
3498
3585
  "identity_sign",
@@ -3600,10 +3687,14 @@ function validatePolicy(raw) {
3600
3687
  ...raw.tier2_anomaly ?? {}
3601
3688
  },
3602
3689
  tier3_always_allow: raw.tier3_always_allow ?? DEFAULT_POLICY.tier3_always_allow,
3603
- approval_channel: {
3604
- ...DEFAULT_CHANNEL,
3605
- ...raw.approval_channel ?? {}
3606
- }
3690
+ approval_channel: (() => {
3691
+ const merged = {
3692
+ ...DEFAULT_CHANNEL,
3693
+ ...raw.approval_channel ?? {}
3694
+ };
3695
+ delete merged.auto_deny;
3696
+ return merged;
3697
+ })()
3607
3698
  };
3608
3699
  }
3609
3700
  function generateDefaultPolicyYaml() {
@@ -3620,6 +3711,7 @@ version: 1
3620
3711
  tier1_always_approve:
3621
3712
  - state_export
3622
3713
  - state_import
3714
+ - state_delete
3623
3715
  - identity_rotate
3624
3716
  - reputation_import
3625
3717
  - bootstrap_provide_guarantee
@@ -3641,7 +3733,6 @@ tier3_always_allow:
3641
3733
  - state_read
3642
3734
  - state_write
3643
3735
  - state_list
3644
- - state_delete
3645
3736
  - identity_create
3646
3737
  - identity_list
3647
3738
  - identity_sign
@@ -3678,10 +3769,10 @@ tier3_always_allow:
3678
3769
 
3679
3770
  # \u2500\u2500\u2500 Approval Channel \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
3680
3771
  # How Sanctuary reaches you when approval is needed.
3772
+ # NOTE: Timeout always results in denial. This is not configurable (SEC-002).
3681
3773
  approval_channel:
3682
3774
  type: stderr
3683
3775
  timeout_seconds: 300
3684
- auto_deny: true
3685
3776
  `;
3686
3777
  }
3687
3778
  async function loadPrincipalPolicy(storagePath) {
@@ -3858,27 +3949,16 @@ var BaselineTracker = class {
3858
3949
 
3859
3950
  // src/principal-policy/approval-channel.ts
3860
3951
  var StderrApprovalChannel = class {
3861
- config;
3862
- constructor(config) {
3863
- this.config = config;
3952
+ constructor(_config) {
3864
3953
  }
3865
3954
  async requestApproval(request) {
3866
3955
  const prompt = this.formatPrompt(request);
3867
3956
  process.stderr.write(prompt + "\n");
3868
- await new Promise((resolve) => setTimeout(resolve, 100));
3869
- if (this.config.auto_deny) {
3870
- return {
3871
- decision: "deny",
3872
- decided_at: (/* @__PURE__ */ new Date()).toISOString(),
3873
- decided_by: "timeout"
3874
- };
3875
- } else {
3876
- return {
3877
- decision: "approve",
3878
- decided_at: (/* @__PURE__ */ new Date()).toISOString(),
3879
- decided_by: "auto"
3880
- };
3881
- }
3957
+ return {
3958
+ decision: "deny",
3959
+ decided_at: (/* @__PURE__ */ new Date()).toISOString(),
3960
+ decided_by: "stderr:non-interactive"
3961
+ };
3882
3962
  }
3883
3963
  formatPrompt(request) {
3884
3964
  const tierLabel = request.tier === 1 ? "Tier 1 \u2014 always requires approval" : "Tier 2 \u2014 behavioral anomaly detected";
@@ -3886,7 +3966,7 @@ var StderrApprovalChannel = class {
3886
3966
  return [
3887
3967
  "",
3888
3968
  "\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557",
3889
- "\u2551 SANCTUARY: Approval Required \u2551",
3969
+ "\u2551 SANCTUARY: Operation Denied (non-interactive channel) \u2551",
3890
3970
  "\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563",
3891
3971
  `\u2551 Operation: ${request.operation.padEnd(50)}\u2551`,
3892
3972
  `\u2551 ${tierLabel.padEnd(62)}\u2551`,
@@ -3897,7 +3977,8 @@ var StderrApprovalChannel = class {
3897
3977
  (line) => `\u2551 ${line.padEnd(60)}\u2551`
3898
3978
  ),
3899
3979
  "\u2551 \u2551",
3900
- this.config.auto_deny ? "\u2551 Auto-denying (configure approval_channel.auto_deny to change) \u2551" : "\u2551 Auto-approving (informational mode) \u2551",
3980
+ "\u2551 Denied: stderr channel cannot accept input (SEC-016) \u2551",
3981
+ "\u2551 Use dashboard or webhook channel for interactive approval. \u2551",
3901
3982
  "\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D",
3902
3983
  ""
3903
3984
  ].join("\n");
@@ -4219,20 +4300,38 @@ function generateDashboardHTML(options) {
4219
4300
  <script>
4220
4301
  (function() {
4221
4302
  const TIMEOUT = ${options.timeoutSeconds};
4222
- const AUTH_TOKEN = ${options.authToken ? `'${options.authToken}'` : "null"};
4303
+ // SEC-012: Auth token is passed via Authorization header only \u2014 never in URLs.
4304
+ // The token is provided by the server at generation time (embedded for initial auth).
4305
+ const AUTH_TOKEN = ${options.authToken ? JSON.stringify(options.authToken) : "null"};
4306
+ let SESSION_ID = null; // Short-lived session for SSE and URL-based requests
4223
4307
  const pending = new Map();
4224
4308
  let auditCount = 0;
4225
4309
 
4226
- // Auth helpers
4310
+ // Auth helpers \u2014 SEC-012: token goes in header, session goes in URL
4227
4311
  function authHeaders() {
4228
4312
  const h = { 'Content-Type': 'application/json' };
4229
4313
  if (AUTH_TOKEN) h['Authorization'] = 'Bearer ' + AUTH_TOKEN;
4230
4314
  return h;
4231
4315
  }
4232
- function authQuery(url) {
4233
- if (!AUTH_TOKEN) return url;
4316
+ function sessionQuery(url) {
4317
+ if (!SESSION_ID) return url;
4234
4318
  const sep = url.includes('?') ? '&' : '?';
4235
- return url + sep + 'token=' + AUTH_TOKEN;
4319
+ return url + sep + 'session=' + SESSION_ID;
4320
+ }
4321
+
4322
+ // SEC-012: Exchange the long-lived token for a short-lived session
4323
+ async function exchangeSession() {
4324
+ if (!AUTH_TOKEN) return;
4325
+ try {
4326
+ const resp = await fetch('/auth/session', { method: 'POST', headers: authHeaders() });
4327
+ if (resp.ok) {
4328
+ const data = await resp.json();
4329
+ SESSION_ID = data.session_id;
4330
+ // Refresh session before expiry (at 80% of TTL)
4331
+ const refreshMs = (data.expires_in_seconds || 300) * 800;
4332
+ setTimeout(async () => { await exchangeSession(); reconnectSSE(); }, refreshMs);
4333
+ }
4334
+ } catch(e) { /* will retry on next connect */ }
4236
4335
  }
4237
4336
 
4238
4337
  // Tab switching
@@ -4245,10 +4344,14 @@ function generateDashboardHTML(options) {
4245
4344
  });
4246
4345
  });
4247
4346
 
4248
- // SSE Connection
4347
+ // SSE Connection \u2014 SEC-012: uses short-lived session token in URL, not auth token
4249
4348
  let evtSource;
4349
+ function reconnectSSE() {
4350
+ if (evtSource) { evtSource.close(); }
4351
+ connect();
4352
+ }
4250
4353
  function connect() {
4251
- evtSource = new EventSource(authQuery('/events'));
4354
+ evtSource = new EventSource(sessionQuery('/events'));
4252
4355
  evtSource.onopen = () => {
4253
4356
  document.getElementById('statusDot').classList.remove('disconnected');
4254
4357
  document.getElementById('statusText').textContent = 'Connected';
@@ -4436,12 +4539,20 @@ function generateDashboardHTML(options) {
4436
4539
  return d.innerHTML;
4437
4540
  }
4438
4541
 
4439
- // Init
4440
- connect();
4441
- fetch('/api/status', { headers: authHeaders() }).then(r => r.json()).then(data => {
4442
- if (data.baseline) updateBaseline(data.baseline);
4443
- if (data.policy) updatePolicy(data.policy);
4444
- }).catch(() => {});
4542
+ // Init \u2014 SEC-012: exchange token for session before connecting SSE
4543
+ (async function init() {
4544
+ await exchangeSession();
4545
+ // Clean token from URL if present (legacy bookmarks)
4546
+ if (window.location.search.includes('token=')) {
4547
+ const clean = window.location.pathname;
4548
+ window.history.replaceState({}, '', clean);
4549
+ }
4550
+ connect();
4551
+ fetch('/api/status', { headers: authHeaders() }).then(r => r.json()).then(data => {
4552
+ if (data.baseline) updateBaseline(data.baseline);
4553
+ if (data.policy) updatePolicy(data.policy);
4554
+ }).catch(() => {});
4555
+ })();
4445
4556
  })();
4446
4557
  </script>
4447
4558
  </body>
@@ -4449,6 +4560,8 @@ function generateDashboardHTML(options) {
4449
4560
  }
4450
4561
 
4451
4562
  // src/principal-policy/dashboard.ts
4563
+ var SESSION_TTL_MS = 5 * 60 * 1e3;
4564
+ var MAX_SESSIONS = 1e3;
4452
4565
  var DashboardApprovalChannel = class {
4453
4566
  config;
4454
4567
  pending = /* @__PURE__ */ new Map();
@@ -4460,6 +4573,9 @@ var DashboardApprovalChannel = class {
4460
4573
  dashboardHTML;
4461
4574
  authToken;
4462
4575
  useTLS;
4576
+ /** SEC-012: Short-lived session store. Sessions replace URL query tokens. */
4577
+ sessions = /* @__PURE__ */ new Map();
4578
+ sessionCleanupTimer = null;
4463
4579
  constructor(config) {
4464
4580
  this.config = config;
4465
4581
  this.authToken = config.auth_token;
@@ -4469,6 +4585,7 @@ var DashboardApprovalChannel = class {
4469
4585
  serverVersion: "0.3.0",
4470
4586
  authToken: this.authToken
4471
4587
  });
4588
+ this.sessionCleanupTimer = setInterval(() => this.cleanupSessions(), 6e4);
4472
4589
  }
4473
4590
  /**
4474
4591
  * Inject dependencies after construction.
@@ -4498,13 +4615,14 @@ var DashboardApprovalChannel = class {
4498
4615
  const baseUrl = `${protocol}://${this.config.host}:${this.config.port}`;
4499
4616
  this.httpServer.listen(this.config.port, this.config.host, () => {
4500
4617
  if (this.authToken) {
4618
+ const hint = this.authToken.slice(0, 4) + "..." + this.authToken.slice(-4);
4501
4619
  process.stderr.write(
4502
4620
  `
4503
- Sanctuary Principal Dashboard: ${baseUrl}/?token=${this.authToken}
4621
+ Sanctuary Principal Dashboard: ${baseUrl}
4504
4622
  `
4505
4623
  );
4506
4624
  process.stderr.write(
4507
- ` Auth token: ${this.authToken}
4625
+ ` Auth required (token: ${hint}). Use Authorization: Bearer <TOKEN> header.
4508
4626
 
4509
4627
  `
4510
4628
  );
@@ -4538,6 +4656,11 @@ var DashboardApprovalChannel = class {
4538
4656
  client.end();
4539
4657
  }
4540
4658
  this.sseClients.clear();
4659
+ this.sessions.clear();
4660
+ if (this.sessionCleanupTimer) {
4661
+ clearInterval(this.sessionCleanupTimer);
4662
+ this.sessionCleanupTimer = null;
4663
+ }
4541
4664
  if (this.httpServer) {
4542
4665
  return new Promise((resolve) => {
4543
4666
  this.httpServer.close(() => resolve());
@@ -4558,7 +4681,8 @@ var DashboardApprovalChannel = class {
4558
4681
  const timer = setTimeout(() => {
4559
4682
  this.pending.delete(id);
4560
4683
  const response = {
4561
- decision: this.config.auto_deny ? "deny" : "approve",
4684
+ // SEC-002: Timeout ALWAYS denies. No configuration can change this.
4685
+ decision: "deny",
4562
4686
  decided_at: (/* @__PURE__ */ new Date()).toISOString(),
4563
4687
  decided_by: "timeout"
4564
4688
  };
@@ -4590,7 +4714,12 @@ var DashboardApprovalChannel = class {
4590
4714
  // ── Authentication ──────────────────────────────────────────────────
4591
4715
  /**
4592
4716
  * Verify bearer token authentication.
4593
- * Checks Authorization header first, falls back to ?token= query param.
4717
+ *
4718
+ * SEC-012: The long-lived auth token is ONLY accepted via the Authorization
4719
+ * header — never in URL query strings. For SSE and page loads that cannot
4720
+ * set headers, a short-lived session token (obtained via POST /auth/session)
4721
+ * is accepted via ?session= query parameter.
4722
+ *
4594
4723
  * Returns true if auth passes, false if blocked (response already sent).
4595
4724
  */
4596
4725
  checkAuth(req, url, res) {
@@ -4602,19 +4731,71 @@ var DashboardApprovalChannel = class {
4602
4731
  return true;
4603
4732
  }
4604
4733
  }
4605
- const queryToken = url.searchParams.get("token");
4606
- if (queryToken === this.authToken) {
4734
+ const sessionId = url.searchParams.get("session");
4735
+ if (sessionId && this.validateSession(sessionId)) {
4607
4736
  return true;
4608
4737
  }
4609
4738
  res.writeHead(401, { "Content-Type": "application/json" });
4610
- res.end(JSON.stringify({ error: "Unauthorized \u2014 valid bearer token required" }));
4739
+ res.end(JSON.stringify({ error: "Unauthorized \u2014 use Authorization: Bearer header or a valid session" }));
4611
4740
  return false;
4612
4741
  }
4742
+ // ── Session Management (SEC-012) ──────────────────────────────────
4743
+ /**
4744
+ * Create a short-lived session by exchanging the long-lived auth token
4745
+ * (provided in the Authorization header) for a session ID.
4746
+ */
4747
+ createSession() {
4748
+ if (this.sessions.size >= MAX_SESSIONS) {
4749
+ this.cleanupSessions();
4750
+ if (this.sessions.size >= MAX_SESSIONS) {
4751
+ const oldest = [...this.sessions.entries()].sort(
4752
+ (a, b) => a[1].created_at - b[1].created_at
4753
+ )[0];
4754
+ if (oldest) this.sessions.delete(oldest[0]);
4755
+ }
4756
+ }
4757
+ const id = crypto.randomBytes(32).toString("hex");
4758
+ const now = Date.now();
4759
+ this.sessions.set(id, {
4760
+ id,
4761
+ created_at: now,
4762
+ expires_at: now + SESSION_TTL_MS
4763
+ });
4764
+ return id;
4765
+ }
4766
+ /**
4767
+ * Validate a session ID — must exist and not be expired.
4768
+ */
4769
+ validateSession(sessionId) {
4770
+ const session = this.sessions.get(sessionId);
4771
+ if (!session) return false;
4772
+ if (Date.now() > session.expires_at) {
4773
+ this.sessions.delete(sessionId);
4774
+ return false;
4775
+ }
4776
+ return true;
4777
+ }
4778
+ /**
4779
+ * Remove all expired sessions.
4780
+ */
4781
+ cleanupSessions() {
4782
+ const now = Date.now();
4783
+ for (const [id, session] of this.sessions) {
4784
+ if (now > session.expires_at) {
4785
+ this.sessions.delete(id);
4786
+ }
4787
+ }
4788
+ }
4613
4789
  // ── HTTP Request Handler ────────────────────────────────────────────
4614
4790
  handleRequest(req, res) {
4615
4791
  const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
4616
4792
  const method = req.method ?? "GET";
4617
- res.setHeader("Access-Control-Allow-Origin", "*");
4793
+ const origin = req.headers.origin;
4794
+ const protocol = this.useTLS ? "https" : "http";
4795
+ const selfOrigin = `${protocol}://${this.config.host}:${this.config.port}`;
4796
+ if (origin === selfOrigin) {
4797
+ res.setHeader("Access-Control-Allow-Origin", origin);
4798
+ }
4618
4799
  res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
4619
4800
  res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
4620
4801
  if (method === "OPTIONS") {
@@ -4624,6 +4805,10 @@ var DashboardApprovalChannel = class {
4624
4805
  }
4625
4806
  if (!this.checkAuth(req, url, res)) return;
4626
4807
  try {
4808
+ if (method === "POST" && url.pathname === "/auth/session") {
4809
+ this.handleSessionExchange(req, res);
4810
+ return;
4811
+ }
4627
4812
  if (method === "GET" && url.pathname === "/") {
4628
4813
  this.serveDashboard(res);
4629
4814
  } else if (method === "GET" && url.pathname === "/events") {
@@ -4650,6 +4835,40 @@ var DashboardApprovalChannel = class {
4650
4835
  }
4651
4836
  }
4652
4837
  // ── Route Handlers ──────────────────────────────────────────────────
4838
+ /**
4839
+ * SEC-012: Exchange a long-lived auth token (in Authorization header)
4840
+ * for a short-lived session ID. The session ID can be used in URL
4841
+ * query parameters without exposing the long-lived credential.
4842
+ *
4843
+ * This endpoint performs its OWN auth check (header-only) because it
4844
+ * must reject query-parameter tokens and is called before the
4845
+ * normal checkAuth flow.
4846
+ */
4847
+ handleSessionExchange(req, res) {
4848
+ if (!this.authToken) {
4849
+ res.writeHead(200, { "Content-Type": "application/json" });
4850
+ res.end(JSON.stringify({ session_id: "no-auth" }));
4851
+ return;
4852
+ }
4853
+ const authHeader = req.headers.authorization;
4854
+ if (!authHeader) {
4855
+ res.writeHead(401, { "Content-Type": "application/json" });
4856
+ res.end(JSON.stringify({ error: "Authorization header required" }));
4857
+ return;
4858
+ }
4859
+ const parts = authHeader.split(" ");
4860
+ if (parts.length !== 2 || parts[0] !== "Bearer" || parts[1] !== this.authToken) {
4861
+ res.writeHead(401, { "Content-Type": "application/json" });
4862
+ res.end(JSON.stringify({ error: "Invalid bearer token" }));
4863
+ return;
4864
+ }
4865
+ const sessionId = this.createSession();
4866
+ res.writeHead(200, { "Content-Type": "application/json" });
4867
+ res.end(JSON.stringify({
4868
+ session_id: sessionId,
4869
+ expires_in_seconds: SESSION_TTL_MS / 1e3
4870
+ }));
4871
+ }
4653
4872
  serveDashboard(res) {
4654
4873
  res.writeHead(200, {
4655
4874
  "Content-Type": "text/html; charset=utf-8",
@@ -4675,7 +4894,8 @@ var DashboardApprovalChannel = class {
4675
4894
  approval_channel: {
4676
4895
  type: this.policy.approval_channel.type,
4677
4896
  timeout_seconds: this.policy.approval_channel.timeout_seconds,
4678
- auto_deny: this.policy.approval_channel.auto_deny
4897
+ auto_deny: true
4898
+ // SEC-002: hardcoded, not configurable
4679
4899
  }
4680
4900
  };
4681
4901
  }
@@ -4716,7 +4936,8 @@ data: ${JSON.stringify(initData)}
4716
4936
  approval_channel: {
4717
4937
  type: this.policy.approval_channel.type,
4718
4938
  timeout_seconds: this.policy.approval_channel.timeout_seconds,
4719
- auto_deny: this.policy.approval_channel.auto_deny
4939
+ auto_deny: true
4940
+ // SEC-002: hardcoded, not configurable
4720
4941
  }
4721
4942
  };
4722
4943
  }
@@ -4889,7 +5110,8 @@ var WebhookApprovalChannel = class {
4889
5110
  const timer = setTimeout(() => {
4890
5111
  this.pending.delete(id);
4891
5112
  const response = {
4892
- decision: this.config.auto_deny ? "deny" : "approve",
5113
+ // SEC-002: Timeout ALWAYS denies. No configuration can change this.
5114
+ decision: "deny",
4893
5115
  decided_at: (/* @__PURE__ */ new Date()).toISOString(),
4894
5116
  decided_by: "timeout"
4895
5117
  };
@@ -5077,16 +5299,29 @@ var ApprovalGate = class {
5077
5299
  if (anomaly) {
5078
5300
  return this.requestApproval(operation, 2, anomaly.reason, anomaly.context);
5079
5301
  }
5080
- this.auditLog.append("l2", `gate_allow:${operation}`, "system", {
5081
- tier: 3,
5082
- operation
5302
+ if (this.policy.tier3_always_allow.includes(operation)) {
5303
+ this.auditLog.append("l2", `gate_allow:${operation}`, "system", {
5304
+ tier: 3,
5305
+ operation
5306
+ });
5307
+ return {
5308
+ allowed: true,
5309
+ tier: 3,
5310
+ reason: "Operation allowed (Tier 3)",
5311
+ approval_required: false
5312
+ };
5313
+ }
5314
+ this.auditLog.append("l2", `gate_unclassified:${operation}`, "system", {
5315
+ tier: 1,
5316
+ operation,
5317
+ warning: "Operation is not classified in any policy tier \u2014 defaulting to Tier 1 (require approval)"
5083
5318
  });
5084
- return {
5085
- allowed: true,
5086
- tier: 3,
5087
- reason: "Operation allowed (Tier 3)",
5088
- approval_required: false
5089
- };
5319
+ return this.requestApproval(
5320
+ operation,
5321
+ 1,
5322
+ `"${operation}" is not classified in any policy tier \u2014 requires approval (SEC-011 safe default)`,
5323
+ { operation, unclassified: true }
5324
+ );
5090
5325
  }
5091
5326
  /**
5092
5327
  * Detect Tier 2 behavioral anomalies.
@@ -5259,7 +5494,8 @@ function createPrincipalPolicyTools(policy, baseline, auditLog) {
5259
5494
  approval_channel: {
5260
5495
  type: policy.approval_channel.type,
5261
5496
  timeout_seconds: policy.approval_channel.timeout_seconds,
5262
- auto_deny: policy.approval_channel.auto_deny
5497
+ auto_deny: true
5498
+ // SEC-002: hardcoded, not configurable
5263
5499
  }
5264
5500
  };
5265
5501
  if (includeDefaults) {
@@ -5790,7 +6026,9 @@ function createHandshakeTools(config, identityManager, masterKey, auditLog) {
5790
6026
  return toolResult({
5791
6027
  session_id: result.session.session_id,
5792
6028
  response: result.response,
5793
- instructions: "Send the 'response' object back to the initiator. When you receive their completion, pass it to sanctuary/handshake_status with this session_id."
6029
+ instructions: "Send the 'response' object back to the initiator. When you receive their completion, pass it to sanctuary/handshake_status with this session_id.",
6030
+ // SEC-ADD-03: Tag response — contains SHR data that will be sent to counterparty
6031
+ _content_trust: "external"
5794
6032
  });
5795
6033
  }
5796
6034
  },
@@ -5843,7 +6081,9 @@ function createHandshakeTools(config, identityManager, masterKey, auditLog) {
5843
6081
  return toolResult({
5844
6082
  completion: result.completion,
5845
6083
  result: result.result,
5846
- instructions: "Send the 'completion' object to the responder so they can verify the handshake. The 'result' object contains the verified counterparty status and trust tier."
6084
+ instructions: "Send the 'completion' object to the responder so they can verify the handshake. The 'result' object contains the verified counterparty status and trust tier.",
6085
+ // SEC-ADD-03: Tag response as containing counterparty-controlled SHR data
6086
+ _content_trust: "external"
5847
6087
  });
5848
6088
  }
5849
6089
  },
@@ -6268,7 +6508,21 @@ function canonicalize(outcome) {
6268
6508
  return stringToBytes(stableStringify(outcome));
6269
6509
  }
6270
6510
  function stableStringify(value) {
6271
- if (value === null || value === void 0) return JSON.stringify(value);
6511
+ if (value === null) return "null";
6512
+ if (value === void 0) return "null";
6513
+ if (typeof value === "number") {
6514
+ if (!Number.isFinite(value)) {
6515
+ throw new Error(
6516
+ `Cannot canonicalize non-finite number: ${value}. NaN, Infinity, and -Infinity are not representable in JSON.`
6517
+ );
6518
+ }
6519
+ if (Object.is(value, -0)) {
6520
+ throw new Error(
6521
+ "Cannot canonicalize negative zero (-0). Use 0 instead for deterministic cross-language serialization."
6522
+ );
6523
+ }
6524
+ return JSON.stringify(value);
6525
+ }
6272
6526
  if (typeof value !== "object") return JSON.stringify(value);
6273
6527
  if (Array.isArray(value)) {
6274
6528
  return "[" + value.map((v) => stableStringify(v)).join(",") + "]";
@@ -6296,11 +6550,12 @@ function createBridgeCommitment(outcome, identity, identityEncryptionKey, includ
6296
6550
  bridge_commitment_id: commitmentId,
6297
6551
  session_id: outcome.session_id,
6298
6552
  sha256_commitment: sha2564.commitment,
6553
+ terms_hash: outcome.terms_hash,
6299
6554
  committer_did: identity.did,
6300
6555
  committed_at: now,
6301
6556
  bridge_version: "sanctuary-concordia-bridge-v1"
6302
6557
  };
6303
- const payloadBytes = stringToBytes(JSON.stringify(commitmentPayload));
6558
+ const payloadBytes = stringToBytes(stableStringify(commitmentPayload));
6304
6559
  const signature = sign(payloadBytes, identity.encrypted_private_key, identityEncryptionKey);
6305
6560
  return {
6306
6561
  bridge_commitment_id: commitmentId,
@@ -6326,11 +6581,12 @@ function verifyBridgeCommitment(commitment, outcome, committerPublicKey) {
6326
6581
  bridge_commitment_id: commitment.bridge_commitment_id,
6327
6582
  session_id: commitment.session_id,
6328
6583
  sha256_commitment: commitment.sha256_commitment,
6584
+ terms_hash: outcome.terms_hash,
6329
6585
  committer_did: commitment.committer_did,
6330
6586
  committed_at: commitment.committed_at,
6331
6587
  bridge_version: commitment.bridge_version
6332
6588
  };
6333
- const payloadBytes = stringToBytes(JSON.stringify(commitmentPayload));
6589
+ const payloadBytes = stringToBytes(stableStringify(commitmentPayload));
6334
6590
  const sigBytes = fromBase64url(commitment.signature);
6335
6591
  const signatureValid = verify(payloadBytes, sigBytes, committerPublicKey);
6336
6592
  const sessionIdMatch = commitment.session_id === outcome.session_id;
@@ -6557,7 +6813,9 @@ function createBridgeTools(storage, masterKey, identityManager, auditLog, handsh
6557
6813
  return toolResult({
6558
6814
  ...result,
6559
6815
  session_id: storedCommitment.session_id,
6560
- committer_did: storedCommitment.committer_did
6816
+ committer_did: storedCommitment.committer_did,
6817
+ // SEC-ADD-03: Tag response as containing counterparty-controlled data
6818
+ _content_trust: "external"
6561
6819
  });
6562
6820
  }
6563
6821
  },
@@ -6651,6 +6909,668 @@ function createBridgeTools(storage, masterKey, identityManager, auditLog, handsh
6651
6909
  ];
6652
6910
  return { tools };
6653
6911
  }
6912
+ function lenientJsonParse(raw) {
6913
+ let cleaned = raw.replace(/\/\/[^\n]*/g, "");
6914
+ cleaned = cleaned.replace(/\/\*[\s\S]*?\*\//g, "");
6915
+ cleaned = cleaned.replace(/,\s*([\]}])/g, "$1");
6916
+ return JSON.parse(cleaned);
6917
+ }
6918
+ async function fileExists(path) {
6919
+ try {
6920
+ await promises.access(path);
6921
+ return true;
6922
+ } catch {
6923
+ return false;
6924
+ }
6925
+ }
6926
+ async function safeReadFile(path) {
6927
+ try {
6928
+ return await promises.readFile(path, "utf-8");
6929
+ } catch {
6930
+ return null;
6931
+ }
6932
+ }
6933
+ async function detectEnvironment(config, deepScan) {
6934
+ const fingerprint = {
6935
+ sanctuary_installed: true,
6936
+ // We're running inside Sanctuary
6937
+ sanctuary_version: config.version,
6938
+ openclaw_detected: false,
6939
+ openclaw_version: null,
6940
+ openclaw_config: null,
6941
+ node_version: process.version,
6942
+ platform: `${process.platform}-${process.arch}`
6943
+ };
6944
+ if (!deepScan) {
6945
+ return fingerprint;
6946
+ }
6947
+ const home = os.homedir();
6948
+ const openclawConfigPath = path.join(home, ".openclaw", "openclaw.json");
6949
+ const openclawEnvPath = path.join(home, ".openclaw", ".env");
6950
+ const openclawMemoryPath = path.join(home, ".openclaw", "workspace", "MEMORY.md");
6951
+ const openclawMemoryDir = path.join(home, ".openclaw", "workspace", "memory");
6952
+ const configExists = await fileExists(openclawConfigPath);
6953
+ const envExists = await fileExists(openclawEnvPath);
6954
+ const memoryExists = await fileExists(openclawMemoryPath);
6955
+ const memoryDirExists = await fileExists(openclawMemoryDir);
6956
+ if (configExists || memoryExists || memoryDirExists) {
6957
+ fingerprint.openclaw_detected = true;
6958
+ fingerprint.openclaw_config = await auditOpenClawConfig(
6959
+ openclawConfigPath,
6960
+ openclawEnvPath,
6961
+ openclawMemoryPath,
6962
+ configExists,
6963
+ envExists,
6964
+ memoryExists
6965
+ );
6966
+ }
6967
+ return fingerprint;
6968
+ }
6969
+ async function auditOpenClawConfig(configPath, envPath, _memoryPath, configExists, envExists, memoryExists) {
6970
+ const audit = {
6971
+ config_path: configExists ? configPath : null,
6972
+ require_approval_enabled: false,
6973
+ sandbox_policy_active: false,
6974
+ sandbox_allow_list: [],
6975
+ sandbox_deny_list: [],
6976
+ memory_encrypted: false,
6977
+ // Stock OpenClaw never encrypts memory
6978
+ env_file_exposed: false,
6979
+ gateway_token_set: false,
6980
+ dm_pairing_enabled: false,
6981
+ mcp_bridge_active: false
6982
+ };
6983
+ if (configExists) {
6984
+ const raw = await safeReadFile(configPath);
6985
+ if (raw) {
6986
+ try {
6987
+ const parsed = lenientJsonParse(raw);
6988
+ const hooks = parsed.hooks;
6989
+ if (hooks) {
6990
+ const beforeToolCall = hooks.before_tool_call;
6991
+ if (beforeToolCall) {
6992
+ const hookStr = JSON.stringify(beforeToolCall);
6993
+ audit.require_approval_enabled = hookStr.includes("requireApproval");
6994
+ }
6995
+ }
6996
+ const tools = parsed.tools;
6997
+ if (tools) {
6998
+ const sandbox = tools.sandbox;
6999
+ if (sandbox) {
7000
+ const sandboxTools = sandbox.tools;
7001
+ if (sandboxTools) {
7002
+ audit.sandbox_policy_active = true;
7003
+ if (Array.isArray(sandboxTools.allow)) {
7004
+ audit.sandbox_allow_list = sandboxTools.allow.filter(
7005
+ (item) => typeof item === "string"
7006
+ );
7007
+ }
7008
+ if (Array.isArray(sandboxTools.alsoAllow)) {
7009
+ audit.sandbox_allow_list = [
7010
+ ...audit.sandbox_allow_list,
7011
+ ...sandboxTools.alsoAllow.filter(
7012
+ (item) => typeof item === "string"
7013
+ )
7014
+ ];
7015
+ }
7016
+ if (Array.isArray(sandboxTools.deny)) {
7017
+ audit.sandbox_deny_list = sandboxTools.deny.filter(
7018
+ (item) => typeof item === "string"
7019
+ );
7020
+ }
7021
+ }
7022
+ }
7023
+ }
7024
+ const mcpServers = parsed.mcpServers;
7025
+ if (mcpServers && Object.keys(mcpServers).length > 0) {
7026
+ audit.mcp_bridge_active = true;
7027
+ }
7028
+ } catch {
7029
+ }
7030
+ }
7031
+ }
7032
+ if (envExists) {
7033
+ const envContent = await safeReadFile(envPath);
7034
+ if (envContent) {
7035
+ const secretPatterns = [
7036
+ /[A-Z_]*API_KEY\s*=/,
7037
+ /[A-Z_]*TOKEN\s*=/,
7038
+ /[A-Z_]*SECRET\s*=/,
7039
+ /[A-Z_]*PASSWORD\s*=/,
7040
+ /[A-Z_]*PRIVATE_KEY\s*=/
7041
+ ];
7042
+ audit.env_file_exposed = secretPatterns.some((p) => p.test(envContent));
7043
+ audit.gateway_token_set = /OPENCLAW_GATEWAY_TOKEN\s*=/.test(envContent);
7044
+ }
7045
+ }
7046
+ if (memoryExists) {
7047
+ audit.memory_encrypted = false;
7048
+ }
7049
+ return audit;
7050
+ }
7051
+
7052
+ // src/audit/analyzer.ts
7053
+ var L1_ENCRYPTION_AT_REST = 10;
7054
+ var L1_IDENTITY_CRYPTOGRAPHIC = 10;
7055
+ var L1_INTEGRITY_VERIFICATION = 8;
7056
+ var L1_STATE_PORTABLE = 7;
7057
+ var L2_THREE_TIER_GATE = 10;
7058
+ var L2_BINARY_GATE = 3;
7059
+ var L2_ANOMALY_DETECTION = 7;
7060
+ var L2_ENCRYPTED_AUDIT = 5;
7061
+ var L2_TOOL_SANDBOXING = 3;
7062
+ var L3_COMMITMENT_SCHEME = 8;
7063
+ var L3_ZK_PROOFS = 7;
7064
+ var L3_DISCLOSURE_POLICIES = 5;
7065
+ var L4_PORTABLE_REPUTATION = 6;
7066
+ var L4_SIGNED_ATTESTATIONS = 6;
7067
+ var L4_SYBIL_DETECTION = 4;
7068
+ var L4_SOVEREIGNTY_GATED = 4;
7069
+ var SEVERITY_ORDER = {
7070
+ critical: 0,
7071
+ high: 1,
7072
+ medium: 2,
7073
+ low: 3
7074
+ };
7075
+ function analyzeSovereignty(env, config) {
7076
+ const l1 = assessL1(env, config);
7077
+ const l2 = assessL2(env);
7078
+ const l3 = assessL3(env);
7079
+ const l4 = assessL4(env);
7080
+ const l1Score = scoreL1(l1);
7081
+ const l2Score = scoreL2(l2);
7082
+ const l3Score = scoreL3(l3);
7083
+ const l4Score = scoreL4(l4);
7084
+ const overallScore = l1Score + l2Score + l3Score + l4Score;
7085
+ const sovereigntyLevel = overallScore >= 80 ? "full" : overallScore >= 50 ? "partial" : overallScore >= 20 ? "minimal" : "none";
7086
+ const gaps = generateGaps(env, l1, l2, l3, l4);
7087
+ gaps.sort((a, b) => SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity]);
7088
+ const recommendations = generateRecommendations(env, l1, l2, l3, l4);
7089
+ return {
7090
+ version: "1.0",
7091
+ audited_at: (/* @__PURE__ */ new Date()).toISOString(),
7092
+ environment: env,
7093
+ layers: {
7094
+ l1_cognitive: l1,
7095
+ l2_operational: l2,
7096
+ l3_selective_disclosure: l3,
7097
+ l4_reputation: l4
7098
+ },
7099
+ overall_score: overallScore,
7100
+ sovereignty_level: sovereigntyLevel,
7101
+ gaps,
7102
+ recommendations
7103
+ };
7104
+ }
7105
+ function assessL1(env, config) {
7106
+ const findings = [];
7107
+ const sanctuaryActive = env.sanctuary_installed;
7108
+ const encryptionAtRest = sanctuaryActive;
7109
+ const keyCustody = sanctuaryActive ? "self" : "none";
7110
+ const integrityVerification = sanctuaryActive;
7111
+ const identityCryptographic = sanctuaryActive;
7112
+ const statePortable = sanctuaryActive;
7113
+ if (sanctuaryActive) {
7114
+ findings.push("AES-256-GCM encryption active for all state");
7115
+ findings.push(`Key derivation: ${config.state.key_derivation}`);
7116
+ findings.push(`Identity provider: ${config.state.identity_provider}`);
7117
+ findings.push("Merkle integrity verification enabled");
7118
+ findings.push("State export/import available");
7119
+ }
7120
+ if (env.openclaw_detected && env.openclaw_config) {
7121
+ if (!env.openclaw_config.memory_encrypted) {
7122
+ findings.push("OpenClaw agent memory (MEMORY.md, daily notes) stored in plaintext");
7123
+ }
7124
+ if (env.openclaw_config.env_file_exposed) {
7125
+ findings.push("OpenClaw .env file contains plaintext API keys/tokens");
7126
+ }
7127
+ }
7128
+ const status = encryptionAtRest && identityCryptographic ? "active" : encryptionAtRest || identityCryptographic ? "partial" : "inactive";
7129
+ return {
7130
+ status,
7131
+ encryption_at_rest: encryptionAtRest,
7132
+ key_custody: keyCustody,
7133
+ integrity_verification: integrityVerification,
7134
+ identity_cryptographic: identityCryptographic,
7135
+ state_portable: statePortable,
7136
+ findings
7137
+ };
7138
+ }
7139
+ function assessL2(env, _config) {
7140
+ const findings = [];
7141
+ const sanctuaryActive = env.sanctuary_installed;
7142
+ let approvalGate = "none";
7143
+ let behavioralAnomalyDetection = false;
7144
+ let auditTrailEncrypted = false;
7145
+ let auditTrailExists = false;
7146
+ let toolSandboxing = "none";
7147
+ if (sanctuaryActive) {
7148
+ approvalGate = "three-tier";
7149
+ behavioralAnomalyDetection = true;
7150
+ auditTrailEncrypted = true;
7151
+ auditTrailExists = true;
7152
+ findings.push("Three-tier Principal Policy gate active");
7153
+ findings.push("Behavioral anomaly detection (BaselineTracker) enabled");
7154
+ findings.push("Encrypted audit trail active");
7155
+ }
7156
+ if (env.openclaw_detected && env.openclaw_config) {
7157
+ if (env.openclaw_config.require_approval_enabled) {
7158
+ if (!sanctuaryActive) {
7159
+ approvalGate = "binary";
7160
+ }
7161
+ findings.push("OpenClaw requireApproval hook enabled (binary approve/deny)");
7162
+ }
7163
+ if (env.openclaw_config.sandbox_policy_active) {
7164
+ if (!sanctuaryActive) {
7165
+ toolSandboxing = "basic";
7166
+ }
7167
+ findings.push(
7168
+ `OpenClaw sandbox policy active (${env.openclaw_config.sandbox_allow_list.length} allowed, ${env.openclaw_config.sandbox_deny_list.length} denied)`
7169
+ );
7170
+ }
7171
+ }
7172
+ const status = approvalGate === "three-tier" && auditTrailEncrypted ? "active" : approvalGate !== "none" || auditTrailExists ? "partial" : "inactive";
7173
+ return {
7174
+ status,
7175
+ approval_gate: approvalGate,
7176
+ behavioral_anomaly_detection: behavioralAnomalyDetection,
7177
+ audit_trail_encrypted: auditTrailEncrypted,
7178
+ audit_trail_exists: auditTrailExists,
7179
+ tool_sandboxing: sanctuaryActive ? "policy-enforced" : toolSandboxing,
7180
+ findings
7181
+ };
7182
+ }
7183
+ function assessL3(env, _config) {
7184
+ const findings = [];
7185
+ const sanctuaryActive = env.sanctuary_installed;
7186
+ let commitmentScheme = "none";
7187
+ let zkProofs = false;
7188
+ let selectiveDisclosurePolicy = false;
7189
+ if (sanctuaryActive) {
7190
+ commitmentScheme = "pedersen+sha256";
7191
+ zkProofs = true;
7192
+ selectiveDisclosurePolicy = true;
7193
+ findings.push("SHA-256 + Pedersen commitment schemes active");
7194
+ findings.push("Schnorr ZK proofs and range proofs available");
7195
+ findings.push("Selective disclosure policies configurable");
7196
+ }
7197
+ const status = commitmentScheme === "pedersen+sha256" && zkProofs ? "active" : commitmentScheme !== "none" ? "partial" : "inactive";
7198
+ return {
7199
+ status,
7200
+ commitment_scheme: commitmentScheme,
7201
+ zero_knowledge_proofs: zkProofs,
7202
+ selective_disclosure_policy: selectiveDisclosurePolicy,
7203
+ findings
7204
+ };
7205
+ }
7206
+ function assessL4(env, _config) {
7207
+ const findings = [];
7208
+ const sanctuaryActive = env.sanctuary_installed;
7209
+ const reputationPortable = sanctuaryActive;
7210
+ const reputationSigned = sanctuaryActive;
7211
+ const sybilDetection = sanctuaryActive;
7212
+ const sovereigntyGated = sanctuaryActive;
7213
+ if (sanctuaryActive) {
7214
+ findings.push("Signed EAS-compatible attestations active");
7215
+ findings.push("Reputation export/import available");
7216
+ findings.push("Sybil detection heuristics enabled");
7217
+ findings.push("Sovereignty-gated reputation tiers active");
7218
+ } else {
7219
+ findings.push("No portable reputation system detected");
7220
+ }
7221
+ const status = reputationPortable && reputationSigned && sovereigntyGated ? "active" : reputationPortable || reputationSigned ? "partial" : "inactive";
7222
+ return {
7223
+ status,
7224
+ reputation_portable: reputationPortable,
7225
+ reputation_signed: reputationSigned,
7226
+ reputation_sybil_detection: sybilDetection,
7227
+ sovereignty_gated_tiers: sovereigntyGated,
7228
+ findings
7229
+ };
7230
+ }
7231
+ function scoreL1(l1) {
7232
+ let score = 0;
7233
+ if (l1.encryption_at_rest) score += L1_ENCRYPTION_AT_REST;
7234
+ if (l1.identity_cryptographic) score += L1_IDENTITY_CRYPTOGRAPHIC;
7235
+ if (l1.integrity_verification) score += L1_INTEGRITY_VERIFICATION;
7236
+ if (l1.state_portable) score += L1_STATE_PORTABLE;
7237
+ return score;
7238
+ }
7239
+ function scoreL2(l2) {
7240
+ let score = 0;
7241
+ if (l2.approval_gate === "three-tier") score += L2_THREE_TIER_GATE;
7242
+ else if (l2.approval_gate === "binary") score += L2_BINARY_GATE;
7243
+ if (l2.behavioral_anomaly_detection) score += L2_ANOMALY_DETECTION;
7244
+ if (l2.audit_trail_encrypted) score += L2_ENCRYPTED_AUDIT;
7245
+ if (l2.tool_sandboxing === "policy-enforced") score += L2_TOOL_SANDBOXING;
7246
+ else if (l2.tool_sandboxing === "basic") score += 1;
7247
+ return score;
7248
+ }
7249
+ function scoreL3(l3) {
7250
+ let score = 0;
7251
+ if (l3.commitment_scheme === "pedersen+sha256") score += L3_COMMITMENT_SCHEME;
7252
+ else if (l3.commitment_scheme === "sha256-only") score += 4;
7253
+ if (l3.zero_knowledge_proofs) score += L3_ZK_PROOFS;
7254
+ if (l3.selective_disclosure_policy) score += L3_DISCLOSURE_POLICIES;
7255
+ return score;
7256
+ }
7257
+ function scoreL4(l4) {
7258
+ let score = 0;
7259
+ if (l4.reputation_portable) score += L4_PORTABLE_REPUTATION;
7260
+ if (l4.reputation_signed) score += L4_SIGNED_ATTESTATIONS;
7261
+ if (l4.reputation_sybil_detection) score += L4_SYBIL_DETECTION;
7262
+ if (l4.sovereignty_gated_tiers) score += L4_SOVEREIGNTY_GATED;
7263
+ return score;
7264
+ }
7265
+ function generateGaps(env, l1, l2, l3, l4) {
7266
+ const gaps = [];
7267
+ const oc = env.openclaw_config;
7268
+ if (oc && !oc.memory_encrypted) {
7269
+ gaps.push({
7270
+ id: "GAP-L1-001",
7271
+ layer: "L1",
7272
+ severity: "critical",
7273
+ title: "Agent memory stored in plaintext",
7274
+ description: "Your agent's memory (MEMORY.md, daily notes, SQLite index) is stored in plaintext at ~/.openclaw/workspace/. Any process with file access can read your agent's full context \u2014 preferences, decisions, conversation history.",
7275
+ openclaw_relevance: "Stock OpenClaw stores all agent memory in plaintext files. There is no built-in encryption for agent state.",
7276
+ sanctuary_solution: "Sanctuary encrypts all state at rest with AES-256-GCM using a key derived from Argon2id, making state opaque to any process that doesn't hold the master key. Use sanctuary/state_write to migrate sensitive state to the encrypted store."
7277
+ });
7278
+ }
7279
+ if (oc && oc.env_file_exposed) {
7280
+ gaps.push({
7281
+ id: "GAP-L1-002",
7282
+ layer: "L1",
7283
+ severity: "critical",
7284
+ title: "Plaintext API keys in .env file",
7285
+ description: "Your .env file contains plaintext API keys and tokens. These secrets are readable by any process with filesystem access.",
7286
+ openclaw_relevance: "OpenClaw stores API keys (LLM providers, gateway tokens) in a plaintext .env file.",
7287
+ sanctuary_solution: "Sanctuary's encrypted state store can hold secrets under the same AES-256-GCM envelope as all other state, tied to your self-custodied identity. Use sanctuary/state_write with namespace 'secrets'."
7288
+ });
7289
+ }
7290
+ if (!l1.identity_cryptographic) {
7291
+ gaps.push({
7292
+ id: "GAP-L1-003",
7293
+ layer: "L1",
7294
+ severity: "critical",
7295
+ title: "No cryptographic agent identity",
7296
+ description: "Your agent has no cryptographic identity. It cannot prove it is who it claims to be to any counterparty, sign messages, or participate in sovereignty handshakes.",
7297
+ openclaw_relevance: env.openclaw_detected ? "OpenClaw has no cryptographic agent identity. Agent identity is implicit (tied to the process/session), not cryptographically verifiable." : null,
7298
+ sanctuary_solution: "Sanctuary provides Ed25519 self-custodied identity with key rotation and delegation. Use sanctuary/identity_create to establish your cryptographic identity."
7299
+ });
7300
+ }
7301
+ if (l2.approval_gate === "binary" && !l2.behavioral_anomaly_detection) {
7302
+ gaps.push({
7303
+ id: "GAP-L2-001",
7304
+ layer: "L2",
7305
+ severity: "high",
7306
+ title: "Binary approval gate (no anomaly detection)",
7307
+ description: "Your approval gate provides binary approve/deny gating without behavioral anomaly detection. Routine operations require the same manual approval as sensitive ones.",
7308
+ openclaw_relevance: env.openclaw_detected ? "OpenClaw's requireApproval hook provides binary approve/deny gating. Sanctuary's three-tier Principal Policy adds behavioral anomaly detection (auto-escalation when agent behavior deviates from baseline), encrypted audit trails, and graduated approval tiers \u2014 so routine operations auto-proceed while sensitive operations require explicit consent." : null,
7309
+ sanctuary_solution: "Sanctuary's three-tier Principal Policy gate auto-allows routine operations (Tier 3), escalates anomalous behavior (Tier 2), and always requires human approval for irreversible operations (Tier 1). Use sanctuary/principal_policy_view to inspect."
7310
+ });
7311
+ } else if (l2.approval_gate === "none") {
7312
+ gaps.push({
7313
+ id: "GAP-L2-001",
7314
+ layer: "L2",
7315
+ severity: "critical",
7316
+ title: "No approval gate",
7317
+ description: "No approval gate is configured. All tool calls execute without oversight.",
7318
+ openclaw_relevance: null,
7319
+ sanctuary_solution: "Sanctuary's Principal Policy evaluates every tool call before execution. Enable it to get three-tier approval gating with behavioral anomaly detection."
7320
+ });
7321
+ }
7322
+ if (l2.tool_sandboxing === "basic") {
7323
+ gaps.push({
7324
+ id: "GAP-L2-002",
7325
+ layer: "L2",
7326
+ severity: "medium",
7327
+ title: "Basic tool sandboxing (no cryptographic attestation)",
7328
+ description: "Your tool sandbox enforces allow/deny lists but provides no cryptographic attestation of execution context.",
7329
+ openclaw_relevance: env.openclaw_detected ? "OpenClaw's sandbox tool policy (tools.sandbox.tools) enforces allow/deny lists. Sanctuary adds cryptographic attestation of execution context \u2014 a verifiable proof that an operation ran within policy, not just that a policy was configured." : null,
7330
+ sanctuary_solution: "Sanctuary provides cryptographic execution attestation via sanctuary/exec_attest and policy-enforced sandboxing with encrypted audit trails."
7331
+ });
7332
+ }
7333
+ if (!l2.audit_trail_exists) {
7334
+ gaps.push({
7335
+ id: "GAP-L2-003",
7336
+ layer: "L2",
7337
+ severity: "high",
7338
+ title: "No audit trail",
7339
+ description: "No audit trail exists for tool call history. There is no record of what operations were executed, when, or by whom.",
7340
+ openclaw_relevance: null,
7341
+ sanctuary_solution: "Sanctuary maintains an encrypted audit log of all operations, queryable via sanctuary/monitor_audit_log."
7342
+ });
7343
+ }
7344
+ if (l3.commitment_scheme === "none") {
7345
+ gaps.push({
7346
+ id: "GAP-L3-001",
7347
+ layer: "L3",
7348
+ severity: "high",
7349
+ title: "No selective disclosure capability",
7350
+ description: "Your agent has no way to prove facts about its state without revealing the state itself. Every disclosure is all-or-nothing.",
7351
+ openclaw_relevance: env.openclaw_detected ? "OpenClaw has no selective disclosure mechanism. When your agent shares information, it shares everything or nothing \u2014 there is no way to prove a claim without revealing the underlying data." : null,
7352
+ sanctuary_solution: "Sanctuary's L3 provides SHA-256 + Pedersen commitments and Schnorr zero-knowledge proofs. Your agent can prove it has a valid credential, sufficient reputation, or a completed transaction without exposing the underlying data. Use sanctuary/zk_commit and sanctuary/zk_prove."
7353
+ });
7354
+ }
7355
+ if (!l4.reputation_portable) {
7356
+ gaps.push({
7357
+ id: "GAP-L4-001",
7358
+ layer: "L4",
7359
+ severity: "high",
7360
+ title: "No portable reputation",
7361
+ description: "Your agent's reputation is platform-locked. If you move to a different harness or platform, your track record doesn't follow.",
7362
+ openclaw_relevance: env.openclaw_detected ? "OpenClaw has no reputation system. Your agent's track record exists only in conversation history, which is not structured, signed, or portable." : null,
7363
+ sanctuary_solution: "Sanctuary's L4 provides signed EAS-compatible attestations that are self-custodied, portable, and cryptographically verifiable. Your reputation is yours, not your platform's. Use sanctuary/reputation_record to start building portable reputation."
7364
+ });
7365
+ }
7366
+ return gaps;
7367
+ }
7368
+ function generateRecommendations(env, l1, l2, l3, l4) {
7369
+ const recs = [];
7370
+ if (!l1.identity_cryptographic) {
7371
+ recs.push({
7372
+ priority: 1,
7373
+ action: "Create a cryptographic identity \u2014 your agent's foundation for all sovereignty operations",
7374
+ tool: "sanctuary/identity_create",
7375
+ effort: "immediate",
7376
+ impact: "critical"
7377
+ });
7378
+ }
7379
+ if (!l1.encryption_at_rest || env.openclaw_config && !env.openclaw_config.memory_encrypted) {
7380
+ recs.push({
7381
+ priority: 2,
7382
+ action: "Migrate plaintext agent state to Sanctuary's encrypted store",
7383
+ tool: "sanctuary/state_write",
7384
+ effort: "minutes",
7385
+ impact: "critical"
7386
+ });
7387
+ }
7388
+ recs.push({
7389
+ priority: 3,
7390
+ action: "Generate a Sovereignty Health Report to present to counterparties",
7391
+ tool: "sanctuary/shr_generate",
7392
+ effort: "immediate",
7393
+ impact: "high"
7394
+ });
7395
+ if (l2.approval_gate !== "three-tier") {
7396
+ recs.push({
7397
+ priority: 4,
7398
+ action: "Enable the three-tier Principal Policy gate for graduated approval",
7399
+ tool: "sanctuary/principal_policy_view",
7400
+ effort: "minutes",
7401
+ impact: "high"
7402
+ });
7403
+ }
7404
+ if (!l4.reputation_signed) {
7405
+ recs.push({
7406
+ priority: 5,
7407
+ action: "Start recording reputation attestations from completed interactions",
7408
+ tool: "sanctuary/reputation_record",
7409
+ effort: "minutes",
7410
+ impact: "medium"
7411
+ });
7412
+ }
7413
+ if (!l3.selective_disclosure_policy) {
7414
+ recs.push({
7415
+ priority: 6,
7416
+ action: "Configure selective disclosure policies for data sharing",
7417
+ tool: "sanctuary/disclosure_set_policy",
7418
+ effort: "hours",
7419
+ impact: "medium"
7420
+ });
7421
+ }
7422
+ return recs;
7423
+ }
7424
+ function formatAuditReport(result) {
7425
+ const { environment: env, layers, overall_score, sovereignty_level, gaps, recommendations } = result;
7426
+ const scoreBar = formatScoreBar(overall_score);
7427
+ const levelLabel = sovereignty_level.toUpperCase();
7428
+ let report = "";
7429
+ report += "\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n";
7430
+ report += " SOVEREIGNTY AUDIT REPORT\n";
7431
+ report += ` Generated: ${result.audited_at}
7432
+ `;
7433
+ report += "\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n";
7434
+ report += "\n";
7435
+ report += ` Overall Score: ${overall_score} / 100 ${scoreBar} ${levelLabel}
7436
+ `;
7437
+ report += "\n";
7438
+ report += " Environment:\n";
7439
+ report += ` \u2022 Sanctuary v${env.sanctuary_version ?? "?"} ${padDots("Sanctuary v" + (env.sanctuary_version ?? "?"))} ${env.sanctuary_installed ? "\u2713 installed" : "\u2717 not found"}
7440
+ `;
7441
+ if (env.openclaw_detected) {
7442
+ report += ` \u2022 OpenClaw ${padDots("OpenClaw")} \u2713 detected
7443
+ `;
7444
+ if (env.openclaw_config) {
7445
+ report += ` \u2022 OpenClaw requireApproval ${padDots("OpenClaw requireApproval")} ${env.openclaw_config.require_approval_enabled ? "\u2713 enabled" : "\u2717 disabled"}
7446
+ `;
7447
+ report += ` \u2022 OpenClaw sandbox policy ${padDots("OpenClaw sandbox policy")} ${env.openclaw_config.sandbox_policy_active ? "\u2713 active" : "\u2717 inactive"}
7448
+ `;
7449
+ }
7450
+ }
7451
+ report += "\n";
7452
+ const l1Score = scoreL1(layers.l1_cognitive);
7453
+ const l2Score = scoreL2(layers.l2_operational);
7454
+ const l3Score = scoreL3(layers.l3_selective_disclosure);
7455
+ const l4Score = scoreL4(layers.l4_reputation);
7456
+ report += " Layer Assessment:\n";
7457
+ report += " \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n";
7458
+ report += " \u2502 Layer \u2502 Status \u2502 Score \u2502\n";
7459
+ report += " \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n";
7460
+ report += ` \u2502 L1 Cognitive Sovereignty \u2502 ${padStatus(layers.l1_cognitive.status)} \u2502 ${padScore(l1Score, 35)} \u2502
7461
+ `;
7462
+ report += ` \u2502 L2 Operational Isolation \u2502 ${padStatus(layers.l2_operational.status)} \u2502 ${padScore(l2Score, 25)} \u2502
7463
+ `;
7464
+ report += ` \u2502 L3 Selective Disclosure \u2502 ${padStatus(layers.l3_selective_disclosure.status)} \u2502 ${padScore(l3Score, 20)} \u2502
7465
+ `;
7466
+ report += ` \u2502 L4 Verifiable Reputation \u2502 ${padStatus(layers.l4_reputation.status)} \u2502 ${padScore(l4Score, 20)} \u2502
7467
+ `;
7468
+ report += " \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n";
7469
+ report += "\n";
7470
+ if (gaps.length > 0) {
7471
+ report += ` \u26A0 ${gaps.length} SOVEREIGNTY GAP${gaps.length !== 1 ? "S" : ""} FOUND
7472
+ `;
7473
+ report += "\n";
7474
+ for (const gap of gaps) {
7475
+ const severityLabel = `[${gap.severity.toUpperCase()}]`;
7476
+ report += ` ${severityLabel} ${gap.id}: ${gap.title}
7477
+ `;
7478
+ const descLines = wordWrap(gap.description, 66);
7479
+ for (const line of descLines) {
7480
+ report += ` ${line}
7481
+ `;
7482
+ }
7483
+ report += ` \u2192 Fix: ${gap.sanctuary_solution.split(".")[0]}.
7484
+ `;
7485
+ if (gap.openclaw_relevance) {
7486
+ report += ` \u2192 OpenClaw context: ${gap.openclaw_relevance.split(".")[0]}.
7487
+ `;
7488
+ }
7489
+ report += "\n";
7490
+ }
7491
+ } else {
7492
+ report += " \u2713 NO SOVEREIGNTY GAPS FOUND\n";
7493
+ report += "\n";
7494
+ }
7495
+ if (recommendations.length > 0) {
7496
+ report += " RECOMMENDED NEXT STEPS (in order):\n";
7497
+ for (const rec of recommendations) {
7498
+ const effortLabel = rec.effort === "immediate" ? "immediate" : rec.effort === "minutes" ? "5 min" : "30 min";
7499
+ report += ` ${rec.priority}. [${effortLabel}] ${rec.action}`;
7500
+ if (rec.tool) {
7501
+ report += `: ${rec.tool}`;
7502
+ }
7503
+ report += "\n";
7504
+ }
7505
+ report += "\n";
7506
+ }
7507
+ report += "\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n";
7508
+ return report;
7509
+ }
7510
+ function formatScoreBar(score) {
7511
+ const filled = Math.round(score / 10);
7512
+ return "[" + "\u25A0".repeat(filled) + "\u2591".repeat(10 - filled) + "]";
7513
+ }
7514
+ function padDots(label) {
7515
+ const totalWidth = 30;
7516
+ const dotsNeeded = Math.max(2, totalWidth - label.length - 4);
7517
+ return ".".repeat(dotsNeeded);
7518
+ }
7519
+ function padStatus(status) {
7520
+ const label = status.toUpperCase();
7521
+ return label + " ".repeat(Math.max(0, 8 - label.length));
7522
+ }
7523
+ function padScore(score, max) {
7524
+ const text = `${score}/${max}`;
7525
+ return " ".repeat(Math.max(0, 5 - text.length)) + text;
7526
+ }
7527
+ function wordWrap(text, maxWidth) {
7528
+ const words = text.split(" ");
7529
+ const lines = [];
7530
+ let current = "";
7531
+ for (const word of words) {
7532
+ if (current.length + word.length + 1 > maxWidth && current.length > 0) {
7533
+ lines.push(current);
7534
+ current = word;
7535
+ } else {
7536
+ current = current.length > 0 ? current + " " + word : word;
7537
+ }
7538
+ }
7539
+ if (current.length > 0) lines.push(current);
7540
+ return lines;
7541
+ }
7542
+
7543
+ // src/audit/tools.ts
7544
+ function createAuditTools(config) {
7545
+ const tools = [
7546
+ {
7547
+ name: "sanctuary/sovereignty_audit",
7548
+ description: "Audit your agent's sovereignty posture. Inspects the local environment for encryption, identity, approval gates, selective disclosure, and reputation \u2014 including OpenClaw-specific configurations. Returns a scored gap analysis with prioritized recommendations.",
7549
+ inputSchema: {
7550
+ type: "object",
7551
+ properties: {
7552
+ deep_scan: {
7553
+ type: "boolean",
7554
+ description: "If true (default), also scans for OpenClaw config, .env files, and memory files. Set to false for a Sanctuary-only assessment."
7555
+ }
7556
+ }
7557
+ },
7558
+ handler: async (args) => {
7559
+ const deepScan = args.deep_scan !== false;
7560
+ const env = await detectEnvironment(config, deepScan);
7561
+ const result = analyzeSovereignty(env, config);
7562
+ const report = formatAuditReport(result);
7563
+ return {
7564
+ content: [
7565
+ { type: "text", text: report },
7566
+ { type: "text", text: JSON.stringify(result, null, 2) }
7567
+ ]
7568
+ };
7569
+ }
7570
+ }
7571
+ ];
7572
+ return { tools };
7573
+ }
6654
7574
 
6655
7575
  // src/index.ts
6656
7576
  init_encoding();
@@ -6742,15 +7662,51 @@ async function createSanctuaryServer(options) {
6742
7662
  }
6743
7663
  } else {
6744
7664
  keyProtection = "recovery-key";
6745
- const existing = await storage.read("_meta", "recovery-key-hash");
6746
- if (existing) {
6747
- masterKey = generateRandomKey();
6748
- recoveryKey = toBase64url(masterKey);
7665
+ const { hashToString: hashToString2 } = await Promise.resolve().then(() => (init_hashing(), hashing_exports));
7666
+ const { stringToBytes: stringToBytes2, bytesToString: bytesToString2 } = await Promise.resolve().then(() => (init_encoding(), encoding_exports));
7667
+ const { fromBase64url: fromBase64url2 } = await Promise.resolve().then(() => (init_encoding(), encoding_exports));
7668
+ const { constantTimeEqual: constantTimeEqual2 } = await Promise.resolve().then(() => (init_encoding(), encoding_exports));
7669
+ const existingHash = await storage.read("_meta", "recovery-key-hash");
7670
+ if (existingHash) {
7671
+ const envRecoveryKey = process.env.SANCTUARY_RECOVERY_KEY;
7672
+ if (!envRecoveryKey) {
7673
+ throw new Error(
7674
+ "Sanctuary: Existing encrypted data found but no credentials provided.\nThis installation was previously set up with a recovery key.\n\nTo start the server, provide one of:\n - SANCTUARY_PASSPHRASE (if you later configured a passphrase)\n - SANCTUARY_RECOVERY_KEY (the recovery key shown at first run)\n\nWithout the correct credentials, encrypted state cannot be accessed.\nRefusing to start to prevent silent data loss."
7675
+ );
7676
+ }
7677
+ let recoveryKeyBytes;
7678
+ try {
7679
+ recoveryKeyBytes = fromBase64url2(envRecoveryKey);
7680
+ } catch {
7681
+ throw new Error(
7682
+ "Sanctuary: SANCTUARY_RECOVERY_KEY is not valid base64url. The recovery key should be the exact string shown at first run."
7683
+ );
7684
+ }
7685
+ if (recoveryKeyBytes.length !== 32) {
7686
+ throw new Error(
7687
+ "Sanctuary: SANCTUARY_RECOVERY_KEY has incorrect length. The recovery key should be the exact string shown at first run."
7688
+ );
7689
+ }
7690
+ const providedHash = hashToString2(recoveryKeyBytes);
7691
+ const storedHash = bytesToString2(existingHash);
7692
+ const providedHashBytes = stringToBytes2(providedHash);
7693
+ const storedHashBytes = stringToBytes2(storedHash);
7694
+ if (!constantTimeEqual2(providedHashBytes, storedHashBytes)) {
7695
+ throw new Error(
7696
+ "Sanctuary: Recovery key does not match the stored key hash.\nThe recovery key provided via SANCTUARY_RECOVERY_KEY is incorrect.\nUse the exact recovery key that was displayed at first run."
7697
+ );
7698
+ }
7699
+ masterKey = recoveryKeyBytes;
6749
7700
  } else {
7701
+ const existingNamespaces = await storage.list("_meta");
7702
+ const hasKeyParams = existingNamespaces.some((e) => e.key === "key-params");
7703
+ if (hasKeyParams) {
7704
+ throw new Error(
7705
+ "Sanctuary: Found existing key derivation parameters but no recovery key hash.\nThis indicates a corrupted or incomplete installation.\nIf you previously used a passphrase, set SANCTUARY_PASSPHRASE to start."
7706
+ );
7707
+ }
6750
7708
  masterKey = generateRandomKey();
6751
7709
  recoveryKey = toBase64url(masterKey);
6752
- const { hashToString: hashToString2 } = await Promise.resolve().then(() => (init_hashing(), hashing_exports));
6753
- const { stringToBytes: stringToBytes2 } = await Promise.resolve().then(() => (init_encoding(), encoding_exports));
6754
7710
  const keyHash = hashToString2(masterKey);
6755
7711
  await storage.write(
6756
7712
  "_meta",
@@ -7016,6 +7972,7 @@ async function createSanctuaryServer(options) {
7016
7972
  auditLog,
7017
7973
  handshakeResults
7018
7974
  );
7975
+ const { tools: auditTools } = createAuditTools(config);
7019
7976
  const policy = await loadPrincipalPolicy(config.storage_path);
7020
7977
  const baseline = new BaselineTracker(storage, masterKey);
7021
7978
  await baseline.load();
@@ -7031,7 +7988,7 @@ async function createSanctuaryServer(options) {
7031
7988
  port: config.dashboard.port,
7032
7989
  host: config.dashboard.host,
7033
7990
  timeout_seconds: policy.approval_channel.timeout_seconds,
7034
- auto_deny: policy.approval_channel.auto_deny,
7991
+ // SEC-002: auto_deny removed — timeout always denies
7035
7992
  auth_token: authToken,
7036
7993
  tls: config.dashboard.tls
7037
7994
  });
@@ -7044,8 +8001,8 @@ async function createSanctuaryServer(options) {
7044
8001
  webhook_secret: config.webhook.secret,
7045
8002
  callback_port: config.webhook.callback_port,
7046
8003
  callback_host: config.webhook.callback_host,
7047
- timeout_seconds: policy.approval_channel.timeout_seconds,
7048
- auto_deny: policy.approval_channel.auto_deny
8004
+ timeout_seconds: policy.approval_channel.timeout_seconds
8005
+ // SEC-002: auto_deny removed — timeout always denies
7049
8006
  });
7050
8007
  await webhook.start();
7051
8008
  approvalChannel = webhook;
@@ -7064,6 +8021,7 @@ async function createSanctuaryServer(options) {
7064
8021
  ...handshakeTools,
7065
8022
  ...federationTools,
7066
8023
  ...bridgeTools,
8024
+ ...auditTools,
7067
8025
  manifestTool
7068
8026
  ];
7069
8027
  const server = createServer(allTools, { gate });