@sanctuary-framework/mcp-server 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -2,9 +2,10 @@
2
2
  import { sha256 } from '@noble/hashes/sha256';
3
3
  import { hmac } from '@noble/hashes/hmac';
4
4
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
5
- import { mkdir, readFile, writeFile, stat, unlink, readdir, chmod } from 'fs/promises';
5
+ import { mkdir, readFile, writeFile, stat, unlink, readdir, chmod, access } from 'fs/promises';
6
6
  import { join } from 'path';
7
7
  import { homedir } from 'os';
8
+ import { createRequire } from 'module';
8
9
  import { randomBytes as randomBytes$1, createHmac } from 'crypto';
9
10
  import { gcm } from '@noble/ciphers/aes.js';
10
11
  import { RistrettoPoint, ed25519 } from '@noble/curves/ed25519';
@@ -13,8 +14,9 @@ import { hkdf } from '@noble/hashes/hkdf';
13
14
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
14
15
  import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
15
16
  import { createServer as createServer$2 } from 'http';
16
- import { createServer as createServer$1 } from 'https';
17
- import { readFileSync } from 'fs';
17
+ import { createServer as createServer$1, get } from 'https';
18
+ import { readFileSync, statSync } from 'fs';
19
+ import { execSync } from 'child_process';
18
20
 
19
21
  var __defProp = Object.defineProperty;
20
22
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -204,9 +206,11 @@ var init_hashing = __esm({
204
206
  init_encoding();
205
207
  }
206
208
  });
209
+ var require2 = createRequire(import.meta.url);
210
+ var { version: PKG_VERSION } = require2("../package.json");
207
211
  function defaultConfig() {
208
212
  return {
209
- version: "0.3.0",
213
+ version: PKG_VERSION,
210
214
  storage_path: join(homedir(), ".sanctuary"),
211
215
  state: {
212
216
  encryption: "aes-256-gcm",
@@ -298,8 +302,13 @@ async function loadConfig(configPath) {
298
302
  try {
299
303
  const raw = await readFile(path, "utf-8");
300
304
  const fileConfig = JSON.parse(raw);
301
- return deepMerge(config, fileConfig);
302
- } catch {
305
+ const merged = deepMerge(config, fileConfig);
306
+ validateConfig(merged);
307
+ return merged;
308
+ } catch (err) {
309
+ if (err instanceof Error && err.message.includes("unimplemented features")) {
310
+ throw err;
311
+ }
303
312
  return config;
304
313
  }
305
314
  }
@@ -307,6 +316,45 @@ async function saveConfig(config, configPath) {
307
316
  const path = join(config.storage_path, "sanctuary.json");
308
317
  await writeFile(path, JSON.stringify(config, null, 2), { mode: 384 });
309
318
  }
319
+ function validateConfig(config) {
320
+ const errors = [];
321
+ const implementedKeyProtection = /* @__PURE__ */ new Set(["passphrase", "none"]);
322
+ if (!implementedKeyProtection.has(config.state.key_protection)) {
323
+ errors.push(
324
+ `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.`
325
+ );
326
+ }
327
+ const implementedEnvironment = /* @__PURE__ */ new Set(["local-process", "docker"]);
328
+ if (!implementedEnvironment.has(config.execution.environment)) {
329
+ errors.push(
330
+ `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.`
331
+ );
332
+ }
333
+ const implementedProofSystem = /* @__PURE__ */ new Set(["commitment-only"]);
334
+ if (!implementedProofSystem.has(config.disclosure.proof_system)) {
335
+ errors.push(
336
+ `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.`
337
+ );
338
+ }
339
+ const implementedDisclosurePolicy = /* @__PURE__ */ new Set(["minimum-necessary"]);
340
+ if (!implementedDisclosurePolicy.has(config.disclosure.default_policy)) {
341
+ errors.push(
342
+ `Unimplemented config value: disclosure.default_policy = "${config.disclosure.default_policy}". Only ${[...implementedDisclosurePolicy].map((v) => `"${v}"`).join(", ")} is currently implemented. Using an unimplemented disclosure policy would silently skip disclosure controls.`
343
+ );
344
+ }
345
+ const implementedReputationMode = /* @__PURE__ */ new Set(["self-custodied"]);
346
+ if (!implementedReputationMode.has(config.reputation.mode)) {
347
+ errors.push(
348
+ `Unimplemented config value: reputation.mode = "${config.reputation.mode}". Only ${[...implementedReputationMode].map((v) => `"${v}"`).join(", ")} is currently implemented. Using an unimplemented reputation mode would silently skip reputation verification.`
349
+ );
350
+ }
351
+ if (errors.length > 0) {
352
+ throw new Error(
353
+ `Sanctuary configuration references unimplemented features:
354
+ ${errors.join("\n")}`
355
+ );
356
+ }
357
+ }
310
358
  function deepMerge(base, override) {
311
359
  const result = { ...base };
312
360
  for (const [key, value] of Object.entries(override)) {
@@ -650,7 +698,11 @@ var RESERVED_NAMESPACE_PREFIXES = [
650
698
  "_commitments",
651
699
  "_reputation",
652
700
  "_escrow",
653
- "_guarantees"
701
+ "_guarantees",
702
+ "_bridge",
703
+ "_federation",
704
+ "_handshake",
705
+ "_shr"
654
706
  ];
655
707
  var StateStore = class {
656
708
  storage;
@@ -917,12 +969,14 @@ var StateStore = class {
917
969
  /**
918
970
  * Import a previously exported state bundle.
919
971
  */
920
- async import(bundleBase64, conflictResolution = "skip") {
972
+ async import(bundleBase64, conflictResolution = "skip", publicKeyResolver) {
921
973
  const bundleBytes = fromBase64url(bundleBase64);
922
974
  const bundleJson = bytesToString(bundleBytes);
923
975
  const bundle = JSON.parse(bundleJson);
924
976
  let importedKeys = 0;
925
977
  let skippedKeys = 0;
978
+ let skippedInvalidSig = 0;
979
+ let skippedUnknownKid = 0;
926
980
  let conflicts = 0;
927
981
  const namespaces = [];
928
982
  for (const [ns, entries] of Object.entries(
@@ -936,6 +990,26 @@ var StateStore = class {
936
990
  }
937
991
  namespaces.push(ns);
938
992
  for (const { key, entry } of entries) {
993
+ const signerPublicKey = publicKeyResolver(entry.kid);
994
+ if (!signerPublicKey) {
995
+ skippedUnknownKid++;
996
+ skippedKeys++;
997
+ continue;
998
+ }
999
+ try {
1000
+ const ciphertextBytes = fromBase64url(entry.payload.ct);
1001
+ const signatureBytes = fromBase64url(entry.sig);
1002
+ const sigValid = verify(ciphertextBytes, signatureBytes, signerPublicKey);
1003
+ if (!sigValid) {
1004
+ skippedInvalidSig++;
1005
+ skippedKeys++;
1006
+ continue;
1007
+ }
1008
+ } catch {
1009
+ skippedInvalidSig++;
1010
+ skippedKeys++;
1011
+ continue;
1012
+ }
939
1013
  const exists = await this.storage.exists(ns, key);
940
1014
  if (exists) {
941
1015
  conflicts++;
@@ -971,12 +1045,16 @@ var StateStore = class {
971
1045
  return {
972
1046
  imported_keys: importedKeys,
973
1047
  skipped_keys: skippedKeys,
1048
+ skipped_invalid_sig: skippedInvalidSig,
1049
+ skipped_unknown_kid: skippedUnknownKid,
974
1050
  conflicts,
975
1051
  namespaces,
976
1052
  imported_at: (/* @__PURE__ */ new Date()).toISOString()
977
1053
  };
978
1054
  }
979
1055
  };
1056
+ var require3 = createRequire(import.meta.url);
1057
+ var { version: PKG_VERSION2 } = require3("../package.json");
980
1058
  var MAX_STRING_BYTES = 1048576;
981
1059
  var MAX_BUNDLE_BYTES = 5242880;
982
1060
  var BUNDLE_FIELDS = /* @__PURE__ */ new Set(["bundle"]);
@@ -1059,7 +1137,7 @@ function createServer(tools, options) {
1059
1137
  const server = new Server(
1060
1138
  {
1061
1139
  name: "sanctuary-mcp-server",
1062
- version: "0.3.0"
1140
+ version: PKG_VERSION2
1063
1141
  },
1064
1142
  {
1065
1143
  capabilities: {
@@ -1159,7 +1237,11 @@ var RESERVED_NAMESPACE_PREFIXES2 = [
1159
1237
  "_commitments",
1160
1238
  "_reputation",
1161
1239
  "_escrow",
1162
- "_guarantees"
1240
+ "_guarantees",
1241
+ "_bridge",
1242
+ "_federation",
1243
+ "_handshake",
1244
+ "_shr"
1163
1245
  ];
1164
1246
  function getReservedNamespaceViolation(namespace) {
1165
1247
  for (const prefix of RESERVED_NAMESPACE_PREFIXES2) {
@@ -1496,6 +1578,13 @@ function createL1Tools(stateStore, storage, masterKey, keyProtection, auditLog)
1496
1578
  required: ["namespace", "key"]
1497
1579
  },
1498
1580
  handler: async (args) => {
1581
+ const reservedViolation = getReservedNamespaceViolation(args.namespace);
1582
+ if (reservedViolation) {
1583
+ return toolResult({
1584
+ error: "namespace_reserved",
1585
+ message: `Namespace "${args.namespace}" is reserved for internal use (prefix: ${reservedViolation}). Cannot read from reserved namespaces.`
1586
+ });
1587
+ }
1499
1588
  const result = await stateStore.read(
1500
1589
  args.namespace,
1501
1590
  args.key,
@@ -1532,6 +1621,13 @@ function createL1Tools(stateStore, storage, masterKey, keyProtection, auditLog)
1532
1621
  required: ["namespace"]
1533
1622
  },
1534
1623
  handler: async (args) => {
1624
+ const reservedViolation = getReservedNamespaceViolation(args.namespace);
1625
+ if (reservedViolation) {
1626
+ return toolResult({
1627
+ error: "namespace_reserved",
1628
+ message: `Namespace "${args.namespace}" is reserved for internal use (prefix: ${reservedViolation}). Cannot list reserved namespaces.`
1629
+ });
1630
+ }
1535
1631
  const result = await stateStore.list(
1536
1632
  args.namespace,
1537
1633
  args.prefix,
@@ -1610,9 +1706,15 @@ function createL1Tools(stateStore, storage, masterKey, keyProtection, auditLog)
1610
1706
  required: ["bundle"]
1611
1707
  },
1612
1708
  handler: async (args) => {
1709
+ const publicKeyResolver = (kid) => {
1710
+ const identity = identityMgr.get(kid);
1711
+ if (!identity) return null;
1712
+ return fromBase64url(identity.public_key);
1713
+ };
1613
1714
  const result = await stateStore.import(
1614
1715
  args.bundle,
1615
- args.conflict_resolution ?? "skip"
1716
+ args.conflict_resolution ?? "skip",
1717
+ publicKeyResolver
1616
1718
  );
1617
1719
  auditLog?.append("l1", "state_import", "principal", {
1618
1720
  imported_keys: result.imported_keys
@@ -2057,7 +2159,7 @@ function createRangeProof(value, blindingFactor, commitment, min, max) {
2057
2159
  bitProofs.push(bitProof);
2058
2160
  }
2059
2161
  const sumBlinding = bitBlindings.reduce(
2060
- (acc, bi, i) => mod(acc + mod(BigInt(1 << i)) * bi),
2162
+ (acc, bi, i) => mod(acc + mod(BigInt(1) << BigInt(i)) * bi),
2061
2163
  0n
2062
2164
  );
2063
2165
  const blindingDiff = mod(b - sumBlinding);
@@ -2099,7 +2201,7 @@ function verifyRangeProof(proof) {
2099
2201
  let reconstructed = RistrettoPoint.ZERO;
2100
2202
  for (let i = 0; i < numBits; i++) {
2101
2203
  const C_i = RistrettoPoint.fromHex(fromBase64url(proof.bit_commitments[i]));
2102
- const weight = mod(BigInt(1 << i));
2204
+ const weight = mod(BigInt(1) << BigInt(i));
2103
2205
  reconstructed = reconstructed.add(safeMultiply(C_i, weight));
2104
2206
  }
2105
2207
  const diff = C.subtract(safeMultiply(G, mod(BigInt(proof.min)))).subtract(reconstructed);
@@ -3154,7 +3256,9 @@ function createL4Tools(storage, masterKey, identityManager, auditLog, handshakeR
3154
3256
  contexts: summary.contexts
3155
3257
  });
3156
3258
  return toolResult({
3157
- summary
3259
+ summary,
3260
+ // SEC-ADD-03: Tag response as containing counterparty-generated attestation data
3261
+ _content_trust: "external"
3158
3262
  });
3159
3263
  }
3160
3264
  },
@@ -3475,24 +3579,27 @@ var DEFAULT_TIER2 = {
3475
3579
  };
3476
3580
  var DEFAULT_CHANNEL = {
3477
3581
  type: "stderr",
3478
- timeout_seconds: 300,
3479
- auto_deny: true
3582
+ timeout_seconds: 300
3583
+ // SEC-002: auto_deny is not configurable. Timeout always denies.
3584
+ // Field omitted intentionally — all channels hardcode deny on timeout.
3480
3585
  };
3481
3586
  var DEFAULT_POLICY = {
3482
3587
  version: 1,
3483
3588
  tier1_always_approve: [
3484
3589
  "state_export",
3485
3590
  "state_import",
3591
+ "state_delete",
3486
3592
  "identity_rotate",
3487
3593
  "reputation_import",
3488
- "bootstrap_provide_guarantee"
3594
+ "reputation_export",
3595
+ "bootstrap_provide_guarantee",
3596
+ "decommission_certificate"
3489
3597
  ],
3490
3598
  tier2_anomaly: DEFAULT_TIER2,
3491
3599
  tier3_always_allow: [
3492
3600
  "state_read",
3493
3601
  "state_write",
3494
3602
  "state_list",
3495
- "state_delete",
3496
3603
  "identity_create",
3497
3604
  "identity_list",
3498
3605
  "identity_sign",
@@ -3503,7 +3610,6 @@ var DEFAULT_POLICY = {
3503
3610
  "disclosure_evaluate",
3504
3611
  "reputation_record",
3505
3612
  "reputation_query",
3506
- "reputation_export",
3507
3613
  "bootstrap_create_escrow",
3508
3614
  "exec_attest",
3509
3615
  "monitor_health",
@@ -3525,7 +3631,14 @@ var DEFAULT_POLICY = {
3525
3631
  "zk_prove",
3526
3632
  "zk_verify",
3527
3633
  "zk_range_prove",
3528
- "zk_range_verify"
3634
+ "zk_range_verify",
3635
+ "context_gate_set_policy",
3636
+ "context_gate_apply_template",
3637
+ "context_gate_recommend",
3638
+ "context_gate_filter",
3639
+ "context_gate_list_policies",
3640
+ "l2_hardening_status",
3641
+ "l2_verify_isolation"
3529
3642
  ],
3530
3643
  approval_channel: DEFAULT_CHANNEL
3531
3644
  };
@@ -3600,10 +3713,14 @@ function validatePolicy(raw) {
3600
3713
  ...raw.tier2_anomaly ?? {}
3601
3714
  },
3602
3715
  tier3_always_allow: raw.tier3_always_allow ?? DEFAULT_POLICY.tier3_always_allow,
3603
- approval_channel: {
3604
- ...DEFAULT_CHANNEL,
3605
- ...raw.approval_channel ?? {}
3606
- }
3716
+ approval_channel: (() => {
3717
+ const merged = {
3718
+ ...DEFAULT_CHANNEL,
3719
+ ...raw.approval_channel ?? {}
3720
+ };
3721
+ delete merged.auto_deny;
3722
+ return merged;
3723
+ })()
3607
3724
  };
3608
3725
  }
3609
3726
  function generateDefaultPolicyYaml() {
@@ -3620,8 +3737,10 @@ version: 1
3620
3737
  tier1_always_approve:
3621
3738
  - state_export
3622
3739
  - state_import
3740
+ - state_delete
3623
3741
  - identity_rotate
3624
3742
  - reputation_import
3743
+ - reputation_export
3625
3744
  - bootstrap_provide_guarantee
3626
3745
 
3627
3746
  # \u2500\u2500\u2500 Tier 2: Behavioral Anomaly Detection \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
@@ -3641,7 +3760,6 @@ tier3_always_allow:
3641
3760
  - state_read
3642
3761
  - state_write
3643
3762
  - state_list
3644
- - state_delete
3645
3763
  - identity_create
3646
3764
  - identity_list
3647
3765
  - identity_sign
@@ -3652,7 +3770,6 @@ tier3_always_allow:
3652
3770
  - disclosure_evaluate
3653
3771
  - reputation_record
3654
3772
  - reputation_query
3655
- - reputation_export
3656
3773
  - bootstrap_create_escrow
3657
3774
  - exec_attest
3658
3775
  - monitor_health
@@ -3675,13 +3792,18 @@ tier3_always_allow:
3675
3792
  - zk_verify
3676
3793
  - zk_range_prove
3677
3794
  - zk_range_verify
3795
+ - context_gate_set_policy
3796
+ - context_gate_apply_template
3797
+ - context_gate_recommend
3798
+ - context_gate_filter
3799
+ - context_gate_list_policies
3678
3800
 
3679
3801
  # \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
3802
  # How Sanctuary reaches you when approval is needed.
3803
+ # NOTE: Timeout always results in denial. This is not configurable (SEC-002).
3681
3804
  approval_channel:
3682
3805
  type: stderr
3683
3806
  timeout_seconds: 300
3684
- auto_deny: true
3685
3807
  `;
3686
3808
  }
3687
3809
  async function loadPrincipalPolicy(storagePath) {
@@ -3858,27 +3980,16 @@ var BaselineTracker = class {
3858
3980
 
3859
3981
  // src/principal-policy/approval-channel.ts
3860
3982
  var StderrApprovalChannel = class {
3861
- config;
3862
- constructor(config) {
3863
- this.config = config;
3983
+ constructor(_config) {
3864
3984
  }
3865
3985
  async requestApproval(request) {
3866
3986
  const prompt = this.formatPrompt(request);
3867
3987
  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
- }
3988
+ return {
3989
+ decision: "deny",
3990
+ decided_at: (/* @__PURE__ */ new Date()).toISOString(),
3991
+ decided_by: "stderr:non-interactive"
3992
+ };
3882
3993
  }
3883
3994
  formatPrompt(request) {
3884
3995
  const tierLabel = request.tier === 1 ? "Tier 1 \u2014 always requires approval" : "Tier 2 \u2014 behavioral anomaly detected";
@@ -3886,7 +3997,7 @@ var StderrApprovalChannel = class {
3886
3997
  return [
3887
3998
  "",
3888
3999
  "\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",
4000
+ "\u2551 SANCTUARY: Operation Denied (non-interactive channel) \u2551",
3890
4001
  "\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
4002
  `\u2551 Operation: ${request.operation.padEnd(50)}\u2551`,
3892
4003
  `\u2551 ${tierLabel.padEnd(62)}\u2551`,
@@ -3897,7 +4008,8 @@ var StderrApprovalChannel = class {
3897
4008
  (line) => `\u2551 ${line.padEnd(60)}\u2551`
3898
4009
  ),
3899
4010
  "\u2551 \u2551",
3900
- this.config.auto_deny ? "\u2551 Auto-denying (configure approval_channel.auto_deny to change) \u2551" : "\u2551 Auto-approving (informational mode) \u2551",
4011
+ "\u2551 Denied: stderr channel cannot accept input (SEC-016) \u2551",
4012
+ "\u2551 Use dashboard or webhook channel for interactive approval. \u2551",
3901
4013
  "\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
4014
  ""
3903
4015
  ].join("\n");
@@ -4201,20 +4313,38 @@ function generateDashboardHTML(options) {
4201
4313
  <script>
4202
4314
  (function() {
4203
4315
  const TIMEOUT = ${options.timeoutSeconds};
4204
- const AUTH_TOKEN = ${options.authToken ? `'${options.authToken}'` : "null"};
4316
+ // SEC-012: Auth token is passed via Authorization header only \u2014 never in URLs.
4317
+ // The token is provided by the server at generation time (embedded for initial auth).
4318
+ const AUTH_TOKEN = ${options.authToken ? JSON.stringify(options.authToken) : "null"};
4319
+ let SESSION_ID = null; // Short-lived session for SSE and URL-based requests
4205
4320
  const pending = new Map();
4206
4321
  let auditCount = 0;
4207
4322
 
4208
- // Auth helpers
4323
+ // Auth helpers \u2014 SEC-012: token goes in header, session goes in URL
4209
4324
  function authHeaders() {
4210
4325
  const h = { 'Content-Type': 'application/json' };
4211
4326
  if (AUTH_TOKEN) h['Authorization'] = 'Bearer ' + AUTH_TOKEN;
4212
4327
  return h;
4213
4328
  }
4214
- function authQuery(url) {
4215
- if (!AUTH_TOKEN) return url;
4329
+ function sessionQuery(url) {
4330
+ if (!SESSION_ID) return url;
4216
4331
  const sep = url.includes('?') ? '&' : '?';
4217
- return url + sep + 'token=' + AUTH_TOKEN;
4332
+ return url + sep + 'session=' + SESSION_ID;
4333
+ }
4334
+
4335
+ // SEC-012: Exchange the long-lived token for a short-lived session
4336
+ async function exchangeSession() {
4337
+ if (!AUTH_TOKEN) return;
4338
+ try {
4339
+ const resp = await fetch('/auth/session', { method: 'POST', headers: authHeaders() });
4340
+ if (resp.ok) {
4341
+ const data = await resp.json();
4342
+ SESSION_ID = data.session_id;
4343
+ // Refresh session before expiry (at 80% of TTL)
4344
+ const refreshMs = (data.expires_in_seconds || 300) * 800;
4345
+ setTimeout(async () => { await exchangeSession(); reconnectSSE(); }, refreshMs);
4346
+ }
4347
+ } catch(e) { /* will retry on next connect */ }
4218
4348
  }
4219
4349
 
4220
4350
  // Tab switching
@@ -4227,10 +4357,14 @@ function generateDashboardHTML(options) {
4227
4357
  });
4228
4358
  });
4229
4359
 
4230
- // SSE Connection
4360
+ // SSE Connection \u2014 SEC-012: uses short-lived session token in URL, not auth token
4231
4361
  let evtSource;
4362
+ function reconnectSSE() {
4363
+ if (evtSource) { evtSource.close(); }
4364
+ connect();
4365
+ }
4232
4366
  function connect() {
4233
- evtSource = new EventSource(authQuery('/events'));
4367
+ evtSource = new EventSource(sessionQuery('/events'));
4234
4368
  evtSource.onopen = () => {
4235
4369
  document.getElementById('statusDot').classList.remove('disconnected');
4236
4370
  document.getElementById('statusText').textContent = 'Connected';
@@ -4418,12 +4552,20 @@ function generateDashboardHTML(options) {
4418
4552
  return d.innerHTML;
4419
4553
  }
4420
4554
 
4421
- // Init
4422
- connect();
4423
- fetch('/api/status', { headers: authHeaders() }).then(r => r.json()).then(data => {
4424
- if (data.baseline) updateBaseline(data.baseline);
4425
- if (data.policy) updatePolicy(data.policy);
4426
- }).catch(() => {});
4555
+ // Init \u2014 SEC-012: exchange token for session before connecting SSE
4556
+ (async function init() {
4557
+ await exchangeSession();
4558
+ // Clean token from URL if present (legacy bookmarks)
4559
+ if (window.location.search.includes('token=')) {
4560
+ const clean = window.location.pathname;
4561
+ window.history.replaceState({}, '', clean);
4562
+ }
4563
+ connect();
4564
+ fetch('/api/status', { headers: authHeaders() }).then(r => r.json()).then(data => {
4565
+ if (data.baseline) updateBaseline(data.baseline);
4566
+ if (data.policy) updatePolicy(data.policy);
4567
+ }).catch(() => {});
4568
+ })();
4427
4569
  })();
4428
4570
  </script>
4429
4571
  </body>
@@ -4431,6 +4573,14 @@ function generateDashboardHTML(options) {
4431
4573
  }
4432
4574
 
4433
4575
  // src/principal-policy/dashboard.ts
4576
+ var require4 = createRequire(import.meta.url);
4577
+ var { version: PKG_VERSION3 } = require4("../../package.json");
4578
+ var SESSION_TTL_MS = 5 * 60 * 1e3;
4579
+ var MAX_SESSIONS = 1e3;
4580
+ var RATE_LIMIT_WINDOW_MS = 6e4;
4581
+ var RATE_LIMIT_GENERAL = 120;
4582
+ var RATE_LIMIT_DECISIONS = 20;
4583
+ var MAX_RATE_LIMIT_ENTRIES = 1e4;
4434
4584
  var DashboardApprovalChannel = class {
4435
4585
  config;
4436
4586
  pending = /* @__PURE__ */ new Map();
@@ -4442,15 +4592,21 @@ var DashboardApprovalChannel = class {
4442
4592
  dashboardHTML;
4443
4593
  authToken;
4444
4594
  useTLS;
4595
+ /** SEC-012: Short-lived session store. Sessions replace URL query tokens. */
4596
+ sessions = /* @__PURE__ */ new Map();
4597
+ sessionCleanupTimer = null;
4598
+ /** Rate limiting: per-IP request tracking */
4599
+ rateLimits = /* @__PURE__ */ new Map();
4445
4600
  constructor(config) {
4446
4601
  this.config = config;
4447
4602
  this.authToken = config.auth_token;
4448
4603
  this.useTLS = !!(config.tls?.cert_path && config.tls?.key_path);
4449
4604
  this.dashboardHTML = generateDashboardHTML({
4450
4605
  timeoutSeconds: config.timeout_seconds,
4451
- serverVersion: "0.3.0",
4606
+ serverVersion: PKG_VERSION3,
4452
4607
  authToken: this.authToken
4453
4608
  });
4609
+ this.sessionCleanupTimer = setInterval(() => this.cleanupSessions(), 6e4);
4454
4610
  }
4455
4611
  /**
4456
4612
  * Inject dependencies after construction.
@@ -4480,13 +4636,14 @@ var DashboardApprovalChannel = class {
4480
4636
  const baseUrl = `${protocol}://${this.config.host}:${this.config.port}`;
4481
4637
  this.httpServer.listen(this.config.port, this.config.host, () => {
4482
4638
  if (this.authToken) {
4639
+ const hint = this.authToken.slice(0, 4) + "..." + this.authToken.slice(-4);
4483
4640
  process.stderr.write(
4484
4641
  `
4485
- Sanctuary Principal Dashboard: ${baseUrl}/?token=${this.authToken}
4642
+ Sanctuary Principal Dashboard: ${baseUrl}
4486
4643
  `
4487
4644
  );
4488
4645
  process.stderr.write(
4489
- ` Auth token: ${this.authToken}
4646
+ ` Auth required (token: ${hint}). Use Authorization: Bearer <TOKEN> header.
4490
4647
 
4491
4648
  `
4492
4649
  );
@@ -4520,6 +4677,12 @@ var DashboardApprovalChannel = class {
4520
4677
  client.end();
4521
4678
  }
4522
4679
  this.sseClients.clear();
4680
+ this.sessions.clear();
4681
+ if (this.sessionCleanupTimer) {
4682
+ clearInterval(this.sessionCleanupTimer);
4683
+ this.sessionCleanupTimer = null;
4684
+ }
4685
+ this.rateLimits.clear();
4523
4686
  if (this.httpServer) {
4524
4687
  return new Promise((resolve) => {
4525
4688
  this.httpServer.close(() => resolve());
@@ -4540,7 +4703,8 @@ var DashboardApprovalChannel = class {
4540
4703
  const timer = setTimeout(() => {
4541
4704
  this.pending.delete(id);
4542
4705
  const response = {
4543
- decision: this.config.auto_deny ? "deny" : "approve",
4706
+ // SEC-002: Timeout ALWAYS denies. No configuration can change this.
4707
+ decision: "deny",
4544
4708
  decided_at: (/* @__PURE__ */ new Date()).toISOString(),
4545
4709
  decided_by: "timeout"
4546
4710
  };
@@ -4572,7 +4736,12 @@ var DashboardApprovalChannel = class {
4572
4736
  // ── Authentication ──────────────────────────────────────────────────
4573
4737
  /**
4574
4738
  * Verify bearer token authentication.
4575
- * Checks Authorization header first, falls back to ?token= query param.
4739
+ *
4740
+ * SEC-012: The long-lived auth token is ONLY accepted via the Authorization
4741
+ * header — never in URL query strings. For SSE and page loads that cannot
4742
+ * set headers, a short-lived session token (obtained via POST /auth/session)
4743
+ * is accepted via ?session= query parameter.
4744
+ *
4576
4745
  * Returns true if auth passes, false if blocked (response already sent).
4577
4746
  */
4578
4747
  checkAuth(req, url, res) {
@@ -4584,19 +4753,126 @@ var DashboardApprovalChannel = class {
4584
4753
  return true;
4585
4754
  }
4586
4755
  }
4587
- const queryToken = url.searchParams.get("token");
4588
- if (queryToken === this.authToken) {
4756
+ const sessionId = url.searchParams.get("session");
4757
+ if (sessionId && this.validateSession(sessionId)) {
4589
4758
  return true;
4590
4759
  }
4591
4760
  res.writeHead(401, { "Content-Type": "application/json" });
4592
- res.end(JSON.stringify({ error: "Unauthorized \u2014 valid bearer token required" }));
4761
+ res.end(JSON.stringify({ error: "Unauthorized \u2014 use Authorization: Bearer header or a valid session" }));
4593
4762
  return false;
4594
4763
  }
4764
+ // ── Session Management (SEC-012) ──────────────────────────────────
4765
+ /**
4766
+ * Create a short-lived session by exchanging the long-lived auth token
4767
+ * (provided in the Authorization header) for a session ID.
4768
+ */
4769
+ createSession() {
4770
+ if (this.sessions.size >= MAX_SESSIONS) {
4771
+ this.cleanupSessions();
4772
+ if (this.sessions.size >= MAX_SESSIONS) {
4773
+ const oldest = [...this.sessions.entries()].sort(
4774
+ (a, b) => a[1].created_at - b[1].created_at
4775
+ )[0];
4776
+ if (oldest) this.sessions.delete(oldest[0]);
4777
+ }
4778
+ }
4779
+ const id = randomBytes$1(32).toString("hex");
4780
+ const now = Date.now();
4781
+ this.sessions.set(id, {
4782
+ id,
4783
+ created_at: now,
4784
+ expires_at: now + SESSION_TTL_MS
4785
+ });
4786
+ return id;
4787
+ }
4788
+ /**
4789
+ * Validate a session ID — must exist and not be expired.
4790
+ */
4791
+ validateSession(sessionId) {
4792
+ const session = this.sessions.get(sessionId);
4793
+ if (!session) return false;
4794
+ if (Date.now() > session.expires_at) {
4795
+ this.sessions.delete(sessionId);
4796
+ return false;
4797
+ }
4798
+ return true;
4799
+ }
4800
+ /**
4801
+ * Remove all expired sessions.
4802
+ */
4803
+ cleanupSessions() {
4804
+ const now = Date.now();
4805
+ for (const [id, session] of this.sessions) {
4806
+ if (now > session.expires_at) {
4807
+ this.sessions.delete(id);
4808
+ }
4809
+ }
4810
+ }
4811
+ // ── Rate Limiting ─────────────────────────────────────────────────
4812
+ /**
4813
+ * Get the remote address from a request, normalizing IPv6-mapped IPv4.
4814
+ */
4815
+ getRemoteAddr(req) {
4816
+ const addr = req.socket.remoteAddress ?? "unknown";
4817
+ return addr.startsWith("::ffff:") ? addr.slice(7) : addr;
4818
+ }
4819
+ /**
4820
+ * Check rate limit for a request. Returns true if allowed, false if rate-limited.
4821
+ * When rate-limited, sends a 429 response.
4822
+ */
4823
+ checkRateLimit(req, res, type) {
4824
+ const addr = this.getRemoteAddr(req);
4825
+ const now = Date.now();
4826
+ const windowStart = now - RATE_LIMIT_WINDOW_MS;
4827
+ let entry = this.rateLimits.get(addr);
4828
+ if (!entry) {
4829
+ if (this.rateLimits.size >= MAX_RATE_LIMIT_ENTRIES) {
4830
+ this.pruneRateLimits(now);
4831
+ }
4832
+ entry = { general: [], decisions: [] };
4833
+ this.rateLimits.set(addr, entry);
4834
+ }
4835
+ entry.general = entry.general.filter((t) => t > windowStart);
4836
+ entry.decisions = entry.decisions.filter((t) => t > windowStart);
4837
+ const limit = type === "decisions" ? RATE_LIMIT_DECISIONS : RATE_LIMIT_GENERAL;
4838
+ const timestamps = entry[type];
4839
+ if (timestamps.length >= limit) {
4840
+ const retryAfter = Math.ceil((timestamps[0] + RATE_LIMIT_WINDOW_MS - now) / 1e3);
4841
+ res.writeHead(429, {
4842
+ "Content-Type": "application/json",
4843
+ "Retry-After": String(Math.max(1, retryAfter))
4844
+ });
4845
+ res.end(JSON.stringify({
4846
+ error: "Rate limit exceeded",
4847
+ retry_after_seconds: Math.max(1, retryAfter)
4848
+ }));
4849
+ return false;
4850
+ }
4851
+ timestamps.push(now);
4852
+ return true;
4853
+ }
4854
+ /**
4855
+ * Remove stale entries from the rate limit map.
4856
+ */
4857
+ pruneRateLimits(now) {
4858
+ const windowStart = now - RATE_LIMIT_WINDOW_MS;
4859
+ for (const [addr, entry] of this.rateLimits) {
4860
+ const hasRecent = entry.general.some((t) => t > windowStart) || entry.decisions.some((t) => t > windowStart);
4861
+ if (!hasRecent) {
4862
+ this.rateLimits.delete(addr);
4863
+ }
4864
+ }
4865
+ }
4595
4866
  // ── HTTP Request Handler ────────────────────────────────────────────
4596
4867
  handleRequest(req, res) {
4597
4868
  const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
4598
4869
  const method = req.method ?? "GET";
4599
- res.setHeader("Access-Control-Allow-Origin", "*");
4870
+ const origin = req.headers.origin;
4871
+ const protocol = this.useTLS ? "https" : "http";
4872
+ const selfOrigin = `${protocol}://${this.config.host}:${this.config.port}`;
4873
+ if (origin === selfOrigin) {
4874
+ res.setHeader("Access-Control-Allow-Origin", origin);
4875
+ }
4600
4876
  res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
4601
4877
  res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
4602
4878
  if (method === "OPTIONS") {
@@ -4605,7 +4881,12 @@ var DashboardApprovalChannel = class {
4605
4881
  return;
4606
4882
  }
4607
4883
  if (!this.checkAuth(req, url, res)) return;
4884
+ if (!this.checkRateLimit(req, res, "general")) return;
4608
4885
  try {
4886
+ if (method === "POST" && url.pathname === "/auth/session") {
4887
+ this.handleSessionExchange(req, res);
4888
+ return;
4889
+ }
4609
4890
  if (method === "GET" && url.pathname === "/") {
4610
4891
  this.serveDashboard(res);
4611
4892
  } else if (method === "GET" && url.pathname === "/events") {
@@ -4617,9 +4898,11 @@ var DashboardApprovalChannel = class {
4617
4898
  } else if (method === "GET" && url.pathname === "/api/audit-log") {
4618
4899
  this.handleAuditLog(url, res);
4619
4900
  } else if (method === "POST" && url.pathname.startsWith("/api/approve/")) {
4901
+ if (!this.checkRateLimit(req, res, "decisions")) return;
4620
4902
  const id = url.pathname.slice("/api/approve/".length);
4621
4903
  this.handleDecision(id, "approve", res);
4622
4904
  } else if (method === "POST" && url.pathname.startsWith("/api/deny/")) {
4905
+ if (!this.checkRateLimit(req, res, "decisions")) return;
4623
4906
  const id = url.pathname.slice("/api/deny/".length);
4624
4907
  this.handleDecision(id, "deny", res);
4625
4908
  } else {
@@ -4632,6 +4915,40 @@ var DashboardApprovalChannel = class {
4632
4915
  }
4633
4916
  }
4634
4917
  // ── Route Handlers ──────────────────────────────────────────────────
4918
+ /**
4919
+ * SEC-012: Exchange a long-lived auth token (in Authorization header)
4920
+ * for a short-lived session ID. The session ID can be used in URL
4921
+ * query parameters without exposing the long-lived credential.
4922
+ *
4923
+ * This endpoint performs its OWN auth check (header-only) because it
4924
+ * must reject query-parameter tokens and is called before the
4925
+ * normal checkAuth flow.
4926
+ */
4927
+ handleSessionExchange(req, res) {
4928
+ if (!this.authToken) {
4929
+ res.writeHead(200, { "Content-Type": "application/json" });
4930
+ res.end(JSON.stringify({ session_id: "no-auth" }));
4931
+ return;
4932
+ }
4933
+ const authHeader = req.headers.authorization;
4934
+ if (!authHeader) {
4935
+ res.writeHead(401, { "Content-Type": "application/json" });
4936
+ res.end(JSON.stringify({ error: "Authorization header required" }));
4937
+ return;
4938
+ }
4939
+ const parts = authHeader.split(" ");
4940
+ if (parts.length !== 2 || parts[0] !== "Bearer" || parts[1] !== this.authToken) {
4941
+ res.writeHead(401, { "Content-Type": "application/json" });
4942
+ res.end(JSON.stringify({ error: "Invalid bearer token" }));
4943
+ return;
4944
+ }
4945
+ const sessionId = this.createSession();
4946
+ res.writeHead(200, { "Content-Type": "application/json" });
4947
+ res.end(JSON.stringify({
4948
+ session_id: sessionId,
4949
+ expires_in_seconds: SESSION_TTL_MS / 1e3
4950
+ }));
4951
+ }
4635
4952
  serveDashboard(res) {
4636
4953
  res.writeHead(200, {
4637
4954
  "Content-Type": "text/html; charset=utf-8",
@@ -4657,7 +4974,8 @@ var DashboardApprovalChannel = class {
4657
4974
  approval_channel: {
4658
4975
  type: this.policy.approval_channel.type,
4659
4976
  timeout_seconds: this.policy.approval_channel.timeout_seconds,
4660
- auto_deny: this.policy.approval_channel.auto_deny
4977
+ auto_deny: true
4978
+ // SEC-002: hardcoded, not configurable
4661
4979
  }
4662
4980
  };
4663
4981
  }
@@ -4698,7 +5016,8 @@ data: ${JSON.stringify(initData)}
4698
5016
  approval_channel: {
4699
5017
  type: this.policy.approval_channel.type,
4700
5018
  timeout_seconds: this.policy.approval_channel.timeout_seconds,
4701
- auto_deny: this.policy.approval_channel.auto_deny
5019
+ auto_deny: true
5020
+ // SEC-002: hardcoded, not configurable
4702
5021
  }
4703
5022
  };
4704
5023
  }
@@ -4871,7 +5190,8 @@ var WebhookApprovalChannel = class {
4871
5190
  const timer = setTimeout(() => {
4872
5191
  this.pending.delete(id);
4873
5192
  const response = {
4874
- decision: this.config.auto_deny ? "deny" : "approve",
5193
+ // SEC-002: Timeout ALWAYS denies. No configuration can change this.
5194
+ decision: "deny",
4875
5195
  decided_at: (/* @__PURE__ */ new Date()).toISOString(),
4876
5196
  decided_by: "timeout"
4877
5197
  };
@@ -5059,16 +5379,29 @@ var ApprovalGate = class {
5059
5379
  if (anomaly) {
5060
5380
  return this.requestApproval(operation, 2, anomaly.reason, anomaly.context);
5061
5381
  }
5062
- this.auditLog.append("l2", `gate_allow:${operation}`, "system", {
5063
- tier: 3,
5064
- operation
5382
+ if (this.policy.tier3_always_allow.includes(operation)) {
5383
+ this.auditLog.append("l2", `gate_allow:${operation}`, "system", {
5384
+ tier: 3,
5385
+ operation
5386
+ });
5387
+ return {
5388
+ allowed: true,
5389
+ tier: 3,
5390
+ reason: "Operation allowed (Tier 3)",
5391
+ approval_required: false
5392
+ };
5393
+ }
5394
+ this.auditLog.append("l2", `gate_unclassified:${operation}`, "system", {
5395
+ tier: 1,
5396
+ operation,
5397
+ warning: "Operation is not classified in any policy tier \u2014 defaulting to Tier 1 (require approval)"
5065
5398
  });
5066
- return {
5067
- allowed: true,
5068
- tier: 3,
5069
- reason: "Operation allowed (Tier 3)",
5070
- approval_required: false
5071
- };
5399
+ return this.requestApproval(
5400
+ operation,
5401
+ 1,
5402
+ `"${operation}" is not classified in any policy tier \u2014 requires approval (SEC-011 safe default)`,
5403
+ { operation, unclassified: true }
5404
+ );
5072
5405
  }
5073
5406
  /**
5074
5407
  * Detect Tier 2 behavioral anomalies.
@@ -5241,7 +5574,8 @@ function createPrincipalPolicyTools(policy, baseline, auditLog) {
5241
5574
  approval_channel: {
5242
5575
  type: policy.approval_channel.type,
5243
5576
  timeout_seconds: policy.approval_channel.timeout_seconds,
5244
- auto_deny: policy.approval_channel.auto_deny
5577
+ auto_deny: true
5578
+ // SEC-002: hardcoded, not configurable
5245
5579
  }
5246
5580
  };
5247
5581
  if (includeDefaults) {
@@ -5311,14 +5645,14 @@ function generateSHR(identityId, opts) {
5311
5645
  code: "PROCESS_ISOLATION_ONLY",
5312
5646
  severity: "warning",
5313
5647
  description: "Process-level isolation only (no TEE)",
5314
- mitigation: "TEE support planned for v0.3.0"
5648
+ mitigation: "TEE support planned for a future release"
5315
5649
  });
5316
5650
  degradations.push({
5317
5651
  layer: "l2",
5318
5652
  code: "SELF_REPORTED_ATTESTATION",
5319
5653
  severity: "warning",
5320
5654
  description: "Attestation is self-reported (no hardware root of trust)",
5321
- mitigation: "TEE attestation planned for v0.3.0"
5655
+ mitigation: "TEE attestation planned for a future release"
5322
5656
  });
5323
5657
  }
5324
5658
  if (config.disclosure.proof_system === "commitment-only") {
@@ -5462,6 +5796,245 @@ function assessSovereigntyLevel(body) {
5462
5796
  return "minimal";
5463
5797
  }
5464
5798
 
5799
+ // src/shr/gateway-adapter.ts
5800
+ var LAYER_WEIGHTS = {
5801
+ l1: 100,
5802
+ l2: 100,
5803
+ l3: 100,
5804
+ l4: 100
5805
+ };
5806
+ var DEGRADATION_IMPACT = {
5807
+ critical: 40,
5808
+ warning: 25,
5809
+ info: 10
5810
+ };
5811
+ function transformSHRForGateway(shr) {
5812
+ const { body, signed_by, signature } = shr;
5813
+ const layerScores = calculateLayerScores(body);
5814
+ const overallScore = calculateOverallScore(layerScores);
5815
+ const trustLevel = determineTrustLevel(overallScore);
5816
+ const signals = extractAuthorizationSignals(body);
5817
+ const degradations = transformDegradations(body.degradations);
5818
+ const constraints = generateAuthorizationConstraints(body);
5819
+ return {
5820
+ shr_version: body.shr_version,
5821
+ agent_identity: signed_by,
5822
+ generated_at: (/* @__PURE__ */ new Date()).toISOString(),
5823
+ context_expires_at: body.expires_at,
5824
+ overall_score: overallScore,
5825
+ recommended_trust_level: trustLevel,
5826
+ layer_scores: {
5827
+ l1_cognitive: layerScores.l1,
5828
+ l2_operational: layerScores.l2,
5829
+ l3_disclosure: layerScores.l3,
5830
+ l4_reputation: layerScores.l4
5831
+ },
5832
+ layer_status: {
5833
+ l1_cognitive: body.layers.l1.status,
5834
+ l2_operational: body.layers.l2.status,
5835
+ l3_disclosure: body.layers.l3.status,
5836
+ l4_reputation: body.layers.l4.status
5837
+ },
5838
+ authorization_signals: signals,
5839
+ degradations,
5840
+ recommended_constraints: constraints,
5841
+ shr_signature: signature,
5842
+ shr_signed_by: signed_by
5843
+ };
5844
+ }
5845
+ function calculateLayerScores(body) {
5846
+ const layers = body.layers;
5847
+ const degradations = body.degradations;
5848
+ let l1Score = LAYER_WEIGHTS.l1;
5849
+ let l2Score = LAYER_WEIGHTS.l2;
5850
+ let l3Score = LAYER_WEIGHTS.l3;
5851
+ let l4Score = LAYER_WEIGHTS.l4;
5852
+ for (const deg of degradations) {
5853
+ const impact = DEGRADATION_IMPACT[deg.severity] || 10;
5854
+ if (deg.layer === "l1") {
5855
+ l1Score = Math.max(0, l1Score - impact);
5856
+ } else if (deg.layer === "l2") {
5857
+ l2Score = Math.max(0, l2Score - impact);
5858
+ } else if (deg.layer === "l3") {
5859
+ l3Score = Math.max(0, l3Score - impact);
5860
+ } else if (deg.layer === "l4") {
5861
+ l4Score = Math.max(0, l4Score - impact);
5862
+ }
5863
+ }
5864
+ if (layers.l1.status === "active" && l1Score > 50) l1Score = Math.min(100, l1Score + 5);
5865
+ if (layers.l2.status === "active" && l2Score > 50) l2Score = Math.min(100, l2Score + 5);
5866
+ if (layers.l3.status === "active" && l3Score > 50) l3Score = Math.min(100, l3Score + 5);
5867
+ if (layers.l4.status === "active" && l4Score > 50) l4Score = Math.min(100, l4Score + 5);
5868
+ if (layers.l1.status === "inactive") l1Score = 0;
5869
+ if (layers.l2.status === "inactive") l2Score = 0;
5870
+ if (layers.l3.status === "inactive") l3Score = 0;
5871
+ if (layers.l4.status === "inactive") l4Score = 0;
5872
+ return {
5873
+ l1: Math.round(l1Score),
5874
+ l2: Math.round(l2Score),
5875
+ l3: Math.round(l3Score),
5876
+ l4: Math.round(l4Score)
5877
+ };
5878
+ }
5879
+ function calculateOverallScore(layerScores) {
5880
+ const average = (layerScores.l1 + layerScores.l2 + layerScores.l3 + layerScores.l4) / 4;
5881
+ return Math.round(average);
5882
+ }
5883
+ function determineTrustLevel(score) {
5884
+ if (score >= 80) return "full";
5885
+ if (score >= 60) return "elevated";
5886
+ if (score >= 40) return "standard";
5887
+ return "restricted";
5888
+ }
5889
+ function extractAuthorizationSignals(body) {
5890
+ const l1 = body.layers.l1;
5891
+ const l3 = body.layers.l3;
5892
+ const l4 = body.layers.l4;
5893
+ return {
5894
+ approval_gate_active: body.capabilities.handshake,
5895
+ // Handshake implies human loop capability
5896
+ context_gating_active: body.capabilities.encrypted_channel,
5897
+ // Proxy for gating capability
5898
+ encryption_at_rest: l1.encryption !== "none" && l1.encryption !== "unencrypted",
5899
+ behavioral_baseline_active: false,
5900
+ // Would need explicit field in SHR v1.1
5901
+ identity_verified: l1.identity_type === "ed25519" || l1.identity_type !== "none",
5902
+ zero_knowledge_capable: l3.status === "active" && l3.proof_system !== "commitment-only",
5903
+ selective_disclosure_active: l3.selective_disclosure,
5904
+ reputation_portable: l4.reputation_portable,
5905
+ handshake_capable: body.capabilities.handshake
5906
+ };
5907
+ }
5908
+ function transformDegradations(degradations) {
5909
+ return degradations.map((deg) => {
5910
+ let authzImpact = "";
5911
+ if (deg.code === "NO_TEE") {
5912
+ authzImpact = "Restricted to read-only operations until TEE available";
5913
+ } else if (deg.code === "PROCESS_ISOLATION_ONLY") {
5914
+ authzImpact = "Requires additional identity verification";
5915
+ } else if (deg.code === "COMMITMENT_ONLY") {
5916
+ authzImpact = "Limited data sharing scope \u2014 no zero-knowledge proofs";
5917
+ } else if (deg.code === "NO_ZK_PROOFS") {
5918
+ authzImpact = "Cannot perform confidential disclosures";
5919
+ } else if (deg.code === "SELF_REPORTED_ATTESTATION") {
5920
+ authzImpact = "Attestation trust degraded \u2014 human verification recommended";
5921
+ } else if (deg.code === "NO_SELECTIVE_DISCLOSURE") {
5922
+ authzImpact = "Must share entire data context, cannot redact";
5923
+ } else if (deg.code === "BASIC_SYBIL_ONLY") {
5924
+ authzImpact = "Restrict to interactions with known agents only";
5925
+ } else {
5926
+ authzImpact = "Unknown authorization impact";
5927
+ }
5928
+ return {
5929
+ layer: deg.layer,
5930
+ code: deg.code,
5931
+ severity: deg.severity,
5932
+ description: deg.description,
5933
+ authorization_impact: authzImpact
5934
+ };
5935
+ });
5936
+ }
5937
+ function generateAuthorizationConstraints(body, _degradations) {
5938
+ const constraints = [];
5939
+ const layers = body.layers;
5940
+ if (layers.l1.status === "degraded" || layers.l1.key_custody !== "self") {
5941
+ constraints.push({
5942
+ type: "identity_verification_required",
5943
+ description: "Additional identity verification required for sensitive operations",
5944
+ rationale: "L1 is degraded or key custody is not self-managed",
5945
+ priority: "high"
5946
+ });
5947
+ }
5948
+ if (!layers.l1.state_portable) {
5949
+ constraints.push({
5950
+ type: "location_bound",
5951
+ description: "Agent state is not portable \u2014 restrict to home environment",
5952
+ rationale: "State cannot be safely migrated across boundaries",
5953
+ priority: "medium"
5954
+ });
5955
+ }
5956
+ if (layers.l2.status === "degraded" || layers.l2.isolation_type === "local-process") {
5957
+ constraints.push({
5958
+ type: "read_only",
5959
+ description: "Restrict to read-only operations until operational isolation improves",
5960
+ rationale: "L2 isolation is process-level only (no TEE)",
5961
+ priority: "high"
5962
+ });
5963
+ }
5964
+ if (!layers.l2.attestation_available) {
5965
+ constraints.push({
5966
+ type: "requires_approval",
5967
+ description: "Human approval required for writes and sensitive reads",
5968
+ rationale: "No attestation available \u2014 self-reported integrity only",
5969
+ priority: "high"
5970
+ });
5971
+ }
5972
+ if (layers.l3.status === "degraded" || !layers.l3.selective_disclosure) {
5973
+ constraints.push({
5974
+ type: "restricted_scope",
5975
+ description: "Limit data sharing to minimal required scope \u2014 no selective disclosure",
5976
+ rationale: "Agent cannot redact data or prove predicates without revealing all context",
5977
+ priority: "high"
5978
+ });
5979
+ }
5980
+ if (layers.l3.proof_system === "commitment-only") {
5981
+ constraints.push({
5982
+ type: "restricted_scope",
5983
+ description: "No zero-knowledge proofs available \u2014 entire state context may be visible",
5984
+ rationale: "Proof system is commitment-only (no ZK)",
5985
+ priority: "medium"
5986
+ });
5987
+ }
5988
+ if (layers.l4.status === "degraded") {
5989
+ constraints.push({
5990
+ type: "known_agents_only",
5991
+ description: "Restrict interactions to known, pre-approved agents",
5992
+ rationale: "Reputation layer is degraded",
5993
+ priority: "medium"
5994
+ });
5995
+ }
5996
+ if (!layers.l4.reputation_portable) {
5997
+ constraints.push({
5998
+ type: "location_bound",
5999
+ description: "Reputation is not portable \u2014 restrict to home environment",
6000
+ rationale: "Cannot present reputation to external parties",
6001
+ priority: "low"
6002
+ });
6003
+ }
6004
+ const layerScores = calculateLayerScores(body);
6005
+ const overallScore = calculateOverallScore(layerScores);
6006
+ if (overallScore < 40) {
6007
+ constraints.push({
6008
+ type: "restricted_scope",
6009
+ description: "Overall sovereignty score below threshold \u2014 restrict to non-sensitive operations",
6010
+ rationale: `Overall sovereignty score is ${overallScore}/100`,
6011
+ priority: "high"
6012
+ });
6013
+ }
6014
+ return constraints;
6015
+ }
6016
+ function transformSHRGeneric(shr) {
6017
+ const context = transformSHRForGateway(shr);
6018
+ return {
6019
+ agent_id: context.agent_identity,
6020
+ sovereignty_score: context.overall_score,
6021
+ trust_level: context.recommended_trust_level,
6022
+ layer_scores: {
6023
+ l1: context.layer_scores.l1_cognitive,
6024
+ l2: context.layer_scores.l2_operational,
6025
+ l3: context.layer_scores.l3_disclosure,
6026
+ l4: context.layer_scores.l4_reputation
6027
+ },
6028
+ capabilities: context.authorization_signals,
6029
+ constraints: context.recommended_constraints.map((c) => ({
6030
+ type: c.type,
6031
+ description: c.description
6032
+ })),
6033
+ expires_at: context.context_expires_at,
6034
+ signature: context.shr_signature
6035
+ };
6036
+ }
6037
+
5465
6038
  // src/shr/tools.ts
5466
6039
  function createSHRTools(config, identityManager, masterKey, auditLog) {
5467
6040
  const generatorOpts = {
@@ -5524,6 +6097,53 @@ function createSHRTools(config, identityManager, masterKey, auditLog) {
5524
6097
  );
5525
6098
  return toolResult(result);
5526
6099
  }
6100
+ },
6101
+ {
6102
+ name: "sanctuary/shr_gateway_export",
6103
+ description: "Export this instance's Sovereignty Health Report formatted for Ping Identity's Agent Gateway or other identity providers. Transforms the SHR into an authorization context with sovereignty scores, capability flags, and recommended access constraints.",
6104
+ inputSchema: {
6105
+ type: "object",
6106
+ properties: {
6107
+ format: {
6108
+ type: "string",
6109
+ enum: ["ping", "generic"],
6110
+ description: "Output format: 'ping' (Ping Identity Gateway format) or 'generic' (format-agnostic). Default: 'ping'."
6111
+ },
6112
+ identity_id: {
6113
+ type: "string",
6114
+ description: "Identity to sign the SHR with. Defaults to primary identity."
6115
+ },
6116
+ validity_minutes: {
6117
+ type: "number",
6118
+ description: "How long the SHR is valid (minutes). Default: 60."
6119
+ }
6120
+ }
6121
+ },
6122
+ handler: async (args) => {
6123
+ const format = args.format || "ping";
6124
+ const validityMs = args.validity_minutes ? args.validity_minutes * 60 * 1e3 : void 0;
6125
+ const shrResult = generateSHR(args.identity_id, {
6126
+ ...generatorOpts,
6127
+ validityMs
6128
+ });
6129
+ if (typeof shrResult === "string") {
6130
+ return toolResult({ error: shrResult });
6131
+ }
6132
+ let context;
6133
+ if (format === "generic") {
6134
+ context = transformSHRGeneric(shrResult);
6135
+ } else {
6136
+ context = transformSHRForGateway(shrResult);
6137
+ }
6138
+ auditLog.append(
6139
+ "l2",
6140
+ "shr_gateway_export",
6141
+ shrResult.body.instance_id,
6142
+ void 0,
6143
+ "success"
6144
+ );
6145
+ return toolResult(context);
6146
+ }
5527
6147
  }
5528
6148
  ];
5529
6149
  return { tools };
@@ -5772,7 +6392,9 @@ function createHandshakeTools(config, identityManager, masterKey, auditLog) {
5772
6392
  return toolResult({
5773
6393
  session_id: result.session.session_id,
5774
6394
  response: result.response,
5775
- instructions: "Send the 'response' object back to the initiator. When you receive their completion, pass it to sanctuary/handshake_status with this session_id."
6395
+ instructions: "Send the 'response' object back to the initiator. When you receive their completion, pass it to sanctuary/handshake_status with this session_id.",
6396
+ // SEC-ADD-03: Tag response — contains SHR data that will be sent to counterparty
6397
+ _content_trust: "external"
5776
6398
  });
5777
6399
  }
5778
6400
  },
@@ -5825,7 +6447,9 @@ function createHandshakeTools(config, identityManager, masterKey, auditLog) {
5825
6447
  return toolResult({
5826
6448
  completion: result.completion,
5827
6449
  result: result.result,
5828
- 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."
6450
+ 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.",
6451
+ // SEC-ADD-03: Tag response as containing counterparty-controlled SHR data
6452
+ _content_trust: "external"
5829
6453
  });
5830
6454
  }
5831
6455
  },
@@ -6250,7 +6874,21 @@ function canonicalize(outcome) {
6250
6874
  return stringToBytes(stableStringify(outcome));
6251
6875
  }
6252
6876
  function stableStringify(value) {
6253
- if (value === null || value === void 0) return JSON.stringify(value);
6877
+ if (value === null) return "null";
6878
+ if (value === void 0) return "null";
6879
+ if (typeof value === "number") {
6880
+ if (!Number.isFinite(value)) {
6881
+ throw new Error(
6882
+ `Cannot canonicalize non-finite number: ${value}. NaN, Infinity, and -Infinity are not representable in JSON.`
6883
+ );
6884
+ }
6885
+ if (Object.is(value, -0)) {
6886
+ throw new Error(
6887
+ "Cannot canonicalize negative zero (-0). Use 0 instead for deterministic cross-language serialization."
6888
+ );
6889
+ }
6890
+ return JSON.stringify(value);
6891
+ }
6254
6892
  if (typeof value !== "object") return JSON.stringify(value);
6255
6893
  if (Array.isArray(value)) {
6256
6894
  return "[" + value.map((v) => stableStringify(v)).join(",") + "]";
@@ -6278,11 +6916,12 @@ function createBridgeCommitment(outcome, identity, identityEncryptionKey, includ
6278
6916
  bridge_commitment_id: commitmentId,
6279
6917
  session_id: outcome.session_id,
6280
6918
  sha256_commitment: sha2564.commitment,
6919
+ terms_hash: outcome.terms_hash,
6281
6920
  committer_did: identity.did,
6282
6921
  committed_at: now,
6283
6922
  bridge_version: "sanctuary-concordia-bridge-v1"
6284
6923
  };
6285
- const payloadBytes = stringToBytes(JSON.stringify(commitmentPayload));
6924
+ const payloadBytes = stringToBytes(stableStringify(commitmentPayload));
6286
6925
  const signature = sign(payloadBytes, identity.encrypted_private_key, identityEncryptionKey);
6287
6926
  return {
6288
6927
  bridge_commitment_id: commitmentId,
@@ -6308,11 +6947,12 @@ function verifyBridgeCommitment(commitment, outcome, committerPublicKey) {
6308
6947
  bridge_commitment_id: commitment.bridge_commitment_id,
6309
6948
  session_id: commitment.session_id,
6310
6949
  sha256_commitment: commitment.sha256_commitment,
6950
+ terms_hash: outcome.terms_hash,
6311
6951
  committer_did: commitment.committer_did,
6312
6952
  committed_at: commitment.committed_at,
6313
6953
  bridge_version: commitment.bridge_version
6314
6954
  };
6315
- const payloadBytes = stringToBytes(JSON.stringify(commitmentPayload));
6955
+ const payloadBytes = stringToBytes(stableStringify(commitmentPayload));
6316
6956
  const sigBytes = fromBase64url(commitment.signature);
6317
6957
  const signatureValid = verify(payloadBytes, sigBytes, committerPublicKey);
6318
6958
  const sessionIdMatch = commitment.session_id === outcome.session_id;
@@ -6539,7 +7179,9 @@ function createBridgeTools(storage, masterKey, identityManager, auditLog, handsh
6539
7179
  return toolResult({
6540
7180
  ...result,
6541
7181
  session_id: storedCommitment.session_id,
6542
- committer_did: storedCommitment.committer_did
7182
+ committer_did: storedCommitment.committer_did,
7183
+ // SEC-ADD-03: Tag response as containing counterparty-controlled data
7184
+ _content_trust: "external"
6543
7185
  });
6544
7186
  }
6545
7187
  },
@@ -6633,35 +7275,2253 @@ function createBridgeTools(storage, masterKey, identityManager, auditLog, handsh
6633
7275
  ];
6634
7276
  return { tools };
6635
7277
  }
6636
-
6637
- // src/index.ts
6638
- init_encoding();
6639
- async function createSanctuaryServer(options) {
6640
- const config = await loadConfig(options?.configPath);
6641
- await mkdir(config.storage_path, { recursive: true, mode: 448 });
6642
- const storage = options?.storage ?? new FilesystemStorage(
6643
- `${config.storage_path}/state`
6644
- );
6645
- let masterKey;
6646
- let keyProtection;
6647
- let recoveryKey;
6648
- const passphrase = options?.passphrase ?? process.env.SANCTUARY_PASSPHRASE;
6649
- if (passphrase) {
6650
- keyProtection = "passphrase";
6651
- let existingParams;
6652
- try {
6653
- const raw = await storage.read("_meta", "key-params");
6654
- if (raw) {
6655
- const { bytesToString: bytesToString2 } = await Promise.resolve().then(() => (init_encoding(), encoding_exports));
6656
- existingParams = JSON.parse(bytesToString2(raw));
6657
- }
6658
- } catch {
6659
- }
6660
- const result = await deriveMasterKey(passphrase, existingParams);
6661
- masterKey = result.key;
6662
- if (!existingParams) {
6663
- const { stringToBytes: stringToBytes2 } = await Promise.resolve().then(() => (init_encoding(), encoding_exports));
6664
- await storage.write(
7278
+ function lenientJsonParse(raw) {
7279
+ let cleaned = raw.replace(/\/\/[^\n]*/g, "");
7280
+ cleaned = cleaned.replace(/\/\*[\s\S]*?\*\//g, "");
7281
+ cleaned = cleaned.replace(/,\s*([\]}])/g, "$1");
7282
+ return JSON.parse(cleaned);
7283
+ }
7284
+ async function fileExists(path) {
7285
+ try {
7286
+ await access(path);
7287
+ return true;
7288
+ } catch {
7289
+ return false;
7290
+ }
7291
+ }
7292
+ async function safeReadFile(path) {
7293
+ try {
7294
+ return await readFile(path, "utf-8");
7295
+ } catch {
7296
+ return null;
7297
+ }
7298
+ }
7299
+ async function detectEnvironment(config, deepScan) {
7300
+ const fingerprint = {
7301
+ sanctuary_installed: true,
7302
+ // We're running inside Sanctuary
7303
+ sanctuary_version: config.version,
7304
+ openclaw_detected: false,
7305
+ openclaw_version: null,
7306
+ openclaw_config: null,
7307
+ node_version: process.version,
7308
+ platform: `${process.platform}-${process.arch}`
7309
+ };
7310
+ if (!deepScan) {
7311
+ return fingerprint;
7312
+ }
7313
+ const home = homedir();
7314
+ const openclawConfigPath = join(home, ".openclaw", "openclaw.json");
7315
+ const openclawEnvPath = join(home, ".openclaw", ".env");
7316
+ const openclawMemoryPath = join(home, ".openclaw", "workspace", "MEMORY.md");
7317
+ const openclawMemoryDir = join(home, ".openclaw", "workspace", "memory");
7318
+ const configExists = await fileExists(openclawConfigPath);
7319
+ const envExists = await fileExists(openclawEnvPath);
7320
+ const memoryExists = await fileExists(openclawMemoryPath);
7321
+ const memoryDirExists = await fileExists(openclawMemoryDir);
7322
+ if (configExists || memoryExists || memoryDirExists) {
7323
+ fingerprint.openclaw_detected = true;
7324
+ fingerprint.openclaw_config = await auditOpenClawConfig(
7325
+ openclawConfigPath,
7326
+ openclawEnvPath,
7327
+ openclawMemoryPath,
7328
+ configExists,
7329
+ envExists,
7330
+ memoryExists
7331
+ );
7332
+ }
7333
+ return fingerprint;
7334
+ }
7335
+ async function auditOpenClawConfig(configPath, envPath, _memoryPath, configExists, envExists, memoryExists) {
7336
+ const audit = {
7337
+ config_path: configExists ? configPath : null,
7338
+ require_approval_enabled: false,
7339
+ sandbox_policy_active: false,
7340
+ sandbox_allow_list: [],
7341
+ sandbox_deny_list: [],
7342
+ memory_encrypted: false,
7343
+ // Stock OpenClaw never encrypts memory
7344
+ env_file_exposed: false,
7345
+ gateway_token_set: false,
7346
+ dm_pairing_enabled: false,
7347
+ mcp_bridge_active: false
7348
+ };
7349
+ if (configExists) {
7350
+ const raw = await safeReadFile(configPath);
7351
+ if (raw) {
7352
+ try {
7353
+ const parsed = lenientJsonParse(raw);
7354
+ const hooks = parsed.hooks;
7355
+ if (hooks) {
7356
+ const beforeToolCall = hooks.before_tool_call;
7357
+ if (beforeToolCall) {
7358
+ const hookStr = JSON.stringify(beforeToolCall);
7359
+ audit.require_approval_enabled = hookStr.includes("requireApproval");
7360
+ }
7361
+ }
7362
+ const tools = parsed.tools;
7363
+ if (tools) {
7364
+ const sandbox = tools.sandbox;
7365
+ if (sandbox) {
7366
+ const sandboxTools = sandbox.tools;
7367
+ if (sandboxTools) {
7368
+ audit.sandbox_policy_active = true;
7369
+ if (Array.isArray(sandboxTools.allow)) {
7370
+ audit.sandbox_allow_list = sandboxTools.allow.filter(
7371
+ (item) => typeof item === "string"
7372
+ );
7373
+ }
7374
+ if (Array.isArray(sandboxTools.alsoAllow)) {
7375
+ audit.sandbox_allow_list = [
7376
+ ...audit.sandbox_allow_list,
7377
+ ...sandboxTools.alsoAllow.filter(
7378
+ (item) => typeof item === "string"
7379
+ )
7380
+ ];
7381
+ }
7382
+ if (Array.isArray(sandboxTools.deny)) {
7383
+ audit.sandbox_deny_list = sandboxTools.deny.filter(
7384
+ (item) => typeof item === "string"
7385
+ );
7386
+ }
7387
+ }
7388
+ }
7389
+ }
7390
+ const mcpServers = parsed.mcpServers;
7391
+ if (mcpServers && Object.keys(mcpServers).length > 0) {
7392
+ audit.mcp_bridge_active = true;
7393
+ }
7394
+ } catch {
7395
+ }
7396
+ }
7397
+ }
7398
+ if (envExists) {
7399
+ const envContent = await safeReadFile(envPath);
7400
+ if (envContent) {
7401
+ const secretPatterns = [
7402
+ /[A-Z_]*API_KEY\s*=/,
7403
+ /[A-Z_]*TOKEN\s*=/,
7404
+ /[A-Z_]*SECRET\s*=/,
7405
+ /[A-Z_]*PASSWORD\s*=/,
7406
+ /[A-Z_]*PRIVATE_KEY\s*=/
7407
+ ];
7408
+ audit.env_file_exposed = secretPatterns.some((p) => p.test(envContent));
7409
+ audit.gateway_token_set = /OPENCLAW_GATEWAY_TOKEN\s*=/.test(envContent);
7410
+ }
7411
+ }
7412
+ if (memoryExists) {
7413
+ audit.memory_encrypted = false;
7414
+ }
7415
+ return audit;
7416
+ }
7417
+
7418
+ // src/audit/analyzer.ts
7419
+ var L1_ENCRYPTION_AT_REST = 10;
7420
+ var L1_IDENTITY_CRYPTOGRAPHIC = 10;
7421
+ var L1_INTEGRITY_VERIFICATION = 8;
7422
+ var L1_STATE_PORTABLE = 7;
7423
+ var L2_THREE_TIER_GATE = 10;
7424
+ var L2_BINARY_GATE = 3;
7425
+ var L2_ANOMALY_DETECTION = 5;
7426
+ var L2_ENCRYPTED_AUDIT = 4;
7427
+ var L2_TOOL_SANDBOXING = 2;
7428
+ var L2_CONTEXT_GATING = 4;
7429
+ var L2_PROCESS_HARDENING = 5;
7430
+ var L3_COMMITMENT_SCHEME = 8;
7431
+ var L3_ZK_PROOFS = 7;
7432
+ var L3_DISCLOSURE_POLICIES = 5;
7433
+ var L4_PORTABLE_REPUTATION = 6;
7434
+ var L4_SIGNED_ATTESTATIONS = 6;
7435
+ var L4_SYBIL_DETECTION = 4;
7436
+ var L4_SOVEREIGNTY_GATED = 4;
7437
+ var SEVERITY_ORDER = {
7438
+ critical: 0,
7439
+ high: 1,
7440
+ medium: 2,
7441
+ low: 3
7442
+ };
7443
+ var INCIDENT_META_SEV1 = {
7444
+ id: "META-SEV1-2026",
7445
+ name: "Meta Sev 1: Unauthorized autonomous data exposure",
7446
+ date: "2026-03-18",
7447
+ description: "AI agent autonomously posted proprietary code, business strategies, and user datasets to an internal forum without human approval. Two-hour exposure window."
7448
+ };
7449
+ var INCIDENT_OPENCLAW_SANDBOX = {
7450
+ id: "OPENCLAW-CVE-2026",
7451
+ name: "OpenClaw sandbox escape via privilege inheritance",
7452
+ date: "2026-03-18",
7453
+ description: "Nine CVEs in four days. Child processes inherited sandbox.mode=off from parent, bypassing runtime confinement. 42,900+ internet-exposed instances, 15,200 vulnerable to RCE.",
7454
+ cves: [
7455
+ "CVE-2026-32048",
7456
+ "CVE-2026-32915",
7457
+ "CVE-2026-32918"
7458
+ ]
7459
+ };
7460
+ var INCIDENT_CONTEXT_LEAKAGE = {
7461
+ id: "CONTEXT-LEAK-CLASS",
7462
+ name: "Context leakage: Full state exposure to inference providers",
7463
+ date: "2026-03",
7464
+ description: "Agents send full context \u2014 conversation history, memory, secrets, internal reasoning \u2014 to remote LLM providers on every inference call with no filtering mechanism."
7465
+ };
7466
+ var INCIDENT_CLAUDE_CODE_LEAK = {
7467
+ id: "CLAUDE-CODE-LEAK-2026",
7468
+ name: "Claude Code source leak: 512K lines exposed via npm source map",
7469
+ date: "2026-03-31",
7470
+ description: "Anthropic accidentally shipped a 59.8 MB source map in npm package v2.1.88, exposing the full Claude Code TypeScript source \u2014 1,900 files, internal model codenames, unreleased features, OAuth flows, and multi-agent coordination logic."
7471
+ };
7472
+ function analyzeSovereignty(env, config) {
7473
+ const l1 = assessL1(env, config);
7474
+ const l2 = assessL2(env);
7475
+ const l3 = assessL3(env);
7476
+ const l4 = assessL4(env);
7477
+ const l1Score = scoreL1(l1);
7478
+ const l2Score = scoreL2(l2);
7479
+ const l3Score = scoreL3(l3);
7480
+ const l4Score = scoreL4(l4);
7481
+ const overallScore = l1Score + l2Score + l3Score + l4Score;
7482
+ const sovereigntyLevel = overallScore >= 80 ? "full" : overallScore >= 50 ? "partial" : overallScore >= 20 ? "minimal" : "none";
7483
+ const gaps = generateGaps(env, l1, l2, l3, l4);
7484
+ gaps.sort((a, b) => SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity]);
7485
+ const recommendations = generateRecommendations(env, l1, l2, l3, l4);
7486
+ return {
7487
+ version: "1.0",
7488
+ audited_at: (/* @__PURE__ */ new Date()).toISOString(),
7489
+ environment: env,
7490
+ layers: {
7491
+ l1_cognitive: l1,
7492
+ l2_operational: l2,
7493
+ l3_selective_disclosure: l3,
7494
+ l4_reputation: l4
7495
+ },
7496
+ overall_score: overallScore,
7497
+ sovereignty_level: sovereigntyLevel,
7498
+ gaps,
7499
+ recommendations
7500
+ };
7501
+ }
7502
+ function assessL1(env, config) {
7503
+ const findings = [];
7504
+ const sanctuaryActive = env.sanctuary_installed;
7505
+ const encryptionAtRest = sanctuaryActive;
7506
+ const keyCustody = sanctuaryActive ? "self" : "none";
7507
+ const integrityVerification = sanctuaryActive;
7508
+ const identityCryptographic = sanctuaryActive;
7509
+ const statePortable = sanctuaryActive;
7510
+ if (sanctuaryActive) {
7511
+ findings.push("AES-256-GCM encryption active for all state");
7512
+ findings.push(`Key derivation: ${config.state.key_derivation}`);
7513
+ findings.push(`Identity provider: ${config.state.identity_provider}`);
7514
+ findings.push("Merkle integrity verification enabled");
7515
+ findings.push("State export/import available");
7516
+ }
7517
+ if (env.openclaw_detected && env.openclaw_config) {
7518
+ if (!env.openclaw_config.memory_encrypted) {
7519
+ findings.push("OpenClaw agent memory (MEMORY.md, daily notes) stored in plaintext");
7520
+ }
7521
+ if (env.openclaw_config.env_file_exposed) {
7522
+ findings.push("OpenClaw .env file contains plaintext API keys/tokens");
7523
+ }
7524
+ }
7525
+ const status = encryptionAtRest && identityCryptographic ? "active" : encryptionAtRest || identityCryptographic ? "partial" : "inactive";
7526
+ return {
7527
+ status,
7528
+ encryption_at_rest: encryptionAtRest,
7529
+ key_custody: keyCustody,
7530
+ integrity_verification: integrityVerification,
7531
+ identity_cryptographic: identityCryptographic,
7532
+ state_portable: statePortable,
7533
+ findings
7534
+ };
7535
+ }
7536
+ function assessL2(env, _config) {
7537
+ const findings = [];
7538
+ const sanctuaryActive = env.sanctuary_installed;
7539
+ let approvalGate = "none";
7540
+ let behavioralAnomalyDetection = false;
7541
+ let auditTrailEncrypted = false;
7542
+ let auditTrailExists = false;
7543
+ let toolSandboxing = "none";
7544
+ let contextGating = false;
7545
+ let processIsolationHardening = "none";
7546
+ if (sanctuaryActive) {
7547
+ approvalGate = "three-tier";
7548
+ behavioralAnomalyDetection = true;
7549
+ auditTrailEncrypted = true;
7550
+ auditTrailExists = true;
7551
+ contextGating = true;
7552
+ findings.push("Three-tier Principal Policy gate active");
7553
+ findings.push("Behavioral anomaly detection (BaselineTracker) enabled");
7554
+ findings.push("Encrypted audit trail active");
7555
+ findings.push("Context gating available (sanctuary/context_gate_set_policy)");
7556
+ }
7557
+ if (env.openclaw_detected && env.openclaw_config) {
7558
+ if (env.openclaw_config.require_approval_enabled) {
7559
+ if (!sanctuaryActive) {
7560
+ approvalGate = "binary";
7561
+ }
7562
+ findings.push("OpenClaw requireApproval hook enabled (binary approve/deny)");
7563
+ }
7564
+ if (env.openclaw_config.sandbox_policy_active) {
7565
+ if (!sanctuaryActive) {
7566
+ toolSandboxing = "basic";
7567
+ }
7568
+ findings.push(
7569
+ `OpenClaw sandbox policy active (${env.openclaw_config.sandbox_allow_list.length} allowed, ${env.openclaw_config.sandbox_deny_list.length} denied)`
7570
+ );
7571
+ }
7572
+ }
7573
+ processIsolationHardening = "none";
7574
+ const status = approvalGate === "three-tier" && auditTrailEncrypted ? "active" : approvalGate !== "none" || auditTrailExists ? "partial" : "inactive";
7575
+ return {
7576
+ status,
7577
+ approval_gate: approvalGate,
7578
+ behavioral_anomaly_detection: behavioralAnomalyDetection,
7579
+ audit_trail_encrypted: auditTrailEncrypted,
7580
+ audit_trail_exists: auditTrailExists,
7581
+ tool_sandboxing: sanctuaryActive ? "policy-enforced" : toolSandboxing,
7582
+ context_gating: contextGating,
7583
+ process_isolation_hardening: processIsolationHardening,
7584
+ findings
7585
+ };
7586
+ }
7587
+ function assessL3(env, _config) {
7588
+ const findings = [];
7589
+ const sanctuaryActive = env.sanctuary_installed;
7590
+ let commitmentScheme = "none";
7591
+ let zkProofs = false;
7592
+ let selectiveDisclosurePolicy = false;
7593
+ if (sanctuaryActive) {
7594
+ commitmentScheme = "pedersen+sha256";
7595
+ zkProofs = true;
7596
+ selectiveDisclosurePolicy = true;
7597
+ findings.push("SHA-256 + Pedersen commitment schemes active");
7598
+ findings.push("Schnorr zero-knowledge proofs (Fiat-Shamir) enabled \u2014 genuine ZK proofs");
7599
+ findings.push("Range proofs (bit-decomposition + OR-proofs) enabled \u2014 genuine ZK proofs");
7600
+ findings.push("Selective disclosure policies configurable");
7601
+ findings.push("Non-interactive proofs with replay-resistant domain separation");
7602
+ }
7603
+ const status = commitmentScheme === "pedersen+sha256" && zkProofs ? "active" : commitmentScheme !== "none" ? "partial" : "inactive";
7604
+ return {
7605
+ status,
7606
+ commitment_scheme: commitmentScheme,
7607
+ zero_knowledge_proofs: zkProofs,
7608
+ selective_disclosure_policy: selectiveDisclosurePolicy,
7609
+ findings
7610
+ };
7611
+ }
7612
+ function assessL4(env, _config) {
7613
+ const findings = [];
7614
+ const sanctuaryActive = env.sanctuary_installed;
7615
+ const reputationPortable = sanctuaryActive;
7616
+ const reputationSigned = sanctuaryActive;
7617
+ const sybilDetection = sanctuaryActive;
7618
+ const sovereigntyGated = sanctuaryActive;
7619
+ if (sanctuaryActive) {
7620
+ findings.push("Signed EAS-compatible attestations active");
7621
+ findings.push("Reputation export/import available");
7622
+ findings.push("Sybil detection heuristics enabled");
7623
+ findings.push("Sovereignty-gated reputation tiers active");
7624
+ } else {
7625
+ findings.push("No portable reputation system detected");
7626
+ }
7627
+ const status = reputationPortable && reputationSigned && sovereigntyGated ? "active" : reputationPortable || reputationSigned ? "partial" : "inactive";
7628
+ return {
7629
+ status,
7630
+ reputation_portable: reputationPortable,
7631
+ reputation_signed: reputationSigned,
7632
+ reputation_sybil_detection: sybilDetection,
7633
+ sovereignty_gated_tiers: sovereigntyGated,
7634
+ findings
7635
+ };
7636
+ }
7637
+ function scoreL1(l1) {
7638
+ let score = 0;
7639
+ if (l1.encryption_at_rest) score += L1_ENCRYPTION_AT_REST;
7640
+ if (l1.identity_cryptographic) score += L1_IDENTITY_CRYPTOGRAPHIC;
7641
+ if (l1.integrity_verification) score += L1_INTEGRITY_VERIFICATION;
7642
+ if (l1.state_portable) score += L1_STATE_PORTABLE;
7643
+ return score;
7644
+ }
7645
+ function scoreL2(l2) {
7646
+ let score = 0;
7647
+ if (l2.approval_gate === "three-tier") score += L2_THREE_TIER_GATE;
7648
+ else if (l2.approval_gate === "binary") score += L2_BINARY_GATE;
7649
+ if (l2.behavioral_anomaly_detection) score += L2_ANOMALY_DETECTION;
7650
+ if (l2.audit_trail_encrypted) score += L2_ENCRYPTED_AUDIT;
7651
+ if (l2.tool_sandboxing === "policy-enforced") score += L2_TOOL_SANDBOXING;
7652
+ else if (l2.tool_sandboxing === "basic") score += 1;
7653
+ if (l2.context_gating) score += L2_CONTEXT_GATING;
7654
+ if (l2.process_isolation_hardening === "hardened") score += L2_PROCESS_HARDENING;
7655
+ else if (l2.process_isolation_hardening === "basic") score += 2;
7656
+ return score;
7657
+ }
7658
+ function scoreL3(l3) {
7659
+ let score = 0;
7660
+ if (l3.commitment_scheme === "pedersen+sha256") score += L3_COMMITMENT_SCHEME;
7661
+ else if (l3.commitment_scheme === "sha256-only") score += 4;
7662
+ if (l3.zero_knowledge_proofs) score += L3_ZK_PROOFS;
7663
+ if (l3.selective_disclosure_policy) score += L3_DISCLOSURE_POLICIES;
7664
+ return score;
7665
+ }
7666
+ function scoreL4(l4) {
7667
+ let score = 0;
7668
+ if (l4.reputation_portable) score += L4_PORTABLE_REPUTATION;
7669
+ if (l4.reputation_signed) score += L4_SIGNED_ATTESTATIONS;
7670
+ if (l4.reputation_sybil_detection) score += L4_SYBIL_DETECTION;
7671
+ if (l4.sovereignty_gated_tiers) score += L4_SOVEREIGNTY_GATED;
7672
+ return score;
7673
+ }
7674
+ function generateGaps(env, l1, l2, l3, l4) {
7675
+ const gaps = [];
7676
+ const oc = env.openclaw_config;
7677
+ if (oc && !oc.memory_encrypted) {
7678
+ gaps.push({
7679
+ id: "GAP-L1-001",
7680
+ layer: "L1",
7681
+ severity: "critical",
7682
+ title: "Agent memory stored in plaintext",
7683
+ 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.",
7684
+ openclaw_relevance: "Stock OpenClaw stores all agent memory in plaintext files. There is no built-in encryption for agent state.",
7685
+ 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.",
7686
+ incident_class: INCIDENT_META_SEV1
7687
+ });
7688
+ }
7689
+ if (oc && oc.env_file_exposed) {
7690
+ gaps.push({
7691
+ id: "GAP-L1-002",
7692
+ layer: "L1",
7693
+ severity: "critical",
7694
+ title: "Plaintext API keys in .env file",
7695
+ description: "Your .env file contains plaintext API keys and tokens. These secrets are readable by any process with filesystem access.",
7696
+ openclaw_relevance: "OpenClaw stores API keys (LLM providers, gateway tokens) in a plaintext .env file.",
7697
+ 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'."
7698
+ });
7699
+ }
7700
+ if (!l1.identity_cryptographic) {
7701
+ gaps.push({
7702
+ id: "GAP-L1-003",
7703
+ layer: "L1",
7704
+ severity: "critical",
7705
+ title: "No cryptographic agent identity",
7706
+ 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.",
7707
+ openclaw_relevance: env.openclaw_detected ? "OpenClaw has no cryptographic agent identity. Agent identity is implicit (tied to the process/session), not cryptographically verifiable." : null,
7708
+ sanctuary_solution: "Sanctuary provides Ed25519 self-custodied identity with key rotation and delegation. Use sanctuary/identity_create to establish your cryptographic identity."
7709
+ });
7710
+ }
7711
+ if (l2.approval_gate === "binary" && !l2.behavioral_anomaly_detection) {
7712
+ gaps.push({
7713
+ id: "GAP-L2-001",
7714
+ layer: "L2",
7715
+ severity: "high",
7716
+ title: "Binary approval gate (no anomaly detection)",
7717
+ description: "Your approval gate provides binary approve/deny gating without behavioral anomaly detection. Routine operations require the same manual approval as sensitive ones.",
7718
+ 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,
7719
+ 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.",
7720
+ incident_class: INCIDENT_META_SEV1
7721
+ });
7722
+ } else if (l2.approval_gate === "none") {
7723
+ gaps.push({
7724
+ id: "GAP-L2-001",
7725
+ layer: "L2",
7726
+ severity: "critical",
7727
+ title: "No approval gate",
7728
+ description: "No approval gate is configured. All tool calls execute without oversight.",
7729
+ openclaw_relevance: null,
7730
+ sanctuary_solution: "Sanctuary's Principal Policy evaluates every tool call before execution. Enable it to get three-tier approval gating with behavioral anomaly detection.",
7731
+ incident_class: INCIDENT_META_SEV1
7732
+ });
7733
+ }
7734
+ if (l2.tool_sandboxing === "basic") {
7735
+ gaps.push({
7736
+ id: "GAP-L2-002",
7737
+ layer: "L2",
7738
+ severity: "medium",
7739
+ title: "Basic tool sandboxing (no cryptographic attestation)",
7740
+ description: "Your tool sandbox enforces allow/deny lists but provides no cryptographic attestation of execution context.",
7741
+ 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,
7742
+ sanctuary_solution: "Sanctuary provides cryptographic execution attestation via sanctuary/exec_attest and policy-enforced sandboxing with encrypted audit trails.",
7743
+ incident_class: INCIDENT_OPENCLAW_SANDBOX
7744
+ });
7745
+ }
7746
+ if (!l2.context_gating) {
7747
+ gaps.push({
7748
+ id: "GAP-L2-003",
7749
+ layer: "L2",
7750
+ severity: "high",
7751
+ title: "No context gating for outbound inference calls",
7752
+ description: "Your agent sends its full context \u2014 conversation history, memory, preferences, internal reasoning \u2014 to remote LLM providers on every inference call. There is no mechanism to filter what leaves the sovereignty boundary. The provider sees everything the agent knows.",
7753
+ openclaw_relevance: env.openclaw_detected ? "OpenClaw sends full agent context (including MEMORY.md, tool results, and conversation history) to the configured LLM provider with every API call. There is no built-in context filtering." : null,
7754
+ sanctuary_solution: "Sanctuary's context gating (sanctuary/context_gate_set_policy + sanctuary/context_gate_filter) lets you define per-provider policies that control exactly what context flows outbound. Redact secrets, hash identifiers, and send only minimum-necessary context for each call.",
7755
+ incident_class: INCIDENT_CONTEXT_LEAKAGE
7756
+ });
7757
+ }
7758
+ if (!l2.audit_trail_exists) {
7759
+ gaps.push({
7760
+ id: "GAP-L2-004",
7761
+ layer: "L2",
7762
+ severity: "high",
7763
+ title: "No audit trail",
7764
+ description: "No audit trail exists for tool call history. There is no record of what operations were executed, when, or by whom.",
7765
+ openclaw_relevance: null,
7766
+ sanctuary_solution: "Sanctuary maintains an encrypted audit log of all operations, queryable via sanctuary/monitor_audit_log.",
7767
+ incident_class: INCIDENT_CLAUDE_CODE_LEAK
7768
+ });
7769
+ }
7770
+ if (l3.commitment_scheme === "none") {
7771
+ gaps.push({
7772
+ id: "GAP-L3-001",
7773
+ layer: "L3",
7774
+ severity: "high",
7775
+ title: "No selective disclosure capability",
7776
+ description: "Your agent has no cryptographic mechanism to prove facts about its state without revealing the state itself. Every disclosure is all-or-nothing: no commitments, no zero-knowledge proofs, no selective disclosure policies.",
7777
+ 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,
7778
+ sanctuary_solution: "Sanctuary's L3 provides SHA-256 + Pedersen commitments with genuine zero-knowledge proofs (Schnorr + range proofs via Fiat-Shamir transform). 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.",
7779
+ incident_class: INCIDENT_META_SEV1
7780
+ });
7781
+ }
7782
+ if (!l4.reputation_portable) {
7783
+ gaps.push({
7784
+ id: "GAP-L4-001",
7785
+ layer: "L4",
7786
+ severity: "high",
7787
+ title: "No portable reputation",
7788
+ description: "Your agent's reputation is platform-locked. If you move to a different harness or platform, your track record doesn't follow.",
7789
+ 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,
7790
+ 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."
7791
+ });
7792
+ }
7793
+ return gaps;
7794
+ }
7795
+ function generateRecommendations(env, l1, l2, l3, l4) {
7796
+ const recs = [];
7797
+ if (!l1.identity_cryptographic) {
7798
+ recs.push({
7799
+ priority: 1,
7800
+ action: "Create a cryptographic identity \u2014 your agent's foundation for all sovereignty operations",
7801
+ tool: "sanctuary/identity_create",
7802
+ effort: "immediate",
7803
+ impact: "critical"
7804
+ });
7805
+ }
7806
+ if (!l1.encryption_at_rest || env.openclaw_config && !env.openclaw_config.memory_encrypted) {
7807
+ recs.push({
7808
+ priority: 2,
7809
+ action: "Migrate plaintext agent state to Sanctuary's encrypted store",
7810
+ tool: "sanctuary/state_write",
7811
+ effort: "minutes",
7812
+ impact: "critical"
7813
+ });
7814
+ }
7815
+ recs.push({
7816
+ priority: 3,
7817
+ action: "Generate a Sovereignty Health Report to present to counterparties",
7818
+ tool: "sanctuary/shr_generate",
7819
+ effort: "immediate",
7820
+ impact: "high"
7821
+ });
7822
+ if (l2.approval_gate !== "three-tier") {
7823
+ recs.push({
7824
+ priority: 4,
7825
+ action: "Enable the three-tier Principal Policy gate for graduated approval",
7826
+ tool: "sanctuary/principal_policy_view",
7827
+ effort: "minutes",
7828
+ impact: "high"
7829
+ });
7830
+ }
7831
+ if (!l2.context_gating) {
7832
+ recs.push({
7833
+ priority: 5,
7834
+ action: "Configure context gating to control what flows to LLM providers",
7835
+ tool: "sanctuary/context_gate_set_policy",
7836
+ effort: "minutes",
7837
+ impact: "high"
7838
+ });
7839
+ }
7840
+ if (!l4.reputation_signed) {
7841
+ recs.push({
7842
+ priority: 6,
7843
+ action: "Start recording reputation attestations from completed interactions",
7844
+ tool: "sanctuary/reputation_record",
7845
+ effort: "minutes",
7846
+ impact: "medium"
7847
+ });
7848
+ }
7849
+ if (!l3.selective_disclosure_policy) {
7850
+ recs.push({
7851
+ priority: 7,
7852
+ action: "Configure selective disclosure policies for data sharing",
7853
+ tool: "sanctuary/disclosure_set_policy",
7854
+ effort: "hours",
7855
+ impact: "medium"
7856
+ });
7857
+ }
7858
+ return recs;
7859
+ }
7860
+ function formatAuditReport(result) {
7861
+ const { environment: env, layers, overall_score, sovereignty_level, gaps, recommendations } = result;
7862
+ const scoreBar = formatScoreBar(overall_score);
7863
+ const levelLabel = sovereignty_level.toUpperCase();
7864
+ let report = "";
7865
+ 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";
7866
+ report += " SOVEREIGNTY AUDIT REPORT\n";
7867
+ report += ` Generated: ${result.audited_at}
7868
+ `;
7869
+ 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";
7870
+ report += "\n";
7871
+ report += ` Overall Score: ${overall_score} / 100 ${scoreBar} ${levelLabel}
7872
+ `;
7873
+ report += "\n";
7874
+ report += " Environment:\n";
7875
+ report += ` \u2022 Sanctuary v${env.sanctuary_version ?? "?"} ${padDots("Sanctuary v" + (env.sanctuary_version ?? "?"))} ${env.sanctuary_installed ? "\u2713 installed" : "\u2717 not found"}
7876
+ `;
7877
+ if (env.openclaw_detected) {
7878
+ report += ` \u2022 OpenClaw ${padDots("OpenClaw")} \u2713 detected
7879
+ `;
7880
+ if (env.openclaw_config) {
7881
+ report += ` \u2022 OpenClaw requireApproval ${padDots("OpenClaw requireApproval")} ${env.openclaw_config.require_approval_enabled ? "\u2713 enabled" : "\u2717 disabled"}
7882
+ `;
7883
+ report += ` \u2022 OpenClaw sandbox policy ${padDots("OpenClaw sandbox policy")} ${env.openclaw_config.sandbox_policy_active ? "\u2713 active" : "\u2717 inactive"}
7884
+ `;
7885
+ }
7886
+ }
7887
+ report += "\n";
7888
+ const l1Score = scoreL1(layers.l1_cognitive);
7889
+ const l2Score = scoreL2(layers.l2_operational);
7890
+ const l3Score = scoreL3(layers.l3_selective_disclosure);
7891
+ const l4Score = scoreL4(layers.l4_reputation);
7892
+ report += " Layer Assessment:\n";
7893
+ 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";
7894
+ report += " \u2502 Layer \u2502 Status \u2502 Score \u2502\n";
7895
+ 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";
7896
+ report += ` \u2502 L1 Cognitive Sovereignty \u2502 ${padStatus(layers.l1_cognitive.status)} \u2502 ${padScore(l1Score, 35)} \u2502
7897
+ `;
7898
+ report += ` \u2502 L2 Operational Isolation \u2502 ${padStatus(layers.l2_operational.status)} \u2502 ${padScore(l2Score, 25)} \u2502
7899
+ `;
7900
+ if (layers.l2_operational.context_gating) {
7901
+ report += ` \u2502 \u2514 Context Gating \u2502 ACTIVE \u2502 \u2502
7902
+ `;
7903
+ }
7904
+ report += ` \u2502 L3 Selective Disclosure \u2502 ${padStatus(layers.l3_selective_disclosure.status)} \u2502 ${padScore(l3Score, 20)} \u2502
7905
+ `;
7906
+ report += ` \u2502 L4 Verifiable Reputation \u2502 ${padStatus(layers.l4_reputation.status)} \u2502 ${padScore(l4Score, 20)} \u2502
7907
+ `;
7908
+ 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";
7909
+ report += "\n";
7910
+ if (gaps.length > 0) {
7911
+ report += ` \u26A0 ${gaps.length} SOVEREIGNTY GAP${gaps.length !== 1 ? "S" : ""} FOUND
7912
+ `;
7913
+ report += "\n";
7914
+ for (const gap of gaps) {
7915
+ const severityLabel = `[${gap.severity.toUpperCase()}]`;
7916
+ report += ` ${severityLabel} ${gap.id}: ${gap.title}
7917
+ `;
7918
+ const descLines = wordWrap(gap.description, 66);
7919
+ for (const line of descLines) {
7920
+ report += ` ${line}
7921
+ `;
7922
+ }
7923
+ if (gap.incident_class) {
7924
+ const ic = gap.incident_class;
7925
+ const cveStr = ic.cves?.length ? ` (${ic.cves.join(", ")})` : "";
7926
+ report += ` \u2192 Incident precedent: ${ic.name}${cveStr} [${ic.date}]
7927
+ `;
7928
+ }
7929
+ report += ` \u2192 Fix: ${gap.sanctuary_solution.split(".")[0]}.
7930
+ `;
7931
+ if (gap.openclaw_relevance) {
7932
+ report += ` \u2192 OpenClaw context: ${gap.openclaw_relevance.split(".")[0]}.
7933
+ `;
7934
+ }
7935
+ report += "\n";
7936
+ }
7937
+ } else {
7938
+ report += " \u2713 NO SOVEREIGNTY GAPS FOUND\n";
7939
+ report += "\n";
7940
+ }
7941
+ if (recommendations.length > 0) {
7942
+ report += " RECOMMENDED NEXT STEPS (in order):\n";
7943
+ for (const rec of recommendations) {
7944
+ const effortLabel = rec.effort === "immediate" ? "immediate" : rec.effort === "minutes" ? "5 min" : "30 min";
7945
+ report += ` ${rec.priority}. [${effortLabel}] ${rec.action}`;
7946
+ if (rec.tool) {
7947
+ report += `: ${rec.tool}`;
7948
+ }
7949
+ report += "\n";
7950
+ }
7951
+ report += "\n";
7952
+ }
7953
+ 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";
7954
+ return report;
7955
+ }
7956
+ function formatScoreBar(score) {
7957
+ const filled = Math.round(score / 10);
7958
+ return "[" + "\u25A0".repeat(filled) + "\u2591".repeat(10 - filled) + "]";
7959
+ }
7960
+ function padDots(label) {
7961
+ const totalWidth = 30;
7962
+ const dotsNeeded = Math.max(2, totalWidth - label.length - 4);
7963
+ return ".".repeat(dotsNeeded);
7964
+ }
7965
+ function padStatus(status) {
7966
+ const label = status.toUpperCase();
7967
+ return label + " ".repeat(Math.max(0, 8 - label.length));
7968
+ }
7969
+ function padScore(score, max) {
7970
+ const text = `${score}/${max}`;
7971
+ return " ".repeat(Math.max(0, 5 - text.length)) + text;
7972
+ }
7973
+ function wordWrap(text, maxWidth) {
7974
+ const words = text.split(" ");
7975
+ const lines = [];
7976
+ let current = "";
7977
+ for (const word of words) {
7978
+ if (current.length + word.length + 1 > maxWidth && current.length > 0) {
7979
+ lines.push(current);
7980
+ current = word;
7981
+ } else {
7982
+ current = current.length > 0 ? current + " " + word : word;
7983
+ }
7984
+ }
7985
+ if (current.length > 0) lines.push(current);
7986
+ return lines;
7987
+ }
7988
+
7989
+ // src/audit/tools.ts
7990
+ function createAuditTools(config) {
7991
+ const tools = [
7992
+ {
7993
+ name: "sanctuary/sovereignty_audit",
7994
+ 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.",
7995
+ inputSchema: {
7996
+ type: "object",
7997
+ properties: {
7998
+ deep_scan: {
7999
+ type: "boolean",
8000
+ description: "If true (default), also scans for OpenClaw config, .env files, and memory files. Set to false for a Sanctuary-only assessment."
8001
+ }
8002
+ }
8003
+ },
8004
+ handler: async (args) => {
8005
+ const deepScan = args.deep_scan !== false;
8006
+ const env = await detectEnvironment(config, deepScan);
8007
+ const result = analyzeSovereignty(env, config);
8008
+ const report = formatAuditReport(result);
8009
+ return {
8010
+ content: [
8011
+ { type: "text", text: report },
8012
+ { type: "text", text: JSON.stringify(result, null, 2) }
8013
+ ]
8014
+ };
8015
+ }
8016
+ }
8017
+ ];
8018
+ return { tools };
8019
+ }
8020
+
8021
+ // src/l2-operational/context-gate.ts
8022
+ init_encoding();
8023
+ init_hashing();
8024
+ var MAX_CONTEXT_FIELDS = 1e3;
8025
+ var MAX_POLICY_RULES = 50;
8026
+ var MAX_PATTERNS_PER_ARRAY = 500;
8027
+ function evaluateField(policy, provider, field) {
8028
+ const exactRule = policy.rules.find((r) => r.provider === provider);
8029
+ const wildcardRule = policy.rules.find((r) => r.provider === "*");
8030
+ const matchedRule = exactRule ?? wildcardRule;
8031
+ if (!matchedRule) {
8032
+ return {
8033
+ field,
8034
+ action: policy.default_action === "deny" ? "deny" : "redact",
8035
+ reason: `No rule matches provider "${provider}"; applying default (${policy.default_action})`
8036
+ };
8037
+ }
8038
+ if (matchesPattern(field, matchedRule.redact)) {
8039
+ return {
8040
+ field,
8041
+ action: "redact",
8042
+ reason: `Field "${field}" is explicitly redacted for ${matchedRule.provider} provider`
8043
+ };
8044
+ }
8045
+ if (matchesPattern(field, matchedRule.hash)) {
8046
+ return {
8047
+ field,
8048
+ action: "hash",
8049
+ reason: `Field "${field}" is hashed for ${matchedRule.provider} provider`
8050
+ };
8051
+ }
8052
+ if (matchesPattern(field, matchedRule.summarize)) {
8053
+ return {
8054
+ field,
8055
+ action: "summarize",
8056
+ reason: `Field "${field}" should be summarized for ${matchedRule.provider} provider`
8057
+ };
8058
+ }
8059
+ if (matchesPattern(field, matchedRule.allow)) {
8060
+ return {
8061
+ field,
8062
+ action: "allow",
8063
+ reason: `Field "${field}" is allowed for ${matchedRule.provider} provider`
8064
+ };
8065
+ }
8066
+ return {
8067
+ field,
8068
+ action: policy.default_action === "deny" ? "deny" : "redact",
8069
+ reason: `Field "${field}" not addressed in ${matchedRule.provider} rule; applying default (${policy.default_action})`
8070
+ };
8071
+ }
8072
+ function filterContext(policy, provider, context) {
8073
+ const fields = Object.keys(context);
8074
+ if (fields.length > MAX_CONTEXT_FIELDS) {
8075
+ throw new Error(
8076
+ `Context object has ${fields.length} fields, exceeding limit of ${MAX_CONTEXT_FIELDS}`
8077
+ );
8078
+ }
8079
+ const decisions = [];
8080
+ let allowed = 0;
8081
+ let redacted = 0;
8082
+ let hashed = 0;
8083
+ let summarized = 0;
8084
+ let denied = 0;
8085
+ for (const field of fields) {
8086
+ const result = evaluateField(policy, provider, field);
8087
+ if (result.action === "hash") {
8088
+ const value = typeof context[field] === "string" ? context[field] : JSON.stringify(context[field]);
8089
+ result.hash_value = hashToString(stringToBytes(value));
8090
+ }
8091
+ decisions.push(result);
8092
+ switch (result.action) {
8093
+ case "allow":
8094
+ allowed++;
8095
+ break;
8096
+ case "redact":
8097
+ redacted++;
8098
+ break;
8099
+ case "hash":
8100
+ hashed++;
8101
+ break;
8102
+ case "summarize":
8103
+ summarized++;
8104
+ break;
8105
+ case "deny":
8106
+ denied++;
8107
+ break;
8108
+ }
8109
+ }
8110
+ const originalHash = hashToString(
8111
+ stringToBytes(JSON.stringify(context))
8112
+ );
8113
+ const filteredOutput = {};
8114
+ for (const decision of decisions) {
8115
+ switch (decision.action) {
8116
+ case "allow":
8117
+ filteredOutput[decision.field] = context[decision.field];
8118
+ break;
8119
+ case "redact":
8120
+ filteredOutput[decision.field] = "[REDACTED]";
8121
+ break;
8122
+ case "hash":
8123
+ filteredOutput[decision.field] = `[HASH:${decision.hash_value}]`;
8124
+ break;
8125
+ case "summarize":
8126
+ filteredOutput[decision.field] = "[SUMMARIZE]";
8127
+ break;
8128
+ }
8129
+ }
8130
+ const filteredHash = hashToString(
8131
+ stringToBytes(JSON.stringify(filteredOutput))
8132
+ );
8133
+ return {
8134
+ policy_id: policy.policy_id,
8135
+ provider,
8136
+ fields_allowed: allowed,
8137
+ fields_redacted: redacted,
8138
+ fields_hashed: hashed,
8139
+ fields_summarized: summarized,
8140
+ fields_denied: denied,
8141
+ decisions,
8142
+ original_context_hash: originalHash,
8143
+ filtered_context_hash: filteredHash,
8144
+ filtered_at: (/* @__PURE__ */ new Date()).toISOString()
8145
+ };
8146
+ }
8147
+ function matchesPattern(field, patterns) {
8148
+ const normalizedField = field.toLowerCase();
8149
+ for (const pattern of patterns) {
8150
+ if (pattern === "*") return true;
8151
+ const normalizedPattern = pattern.toLowerCase();
8152
+ if (normalizedPattern === normalizedField) return true;
8153
+ if (normalizedPattern.endsWith("*") && normalizedField.startsWith(normalizedPattern.slice(0, -1))) return true;
8154
+ if (normalizedPattern.startsWith("*") && normalizedField.endsWith(normalizedPattern.slice(1))) return true;
8155
+ }
8156
+ return false;
8157
+ }
8158
+ var ContextGatePolicyStore = class {
8159
+ storage;
8160
+ encryptionKey;
8161
+ policies = /* @__PURE__ */ new Map();
8162
+ constructor(storage, masterKey) {
8163
+ this.storage = storage;
8164
+ this.encryptionKey = derivePurposeKey(masterKey, "l2-context-gate");
8165
+ }
8166
+ /**
8167
+ * Create and store a new context-gating policy.
8168
+ */
8169
+ async create(policyName, rules, defaultAction, identityId) {
8170
+ const policyId = `cg-${Date.now()}-${toBase64url(randomBytes(8))}`;
8171
+ const now = (/* @__PURE__ */ new Date()).toISOString();
8172
+ const policy = {
8173
+ policy_id: policyId,
8174
+ policy_name: policyName,
8175
+ rules,
8176
+ default_action: defaultAction,
8177
+ identity_id: identityId,
8178
+ created_at: now,
8179
+ updated_at: now
8180
+ };
8181
+ await this.persist(policy);
8182
+ this.policies.set(policyId, policy);
8183
+ return policy;
8184
+ }
8185
+ /**
8186
+ * Get a policy by ID.
8187
+ */
8188
+ async get(policyId) {
8189
+ if (this.policies.has(policyId)) {
8190
+ return this.policies.get(policyId);
8191
+ }
8192
+ const raw = await this.storage.read("_context_gate_policies", policyId);
8193
+ if (!raw) return null;
8194
+ try {
8195
+ const encrypted = JSON.parse(bytesToString(raw));
8196
+ const decrypted = decrypt(encrypted, this.encryptionKey);
8197
+ const policy = JSON.parse(bytesToString(decrypted));
8198
+ this.policies.set(policyId, policy);
8199
+ return policy;
8200
+ } catch {
8201
+ return null;
8202
+ }
8203
+ }
8204
+ /**
8205
+ * List all context-gating policies.
8206
+ */
8207
+ async list() {
8208
+ await this.loadAll();
8209
+ return Array.from(this.policies.values());
8210
+ }
8211
+ /**
8212
+ * Load all persisted policies into memory.
8213
+ */
8214
+ async loadAll() {
8215
+ try {
8216
+ const entries = await this.storage.list("_context_gate_policies");
8217
+ for (const meta of entries) {
8218
+ if (this.policies.has(meta.key)) continue;
8219
+ const raw = await this.storage.read("_context_gate_policies", meta.key);
8220
+ if (!raw) continue;
8221
+ try {
8222
+ const encrypted = JSON.parse(bytesToString(raw));
8223
+ const decrypted = decrypt(encrypted, this.encryptionKey);
8224
+ const policy = JSON.parse(bytesToString(decrypted));
8225
+ this.policies.set(policy.policy_id, policy);
8226
+ } catch {
8227
+ }
8228
+ }
8229
+ } catch {
8230
+ }
8231
+ }
8232
+ async persist(policy) {
8233
+ const serialized = stringToBytes(JSON.stringify(policy));
8234
+ const encrypted = encrypt(serialized, this.encryptionKey);
8235
+ await this.storage.write(
8236
+ "_context_gate_policies",
8237
+ policy.policy_id,
8238
+ stringToBytes(JSON.stringify(encrypted))
8239
+ );
8240
+ }
8241
+ };
8242
+
8243
+ // src/l2-operational/context-gate-templates.ts
8244
+ var ALWAYS_REDACT_SECRETS = [
8245
+ "api_key",
8246
+ "secret_*",
8247
+ "*_secret",
8248
+ "*_token",
8249
+ "*_key",
8250
+ "password",
8251
+ "*_password",
8252
+ "credential",
8253
+ "*_credential",
8254
+ "private_key",
8255
+ "recovery_key",
8256
+ "passphrase",
8257
+ "auth_*"
8258
+ ];
8259
+ var PII_PATTERNS = [
8260
+ "*_pii",
8261
+ "name",
8262
+ "full_name",
8263
+ "email",
8264
+ "email_address",
8265
+ "phone",
8266
+ "phone_number",
8267
+ "address",
8268
+ "ssn",
8269
+ "date_of_birth",
8270
+ "ip_address",
8271
+ "credit_card",
8272
+ "card_number",
8273
+ "cvv",
8274
+ "bank_account",
8275
+ "account_number",
8276
+ "routing_number"
8277
+ ];
8278
+ var INTERNAL_STATE_PATTERNS = [
8279
+ "memory",
8280
+ "agent_memory",
8281
+ "internal_reasoning",
8282
+ "internal_state",
8283
+ "reasoning_trace",
8284
+ "chain_of_thought",
8285
+ "private_notes",
8286
+ "soul",
8287
+ "personality",
8288
+ "system_prompt"
8289
+ ];
8290
+ var ID_PATTERNS = [
8291
+ "user_id",
8292
+ "session_id",
8293
+ "agent_id",
8294
+ "identity_id",
8295
+ "conversation_id",
8296
+ "thread_id"
8297
+ ];
8298
+ var HISTORY_PATTERNS = [
8299
+ "conversation_history",
8300
+ "message_history",
8301
+ "chat_history",
8302
+ "context_window",
8303
+ "previous_messages"
8304
+ ];
8305
+ var INFERENCE_MINIMAL = {
8306
+ id: "inference-minimal",
8307
+ name: "Inference Minimal",
8308
+ description: "Maximum privacy. Only the current task and query reach the LLM provider.",
8309
+ use_when: "You want the strictest possible context control for inference calls. The LLM sees only what it needs for the immediate task.",
8310
+ rules: [
8311
+ {
8312
+ provider: "inference",
8313
+ allow: [
8314
+ "task",
8315
+ "task_description",
8316
+ "current_query",
8317
+ "query",
8318
+ "prompt",
8319
+ "question",
8320
+ "instruction"
8321
+ ],
8322
+ redact: [
8323
+ ...ALWAYS_REDACT_SECRETS,
8324
+ ...PII_PATTERNS,
8325
+ ...INTERNAL_STATE_PATTERNS,
8326
+ ...HISTORY_PATTERNS,
8327
+ "tool_results",
8328
+ "previous_results"
8329
+ ],
8330
+ hash: [...ID_PATTERNS],
8331
+ summarize: []
8332
+ }
8333
+ ],
8334
+ default_action: "redact"
8335
+ };
8336
+ var INFERENCE_STANDARD = {
8337
+ id: "inference-standard",
8338
+ name: "Inference Standard",
8339
+ description: "Balanced privacy. Task, query, and tool results pass through. History flagged for summarization. Secrets and PII redacted.",
8340
+ use_when: "You need the LLM to have enough context for multi-step tasks while keeping secrets, PII, and internal reasoning private.",
8341
+ rules: [
8342
+ {
8343
+ provider: "inference",
8344
+ allow: [
8345
+ "task",
8346
+ "task_description",
8347
+ "current_query",
8348
+ "query",
8349
+ "prompt",
8350
+ "question",
8351
+ "instruction",
8352
+ "tool_results",
8353
+ "tool_output",
8354
+ "previous_results",
8355
+ "current_step",
8356
+ "remaining_steps",
8357
+ "objective",
8358
+ "constraints",
8359
+ "format",
8360
+ "output_format"
8361
+ ],
8362
+ redact: [
8363
+ ...ALWAYS_REDACT_SECRETS,
8364
+ ...PII_PATTERNS,
8365
+ ...INTERNAL_STATE_PATTERNS
8366
+ ],
8367
+ hash: [...ID_PATTERNS],
8368
+ summarize: [...HISTORY_PATTERNS]
8369
+ }
8370
+ ],
8371
+ default_action: "redact"
8372
+ };
8373
+ var LOGGING_STRICT = {
8374
+ id: "logging-strict",
8375
+ name: "Logging Strict",
8376
+ description: "Redacts all content for logging and analytics providers. Only operation metadata passes through.",
8377
+ use_when: "You send telemetry to logging or analytics services and want usage metrics without any content exposure.",
8378
+ rules: [
8379
+ {
8380
+ provider: "logging",
8381
+ allow: [
8382
+ "operation",
8383
+ "operation_name",
8384
+ "tool_name",
8385
+ "timestamp",
8386
+ "duration_ms",
8387
+ "status",
8388
+ "error_code",
8389
+ "event_type"
8390
+ ],
8391
+ redact: [
8392
+ ...ALWAYS_REDACT_SECRETS,
8393
+ ...PII_PATTERNS,
8394
+ ...INTERNAL_STATE_PATTERNS,
8395
+ ...HISTORY_PATTERNS
8396
+ ],
8397
+ hash: [...ID_PATTERNS],
8398
+ summarize: []
8399
+ },
8400
+ {
8401
+ provider: "analytics",
8402
+ allow: [
8403
+ "event_type",
8404
+ "timestamp",
8405
+ "duration_ms",
8406
+ "status",
8407
+ "tool_name"
8408
+ ],
8409
+ redact: [
8410
+ ...ALWAYS_REDACT_SECRETS,
8411
+ ...PII_PATTERNS,
8412
+ ...INTERNAL_STATE_PATTERNS,
8413
+ ...HISTORY_PATTERNS
8414
+ ],
8415
+ hash: [...ID_PATTERNS],
8416
+ summarize: []
8417
+ }
8418
+ ],
8419
+ default_action: "redact"
8420
+ };
8421
+ var TOOL_API_SCOPED = {
8422
+ id: "tool-api-scoped",
8423
+ name: "Tool API Scoped",
8424
+ description: "Allows tool-specific parameters for external API calls. Redacts memory, history, secrets, and PII.",
8425
+ use_when: "Your agent calls external APIs (search, database, web) and you want to send query parameters without full agent context. Note: 'headers' and 'body' are redacted by default because they frequently carry authorization tokens. Add them to 'allow' only if you verify they contain no credentials for your use case.",
8426
+ rules: [
8427
+ {
8428
+ provider: "tool-api",
8429
+ allow: [
8430
+ "task",
8431
+ "task_description",
8432
+ "query",
8433
+ "search_query",
8434
+ "tool_input",
8435
+ "tool_parameters",
8436
+ "url",
8437
+ "endpoint",
8438
+ "method",
8439
+ "filter",
8440
+ "sort",
8441
+ "limit",
8442
+ "offset"
8443
+ ],
8444
+ redact: [
8445
+ ...ALWAYS_REDACT_SECRETS,
8446
+ ...PII_PATTERNS,
8447
+ ...INTERNAL_STATE_PATTERNS,
8448
+ ...HISTORY_PATTERNS
8449
+ ],
8450
+ hash: [...ID_PATTERNS],
8451
+ summarize: []
8452
+ }
8453
+ ],
8454
+ default_action: "redact"
8455
+ };
8456
+ var TEMPLATES = {
8457
+ "inference-minimal": INFERENCE_MINIMAL,
8458
+ "inference-standard": INFERENCE_STANDARD,
8459
+ "logging-strict": LOGGING_STRICT,
8460
+ "tool-api-scoped": TOOL_API_SCOPED
8461
+ };
8462
+ function listTemplateIds() {
8463
+ return Object.keys(TEMPLATES);
8464
+ }
8465
+ function getTemplate(id) {
8466
+ return TEMPLATES[id];
8467
+ }
8468
+
8469
+ // src/l2-operational/context-gate-recommend.ts
8470
+ var CLASSIFICATION_RULES = [
8471
+ // ── Secrets (always redact, high confidence) ─────────────────────
8472
+ {
8473
+ patterns: [
8474
+ "api_key",
8475
+ "apikey",
8476
+ "api_secret",
8477
+ "secret",
8478
+ "secret_key",
8479
+ "secret_token",
8480
+ "password",
8481
+ "passwd",
8482
+ "pass",
8483
+ "credential",
8484
+ "credentials",
8485
+ "private_key",
8486
+ "privkey",
8487
+ "recovery_key",
8488
+ "passphrase",
8489
+ "token",
8490
+ "access_token",
8491
+ "refresh_token",
8492
+ "bearer_token",
8493
+ "auth_token",
8494
+ "auth_header",
8495
+ "authorization",
8496
+ "encryption_key",
8497
+ "master_key",
8498
+ "signing_key",
8499
+ "webhook_secret",
8500
+ "client_secret",
8501
+ "connection_string"
8502
+ ],
8503
+ action: "redact",
8504
+ confidence: "high",
8505
+ reason: "Matches known secret/credential pattern"
8506
+ },
8507
+ // ── PII (always redact, high confidence) ─────────────────────────
8508
+ {
8509
+ patterns: [
8510
+ "name",
8511
+ "full_name",
8512
+ "first_name",
8513
+ "last_name",
8514
+ "display_name",
8515
+ "email",
8516
+ "email_address",
8517
+ "phone",
8518
+ "phone_number",
8519
+ "mobile",
8520
+ "address",
8521
+ "street_address",
8522
+ "mailing_address",
8523
+ "ssn",
8524
+ "social_security",
8525
+ "date_of_birth",
8526
+ "dob",
8527
+ "birthday",
8528
+ "ip_address",
8529
+ "ip",
8530
+ "location",
8531
+ "geolocation",
8532
+ "coordinates",
8533
+ "credit_card",
8534
+ "card_number",
8535
+ "cvv",
8536
+ "bank_account",
8537
+ "routing_number",
8538
+ "passport",
8539
+ "drivers_license",
8540
+ "license_number"
8541
+ ],
8542
+ action: "redact",
8543
+ confidence: "high",
8544
+ reason: "Matches known PII pattern"
8545
+ },
8546
+ // ── Internal agent state (redact, high confidence) ───────────────
8547
+ {
8548
+ patterns: [
8549
+ "memory",
8550
+ "agent_memory",
8551
+ "long_term_memory",
8552
+ "internal_reasoning",
8553
+ "reasoning_trace",
8554
+ "chain_of_thought",
8555
+ "internal_state",
8556
+ "agent_state",
8557
+ "private_notes",
8558
+ "scratchpad",
8559
+ "soul",
8560
+ "personality",
8561
+ "persona",
8562
+ "system_prompt",
8563
+ "system_message",
8564
+ "system_instruction",
8565
+ "preferences",
8566
+ "user_preferences",
8567
+ "agent_preferences",
8568
+ "beliefs",
8569
+ "goals",
8570
+ "motivations"
8571
+ ],
8572
+ action: "redact",
8573
+ confidence: "high",
8574
+ reason: "Matches known internal agent state pattern"
8575
+ },
8576
+ // ── IDs (hash, medium confidence) ────────────────────────────────
8577
+ {
8578
+ patterns: [
8579
+ "user_id",
8580
+ "userid",
8581
+ "session_id",
8582
+ "sessionid",
8583
+ "agent_id",
8584
+ "agentid",
8585
+ "identity_id",
8586
+ "conversation_id",
8587
+ "thread_id",
8588
+ "threadid",
8589
+ "request_id",
8590
+ "requestid",
8591
+ "correlation_id",
8592
+ "trace_id",
8593
+ "traceid",
8594
+ "account_id",
8595
+ "accountid"
8596
+ ],
8597
+ action: "hash",
8598
+ confidence: "medium",
8599
+ reason: "Matches known identifier pattern \u2014 hash preserves correlation without exposing value"
8600
+ },
8601
+ // ── History (summarize, medium confidence) ───────────────────────
8602
+ {
8603
+ patterns: [
8604
+ "conversation_history",
8605
+ "chat_history",
8606
+ "message_history",
8607
+ "messages",
8608
+ "previous_messages",
8609
+ "prior_messages",
8610
+ "context_window",
8611
+ "interaction_history",
8612
+ "audit_log",
8613
+ "event_log"
8614
+ ],
8615
+ action: "summarize",
8616
+ confidence: "medium",
8617
+ reason: "Matches known history/log pattern \u2014 summarize to reduce exposure"
8618
+ },
8619
+ // ── Task/query (allow, medium confidence) ────────────────────────
8620
+ {
8621
+ patterns: [
8622
+ "task",
8623
+ "task_description",
8624
+ "query",
8625
+ "current_query",
8626
+ "search_query",
8627
+ "prompt",
8628
+ "user_prompt",
8629
+ "question",
8630
+ "current_question",
8631
+ "instruction",
8632
+ "instructions",
8633
+ "objective",
8634
+ "goal",
8635
+ "current_step",
8636
+ "next_step",
8637
+ "remaining_steps",
8638
+ "constraints",
8639
+ "requirements",
8640
+ "output_format",
8641
+ "format",
8642
+ "tool_results",
8643
+ "tool_output",
8644
+ "tool_input",
8645
+ "tool_parameters"
8646
+ ],
8647
+ action: "allow",
8648
+ confidence: "medium",
8649
+ reason: "Matches known task/query pattern \u2014 likely needed for inference"
8650
+ }
8651
+ ];
8652
+ function classifyField(fieldName) {
8653
+ const normalized = fieldName.toLowerCase().trim();
8654
+ for (const rule of CLASSIFICATION_RULES) {
8655
+ for (const pattern of rule.patterns) {
8656
+ if (matchesFieldPattern(normalized, pattern)) {
8657
+ return {
8658
+ field: fieldName,
8659
+ recommended_action: rule.action,
8660
+ reason: rule.reason,
8661
+ confidence: rule.confidence,
8662
+ matched_pattern: pattern
8663
+ };
8664
+ }
8665
+ }
8666
+ }
8667
+ return {
8668
+ field: fieldName,
8669
+ recommended_action: "redact",
8670
+ reason: "No known pattern matched \u2014 defaulting to redact (conservative)",
8671
+ confidence: "low",
8672
+ matched_pattern: null
8673
+ };
8674
+ }
8675
+ function recommendPolicy(context, provider = "inference") {
8676
+ const fields = Object.keys(context);
8677
+ const classifications = fields.map(classifyField);
8678
+ const warnings = [];
8679
+ const allow = [];
8680
+ const redact = [];
8681
+ const hash2 = [];
8682
+ const summarize = [];
8683
+ for (const c of classifications) {
8684
+ switch (c.recommended_action) {
8685
+ case "allow":
8686
+ allow.push(c.field);
8687
+ break;
8688
+ case "redact":
8689
+ redact.push(c.field);
8690
+ break;
8691
+ case "hash":
8692
+ hash2.push(c.field);
8693
+ break;
8694
+ case "summarize":
8695
+ summarize.push(c.field);
8696
+ break;
8697
+ }
8698
+ }
8699
+ const lowConfidence = classifications.filter((c) => c.confidence === "low");
8700
+ if (lowConfidence.length > 0) {
8701
+ warnings.push(
8702
+ `${lowConfidence.length} field(s) could not be classified by pattern and will default to redact: ${lowConfidence.map((c) => c.field).join(", ")}. Review these manually.`
8703
+ );
8704
+ }
8705
+ for (const [key, value] of Object.entries(context)) {
8706
+ if (typeof value === "string" && value.length > 5e3) {
8707
+ const existing = classifications.find((c) => c.field === key);
8708
+ if (existing && existing.recommended_action === "allow") {
8709
+ warnings.push(
8710
+ `Field "${key}" is allowed but contains ${value.length} characters. Consider summarizing it to reduce context size and exposure.`
8711
+ );
8712
+ }
8713
+ }
8714
+ }
8715
+ return {
8716
+ provider,
8717
+ classifications,
8718
+ recommended_rules: { allow, redact, hash: hash2, summarize },
8719
+ default_action: "redact",
8720
+ summary: {
8721
+ total_fields: fields.length,
8722
+ allow: allow.length,
8723
+ redact: redact.length,
8724
+ hash: hash2.length,
8725
+ summarize: summarize.length
8726
+ },
8727
+ warnings
8728
+ };
8729
+ }
8730
+ function matchesFieldPattern(normalizedField, pattern) {
8731
+ if (normalizedField === pattern) return true;
8732
+ if (pattern.length >= 3 && normalizedField.includes(pattern)) {
8733
+ const idx = normalizedField.indexOf(pattern);
8734
+ const before = idx === 0 || normalizedField[idx - 1] === "_" || normalizedField[idx - 1] === "-";
8735
+ const after = idx + pattern.length === normalizedField.length || normalizedField[idx + pattern.length] === "_" || normalizedField[idx + pattern.length] === "-";
8736
+ return before && after;
8737
+ }
8738
+ return false;
8739
+ }
8740
+
8741
+ // src/l2-operational/context-gate-tools.ts
8742
+ function createContextGateTools(storage, masterKey, auditLog) {
8743
+ const policyStore = new ContextGatePolicyStore(storage, masterKey);
8744
+ const tools = [
8745
+ // ── Set Policy ──────────────────────────────────────────────────
8746
+ {
8747
+ name: "sanctuary/context_gate_set_policy",
8748
+ description: "Create a context-gating policy that controls what information flows to remote providers (LLM APIs, tool APIs, logging services). Each rule specifies a provider category and which context fields to allow, redact, hash, or flag for summarization. Redact rules take absolute priority \u2014 if a field is in both 'allow' and 'redact', it is redacted. Default action applies to any field not mentioned in any rule. Use this to prevent your full agent context from being sent to remote LLM providers during inference calls.",
8749
+ inputSchema: {
8750
+ type: "object",
8751
+ properties: {
8752
+ policy_name: {
8753
+ type: "string",
8754
+ description: "Human-readable name for this policy (e.g., 'inference-minimal', 'tool-api-strict')"
8755
+ },
8756
+ rules: {
8757
+ type: "array",
8758
+ description: "Array of rules. Each rule has: provider (inference|tool-api|logging|analytics|peer-agent|custom|*), allow (fields to pass through), redact (fields to remove \u2014 highest priority), hash (fields to replace with SHA-256 hash), summarize (fields to flag for compression).",
8759
+ items: {
8760
+ type: "object",
8761
+ properties: {
8762
+ provider: {
8763
+ type: "string",
8764
+ description: "Provider category: inference, tool-api, logging, analytics, peer-agent, custom, or * for all"
8765
+ },
8766
+ allow: {
8767
+ type: "array",
8768
+ items: { type: "string" },
8769
+ description: "Fields/patterns to allow through (e.g., 'task_description', 'current_query', 'tool_*')"
8770
+ },
8771
+ redact: {
8772
+ type: "array",
8773
+ items: { type: "string" },
8774
+ description: "Fields/patterns to redact (e.g., 'conversation_history', 'secret_*', '*_pii'). Takes absolute priority."
8775
+ },
8776
+ hash: {
8777
+ type: "array",
8778
+ items: { type: "string" },
8779
+ description: "Fields/patterns to replace with SHA-256 hash (e.g., 'user_id', 'session_id')"
8780
+ },
8781
+ summarize: {
8782
+ type: "array",
8783
+ items: { type: "string" },
8784
+ description: "Fields/patterns to flag for summarization (advisory \u2014 agent should compress these before sending)"
8785
+ }
8786
+ },
8787
+ required: ["provider", "allow", "redact"]
8788
+ }
8789
+ },
8790
+ default_action: {
8791
+ type: "string",
8792
+ enum: ["redact", "deny"],
8793
+ description: "Action for fields not matched by any rule. 'redact' removes the field value; 'deny' blocks the entire request. Default: 'redact'."
8794
+ },
8795
+ identity_id: {
8796
+ type: "string",
8797
+ description: "Bind this policy to a specific identity (optional)"
8798
+ }
8799
+ },
8800
+ required: ["policy_name", "rules"]
8801
+ },
8802
+ handler: async (args) => {
8803
+ const policyName = args.policy_name;
8804
+ const rawRules = args.rules;
8805
+ const defaultAction = args.default_action ?? "redact";
8806
+ const identityId = args.identity_id;
8807
+ if (!Array.isArray(rawRules)) {
8808
+ return toolResult({ error: "invalid_rules", message: "rules must be an array" });
8809
+ }
8810
+ if (rawRules.length > MAX_POLICY_RULES) {
8811
+ return toolResult({
8812
+ error: "too_many_rules",
8813
+ message: `Policy has ${rawRules.length} rules, exceeding limit of ${MAX_POLICY_RULES}`
8814
+ });
8815
+ }
8816
+ const rules = [];
8817
+ for (const r of rawRules) {
8818
+ const allow = Array.isArray(r.allow) ? r.allow : [];
8819
+ const redact = Array.isArray(r.redact) ? r.redact : [];
8820
+ const hash2 = Array.isArray(r.hash) ? r.hash : [];
8821
+ const summarize = Array.isArray(r.summarize) ? r.summarize : [];
8822
+ for (const [name, arr] of [["allow", allow], ["redact", redact], ["hash", hash2], ["summarize", summarize]]) {
8823
+ if (arr.length > MAX_PATTERNS_PER_ARRAY) {
8824
+ return toolResult({
8825
+ error: "too_many_patterns",
8826
+ message: `Rule ${name} array has ${arr.length} patterns, exceeding limit of ${MAX_PATTERNS_PER_ARRAY}`
8827
+ });
8828
+ }
8829
+ }
8830
+ rules.push({
8831
+ provider: r.provider ?? "*",
8832
+ allow,
8833
+ redact,
8834
+ hash: hash2,
8835
+ summarize
8836
+ });
8837
+ }
8838
+ const policy = await policyStore.create(
8839
+ policyName,
8840
+ rules,
8841
+ defaultAction,
8842
+ identityId
8843
+ );
8844
+ auditLog.append("l2", "context_gate_set_policy", identityId ?? "system", {
8845
+ policy_id: policy.policy_id,
8846
+ policy_name: policyName,
8847
+ rule_count: rules.length,
8848
+ default_action: defaultAction
8849
+ });
8850
+ return toolResult({
8851
+ policy_id: policy.policy_id,
8852
+ policy_name: policy.policy_name,
8853
+ rules: policy.rules,
8854
+ default_action: policy.default_action,
8855
+ created_at: policy.created_at,
8856
+ message: "Context-gating policy created. Use sanctuary/context_gate_filter to apply this policy before making outbound calls."
8857
+ });
8858
+ }
8859
+ },
8860
+ // ── Apply Template ───────────────────────────────────────────────
8861
+ {
8862
+ name: "sanctuary/context_gate_apply_template",
8863
+ description: "Apply a starter context-gating template. Available templates: inference-minimal (strictest \u2014 only task and query pass through), inference-standard (balanced \u2014 adds tool results, summarizes history), logging-strict (redacts all content for telemetry services), tool-api-scoped (allows tool parameters, redacts agent state). Templates are starting points \u2014 customize after applying.",
8864
+ inputSchema: {
8865
+ type: "object",
8866
+ properties: {
8867
+ template_id: {
8868
+ type: "string",
8869
+ description: "Template to apply: inference-minimal, inference-standard, logging-strict, or tool-api-scoped"
8870
+ },
8871
+ identity_id: {
8872
+ type: "string",
8873
+ description: "Bind this policy to a specific identity (optional)"
8874
+ }
8875
+ },
8876
+ required: ["template_id"]
8877
+ },
8878
+ handler: async (args) => {
8879
+ const templateId = args.template_id;
8880
+ const identityId = args.identity_id;
8881
+ const template = getTemplate(templateId);
8882
+ if (!template) {
8883
+ return toolResult({
8884
+ error: "template_not_found",
8885
+ message: `Unknown template "${templateId}"`,
8886
+ available_templates: listTemplateIds().map((id) => {
8887
+ const t = TEMPLATES[id];
8888
+ return { id, name: t.name, description: t.description };
8889
+ })
8890
+ });
8891
+ }
8892
+ const policy = await policyStore.create(
8893
+ template.name,
8894
+ template.rules,
8895
+ template.default_action,
8896
+ identityId
8897
+ );
8898
+ auditLog.append("l2", "context_gate_apply_template", identityId ?? "system", {
8899
+ policy_id: policy.policy_id,
8900
+ template_id: templateId
8901
+ });
8902
+ return toolResult({
8903
+ policy_id: policy.policy_id,
8904
+ template_applied: templateId,
8905
+ policy_name: template.name,
8906
+ description: template.description,
8907
+ use_when: template.use_when,
8908
+ rules: policy.rules,
8909
+ default_action: policy.default_action,
8910
+ created_at: policy.created_at,
8911
+ message: "Template applied. Use sanctuary/context_gate_filter with this policy_id to filter context before outbound calls. Customize rules with sanctuary/context_gate_set_policy if needed."
8912
+ });
8913
+ }
8914
+ },
8915
+ // ── Recommend Policy ────────────────────────────────────────────
8916
+ {
8917
+ name: "sanctuary/context_gate_recommend",
8918
+ description: "Analyze a sample context object and recommend a context-gating policy based on field name heuristics. Classifies each field as allow, redact, hash, or summarize with confidence levels. Returns a ready-to-apply rule set. When in doubt, recommends redact (conservative). Review the recommendations before applying.",
8919
+ inputSchema: {
8920
+ type: "object",
8921
+ properties: {
8922
+ context: {
8923
+ type: "object",
8924
+ description: "A sample context object to analyze. Each top-level key will be classified. Values are inspected for size warnings but not stored."
8925
+ },
8926
+ provider: {
8927
+ type: "string",
8928
+ description: "Provider category to generate rules for. Default: 'inference'."
8929
+ }
8930
+ },
8931
+ required: ["context"]
8932
+ },
8933
+ handler: async (args) => {
8934
+ const context = args.context;
8935
+ const provider = args.provider ?? "inference";
8936
+ const contextKeys = Object.keys(context);
8937
+ if (contextKeys.length > MAX_CONTEXT_FIELDS) {
8938
+ return toolResult({
8939
+ error: "context_too_large",
8940
+ message: `Context has ${contextKeys.length} fields, exceeding limit of ${MAX_CONTEXT_FIELDS}`
8941
+ });
8942
+ }
8943
+ const recommendation = recommendPolicy(context, provider);
8944
+ auditLog.append("l2", "context_gate_recommend", "system", {
8945
+ provider,
8946
+ fields_analyzed: recommendation.summary.total_fields,
8947
+ fields_allow: recommendation.summary.allow,
8948
+ fields_redact: recommendation.summary.redact,
8949
+ fields_hash: recommendation.summary.hash,
8950
+ fields_summarize: recommendation.summary.summarize
8951
+ });
8952
+ return toolResult({
8953
+ ...recommendation,
8954
+ next_steps: "Review the classifications above. If they look correct, you can apply them directly with sanctuary/context_gate_set_policy using the recommended_rules. Or start with a template via sanctuary/context_gate_apply_template and customize from there.",
8955
+ available_templates: listTemplateIds().map((id) => {
8956
+ const t = TEMPLATES[id];
8957
+ return { id, name: t.name, description: t.description };
8958
+ })
8959
+ });
8960
+ }
8961
+ },
8962
+ // ── Filter Context ──────────────────────────────────────────────
8963
+ {
8964
+ name: "sanctuary/context_gate_filter",
8965
+ description: "Filter agent context through a gating policy before sending to a remote provider. Returns per-field decisions (allow, redact, hash, summarize) and content hashes for the audit trail. Call this BEFORE making any outbound API call to ensure you are only sending the minimum necessary context. The filtered output tells you exactly what can be sent safely.",
8966
+ inputSchema: {
8967
+ type: "object",
8968
+ properties: {
8969
+ policy_id: {
8970
+ type: "string",
8971
+ description: "ID of the context-gating policy to apply"
8972
+ },
8973
+ provider: {
8974
+ type: "string",
8975
+ description: "Provider category for this call: inference, tool-api, logging, analytics, peer-agent, or custom"
8976
+ },
8977
+ context: {
8978
+ type: "object",
8979
+ description: "The context object to filter. Each top-level key is evaluated against the policy. Example keys: task_description, conversation_history, user_preferences, api_keys, memory, internal_reasoning"
8980
+ }
8981
+ },
8982
+ required: ["policy_id", "provider", "context"]
8983
+ },
8984
+ handler: async (args) => {
8985
+ const policyId = args.policy_id;
8986
+ const provider = args.provider;
8987
+ const context = args.context;
8988
+ const contextKeys = Object.keys(context);
8989
+ if (contextKeys.length > MAX_CONTEXT_FIELDS) {
8990
+ return toolResult({
8991
+ error: "context_too_large",
8992
+ message: `Context has ${contextKeys.length} fields, exceeding limit of ${MAX_CONTEXT_FIELDS}`
8993
+ });
8994
+ }
8995
+ const policy = await policyStore.get(policyId);
8996
+ if (!policy) {
8997
+ return toolResult({
8998
+ error: "policy_not_found",
8999
+ message: `No context-gating policy found with ID "${policyId}"`
9000
+ });
9001
+ }
9002
+ const result = filterContext(policy, provider, context);
9003
+ const deniedFields = result.decisions.filter((d) => d.action === "deny");
9004
+ if (deniedFields.length > 0) {
9005
+ auditLog.append("l2", "context_gate_deny", policy.identity_id ?? "system", {
9006
+ policy_id: policyId,
9007
+ provider,
9008
+ denied_fields: deniedFields.map((d) => d.field),
9009
+ original_context_hash: result.original_context_hash
9010
+ });
9011
+ return toolResult({
9012
+ blocked: true,
9013
+ reason: "Context contains fields that trigger deny action",
9014
+ denied_fields: deniedFields.map((d) => ({
9015
+ field: d.field,
9016
+ reason: d.reason
9017
+ })),
9018
+ recommendation: "Remove the denied fields from context before retrying, or update the policy to handle these fields differently."
9019
+ });
9020
+ }
9021
+ const safeContext = {};
9022
+ for (const decision of result.decisions) {
9023
+ switch (decision.action) {
9024
+ case "allow":
9025
+ safeContext[decision.field] = context[decision.field];
9026
+ break;
9027
+ case "redact":
9028
+ break;
9029
+ case "hash":
9030
+ safeContext[decision.field] = decision.hash_value;
9031
+ break;
9032
+ case "summarize":
9033
+ safeContext[decision.field] = context[decision.field];
9034
+ break;
9035
+ }
9036
+ }
9037
+ auditLog.append("l2", "context_gate_filter", policy.identity_id ?? "system", {
9038
+ policy_id: policyId,
9039
+ provider,
9040
+ fields_total: Object.keys(context).length,
9041
+ fields_allowed: result.fields_allowed,
9042
+ fields_redacted: result.fields_redacted,
9043
+ fields_hashed: result.fields_hashed,
9044
+ fields_summarized: result.fields_summarized,
9045
+ original_context_hash: result.original_context_hash,
9046
+ filtered_context_hash: result.filtered_context_hash
9047
+ });
9048
+ return toolResult({
9049
+ blocked: false,
9050
+ safe_context: safeContext,
9051
+ summary: {
9052
+ total_fields: Object.keys(context).length,
9053
+ allowed: result.fields_allowed,
9054
+ redacted: result.fields_redacted,
9055
+ hashed: result.fields_hashed,
9056
+ summarized: result.fields_summarized
9057
+ },
9058
+ decisions: result.decisions,
9059
+ audit: {
9060
+ original_context_hash: result.original_context_hash,
9061
+ filtered_context_hash: result.filtered_context_hash,
9062
+ filtered_at: result.filtered_at
9063
+ },
9064
+ guidance: result.fields_summarized > 0 ? "Some fields are marked for summarization. Consider compressing them before sending to reduce context size and information exposure." : void 0
9065
+ });
9066
+ }
9067
+ },
9068
+ // ── List Policies ───────────────────────────────────────────────
9069
+ {
9070
+ name: "sanctuary/context_gate_list_policies",
9071
+ description: "List all configured context-gating policies. Returns policy IDs, names, rule summaries, and default actions.",
9072
+ inputSchema: {
9073
+ type: "object",
9074
+ properties: {}
9075
+ },
9076
+ handler: async () => {
9077
+ const policies = await policyStore.list();
9078
+ auditLog.append("l2", "context_gate_list_policies", "system", {
9079
+ policy_count: policies.length
9080
+ });
9081
+ return toolResult({
9082
+ policies: policies.map((p) => ({
9083
+ policy_id: p.policy_id,
9084
+ policy_name: p.policy_name,
9085
+ rule_count: p.rules.length,
9086
+ providers: p.rules.map((r) => r.provider),
9087
+ default_action: p.default_action,
9088
+ identity_id: p.identity_id ?? null,
9089
+ created_at: p.created_at,
9090
+ updated_at: p.updated_at
9091
+ })),
9092
+ count: policies.length,
9093
+ message: policies.length === 0 ? "No context-gating policies configured. Use sanctuary/context_gate_set_policy to create one." : `${policies.length} context-gating ${policies.length === 1 ? "policy" : "policies"} configured.`
9094
+ });
9095
+ }
9096
+ }
9097
+ ];
9098
+ return { tools, policyStore };
9099
+ }
9100
+ function checkMemoryProtection() {
9101
+ const checks = {
9102
+ aslr_enabled: checkASLR(),
9103
+ stack_canaries: true,
9104
+ // Enabled by default in Node.js runtime
9105
+ secure_buffer_zeros: true,
9106
+ // We use crypto.randomBytes and explicit zeroing
9107
+ argon2id_kdf: true
9108
+ // Master key derivation uses Argon2id
9109
+ };
9110
+ const activeCount = Object.values(checks).filter((v) => v).length;
9111
+ const overall = activeCount >= 4 ? "full" : activeCount >= 3 ? "partial" : "minimal";
9112
+ return {
9113
+ ...checks,
9114
+ overall
9115
+ };
9116
+ }
9117
+ function checkASLR() {
9118
+ if (process.platform === "linux") {
9119
+ try {
9120
+ const result = execSync("cat /proc/sys/kernel/randomize_va_space", {
9121
+ encoding: "utf-8",
9122
+ stdio: ["pipe", "pipe", "ignore"]
9123
+ }).trim();
9124
+ return result === "2";
9125
+ } catch {
9126
+ return false;
9127
+ }
9128
+ }
9129
+ if (process.platform === "darwin") {
9130
+ return true;
9131
+ }
9132
+ return false;
9133
+ }
9134
+ function checkProcessIsolation() {
9135
+ const isContainer = detectContainer();
9136
+ const isVM = detectVM();
9137
+ const isSandboxed = detectSandbox();
9138
+ let isolationLevel = "none";
9139
+ if (isContainer) isolationLevel = "hardened";
9140
+ else if (isVM) isolationLevel = "hardened";
9141
+ else if (isSandboxed) isolationLevel = "basic";
9142
+ const details = {};
9143
+ if (isContainer && isContainer !== true) details.container_type = isContainer;
9144
+ if (isVM && isVM !== true) details.vm_type = isVM;
9145
+ if (isSandboxed && isSandboxed !== true) details.sandbox_type = isSandboxed;
9146
+ return {
9147
+ isolation_level: isolationLevel,
9148
+ is_container: isContainer !== false,
9149
+ is_vm: isVM !== false,
9150
+ is_sandboxed: isSandboxed !== false,
9151
+ is_tee: false,
9152
+ details
9153
+ };
9154
+ }
9155
+ function detectContainer() {
9156
+ try {
9157
+ if (process.env.DOCKER_HOST) return "docker";
9158
+ try {
9159
+ statSync("/.dockerenv");
9160
+ return "docker";
9161
+ } catch {
9162
+ }
9163
+ if (process.platform === "linux") {
9164
+ const cgroup = execSync("cat /proc/1/cgroup 2>/dev/null || echo ''", {
9165
+ encoding: "utf-8"
9166
+ });
9167
+ if (cgroup.includes("docker")) return "docker";
9168
+ if (cgroup.includes("lxc")) return "lxc";
9169
+ if (cgroup.includes("kubepods") || cgroup.includes("kubernetes")) return "kubernetes";
9170
+ }
9171
+ if (process.env.container === "podman") return "podman";
9172
+ if (process.env.CONTAINER_ID) return "oci";
9173
+ return false;
9174
+ } catch {
9175
+ return false;
9176
+ }
9177
+ }
9178
+ function detectVM() {
9179
+ if (process.platform === "linux") {
9180
+ try {
9181
+ const dmidecode = execSync("dmidecode -s system-product-name 2>/dev/null || echo ''", {
9182
+ encoding: "utf-8"
9183
+ }).toLowerCase();
9184
+ if (dmidecode.includes("vmware")) return "vmware";
9185
+ if (dmidecode.includes("virtualbox")) return "virtualbox";
9186
+ if (dmidecode.includes("kvm")) return "kvm";
9187
+ if (dmidecode.includes("xen")) return "xen";
9188
+ if (dmidecode.includes("hyper-v")) return "hyper-v";
9189
+ const cpuinfo = execSync("grep -i hypervisor /proc/cpuinfo || echo ''", {
9190
+ encoding: "utf-8"
9191
+ });
9192
+ if (cpuinfo.length > 0) return "detected";
9193
+ } catch {
9194
+ }
9195
+ }
9196
+ if (process.platform === "darwin") {
9197
+ try {
9198
+ const bootargs = execSync(
9199
+ "nvram boot-args 2>/dev/null | grep -i 'parallels\\|vmware\\|virtualbox' || echo ''",
9200
+ {
9201
+ encoding: "utf-8"
9202
+ }
9203
+ );
9204
+ if (bootargs.length > 0) return "detected";
9205
+ } catch {
9206
+ }
9207
+ }
9208
+ return false;
9209
+ }
9210
+ function detectSandbox() {
9211
+ if (process.platform === "darwin") {
9212
+ if (process.env.APP_SANDBOX_READ_ONLY_HOME === "1") return "app-sandbox";
9213
+ if (process.env.TMPDIR && process.env.TMPDIR.includes("AppSandbox")) return "app-sandbox";
9214
+ }
9215
+ if (process.platform === "openbsd") {
9216
+ try {
9217
+ const pledge = execSync("pledge -v 2>/dev/null || echo ''", {
9218
+ encoding: "utf-8"
9219
+ });
9220
+ if (pledge.length > 0) return "pledge";
9221
+ } catch {
9222
+ }
9223
+ }
9224
+ if (process.platform === "linux") {
9225
+ if (process.env.container === "lxc") return "lxc";
9226
+ try {
9227
+ const context = execSync("getenforce 2>/dev/null || echo ''", {
9228
+ encoding: "utf-8"
9229
+ }).trim();
9230
+ if (context === "Enforcing") return "selinux";
9231
+ } catch {
9232
+ }
9233
+ }
9234
+ return false;
9235
+ }
9236
+ function checkFilesystemPermissions(storagePath) {
9237
+ try {
9238
+ const stats = statSync(storagePath);
9239
+ const mode = stats.mode & parseInt("777", 8);
9240
+ const modeString = mode.toString(8).padStart(3, "0");
9241
+ const isSecure = mode === parseInt("700", 8);
9242
+ const groupReadable = (mode & parseInt("040", 8)) !== 0;
9243
+ const othersReadable = (mode & parseInt("007", 8)) !== 0;
9244
+ const currentUid = process.getuid?.() || -1;
9245
+ const ownerIsCurrentUser = stats.uid === currentUid;
9246
+ let overall = "secure";
9247
+ if (groupReadable || othersReadable) overall = "insecure";
9248
+ else if (!ownerIsCurrentUser) overall = "warning";
9249
+ return {
9250
+ sanctuary_storage_protected: isSecure,
9251
+ sanctuary_storage_mode: modeString,
9252
+ owner_is_current_user: ownerIsCurrentUser,
9253
+ group_readable: groupReadable,
9254
+ others_readable: othersReadable,
9255
+ overall
9256
+ };
9257
+ } catch {
9258
+ return {
9259
+ sanctuary_storage_protected: false,
9260
+ sanctuary_storage_mode: "unknown",
9261
+ owner_is_current_user: false,
9262
+ group_readable: false,
9263
+ others_readable: false,
9264
+ overall: "warning"
9265
+ };
9266
+ }
9267
+ }
9268
+ function checkRuntimeIntegrity() {
9269
+ return {
9270
+ config_hash_stable: true,
9271
+ environment_state: "clean",
9272
+ discrepancies: []
9273
+ };
9274
+ }
9275
+ function assessL2Hardening(storagePath) {
9276
+ const memory = checkMemoryProtection();
9277
+ const isolation = checkProcessIsolation();
9278
+ const filesystem = checkFilesystemPermissions(storagePath);
9279
+ const integrity = checkRuntimeIntegrity();
9280
+ let checksPassed = 0;
9281
+ let checksTotal = 0;
9282
+ if (memory.aslr_enabled) checksPassed++;
9283
+ checksTotal++;
9284
+ if (memory.stack_canaries) checksPassed++;
9285
+ checksTotal++;
9286
+ if (memory.secure_buffer_zeros) checksPassed++;
9287
+ checksTotal++;
9288
+ if (memory.argon2id_kdf) checksPassed++;
9289
+ checksTotal++;
9290
+ if (isolation.is_container) checksPassed++;
9291
+ checksTotal++;
9292
+ if (isolation.is_vm) checksPassed++;
9293
+ checksTotal++;
9294
+ if (isolation.is_sandboxed) checksPassed++;
9295
+ checksTotal++;
9296
+ if (filesystem.sanctuary_storage_protected) checksPassed++;
9297
+ checksTotal++;
9298
+ {
9299
+ checksPassed++;
9300
+ }
9301
+ checksTotal++;
9302
+ let hardeningLevel = isolation.isolation_level;
9303
+ if (filesystem.overall === "insecure" || memory.overall === "none" || memory.overall === "minimal") {
9304
+ if (hardeningLevel === "hardened") {
9305
+ hardeningLevel = "basic";
9306
+ } else if (hardeningLevel === "basic") {
9307
+ hardeningLevel = "none";
9308
+ }
9309
+ }
9310
+ const summaryParts = [];
9311
+ if (isolation.is_container || isolation.is_vm) {
9312
+ summaryParts.push(`Running in ${isolation.details.container_type || isolation.details.vm_type || "isolated environment"}`);
9313
+ }
9314
+ if (memory.aslr_enabled) {
9315
+ summaryParts.push("ASLR enabled");
9316
+ }
9317
+ if (filesystem.sanctuary_storage_protected) {
9318
+ summaryParts.push("Storage permissions secured (0700)");
9319
+ }
9320
+ const summary = summaryParts.length > 0 ? summaryParts.join("; ") : "No process-level hardening detected";
9321
+ return {
9322
+ hardening_level: hardeningLevel,
9323
+ memory_protection: memory,
9324
+ process_isolation: isolation,
9325
+ filesystem_permissions: filesystem,
9326
+ runtime_integrity: integrity,
9327
+ checks_passed: checksPassed,
9328
+ checks_total: checksTotal,
9329
+ summary
9330
+ };
9331
+ }
9332
+
9333
+ // src/l2-operational/hardening-tools.ts
9334
+ function createL2HardeningTools(storagePath, auditLog) {
9335
+ return [
9336
+ {
9337
+ name: "sanctuary/l2_hardening_status",
9338
+ description: "L2 Process Hardening Status \u2014 Verify software-based operational isolation. Reports memory protection, process isolation level, filesystem permissions, and overall hardening assessment. Read-only. Tier 3 \u2014 always allowed.",
9339
+ inputSchema: {
9340
+ type: "object",
9341
+ properties: {
9342
+ include_details: {
9343
+ type: "boolean",
9344
+ description: "If true, include detailed check results for memory, process, and filesystem. If false, show summary only.",
9345
+ default: false
9346
+ }
9347
+ }
9348
+ },
9349
+ handler: async (args) => {
9350
+ const includeDetails = args.include_details ?? false;
9351
+ const status = assessL2Hardening(storagePath);
9352
+ auditLog.append(
9353
+ "l2",
9354
+ "l2_hardening_status",
9355
+ "system",
9356
+ { include_details: includeDetails }
9357
+ );
9358
+ if (includeDetails) {
9359
+ return toolResult({
9360
+ hardening_level: status.hardening_level,
9361
+ summary: status.summary,
9362
+ checks_passed: status.checks_passed,
9363
+ checks_total: status.checks_total,
9364
+ memory_protection: {
9365
+ aslr_enabled: status.memory_protection.aslr_enabled,
9366
+ stack_canaries: status.memory_protection.stack_canaries,
9367
+ secure_buffer_zeros: status.memory_protection.secure_buffer_zeros,
9368
+ argon2id_kdf: status.memory_protection.argon2id_kdf,
9369
+ overall: status.memory_protection.overall
9370
+ },
9371
+ process_isolation: {
9372
+ isolation_level: status.process_isolation.isolation_level,
9373
+ is_container: status.process_isolation.is_container,
9374
+ is_vm: status.process_isolation.is_vm,
9375
+ is_sandboxed: status.process_isolation.is_sandboxed,
9376
+ is_tee: status.process_isolation.is_tee,
9377
+ details: status.process_isolation.details
9378
+ },
9379
+ filesystem_permissions: {
9380
+ sanctuary_storage_protected: status.filesystem_permissions.sanctuary_storage_protected,
9381
+ sanctuary_storage_mode: status.filesystem_permissions.sanctuary_storage_mode,
9382
+ owner_is_current_user: status.filesystem_permissions.owner_is_current_user,
9383
+ group_readable: status.filesystem_permissions.group_readable,
9384
+ others_readable: status.filesystem_permissions.others_readable,
9385
+ overall: status.filesystem_permissions.overall
9386
+ },
9387
+ runtime_integrity: {
9388
+ config_hash_stable: status.runtime_integrity.config_hash_stable,
9389
+ environment_state: status.runtime_integrity.environment_state,
9390
+ discrepancies: status.runtime_integrity.discrepancies
9391
+ }
9392
+ });
9393
+ } else {
9394
+ return toolResult({
9395
+ hardening_level: status.hardening_level,
9396
+ summary: status.summary,
9397
+ checks_passed: status.checks_passed,
9398
+ checks_total: status.checks_total,
9399
+ note: "Pass include_details: true to see full breakdown of memory, process isolation, and filesystem checks."
9400
+ });
9401
+ }
9402
+ }
9403
+ },
9404
+ {
9405
+ name: "sanctuary/l2_verify_isolation",
9406
+ description: "Verify L2 process isolation at runtime. Checks whether the Sanctuary server is running in an isolated environment (container, VM, sandbox) and validates filesystem and memory protections. Reports isolation level and any issues. Read-only. Tier 3 \u2014 always allowed.",
9407
+ inputSchema: {
9408
+ type: "object",
9409
+ properties: {
9410
+ check_filesystem: {
9411
+ type: "boolean",
9412
+ description: "If true, verify Sanctuary storage directory permissions.",
9413
+ default: true
9414
+ },
9415
+ check_memory: {
9416
+ type: "boolean",
9417
+ description: "If true, verify memory protection mechanisms (ASLR, etc.).",
9418
+ default: true
9419
+ },
9420
+ check_process: {
9421
+ type: "boolean",
9422
+ description: "If true, detect container, VM, or sandbox environment.",
9423
+ default: true
9424
+ }
9425
+ }
9426
+ },
9427
+ handler: async (args) => {
9428
+ const checkFilesystem = args.check_filesystem ?? true;
9429
+ const checkMemory = args.check_memory ?? true;
9430
+ const checkProcess = args.check_process ?? true;
9431
+ const status = assessL2Hardening(storagePath);
9432
+ auditLog.append(
9433
+ "l2",
9434
+ "l2_verify_isolation",
9435
+ "system",
9436
+ {
9437
+ check_filesystem: checkFilesystem,
9438
+ check_memory: checkMemory,
9439
+ check_process: checkProcess
9440
+ }
9441
+ );
9442
+ const results = {
9443
+ isolation_level: status.hardening_level,
9444
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
9445
+ };
9446
+ if (checkFilesystem) {
9447
+ const fs = status.filesystem_permissions;
9448
+ results.filesystem = {
9449
+ sanctuary_storage_protected: fs.sanctuary_storage_protected,
9450
+ storage_mode: fs.sanctuary_storage_mode,
9451
+ is_secure: fs.overall === "secure",
9452
+ issues: fs.overall === "insecure" ? [
9453
+ "Storage directory is readable by group or others. Recommend: chmod 700 on Sanctuary storage path."
9454
+ ] : fs.overall === "warning" ? [
9455
+ "Storage directory not owned by current user. Verify correct user is running Sanctuary."
9456
+ ] : []
9457
+ };
9458
+ }
9459
+ if (checkMemory) {
9460
+ const mem = status.memory_protection;
9461
+ const issues = [];
9462
+ if (!mem.aslr_enabled) {
9463
+ issues.push(
9464
+ "ASLR not detected. On Linux, enable with: echo 2 | sudo tee /proc/sys/kernel/randomize_va_space"
9465
+ );
9466
+ }
9467
+ results.memory = {
9468
+ aslr_enabled: mem.aslr_enabled,
9469
+ stack_canaries: mem.stack_canaries,
9470
+ secure_buffer_handling: mem.secure_buffer_zeros,
9471
+ argon2id_key_derivation: mem.argon2id_kdf,
9472
+ protection_level: mem.overall,
9473
+ issues
9474
+ };
9475
+ }
9476
+ if (checkProcess) {
9477
+ const iso = status.process_isolation;
9478
+ results.process = {
9479
+ isolation_level: iso.isolation_level,
9480
+ in_container: iso.is_container,
9481
+ in_vm: iso.is_vm,
9482
+ sandboxed: iso.is_sandboxed,
9483
+ has_tee: iso.is_tee,
9484
+ environment: iso.details,
9485
+ recommendation: iso.isolation_level === "none" ? "Consider running Sanctuary in a container or VM for improved isolation." : iso.isolation_level === "basic" ? "Basic isolation detected. Container or VM would provide stronger guarantees." : "Running in isolated environment \u2014 process-level isolation is strong."
9486
+ };
9487
+ }
9488
+ return toolResult({
9489
+ status: "verified",
9490
+ results
9491
+ });
9492
+ }
9493
+ }
9494
+ ];
9495
+ }
9496
+
9497
+ // src/index.ts
9498
+ init_encoding();
9499
+ async function createSanctuaryServer(options) {
9500
+ const config = await loadConfig(options?.configPath);
9501
+ await mkdir(config.storage_path, { recursive: true, mode: 448 });
9502
+ const storage = options?.storage ?? new FilesystemStorage(
9503
+ `${config.storage_path}/state`
9504
+ );
9505
+ let masterKey;
9506
+ let keyProtection;
9507
+ let recoveryKey;
9508
+ const passphrase = options?.passphrase ?? process.env.SANCTUARY_PASSPHRASE;
9509
+ if (passphrase) {
9510
+ keyProtection = "passphrase";
9511
+ let existingParams;
9512
+ try {
9513
+ const raw = await storage.read("_meta", "key-params");
9514
+ if (raw) {
9515
+ const { bytesToString: bytesToString2 } = await Promise.resolve().then(() => (init_encoding(), encoding_exports));
9516
+ existingParams = JSON.parse(bytesToString2(raw));
9517
+ }
9518
+ } catch {
9519
+ }
9520
+ const result = await deriveMasterKey(passphrase, existingParams);
9521
+ masterKey = result.key;
9522
+ if (!existingParams) {
9523
+ const { stringToBytes: stringToBytes2 } = await Promise.resolve().then(() => (init_encoding(), encoding_exports));
9524
+ await storage.write(
6665
9525
  "_meta",
6666
9526
  "key-params",
6667
9527
  stringToBytes2(JSON.stringify(result.params))
@@ -6669,15 +9529,51 @@ async function createSanctuaryServer(options) {
6669
9529
  }
6670
9530
  } else {
6671
9531
  keyProtection = "recovery-key";
6672
- const existing = await storage.read("_meta", "recovery-key-hash");
6673
- if (existing) {
6674
- masterKey = generateRandomKey();
6675
- recoveryKey = toBase64url(masterKey);
9532
+ const { hashToString: hashToString2 } = await Promise.resolve().then(() => (init_hashing(), hashing_exports));
9533
+ const { stringToBytes: stringToBytes2, bytesToString: bytesToString2 } = await Promise.resolve().then(() => (init_encoding(), encoding_exports));
9534
+ const { fromBase64url: fromBase64url2 } = await Promise.resolve().then(() => (init_encoding(), encoding_exports));
9535
+ const { constantTimeEqual: constantTimeEqual2 } = await Promise.resolve().then(() => (init_encoding(), encoding_exports));
9536
+ const existingHash = await storage.read("_meta", "recovery-key-hash");
9537
+ if (existingHash) {
9538
+ const envRecoveryKey = process.env.SANCTUARY_RECOVERY_KEY;
9539
+ if (!envRecoveryKey) {
9540
+ throw new Error(
9541
+ "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."
9542
+ );
9543
+ }
9544
+ let recoveryKeyBytes;
9545
+ try {
9546
+ recoveryKeyBytes = fromBase64url2(envRecoveryKey);
9547
+ } catch {
9548
+ throw new Error(
9549
+ "Sanctuary: SANCTUARY_RECOVERY_KEY is not valid base64url. The recovery key should be the exact string shown at first run."
9550
+ );
9551
+ }
9552
+ if (recoveryKeyBytes.length !== 32) {
9553
+ throw new Error(
9554
+ "Sanctuary: SANCTUARY_RECOVERY_KEY has incorrect length. The recovery key should be the exact string shown at first run."
9555
+ );
9556
+ }
9557
+ const providedHash = hashToString2(recoveryKeyBytes);
9558
+ const storedHash = bytesToString2(existingHash);
9559
+ const providedHashBytes = stringToBytes2(providedHash);
9560
+ const storedHashBytes = stringToBytes2(storedHash);
9561
+ if (!constantTimeEqual2(providedHashBytes, storedHashBytes)) {
9562
+ throw new Error(
9563
+ "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."
9564
+ );
9565
+ }
9566
+ masterKey = recoveryKeyBytes;
6676
9567
  } else {
9568
+ const existingNamespaces = await storage.list("_meta");
9569
+ const hasKeyParams = existingNamespaces.some((e) => e.key === "key-params");
9570
+ if (hasKeyParams) {
9571
+ throw new Error(
9572
+ "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."
9573
+ );
9574
+ }
6677
9575
  masterKey = generateRandomKey();
6678
9576
  recoveryKey = toBase64url(masterKey);
6679
- const { hashToString: hashToString2 } = await Promise.resolve().then(() => (init_hashing(), hashing_exports));
6680
- const { stringToBytes: stringToBytes2 } = await Promise.resolve().then(() => (init_encoding(), encoding_exports));
6681
9577
  const keyHash = hashToString2(masterKey);
6682
9578
  await storage.write(
6683
9579
  "_meta",
@@ -6764,7 +9660,7 @@ async function createSanctuaryServer(options) {
6764
9660
  layer: "l2",
6765
9661
  description: "Process-level isolation only (no TEE)",
6766
9662
  severity: "warning",
6767
- mitigation: "TEE support planned for v0.3.0"
9663
+ mitigation: "TEE support planned for a future release"
6768
9664
  });
6769
9665
  if (config.disclosure.proof_system === "commitment-only") {
6770
9666
  degradations.push({
@@ -6904,7 +9800,7 @@ async function createSanctuaryServer(options) {
6904
9800
  },
6905
9801
  limitations: [
6906
9802
  "L1 identity uses ed25519 only; KERI support planned for v0.2.0",
6907
- "L2 isolation is process-level only; TEE support planned for v0.3.0",
9803
+ "L2 isolation is process-level only; TEE support planned for a future release",
6908
9804
  "L3 uses commitment schemes only; ZK proofs planned for v0.2.0",
6909
9805
  "L4 Sybil resistance is escrow-based only",
6910
9806
  "Spec license: CC-BY-4.0 | Code license: Apache-2.0"
@@ -6925,7 +9821,7 @@ async function createSanctuaryServer(options) {
6925
9821
  masterKey,
6926
9822
  auditLog
6927
9823
  );
6928
- const { tools: l4Tools } = createL4Tools(
9824
+ const { tools: l4Tools} = createL4Tools(
6929
9825
  storage,
6930
9826
  masterKey,
6931
9827
  identityManager,
@@ -6943,6 +9839,13 @@ async function createSanctuaryServer(options) {
6943
9839
  auditLog,
6944
9840
  handshakeResults
6945
9841
  );
9842
+ const { tools: auditTools } = createAuditTools(config);
9843
+ const { tools: contextGateTools } = createContextGateTools(
9844
+ storage,
9845
+ masterKey,
9846
+ auditLog
9847
+ );
9848
+ const hardeningTools = createL2HardeningTools(config.storage_path, auditLog);
6946
9849
  const policy = await loadPrincipalPolicy(config.storage_path);
6947
9850
  const baseline = new BaselineTracker(storage, masterKey);
6948
9851
  await baseline.load();
@@ -6958,7 +9861,7 @@ async function createSanctuaryServer(options) {
6958
9861
  port: config.dashboard.port,
6959
9862
  host: config.dashboard.host,
6960
9863
  timeout_seconds: policy.approval_channel.timeout_seconds,
6961
- auto_deny: policy.approval_channel.auto_deny,
9864
+ // SEC-002: auto_deny removed — timeout always denies
6962
9865
  auth_token: authToken,
6963
9866
  tls: config.dashboard.tls
6964
9867
  });
@@ -6971,8 +9874,8 @@ async function createSanctuaryServer(options) {
6971
9874
  webhook_secret: config.webhook.secret,
6972
9875
  callback_port: config.webhook.callback_port,
6973
9876
  callback_host: config.webhook.callback_host,
6974
- timeout_seconds: policy.approval_channel.timeout_seconds,
6975
- auto_deny: policy.approval_channel.auto_deny
9877
+ timeout_seconds: policy.approval_channel.timeout_seconds
9878
+ // SEC-002: auto_deny removed — timeout always denies
6976
9879
  });
6977
9880
  await webhook.start();
6978
9881
  approvalChannel = webhook;
@@ -6991,6 +9894,9 @@ async function createSanctuaryServer(options) {
6991
9894
  ...handshakeTools,
6992
9895
  ...federationTools,
6993
9896
  ...bridgeTools,
9897
+ ...auditTools,
9898
+ ...contextGateTools,
9899
+ ...hardeningTools,
6994
9900
  manifestTool
6995
9901
  ];
6996
9902
  const server = createServer(allTools, { gate });
@@ -7015,8 +9921,78 @@ async function createSanctuaryServer(options) {
7015
9921
  }
7016
9922
  return { server, config };
7017
9923
  }
7018
-
7019
- // src/cli.ts
9924
+ var REGISTRY_URL = "https://registry.npmjs.org/@sanctuary-framework/mcp-server/latest";
9925
+ var TIMEOUT_MS = 3e3;
9926
+ function isNewerVersion(current, latest) {
9927
+ const parse = (v) => v.replace(/^v/, "").split(".").map(Number);
9928
+ const [curMajor = 0, curMinor = 0, curPatch = 0] = parse(current);
9929
+ const [latMajor = 0, latMinor = 0, latPatch = 0] = parse(latest);
9930
+ if (latMajor !== curMajor) return latMajor > curMajor;
9931
+ if (latMinor !== curMinor) return latMinor > curMinor;
9932
+ return latPatch > curPatch;
9933
+ }
9934
+ function formatUpdateMessage(current, latest) {
9935
+ return `[Sanctuary] Update available: ${current} \u2192 ${latest} \u2014 run: npx @sanctuary-framework/mcp-server@latest`;
9936
+ }
9937
+ function fetchLatestVersion(currentVersion) {
9938
+ return new Promise((resolve) => {
9939
+ const req = get(
9940
+ REGISTRY_URL,
9941
+ {
9942
+ headers: { Accept: "application/json" },
9943
+ timeout: TIMEOUT_MS
9944
+ },
9945
+ (res) => {
9946
+ if (res.statusCode !== 200) {
9947
+ res.resume();
9948
+ resolve(null);
9949
+ return;
9950
+ }
9951
+ let data = "";
9952
+ res.setEncoding("utf-8");
9953
+ res.on("data", (chunk) => {
9954
+ data += chunk;
9955
+ if (data.length > 32768) {
9956
+ res.destroy();
9957
+ resolve(null);
9958
+ }
9959
+ });
9960
+ res.on("end", () => {
9961
+ try {
9962
+ const json = JSON.parse(data);
9963
+ const latest = json.version;
9964
+ if (typeof latest === "string" && isNewerVersion(currentVersion, latest)) {
9965
+ resolve(latest);
9966
+ } else {
9967
+ resolve(null);
9968
+ }
9969
+ } catch {
9970
+ resolve(null);
9971
+ }
9972
+ });
9973
+ }
9974
+ );
9975
+ req.on("error", () => resolve(null));
9976
+ req.on("timeout", () => {
9977
+ req.destroy();
9978
+ resolve(null);
9979
+ });
9980
+ });
9981
+ }
9982
+ async function checkForUpdate(currentVersion) {
9983
+ if (process.env.SANCTUARY_NO_UPDATE_CHECK === "1") {
9984
+ return;
9985
+ }
9986
+ try {
9987
+ const latest = await fetchLatestVersion(currentVersion);
9988
+ if (latest) {
9989
+ console.error(formatUpdateMessage(currentVersion, latest));
9990
+ }
9991
+ } catch {
9992
+ }
9993
+ }
9994
+ var require5 = createRequire(import.meta.url);
9995
+ var { version: PKG_VERSION4 } = require5("../package.json");
7020
9996
  async function main() {
7021
9997
  const args = process.argv.slice(2);
7022
9998
  let passphrase = process.env.SANCTUARY_PASSPHRASE;
@@ -7029,7 +10005,7 @@ async function main() {
7029
10005
  printHelp();
7030
10006
  process.exit(0);
7031
10007
  } else if (args[i] === "--version" || args[i] === "-v") {
7032
- console.log("@sanctuary-framework/mcp-server 0.3.0");
10008
+ console.log(`@sanctuary-framework/mcp-server ${PKG_VERSION4}`);
7033
10009
  process.exit(0);
7034
10010
  }
7035
10011
  }
@@ -7040,6 +10016,7 @@ async function main() {
7040
10016
  console.error(`Sanctuary MCP Server v${config.version} running (stdio)`);
7041
10017
  console.error(`Storage: ${config.storage_path}`);
7042
10018
  console.error("Tools: all registered");
10019
+ checkForUpdate(PKG_VERSION4);
7043
10020
  } else {
7044
10021
  console.error("HTTP transport not yet implemented. Use stdio.");
7045
10022
  process.exit(1);
@@ -7047,7 +10024,7 @@ async function main() {
7047
10024
  }
7048
10025
  function printHelp() {
7049
10026
  console.log(`
7050
- @sanctuary-framework/mcp-server v0.3.0
10027
+ @sanctuary-framework/mcp-server v${PKG_VERSION4}
7051
10028
 
7052
10029
  Sovereignty infrastructure for agents in the agentic economy.
7053
10030
 
@@ -7069,6 +10046,7 @@ Environment variables:
7069
10046
  SANCTUARY_WEBHOOK_ENABLED "true" to enable webhook approvals
7070
10047
  SANCTUARY_WEBHOOK_URL Webhook target URL
7071
10048
  SANCTUARY_WEBHOOK_SECRET HMAC-SHA256 shared secret
10049
+ SANCTUARY_NO_UPDATE_CHECK "1" to disable startup update check
7072
10050
 
7073
10051
  For more info: https://github.com/eriknewton/sanctuary-framework
7074
10052
  `);