@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/index.cjs CHANGED
@@ -5,6 +5,7 @@ var hmac = require('@noble/hashes/hmac');
5
5
  var promises = require('fs/promises');
6
6
  var path = require('path');
7
7
  var os = require('os');
8
+ var module$1 = require('module');
8
9
  var crypto = require('crypto');
9
10
  var aes_js = require('@noble/ciphers/aes.js');
10
11
  var ed25519 = require('@noble/curves/ed25519');
@@ -15,7 +16,9 @@ var types_js = require('@modelcontextprotocol/sdk/types.js');
15
16
  var http = require('http');
16
17
  var https = require('https');
17
18
  var fs = require('fs');
19
+ var child_process = require('child_process');
18
20
 
21
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
19
22
  var __defProp = Object.defineProperty;
20
23
  var __getOwnPropNames = Object.getOwnPropertyNames;
21
24
  var __esm = (fn, res) => function __init() {
@@ -204,9 +207,11 @@ var init_hashing = __esm({
204
207
  init_encoding();
205
208
  }
206
209
  });
210
+ var require2 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
211
+ var { version: PKG_VERSION } = require2("../package.json");
207
212
  function defaultConfig() {
208
213
  return {
209
- version: "0.3.0",
214
+ version: PKG_VERSION,
210
215
  storage_path: path.join(os.homedir(), ".sanctuary"),
211
216
  state: {
212
217
  encryption: "aes-256-gcm",
@@ -298,8 +303,13 @@ async function loadConfig(configPath) {
298
303
  try {
299
304
  const raw = await promises.readFile(path$1, "utf-8");
300
305
  const fileConfig = JSON.parse(raw);
301
- return deepMerge(config, fileConfig);
302
- } catch {
306
+ const merged = deepMerge(config, fileConfig);
307
+ validateConfig(merged);
308
+ return merged;
309
+ } catch (err) {
310
+ if (err instanceof Error && err.message.includes("unimplemented features")) {
311
+ throw err;
312
+ }
303
313
  return config;
304
314
  }
305
315
  }
@@ -307,6 +317,45 @@ async function saveConfig(config, configPath) {
307
317
  const path$1 = path.join(config.storage_path, "sanctuary.json");
308
318
  await promises.writeFile(path$1, JSON.stringify(config, null, 2), { mode: 384 });
309
319
  }
320
+ function validateConfig(config) {
321
+ const errors = [];
322
+ const implementedKeyProtection = /* @__PURE__ */ new Set(["passphrase", "none"]);
323
+ if (!implementedKeyProtection.has(config.state.key_protection)) {
324
+ errors.push(
325
+ `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.`
326
+ );
327
+ }
328
+ const implementedEnvironment = /* @__PURE__ */ new Set(["local-process", "docker"]);
329
+ if (!implementedEnvironment.has(config.execution.environment)) {
330
+ errors.push(
331
+ `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.`
332
+ );
333
+ }
334
+ const implementedProofSystem = /* @__PURE__ */ new Set(["commitment-only"]);
335
+ if (!implementedProofSystem.has(config.disclosure.proof_system)) {
336
+ errors.push(
337
+ `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.`
338
+ );
339
+ }
340
+ const implementedDisclosurePolicy = /* @__PURE__ */ new Set(["minimum-necessary"]);
341
+ if (!implementedDisclosurePolicy.has(config.disclosure.default_policy)) {
342
+ errors.push(
343
+ `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.`
344
+ );
345
+ }
346
+ const implementedReputationMode = /* @__PURE__ */ new Set(["self-custodied"]);
347
+ if (!implementedReputationMode.has(config.reputation.mode)) {
348
+ errors.push(
349
+ `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.`
350
+ );
351
+ }
352
+ if (errors.length > 0) {
353
+ throw new Error(
354
+ `Sanctuary configuration references unimplemented features:
355
+ ${errors.join("\n")}`
356
+ );
357
+ }
358
+ }
310
359
  function deepMerge(base, override) {
311
360
  const result = { ...base };
312
361
  for (const [key, value] of Object.entries(override)) {
@@ -650,7 +699,11 @@ var RESERVED_NAMESPACE_PREFIXES = [
650
699
  "_commitments",
651
700
  "_reputation",
652
701
  "_escrow",
653
- "_guarantees"
702
+ "_guarantees",
703
+ "_bridge",
704
+ "_federation",
705
+ "_handshake",
706
+ "_shr"
654
707
  ];
655
708
  var StateStore = class {
656
709
  storage;
@@ -917,12 +970,14 @@ var StateStore = class {
917
970
  /**
918
971
  * Import a previously exported state bundle.
919
972
  */
920
- async import(bundleBase64, conflictResolution = "skip") {
973
+ async import(bundleBase64, conflictResolution = "skip", publicKeyResolver) {
921
974
  const bundleBytes = fromBase64url(bundleBase64);
922
975
  const bundleJson = bytesToString(bundleBytes);
923
976
  const bundle = JSON.parse(bundleJson);
924
977
  let importedKeys = 0;
925
978
  let skippedKeys = 0;
979
+ let skippedInvalidSig = 0;
980
+ let skippedUnknownKid = 0;
926
981
  let conflicts = 0;
927
982
  const namespaces = [];
928
983
  for (const [ns, entries] of Object.entries(
@@ -936,6 +991,26 @@ var StateStore = class {
936
991
  }
937
992
  namespaces.push(ns);
938
993
  for (const { key, entry } of entries) {
994
+ const signerPublicKey = publicKeyResolver(entry.kid);
995
+ if (!signerPublicKey) {
996
+ skippedUnknownKid++;
997
+ skippedKeys++;
998
+ continue;
999
+ }
1000
+ try {
1001
+ const ciphertextBytes = fromBase64url(entry.payload.ct);
1002
+ const signatureBytes = fromBase64url(entry.sig);
1003
+ const sigValid = verify(ciphertextBytes, signatureBytes, signerPublicKey);
1004
+ if (!sigValid) {
1005
+ skippedInvalidSig++;
1006
+ skippedKeys++;
1007
+ continue;
1008
+ }
1009
+ } catch {
1010
+ skippedInvalidSig++;
1011
+ skippedKeys++;
1012
+ continue;
1013
+ }
939
1014
  const exists = await this.storage.exists(ns, key);
940
1015
  if (exists) {
941
1016
  conflicts++;
@@ -971,12 +1046,16 @@ var StateStore = class {
971
1046
  return {
972
1047
  imported_keys: importedKeys,
973
1048
  skipped_keys: skippedKeys,
1049
+ skipped_invalid_sig: skippedInvalidSig,
1050
+ skipped_unknown_kid: skippedUnknownKid,
974
1051
  conflicts,
975
1052
  namespaces,
976
1053
  imported_at: (/* @__PURE__ */ new Date()).toISOString()
977
1054
  };
978
1055
  }
979
1056
  };
1057
+ var require3 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
1058
+ var { version: PKG_VERSION2 } = require3("../package.json");
980
1059
  var MAX_STRING_BYTES = 1048576;
981
1060
  var MAX_BUNDLE_BYTES = 5242880;
982
1061
  var BUNDLE_FIELDS = /* @__PURE__ */ new Set(["bundle"]);
@@ -1059,7 +1138,7 @@ function createServer(tools, options) {
1059
1138
  const server = new index_js.Server(
1060
1139
  {
1061
1140
  name: "sanctuary-mcp-server",
1062
- version: "0.3.0"
1141
+ version: PKG_VERSION2
1063
1142
  },
1064
1143
  {
1065
1144
  capabilities: {
@@ -1159,7 +1238,11 @@ var RESERVED_NAMESPACE_PREFIXES2 = [
1159
1238
  "_commitments",
1160
1239
  "_reputation",
1161
1240
  "_escrow",
1162
- "_guarantees"
1241
+ "_guarantees",
1242
+ "_bridge",
1243
+ "_federation",
1244
+ "_handshake",
1245
+ "_shr"
1163
1246
  ];
1164
1247
  function getReservedNamespaceViolation(namespace) {
1165
1248
  for (const prefix of RESERVED_NAMESPACE_PREFIXES2) {
@@ -1496,6 +1579,13 @@ function createL1Tools(stateStore, storage, masterKey, keyProtection, auditLog)
1496
1579
  required: ["namespace", "key"]
1497
1580
  },
1498
1581
  handler: async (args) => {
1582
+ const reservedViolation = getReservedNamespaceViolation(args.namespace);
1583
+ if (reservedViolation) {
1584
+ return toolResult({
1585
+ error: "namespace_reserved",
1586
+ message: `Namespace "${args.namespace}" is reserved for internal use (prefix: ${reservedViolation}). Cannot read from reserved namespaces.`
1587
+ });
1588
+ }
1499
1589
  const result = await stateStore.read(
1500
1590
  args.namespace,
1501
1591
  args.key,
@@ -1532,6 +1622,13 @@ function createL1Tools(stateStore, storage, masterKey, keyProtection, auditLog)
1532
1622
  required: ["namespace"]
1533
1623
  },
1534
1624
  handler: async (args) => {
1625
+ const reservedViolation = getReservedNamespaceViolation(args.namespace);
1626
+ if (reservedViolation) {
1627
+ return toolResult({
1628
+ error: "namespace_reserved",
1629
+ message: `Namespace "${args.namespace}" is reserved for internal use (prefix: ${reservedViolation}). Cannot list reserved namespaces.`
1630
+ });
1631
+ }
1535
1632
  const result = await stateStore.list(
1536
1633
  args.namespace,
1537
1634
  args.prefix,
@@ -1610,9 +1707,15 @@ function createL1Tools(stateStore, storage, masterKey, keyProtection, auditLog)
1610
1707
  required: ["bundle"]
1611
1708
  },
1612
1709
  handler: async (args) => {
1710
+ const publicKeyResolver = (kid) => {
1711
+ const identity = identityMgr.get(kid);
1712
+ if (!identity) return null;
1713
+ return fromBase64url(identity.public_key);
1714
+ };
1613
1715
  const result = await stateStore.import(
1614
1716
  args.bundle,
1615
- args.conflict_resolution ?? "skip"
1717
+ args.conflict_resolution ?? "skip",
1718
+ publicKeyResolver
1616
1719
  );
1617
1720
  auditLog?.append("l1", "state_import", "principal", {
1618
1721
  imported_keys: result.imported_keys
@@ -2057,7 +2160,7 @@ function createRangeProof(value, blindingFactor, commitment, min, max) {
2057
2160
  bitProofs.push(bitProof);
2058
2161
  }
2059
2162
  const sumBlinding = bitBlindings.reduce(
2060
- (acc, bi, i) => mod(acc + mod(BigInt(1 << i)) * bi),
2163
+ (acc, bi, i) => mod(acc + mod(BigInt(1) << BigInt(i)) * bi),
2061
2164
  0n
2062
2165
  );
2063
2166
  const blindingDiff = mod(b - sumBlinding);
@@ -2099,7 +2202,7 @@ function verifyRangeProof(proof) {
2099
2202
  let reconstructed = ed25519.RistrettoPoint.ZERO;
2100
2203
  for (let i = 0; i < numBits; i++) {
2101
2204
  const C_i = ed25519.RistrettoPoint.fromHex(fromBase64url(proof.bit_commitments[i]));
2102
- const weight = mod(BigInt(1 << i));
2205
+ const weight = mod(BigInt(1) << BigInt(i));
2103
2206
  reconstructed = reconstructed.add(safeMultiply(C_i, weight));
2104
2207
  }
2105
2208
  const diff = C.subtract(safeMultiply(G, mod(BigInt(proof.min)))).subtract(reconstructed);
@@ -3154,7 +3257,9 @@ function createL4Tools(storage, masterKey, identityManager, auditLog, handshakeR
3154
3257
  contexts: summary.contexts
3155
3258
  });
3156
3259
  return toolResult({
3157
- summary
3260
+ summary,
3261
+ // SEC-ADD-03: Tag response as containing counterparty-generated attestation data
3262
+ _content_trust: "external"
3158
3263
  });
3159
3264
  }
3160
3265
  },
@@ -3475,24 +3580,27 @@ var DEFAULT_TIER2 = {
3475
3580
  };
3476
3581
  var DEFAULT_CHANNEL = {
3477
3582
  type: "stderr",
3478
- timeout_seconds: 300,
3479
- auto_deny: true
3583
+ timeout_seconds: 300
3584
+ // SEC-002: auto_deny is not configurable. Timeout always denies.
3585
+ // Field omitted intentionally — all channels hardcode deny on timeout.
3480
3586
  };
3481
3587
  var DEFAULT_POLICY = {
3482
3588
  version: 1,
3483
3589
  tier1_always_approve: [
3484
3590
  "state_export",
3485
3591
  "state_import",
3592
+ "state_delete",
3486
3593
  "identity_rotate",
3487
3594
  "reputation_import",
3488
- "bootstrap_provide_guarantee"
3595
+ "reputation_export",
3596
+ "bootstrap_provide_guarantee",
3597
+ "decommission_certificate"
3489
3598
  ],
3490
3599
  tier2_anomaly: DEFAULT_TIER2,
3491
3600
  tier3_always_allow: [
3492
3601
  "state_read",
3493
3602
  "state_write",
3494
3603
  "state_list",
3495
- "state_delete",
3496
3604
  "identity_create",
3497
3605
  "identity_list",
3498
3606
  "identity_sign",
@@ -3503,7 +3611,6 @@ var DEFAULT_POLICY = {
3503
3611
  "disclosure_evaluate",
3504
3612
  "reputation_record",
3505
3613
  "reputation_query",
3506
- "reputation_export",
3507
3614
  "bootstrap_create_escrow",
3508
3615
  "exec_attest",
3509
3616
  "monitor_health",
@@ -3525,7 +3632,14 @@ var DEFAULT_POLICY = {
3525
3632
  "zk_prove",
3526
3633
  "zk_verify",
3527
3634
  "zk_range_prove",
3528
- "zk_range_verify"
3635
+ "zk_range_verify",
3636
+ "context_gate_set_policy",
3637
+ "context_gate_apply_template",
3638
+ "context_gate_recommend",
3639
+ "context_gate_filter",
3640
+ "context_gate_list_policies",
3641
+ "l2_hardening_status",
3642
+ "l2_verify_isolation"
3529
3643
  ],
3530
3644
  approval_channel: DEFAULT_CHANNEL
3531
3645
  };
@@ -3600,10 +3714,14 @@ function validatePolicy(raw) {
3600
3714
  ...raw.tier2_anomaly ?? {}
3601
3715
  },
3602
3716
  tier3_always_allow: raw.tier3_always_allow ?? DEFAULT_POLICY.tier3_always_allow,
3603
- approval_channel: {
3604
- ...DEFAULT_CHANNEL,
3605
- ...raw.approval_channel ?? {}
3606
- }
3717
+ approval_channel: (() => {
3718
+ const merged = {
3719
+ ...DEFAULT_CHANNEL,
3720
+ ...raw.approval_channel ?? {}
3721
+ };
3722
+ delete merged.auto_deny;
3723
+ return merged;
3724
+ })()
3607
3725
  };
3608
3726
  }
3609
3727
  function generateDefaultPolicyYaml() {
@@ -3620,8 +3738,10 @@ version: 1
3620
3738
  tier1_always_approve:
3621
3739
  - state_export
3622
3740
  - state_import
3741
+ - state_delete
3623
3742
  - identity_rotate
3624
3743
  - reputation_import
3744
+ - reputation_export
3625
3745
  - bootstrap_provide_guarantee
3626
3746
 
3627
3747
  # \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 +3761,6 @@ tier3_always_allow:
3641
3761
  - state_read
3642
3762
  - state_write
3643
3763
  - state_list
3644
- - state_delete
3645
3764
  - identity_create
3646
3765
  - identity_list
3647
3766
  - identity_sign
@@ -3652,7 +3771,6 @@ tier3_always_allow:
3652
3771
  - disclosure_evaluate
3653
3772
  - reputation_record
3654
3773
  - reputation_query
3655
- - reputation_export
3656
3774
  - bootstrap_create_escrow
3657
3775
  - exec_attest
3658
3776
  - monitor_health
@@ -3675,13 +3793,18 @@ tier3_always_allow:
3675
3793
  - zk_verify
3676
3794
  - zk_range_prove
3677
3795
  - zk_range_verify
3796
+ - context_gate_set_policy
3797
+ - context_gate_apply_template
3798
+ - context_gate_recommend
3799
+ - context_gate_filter
3800
+ - context_gate_list_policies
3678
3801
 
3679
3802
  # \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
3803
  # How Sanctuary reaches you when approval is needed.
3804
+ # NOTE: Timeout always results in denial. This is not configurable (SEC-002).
3681
3805
  approval_channel:
3682
3806
  type: stderr
3683
3807
  timeout_seconds: 300
3684
- auto_deny: true
3685
3808
  `;
3686
3809
  }
3687
3810
  async function loadPrincipalPolicy(storagePath) {
@@ -3858,27 +3981,16 @@ var BaselineTracker = class {
3858
3981
 
3859
3982
  // src/principal-policy/approval-channel.ts
3860
3983
  var StderrApprovalChannel = class {
3861
- config;
3862
- constructor(config) {
3863
- this.config = config;
3984
+ constructor(_config) {
3864
3985
  }
3865
3986
  async requestApproval(request) {
3866
3987
  const prompt = this.formatPrompt(request);
3867
3988
  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
- }
3989
+ return {
3990
+ decision: "deny",
3991
+ decided_at: (/* @__PURE__ */ new Date()).toISOString(),
3992
+ decided_by: "stderr:non-interactive"
3993
+ };
3882
3994
  }
3883
3995
  formatPrompt(request) {
3884
3996
  const tierLabel = request.tier === 1 ? "Tier 1 \u2014 always requires approval" : "Tier 2 \u2014 behavioral anomaly detected";
@@ -3886,7 +3998,7 @@ var StderrApprovalChannel = class {
3886
3998
  return [
3887
3999
  "",
3888
4000
  "\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",
4001
+ "\u2551 SANCTUARY: Operation Denied (non-interactive channel) \u2551",
3890
4002
  "\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
4003
  `\u2551 Operation: ${request.operation.padEnd(50)}\u2551`,
3892
4004
  `\u2551 ${tierLabel.padEnd(62)}\u2551`,
@@ -3897,7 +4009,8 @@ var StderrApprovalChannel = class {
3897
4009
  (line) => `\u2551 ${line.padEnd(60)}\u2551`
3898
4010
  ),
3899
4011
  "\u2551 \u2551",
3900
- this.config.auto_deny ? "\u2551 Auto-denying (configure approval_channel.auto_deny to change) \u2551" : "\u2551 Auto-approving (informational mode) \u2551",
4012
+ "\u2551 Denied: stderr channel cannot accept input (SEC-016) \u2551",
4013
+ "\u2551 Use dashboard or webhook channel for interactive approval. \u2551",
3901
4014
  "\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
4015
  ""
3903
4016
  ].join("\n");
@@ -4219,20 +4332,38 @@ function generateDashboardHTML(options) {
4219
4332
  <script>
4220
4333
  (function() {
4221
4334
  const TIMEOUT = ${options.timeoutSeconds};
4222
- const AUTH_TOKEN = ${options.authToken ? `'${options.authToken}'` : "null"};
4335
+ // SEC-012: Auth token is passed via Authorization header only \u2014 never in URLs.
4336
+ // The token is provided by the server at generation time (embedded for initial auth).
4337
+ const AUTH_TOKEN = ${options.authToken ? JSON.stringify(options.authToken) : "null"};
4338
+ let SESSION_ID = null; // Short-lived session for SSE and URL-based requests
4223
4339
  const pending = new Map();
4224
4340
  let auditCount = 0;
4225
4341
 
4226
- // Auth helpers
4342
+ // Auth helpers \u2014 SEC-012: token goes in header, session goes in URL
4227
4343
  function authHeaders() {
4228
4344
  const h = { 'Content-Type': 'application/json' };
4229
4345
  if (AUTH_TOKEN) h['Authorization'] = 'Bearer ' + AUTH_TOKEN;
4230
4346
  return h;
4231
4347
  }
4232
- function authQuery(url) {
4233
- if (!AUTH_TOKEN) return url;
4348
+ function sessionQuery(url) {
4349
+ if (!SESSION_ID) return url;
4234
4350
  const sep = url.includes('?') ? '&' : '?';
4235
- return url + sep + 'token=' + AUTH_TOKEN;
4351
+ return url + sep + 'session=' + SESSION_ID;
4352
+ }
4353
+
4354
+ // SEC-012: Exchange the long-lived token for a short-lived session
4355
+ async function exchangeSession() {
4356
+ if (!AUTH_TOKEN) return;
4357
+ try {
4358
+ const resp = await fetch('/auth/session', { method: 'POST', headers: authHeaders() });
4359
+ if (resp.ok) {
4360
+ const data = await resp.json();
4361
+ SESSION_ID = data.session_id;
4362
+ // Refresh session before expiry (at 80% of TTL)
4363
+ const refreshMs = (data.expires_in_seconds || 300) * 800;
4364
+ setTimeout(async () => { await exchangeSession(); reconnectSSE(); }, refreshMs);
4365
+ }
4366
+ } catch(e) { /* will retry on next connect */ }
4236
4367
  }
4237
4368
 
4238
4369
  // Tab switching
@@ -4245,10 +4376,14 @@ function generateDashboardHTML(options) {
4245
4376
  });
4246
4377
  });
4247
4378
 
4248
- // SSE Connection
4379
+ // SSE Connection \u2014 SEC-012: uses short-lived session token in URL, not auth token
4249
4380
  let evtSource;
4381
+ function reconnectSSE() {
4382
+ if (evtSource) { evtSource.close(); }
4383
+ connect();
4384
+ }
4250
4385
  function connect() {
4251
- evtSource = new EventSource(authQuery('/events'));
4386
+ evtSource = new EventSource(sessionQuery('/events'));
4252
4387
  evtSource.onopen = () => {
4253
4388
  document.getElementById('statusDot').classList.remove('disconnected');
4254
4389
  document.getElementById('statusText').textContent = 'Connected';
@@ -4436,12 +4571,20 @@ function generateDashboardHTML(options) {
4436
4571
  return d.innerHTML;
4437
4572
  }
4438
4573
 
4439
- // Init
4440
- connect();
4441
- fetch('/api/status', { headers: authHeaders() }).then(r => r.json()).then(data => {
4442
- if (data.baseline) updateBaseline(data.baseline);
4443
- if (data.policy) updatePolicy(data.policy);
4444
- }).catch(() => {});
4574
+ // Init \u2014 SEC-012: exchange token for session before connecting SSE
4575
+ (async function init() {
4576
+ await exchangeSession();
4577
+ // Clean token from URL if present (legacy bookmarks)
4578
+ if (window.location.search.includes('token=')) {
4579
+ const clean = window.location.pathname;
4580
+ window.history.replaceState({}, '', clean);
4581
+ }
4582
+ connect();
4583
+ fetch('/api/status', { headers: authHeaders() }).then(r => r.json()).then(data => {
4584
+ if (data.baseline) updateBaseline(data.baseline);
4585
+ if (data.policy) updatePolicy(data.policy);
4586
+ }).catch(() => {});
4587
+ })();
4445
4588
  })();
4446
4589
  </script>
4447
4590
  </body>
@@ -4449,6 +4592,14 @@ function generateDashboardHTML(options) {
4449
4592
  }
4450
4593
 
4451
4594
  // src/principal-policy/dashboard.ts
4595
+ var require4 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
4596
+ var { version: PKG_VERSION3 } = require4("../../package.json");
4597
+ var SESSION_TTL_MS = 5 * 60 * 1e3;
4598
+ var MAX_SESSIONS = 1e3;
4599
+ var RATE_LIMIT_WINDOW_MS = 6e4;
4600
+ var RATE_LIMIT_GENERAL = 120;
4601
+ var RATE_LIMIT_DECISIONS = 20;
4602
+ var MAX_RATE_LIMIT_ENTRIES = 1e4;
4452
4603
  var DashboardApprovalChannel = class {
4453
4604
  config;
4454
4605
  pending = /* @__PURE__ */ new Map();
@@ -4460,15 +4611,21 @@ var DashboardApprovalChannel = class {
4460
4611
  dashboardHTML;
4461
4612
  authToken;
4462
4613
  useTLS;
4614
+ /** SEC-012: Short-lived session store. Sessions replace URL query tokens. */
4615
+ sessions = /* @__PURE__ */ new Map();
4616
+ sessionCleanupTimer = null;
4617
+ /** Rate limiting: per-IP request tracking */
4618
+ rateLimits = /* @__PURE__ */ new Map();
4463
4619
  constructor(config) {
4464
4620
  this.config = config;
4465
4621
  this.authToken = config.auth_token;
4466
4622
  this.useTLS = !!(config.tls?.cert_path && config.tls?.key_path);
4467
4623
  this.dashboardHTML = generateDashboardHTML({
4468
4624
  timeoutSeconds: config.timeout_seconds,
4469
- serverVersion: "0.3.0",
4625
+ serverVersion: PKG_VERSION3,
4470
4626
  authToken: this.authToken
4471
4627
  });
4628
+ this.sessionCleanupTimer = setInterval(() => this.cleanupSessions(), 6e4);
4472
4629
  }
4473
4630
  /**
4474
4631
  * Inject dependencies after construction.
@@ -4498,13 +4655,14 @@ var DashboardApprovalChannel = class {
4498
4655
  const baseUrl = `${protocol}://${this.config.host}:${this.config.port}`;
4499
4656
  this.httpServer.listen(this.config.port, this.config.host, () => {
4500
4657
  if (this.authToken) {
4658
+ const hint = this.authToken.slice(0, 4) + "..." + this.authToken.slice(-4);
4501
4659
  process.stderr.write(
4502
4660
  `
4503
- Sanctuary Principal Dashboard: ${baseUrl}/?token=${this.authToken}
4661
+ Sanctuary Principal Dashboard: ${baseUrl}
4504
4662
  `
4505
4663
  );
4506
4664
  process.stderr.write(
4507
- ` Auth token: ${this.authToken}
4665
+ ` Auth required (token: ${hint}). Use Authorization: Bearer <TOKEN> header.
4508
4666
 
4509
4667
  `
4510
4668
  );
@@ -4538,6 +4696,12 @@ var DashboardApprovalChannel = class {
4538
4696
  client.end();
4539
4697
  }
4540
4698
  this.sseClients.clear();
4699
+ this.sessions.clear();
4700
+ if (this.sessionCleanupTimer) {
4701
+ clearInterval(this.sessionCleanupTimer);
4702
+ this.sessionCleanupTimer = null;
4703
+ }
4704
+ this.rateLimits.clear();
4541
4705
  if (this.httpServer) {
4542
4706
  return new Promise((resolve) => {
4543
4707
  this.httpServer.close(() => resolve());
@@ -4558,7 +4722,8 @@ var DashboardApprovalChannel = class {
4558
4722
  const timer = setTimeout(() => {
4559
4723
  this.pending.delete(id);
4560
4724
  const response = {
4561
- decision: this.config.auto_deny ? "deny" : "approve",
4725
+ // SEC-002: Timeout ALWAYS denies. No configuration can change this.
4726
+ decision: "deny",
4562
4727
  decided_at: (/* @__PURE__ */ new Date()).toISOString(),
4563
4728
  decided_by: "timeout"
4564
4729
  };
@@ -4590,7 +4755,12 @@ var DashboardApprovalChannel = class {
4590
4755
  // ── Authentication ──────────────────────────────────────────────────
4591
4756
  /**
4592
4757
  * Verify bearer token authentication.
4593
- * Checks Authorization header first, falls back to ?token= query param.
4758
+ *
4759
+ * SEC-012: The long-lived auth token is ONLY accepted via the Authorization
4760
+ * header — never in URL query strings. For SSE and page loads that cannot
4761
+ * set headers, a short-lived session token (obtained via POST /auth/session)
4762
+ * is accepted via ?session= query parameter.
4763
+ *
4594
4764
  * Returns true if auth passes, false if blocked (response already sent).
4595
4765
  */
4596
4766
  checkAuth(req, url, res) {
@@ -4602,19 +4772,126 @@ var DashboardApprovalChannel = class {
4602
4772
  return true;
4603
4773
  }
4604
4774
  }
4605
- const queryToken = url.searchParams.get("token");
4606
- if (queryToken === this.authToken) {
4775
+ const sessionId = url.searchParams.get("session");
4776
+ if (sessionId && this.validateSession(sessionId)) {
4607
4777
  return true;
4608
4778
  }
4609
4779
  res.writeHead(401, { "Content-Type": "application/json" });
4610
- res.end(JSON.stringify({ error: "Unauthorized \u2014 valid bearer token required" }));
4780
+ res.end(JSON.stringify({ error: "Unauthorized \u2014 use Authorization: Bearer header or a valid session" }));
4611
4781
  return false;
4612
4782
  }
4783
+ // ── Session Management (SEC-012) ──────────────────────────────────
4784
+ /**
4785
+ * Create a short-lived session by exchanging the long-lived auth token
4786
+ * (provided in the Authorization header) for a session ID.
4787
+ */
4788
+ createSession() {
4789
+ if (this.sessions.size >= MAX_SESSIONS) {
4790
+ this.cleanupSessions();
4791
+ if (this.sessions.size >= MAX_SESSIONS) {
4792
+ const oldest = [...this.sessions.entries()].sort(
4793
+ (a, b) => a[1].created_at - b[1].created_at
4794
+ )[0];
4795
+ if (oldest) this.sessions.delete(oldest[0]);
4796
+ }
4797
+ }
4798
+ const id = crypto.randomBytes(32).toString("hex");
4799
+ const now = Date.now();
4800
+ this.sessions.set(id, {
4801
+ id,
4802
+ created_at: now,
4803
+ expires_at: now + SESSION_TTL_MS
4804
+ });
4805
+ return id;
4806
+ }
4807
+ /**
4808
+ * Validate a session ID — must exist and not be expired.
4809
+ */
4810
+ validateSession(sessionId) {
4811
+ const session = this.sessions.get(sessionId);
4812
+ if (!session) return false;
4813
+ if (Date.now() > session.expires_at) {
4814
+ this.sessions.delete(sessionId);
4815
+ return false;
4816
+ }
4817
+ return true;
4818
+ }
4819
+ /**
4820
+ * Remove all expired sessions.
4821
+ */
4822
+ cleanupSessions() {
4823
+ const now = Date.now();
4824
+ for (const [id, session] of this.sessions) {
4825
+ if (now > session.expires_at) {
4826
+ this.sessions.delete(id);
4827
+ }
4828
+ }
4829
+ }
4830
+ // ── Rate Limiting ─────────────────────────────────────────────────
4831
+ /**
4832
+ * Get the remote address from a request, normalizing IPv6-mapped IPv4.
4833
+ */
4834
+ getRemoteAddr(req) {
4835
+ const addr = req.socket.remoteAddress ?? "unknown";
4836
+ return addr.startsWith("::ffff:") ? addr.slice(7) : addr;
4837
+ }
4838
+ /**
4839
+ * Check rate limit for a request. Returns true if allowed, false if rate-limited.
4840
+ * When rate-limited, sends a 429 response.
4841
+ */
4842
+ checkRateLimit(req, res, type) {
4843
+ const addr = this.getRemoteAddr(req);
4844
+ const now = Date.now();
4845
+ const windowStart = now - RATE_LIMIT_WINDOW_MS;
4846
+ let entry = this.rateLimits.get(addr);
4847
+ if (!entry) {
4848
+ if (this.rateLimits.size >= MAX_RATE_LIMIT_ENTRIES) {
4849
+ this.pruneRateLimits(now);
4850
+ }
4851
+ entry = { general: [], decisions: [] };
4852
+ this.rateLimits.set(addr, entry);
4853
+ }
4854
+ entry.general = entry.general.filter((t) => t > windowStart);
4855
+ entry.decisions = entry.decisions.filter((t) => t > windowStart);
4856
+ const limit = type === "decisions" ? RATE_LIMIT_DECISIONS : RATE_LIMIT_GENERAL;
4857
+ const timestamps = entry[type];
4858
+ if (timestamps.length >= limit) {
4859
+ const retryAfter = Math.ceil((timestamps[0] + RATE_LIMIT_WINDOW_MS - now) / 1e3);
4860
+ res.writeHead(429, {
4861
+ "Content-Type": "application/json",
4862
+ "Retry-After": String(Math.max(1, retryAfter))
4863
+ });
4864
+ res.end(JSON.stringify({
4865
+ error: "Rate limit exceeded",
4866
+ retry_after_seconds: Math.max(1, retryAfter)
4867
+ }));
4868
+ return false;
4869
+ }
4870
+ timestamps.push(now);
4871
+ return true;
4872
+ }
4873
+ /**
4874
+ * Remove stale entries from the rate limit map.
4875
+ */
4876
+ pruneRateLimits(now) {
4877
+ const windowStart = now - RATE_LIMIT_WINDOW_MS;
4878
+ for (const [addr, entry] of this.rateLimits) {
4879
+ const hasRecent = entry.general.some((t) => t > windowStart) || entry.decisions.some((t) => t > windowStart);
4880
+ if (!hasRecent) {
4881
+ this.rateLimits.delete(addr);
4882
+ }
4883
+ }
4884
+ }
4613
4885
  // ── HTTP Request Handler ────────────────────────────────────────────
4614
4886
  handleRequest(req, res) {
4615
4887
  const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
4616
4888
  const method = req.method ?? "GET";
4617
- res.setHeader("Access-Control-Allow-Origin", "*");
4889
+ const origin = req.headers.origin;
4890
+ const protocol = this.useTLS ? "https" : "http";
4891
+ const selfOrigin = `${protocol}://${this.config.host}:${this.config.port}`;
4892
+ if (origin === selfOrigin) {
4893
+ res.setHeader("Access-Control-Allow-Origin", origin);
4894
+ }
4618
4895
  res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
4619
4896
  res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
4620
4897
  if (method === "OPTIONS") {
@@ -4623,7 +4900,12 @@ var DashboardApprovalChannel = class {
4623
4900
  return;
4624
4901
  }
4625
4902
  if (!this.checkAuth(req, url, res)) return;
4903
+ if (!this.checkRateLimit(req, res, "general")) return;
4626
4904
  try {
4905
+ if (method === "POST" && url.pathname === "/auth/session") {
4906
+ this.handleSessionExchange(req, res);
4907
+ return;
4908
+ }
4627
4909
  if (method === "GET" && url.pathname === "/") {
4628
4910
  this.serveDashboard(res);
4629
4911
  } else if (method === "GET" && url.pathname === "/events") {
@@ -4635,9 +4917,11 @@ var DashboardApprovalChannel = class {
4635
4917
  } else if (method === "GET" && url.pathname === "/api/audit-log") {
4636
4918
  this.handleAuditLog(url, res);
4637
4919
  } else if (method === "POST" && url.pathname.startsWith("/api/approve/")) {
4920
+ if (!this.checkRateLimit(req, res, "decisions")) return;
4638
4921
  const id = url.pathname.slice("/api/approve/".length);
4639
4922
  this.handleDecision(id, "approve", res);
4640
4923
  } else if (method === "POST" && url.pathname.startsWith("/api/deny/")) {
4924
+ if (!this.checkRateLimit(req, res, "decisions")) return;
4641
4925
  const id = url.pathname.slice("/api/deny/".length);
4642
4926
  this.handleDecision(id, "deny", res);
4643
4927
  } else {
@@ -4650,6 +4934,40 @@ var DashboardApprovalChannel = class {
4650
4934
  }
4651
4935
  }
4652
4936
  // ── Route Handlers ──────────────────────────────────────────────────
4937
+ /**
4938
+ * SEC-012: Exchange a long-lived auth token (in Authorization header)
4939
+ * for a short-lived session ID. The session ID can be used in URL
4940
+ * query parameters without exposing the long-lived credential.
4941
+ *
4942
+ * This endpoint performs its OWN auth check (header-only) because it
4943
+ * must reject query-parameter tokens and is called before the
4944
+ * normal checkAuth flow.
4945
+ */
4946
+ handleSessionExchange(req, res) {
4947
+ if (!this.authToken) {
4948
+ res.writeHead(200, { "Content-Type": "application/json" });
4949
+ res.end(JSON.stringify({ session_id: "no-auth" }));
4950
+ return;
4951
+ }
4952
+ const authHeader = req.headers.authorization;
4953
+ if (!authHeader) {
4954
+ res.writeHead(401, { "Content-Type": "application/json" });
4955
+ res.end(JSON.stringify({ error: "Authorization header required" }));
4956
+ return;
4957
+ }
4958
+ const parts = authHeader.split(" ");
4959
+ if (parts.length !== 2 || parts[0] !== "Bearer" || parts[1] !== this.authToken) {
4960
+ res.writeHead(401, { "Content-Type": "application/json" });
4961
+ res.end(JSON.stringify({ error: "Invalid bearer token" }));
4962
+ return;
4963
+ }
4964
+ const sessionId = this.createSession();
4965
+ res.writeHead(200, { "Content-Type": "application/json" });
4966
+ res.end(JSON.stringify({
4967
+ session_id: sessionId,
4968
+ expires_in_seconds: SESSION_TTL_MS / 1e3
4969
+ }));
4970
+ }
4653
4971
  serveDashboard(res) {
4654
4972
  res.writeHead(200, {
4655
4973
  "Content-Type": "text/html; charset=utf-8",
@@ -4675,7 +4993,8 @@ var DashboardApprovalChannel = class {
4675
4993
  approval_channel: {
4676
4994
  type: this.policy.approval_channel.type,
4677
4995
  timeout_seconds: this.policy.approval_channel.timeout_seconds,
4678
- auto_deny: this.policy.approval_channel.auto_deny
4996
+ auto_deny: true
4997
+ // SEC-002: hardcoded, not configurable
4679
4998
  }
4680
4999
  };
4681
5000
  }
@@ -4716,7 +5035,8 @@ data: ${JSON.stringify(initData)}
4716
5035
  approval_channel: {
4717
5036
  type: this.policy.approval_channel.type,
4718
5037
  timeout_seconds: this.policy.approval_channel.timeout_seconds,
4719
- auto_deny: this.policy.approval_channel.auto_deny
5038
+ auto_deny: true
5039
+ // SEC-002: hardcoded, not configurable
4720
5040
  }
4721
5041
  };
4722
5042
  }
@@ -4889,7 +5209,8 @@ var WebhookApprovalChannel = class {
4889
5209
  const timer = setTimeout(() => {
4890
5210
  this.pending.delete(id);
4891
5211
  const response = {
4892
- decision: this.config.auto_deny ? "deny" : "approve",
5212
+ // SEC-002: Timeout ALWAYS denies. No configuration can change this.
5213
+ decision: "deny",
4893
5214
  decided_at: (/* @__PURE__ */ new Date()).toISOString(),
4894
5215
  decided_by: "timeout"
4895
5216
  };
@@ -5077,16 +5398,29 @@ var ApprovalGate = class {
5077
5398
  if (anomaly) {
5078
5399
  return this.requestApproval(operation, 2, anomaly.reason, anomaly.context);
5079
5400
  }
5080
- this.auditLog.append("l2", `gate_allow:${operation}`, "system", {
5081
- tier: 3,
5082
- operation
5401
+ if (this.policy.tier3_always_allow.includes(operation)) {
5402
+ this.auditLog.append("l2", `gate_allow:${operation}`, "system", {
5403
+ tier: 3,
5404
+ operation
5405
+ });
5406
+ return {
5407
+ allowed: true,
5408
+ tier: 3,
5409
+ reason: "Operation allowed (Tier 3)",
5410
+ approval_required: false
5411
+ };
5412
+ }
5413
+ this.auditLog.append("l2", `gate_unclassified:${operation}`, "system", {
5414
+ tier: 1,
5415
+ operation,
5416
+ warning: "Operation is not classified in any policy tier \u2014 defaulting to Tier 1 (require approval)"
5083
5417
  });
5084
- return {
5085
- allowed: true,
5086
- tier: 3,
5087
- reason: "Operation allowed (Tier 3)",
5088
- approval_required: false
5089
- };
5418
+ return this.requestApproval(
5419
+ operation,
5420
+ 1,
5421
+ `"${operation}" is not classified in any policy tier \u2014 requires approval (SEC-011 safe default)`,
5422
+ { operation, unclassified: true }
5423
+ );
5090
5424
  }
5091
5425
  /**
5092
5426
  * Detect Tier 2 behavioral anomalies.
@@ -5259,7 +5593,8 @@ function createPrincipalPolicyTools(policy, baseline, auditLog) {
5259
5593
  approval_channel: {
5260
5594
  type: policy.approval_channel.type,
5261
5595
  timeout_seconds: policy.approval_channel.timeout_seconds,
5262
- auto_deny: policy.approval_channel.auto_deny
5596
+ auto_deny: true
5597
+ // SEC-002: hardcoded, not configurable
5263
5598
  }
5264
5599
  };
5265
5600
  if (includeDefaults) {
@@ -5329,14 +5664,14 @@ function generateSHR(identityId, opts) {
5329
5664
  code: "PROCESS_ISOLATION_ONLY",
5330
5665
  severity: "warning",
5331
5666
  description: "Process-level isolation only (no TEE)",
5332
- mitigation: "TEE support planned for v0.3.0"
5667
+ mitigation: "TEE support planned for a future release"
5333
5668
  });
5334
5669
  degradations.push({
5335
5670
  layer: "l2",
5336
5671
  code: "SELF_REPORTED_ATTESTATION",
5337
5672
  severity: "warning",
5338
5673
  description: "Attestation is self-reported (no hardware root of trust)",
5339
- mitigation: "TEE attestation planned for v0.3.0"
5674
+ mitigation: "TEE attestation planned for a future release"
5340
5675
  });
5341
5676
  }
5342
5677
  if (config.disclosure.proof_system === "commitment-only") {
@@ -5480,6 +5815,245 @@ function assessSovereigntyLevel(body) {
5480
5815
  return "minimal";
5481
5816
  }
5482
5817
 
5818
+ // src/shr/gateway-adapter.ts
5819
+ var LAYER_WEIGHTS = {
5820
+ l1: 100,
5821
+ l2: 100,
5822
+ l3: 100,
5823
+ l4: 100
5824
+ };
5825
+ var DEGRADATION_IMPACT = {
5826
+ critical: 40,
5827
+ warning: 25,
5828
+ info: 10
5829
+ };
5830
+ function transformSHRForGateway(shr) {
5831
+ const { body, signed_by, signature } = shr;
5832
+ const layerScores = calculateLayerScores(body);
5833
+ const overallScore = calculateOverallScore(layerScores);
5834
+ const trustLevel = determineTrustLevel(overallScore);
5835
+ const signals = extractAuthorizationSignals(body);
5836
+ const degradations = transformDegradations(body.degradations);
5837
+ const constraints = generateAuthorizationConstraints(body);
5838
+ return {
5839
+ shr_version: body.shr_version,
5840
+ agent_identity: signed_by,
5841
+ generated_at: (/* @__PURE__ */ new Date()).toISOString(),
5842
+ context_expires_at: body.expires_at,
5843
+ overall_score: overallScore,
5844
+ recommended_trust_level: trustLevel,
5845
+ layer_scores: {
5846
+ l1_cognitive: layerScores.l1,
5847
+ l2_operational: layerScores.l2,
5848
+ l3_disclosure: layerScores.l3,
5849
+ l4_reputation: layerScores.l4
5850
+ },
5851
+ layer_status: {
5852
+ l1_cognitive: body.layers.l1.status,
5853
+ l2_operational: body.layers.l2.status,
5854
+ l3_disclosure: body.layers.l3.status,
5855
+ l4_reputation: body.layers.l4.status
5856
+ },
5857
+ authorization_signals: signals,
5858
+ degradations,
5859
+ recommended_constraints: constraints,
5860
+ shr_signature: signature,
5861
+ shr_signed_by: signed_by
5862
+ };
5863
+ }
5864
+ function calculateLayerScores(body) {
5865
+ const layers = body.layers;
5866
+ const degradations = body.degradations;
5867
+ let l1Score = LAYER_WEIGHTS.l1;
5868
+ let l2Score = LAYER_WEIGHTS.l2;
5869
+ let l3Score = LAYER_WEIGHTS.l3;
5870
+ let l4Score = LAYER_WEIGHTS.l4;
5871
+ for (const deg of degradations) {
5872
+ const impact = DEGRADATION_IMPACT[deg.severity] || 10;
5873
+ if (deg.layer === "l1") {
5874
+ l1Score = Math.max(0, l1Score - impact);
5875
+ } else if (deg.layer === "l2") {
5876
+ l2Score = Math.max(0, l2Score - impact);
5877
+ } else if (deg.layer === "l3") {
5878
+ l3Score = Math.max(0, l3Score - impact);
5879
+ } else if (deg.layer === "l4") {
5880
+ l4Score = Math.max(0, l4Score - impact);
5881
+ }
5882
+ }
5883
+ if (layers.l1.status === "active" && l1Score > 50) l1Score = Math.min(100, l1Score + 5);
5884
+ if (layers.l2.status === "active" && l2Score > 50) l2Score = Math.min(100, l2Score + 5);
5885
+ if (layers.l3.status === "active" && l3Score > 50) l3Score = Math.min(100, l3Score + 5);
5886
+ if (layers.l4.status === "active" && l4Score > 50) l4Score = Math.min(100, l4Score + 5);
5887
+ if (layers.l1.status === "inactive") l1Score = 0;
5888
+ if (layers.l2.status === "inactive") l2Score = 0;
5889
+ if (layers.l3.status === "inactive") l3Score = 0;
5890
+ if (layers.l4.status === "inactive") l4Score = 0;
5891
+ return {
5892
+ l1: Math.round(l1Score),
5893
+ l2: Math.round(l2Score),
5894
+ l3: Math.round(l3Score),
5895
+ l4: Math.round(l4Score)
5896
+ };
5897
+ }
5898
+ function calculateOverallScore(layerScores) {
5899
+ const average = (layerScores.l1 + layerScores.l2 + layerScores.l3 + layerScores.l4) / 4;
5900
+ return Math.round(average);
5901
+ }
5902
+ function determineTrustLevel(score) {
5903
+ if (score >= 80) return "full";
5904
+ if (score >= 60) return "elevated";
5905
+ if (score >= 40) return "standard";
5906
+ return "restricted";
5907
+ }
5908
+ function extractAuthorizationSignals(body) {
5909
+ const l1 = body.layers.l1;
5910
+ const l3 = body.layers.l3;
5911
+ const l4 = body.layers.l4;
5912
+ return {
5913
+ approval_gate_active: body.capabilities.handshake,
5914
+ // Handshake implies human loop capability
5915
+ context_gating_active: body.capabilities.encrypted_channel,
5916
+ // Proxy for gating capability
5917
+ encryption_at_rest: l1.encryption !== "none" && l1.encryption !== "unencrypted",
5918
+ behavioral_baseline_active: false,
5919
+ // Would need explicit field in SHR v1.1
5920
+ identity_verified: l1.identity_type === "ed25519" || l1.identity_type !== "none",
5921
+ zero_knowledge_capable: l3.status === "active" && l3.proof_system !== "commitment-only",
5922
+ selective_disclosure_active: l3.selective_disclosure,
5923
+ reputation_portable: l4.reputation_portable,
5924
+ handshake_capable: body.capabilities.handshake
5925
+ };
5926
+ }
5927
+ function transformDegradations(degradations) {
5928
+ return degradations.map((deg) => {
5929
+ let authzImpact = "";
5930
+ if (deg.code === "NO_TEE") {
5931
+ authzImpact = "Restricted to read-only operations until TEE available";
5932
+ } else if (deg.code === "PROCESS_ISOLATION_ONLY") {
5933
+ authzImpact = "Requires additional identity verification";
5934
+ } else if (deg.code === "COMMITMENT_ONLY") {
5935
+ authzImpact = "Limited data sharing scope \u2014 no zero-knowledge proofs";
5936
+ } else if (deg.code === "NO_ZK_PROOFS") {
5937
+ authzImpact = "Cannot perform confidential disclosures";
5938
+ } else if (deg.code === "SELF_REPORTED_ATTESTATION") {
5939
+ authzImpact = "Attestation trust degraded \u2014 human verification recommended";
5940
+ } else if (deg.code === "NO_SELECTIVE_DISCLOSURE") {
5941
+ authzImpact = "Must share entire data context, cannot redact";
5942
+ } else if (deg.code === "BASIC_SYBIL_ONLY") {
5943
+ authzImpact = "Restrict to interactions with known agents only";
5944
+ } else {
5945
+ authzImpact = "Unknown authorization impact";
5946
+ }
5947
+ return {
5948
+ layer: deg.layer,
5949
+ code: deg.code,
5950
+ severity: deg.severity,
5951
+ description: deg.description,
5952
+ authorization_impact: authzImpact
5953
+ };
5954
+ });
5955
+ }
5956
+ function generateAuthorizationConstraints(body, _degradations) {
5957
+ const constraints = [];
5958
+ const layers = body.layers;
5959
+ if (layers.l1.status === "degraded" || layers.l1.key_custody !== "self") {
5960
+ constraints.push({
5961
+ type: "identity_verification_required",
5962
+ description: "Additional identity verification required for sensitive operations",
5963
+ rationale: "L1 is degraded or key custody is not self-managed",
5964
+ priority: "high"
5965
+ });
5966
+ }
5967
+ if (!layers.l1.state_portable) {
5968
+ constraints.push({
5969
+ type: "location_bound",
5970
+ description: "Agent state is not portable \u2014 restrict to home environment",
5971
+ rationale: "State cannot be safely migrated across boundaries",
5972
+ priority: "medium"
5973
+ });
5974
+ }
5975
+ if (layers.l2.status === "degraded" || layers.l2.isolation_type === "local-process") {
5976
+ constraints.push({
5977
+ type: "read_only",
5978
+ description: "Restrict to read-only operations until operational isolation improves",
5979
+ rationale: "L2 isolation is process-level only (no TEE)",
5980
+ priority: "high"
5981
+ });
5982
+ }
5983
+ if (!layers.l2.attestation_available) {
5984
+ constraints.push({
5985
+ type: "requires_approval",
5986
+ description: "Human approval required for writes and sensitive reads",
5987
+ rationale: "No attestation available \u2014 self-reported integrity only",
5988
+ priority: "high"
5989
+ });
5990
+ }
5991
+ if (layers.l3.status === "degraded" || !layers.l3.selective_disclosure) {
5992
+ constraints.push({
5993
+ type: "restricted_scope",
5994
+ description: "Limit data sharing to minimal required scope \u2014 no selective disclosure",
5995
+ rationale: "Agent cannot redact data or prove predicates without revealing all context",
5996
+ priority: "high"
5997
+ });
5998
+ }
5999
+ if (layers.l3.proof_system === "commitment-only") {
6000
+ constraints.push({
6001
+ type: "restricted_scope",
6002
+ description: "No zero-knowledge proofs available \u2014 entire state context may be visible",
6003
+ rationale: "Proof system is commitment-only (no ZK)",
6004
+ priority: "medium"
6005
+ });
6006
+ }
6007
+ if (layers.l4.status === "degraded") {
6008
+ constraints.push({
6009
+ type: "known_agents_only",
6010
+ description: "Restrict interactions to known, pre-approved agents",
6011
+ rationale: "Reputation layer is degraded",
6012
+ priority: "medium"
6013
+ });
6014
+ }
6015
+ if (!layers.l4.reputation_portable) {
6016
+ constraints.push({
6017
+ type: "location_bound",
6018
+ description: "Reputation is not portable \u2014 restrict to home environment",
6019
+ rationale: "Cannot present reputation to external parties",
6020
+ priority: "low"
6021
+ });
6022
+ }
6023
+ const layerScores = calculateLayerScores(body);
6024
+ const overallScore = calculateOverallScore(layerScores);
6025
+ if (overallScore < 40) {
6026
+ constraints.push({
6027
+ type: "restricted_scope",
6028
+ description: "Overall sovereignty score below threshold \u2014 restrict to non-sensitive operations",
6029
+ rationale: `Overall sovereignty score is ${overallScore}/100`,
6030
+ priority: "high"
6031
+ });
6032
+ }
6033
+ return constraints;
6034
+ }
6035
+ function transformSHRGeneric(shr) {
6036
+ const context = transformSHRForGateway(shr);
6037
+ return {
6038
+ agent_id: context.agent_identity,
6039
+ sovereignty_score: context.overall_score,
6040
+ trust_level: context.recommended_trust_level,
6041
+ layer_scores: {
6042
+ l1: context.layer_scores.l1_cognitive,
6043
+ l2: context.layer_scores.l2_operational,
6044
+ l3: context.layer_scores.l3_disclosure,
6045
+ l4: context.layer_scores.l4_reputation
6046
+ },
6047
+ capabilities: context.authorization_signals,
6048
+ constraints: context.recommended_constraints.map((c) => ({
6049
+ type: c.type,
6050
+ description: c.description
6051
+ })),
6052
+ expires_at: context.context_expires_at,
6053
+ signature: context.shr_signature
6054
+ };
6055
+ }
6056
+
5483
6057
  // src/shr/tools.ts
5484
6058
  function createSHRTools(config, identityManager, masterKey, auditLog) {
5485
6059
  const generatorOpts = {
@@ -5542,6 +6116,53 @@ function createSHRTools(config, identityManager, masterKey, auditLog) {
5542
6116
  );
5543
6117
  return toolResult(result);
5544
6118
  }
6119
+ },
6120
+ {
6121
+ name: "sanctuary/shr_gateway_export",
6122
+ 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.",
6123
+ inputSchema: {
6124
+ type: "object",
6125
+ properties: {
6126
+ format: {
6127
+ type: "string",
6128
+ enum: ["ping", "generic"],
6129
+ description: "Output format: 'ping' (Ping Identity Gateway format) or 'generic' (format-agnostic). Default: 'ping'."
6130
+ },
6131
+ identity_id: {
6132
+ type: "string",
6133
+ description: "Identity to sign the SHR with. Defaults to primary identity."
6134
+ },
6135
+ validity_minutes: {
6136
+ type: "number",
6137
+ description: "How long the SHR is valid (minutes). Default: 60."
6138
+ }
6139
+ }
6140
+ },
6141
+ handler: async (args) => {
6142
+ const format = args.format || "ping";
6143
+ const validityMs = args.validity_minutes ? args.validity_minutes * 60 * 1e3 : void 0;
6144
+ const shrResult = generateSHR(args.identity_id, {
6145
+ ...generatorOpts,
6146
+ validityMs
6147
+ });
6148
+ if (typeof shrResult === "string") {
6149
+ return toolResult({ error: shrResult });
6150
+ }
6151
+ let context;
6152
+ if (format === "generic") {
6153
+ context = transformSHRGeneric(shrResult);
6154
+ } else {
6155
+ context = transformSHRForGateway(shrResult);
6156
+ }
6157
+ auditLog.append(
6158
+ "l2",
6159
+ "shr_gateway_export",
6160
+ shrResult.body.instance_id,
6161
+ void 0,
6162
+ "success"
6163
+ );
6164
+ return toolResult(context);
6165
+ }
5545
6166
  }
5546
6167
  ];
5547
6168
  return { tools };
@@ -5790,7 +6411,9 @@ function createHandshakeTools(config, identityManager, masterKey, auditLog) {
5790
6411
  return toolResult({
5791
6412
  session_id: result.session.session_id,
5792
6413
  response: result.response,
5793
- instructions: "Send the 'response' object back to the initiator. When you receive their completion, pass it to sanctuary/handshake_status with this session_id."
6414
+ instructions: "Send the 'response' object back to the initiator. When you receive their completion, pass it to sanctuary/handshake_status with this session_id.",
6415
+ // SEC-ADD-03: Tag response — contains SHR data that will be sent to counterparty
6416
+ _content_trust: "external"
5794
6417
  });
5795
6418
  }
5796
6419
  },
@@ -5843,7 +6466,9 @@ function createHandshakeTools(config, identityManager, masterKey, auditLog) {
5843
6466
  return toolResult({
5844
6467
  completion: result.completion,
5845
6468
  result: result.result,
5846
- instructions: "Send the 'completion' object to the responder so they can verify the handshake. The 'result' object contains the verified counterparty status and trust tier."
6469
+ 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.",
6470
+ // SEC-ADD-03: Tag response as containing counterparty-controlled SHR data
6471
+ _content_trust: "external"
5847
6472
  });
5848
6473
  }
5849
6474
  },
@@ -6268,7 +6893,21 @@ function canonicalize(outcome) {
6268
6893
  return stringToBytes(stableStringify(outcome));
6269
6894
  }
6270
6895
  function stableStringify(value) {
6271
- if (value === null || value === void 0) return JSON.stringify(value);
6896
+ if (value === null) return "null";
6897
+ if (value === void 0) return "null";
6898
+ if (typeof value === "number") {
6899
+ if (!Number.isFinite(value)) {
6900
+ throw new Error(
6901
+ `Cannot canonicalize non-finite number: ${value}. NaN, Infinity, and -Infinity are not representable in JSON.`
6902
+ );
6903
+ }
6904
+ if (Object.is(value, -0)) {
6905
+ throw new Error(
6906
+ "Cannot canonicalize negative zero (-0). Use 0 instead for deterministic cross-language serialization."
6907
+ );
6908
+ }
6909
+ return JSON.stringify(value);
6910
+ }
6272
6911
  if (typeof value !== "object") return JSON.stringify(value);
6273
6912
  if (Array.isArray(value)) {
6274
6913
  return "[" + value.map((v) => stableStringify(v)).join(",") + "]";
@@ -6296,11 +6935,12 @@ function createBridgeCommitment(outcome, identity, identityEncryptionKey, includ
6296
6935
  bridge_commitment_id: commitmentId,
6297
6936
  session_id: outcome.session_id,
6298
6937
  sha256_commitment: sha2564.commitment,
6938
+ terms_hash: outcome.terms_hash,
6299
6939
  committer_did: identity.did,
6300
6940
  committed_at: now,
6301
6941
  bridge_version: "sanctuary-concordia-bridge-v1"
6302
6942
  };
6303
- const payloadBytes = stringToBytes(JSON.stringify(commitmentPayload));
6943
+ const payloadBytes = stringToBytes(stableStringify(commitmentPayload));
6304
6944
  const signature = sign(payloadBytes, identity.encrypted_private_key, identityEncryptionKey);
6305
6945
  return {
6306
6946
  bridge_commitment_id: commitmentId,
@@ -6326,11 +6966,12 @@ function verifyBridgeCommitment(commitment, outcome, committerPublicKey) {
6326
6966
  bridge_commitment_id: commitment.bridge_commitment_id,
6327
6967
  session_id: commitment.session_id,
6328
6968
  sha256_commitment: commitment.sha256_commitment,
6969
+ terms_hash: outcome.terms_hash,
6329
6970
  committer_did: commitment.committer_did,
6330
6971
  committed_at: commitment.committed_at,
6331
6972
  bridge_version: commitment.bridge_version
6332
6973
  };
6333
- const payloadBytes = stringToBytes(JSON.stringify(commitmentPayload));
6974
+ const payloadBytes = stringToBytes(stableStringify(commitmentPayload));
6334
6975
  const sigBytes = fromBase64url(commitment.signature);
6335
6976
  const signatureValid = verify(payloadBytes, sigBytes, committerPublicKey);
6336
6977
  const sessionIdMatch = commitment.session_id === outcome.session_id;
@@ -6557,7 +7198,9 @@ function createBridgeTools(storage, masterKey, identityManager, auditLog, handsh
6557
7198
  return toolResult({
6558
7199
  ...result,
6559
7200
  session_id: storedCommitment.session_id,
6560
- committer_did: storedCommitment.committer_did
7201
+ committer_did: storedCommitment.committer_did,
7202
+ // SEC-ADD-03: Tag response as containing counterparty-controlled data
7203
+ _content_trust: "external"
6561
7204
  });
6562
7205
  }
6563
7206
  },
@@ -6651,27 +7294,2245 @@ function createBridgeTools(storage, masterKey, identityManager, auditLog, handsh
6651
7294
  ];
6652
7295
  return { tools };
6653
7296
  }
6654
-
6655
- // src/index.ts
6656
- init_encoding();
6657
-
6658
- // src/storage/memory.ts
6659
- var MemoryStorage = class {
6660
- store = /* @__PURE__ */ new Map();
6661
- storageKey(namespace, key) {
6662
- return `${namespace}/${key}`;
6663
- }
6664
- async write(namespace, key, data) {
6665
- this.store.set(this.storageKey(namespace, key), {
6666
- data: new Uint8Array(data),
6667
- // Copy to prevent external mutation
6668
- modified_at: (/* @__PURE__ */ new Date()).toISOString()
6669
- });
7297
+ function lenientJsonParse(raw) {
7298
+ let cleaned = raw.replace(/\/\/[^\n]*/g, "");
7299
+ cleaned = cleaned.replace(/\/\*[\s\S]*?\*\//g, "");
7300
+ cleaned = cleaned.replace(/,\s*([\]}])/g, "$1");
7301
+ return JSON.parse(cleaned);
7302
+ }
7303
+ async function fileExists(path) {
7304
+ try {
7305
+ await promises.access(path);
7306
+ return true;
7307
+ } catch {
7308
+ return false;
6670
7309
  }
6671
- async read(namespace, key) {
6672
- const entry = this.store.get(this.storageKey(namespace, key));
6673
- if (!entry) return null;
6674
- return new Uint8Array(entry.data);
7310
+ }
7311
+ async function safeReadFile(path) {
7312
+ try {
7313
+ return await promises.readFile(path, "utf-8");
7314
+ } catch {
7315
+ return null;
7316
+ }
7317
+ }
7318
+ async function detectEnvironment(config, deepScan) {
7319
+ const fingerprint = {
7320
+ sanctuary_installed: true,
7321
+ // We're running inside Sanctuary
7322
+ sanctuary_version: config.version,
7323
+ openclaw_detected: false,
7324
+ openclaw_version: null,
7325
+ openclaw_config: null,
7326
+ node_version: process.version,
7327
+ platform: `${process.platform}-${process.arch}`
7328
+ };
7329
+ if (!deepScan) {
7330
+ return fingerprint;
7331
+ }
7332
+ const home = os.homedir();
7333
+ const openclawConfigPath = path.join(home, ".openclaw", "openclaw.json");
7334
+ const openclawEnvPath = path.join(home, ".openclaw", ".env");
7335
+ const openclawMemoryPath = path.join(home, ".openclaw", "workspace", "MEMORY.md");
7336
+ const openclawMemoryDir = path.join(home, ".openclaw", "workspace", "memory");
7337
+ const configExists = await fileExists(openclawConfigPath);
7338
+ const envExists = await fileExists(openclawEnvPath);
7339
+ const memoryExists = await fileExists(openclawMemoryPath);
7340
+ const memoryDirExists = await fileExists(openclawMemoryDir);
7341
+ if (configExists || memoryExists || memoryDirExists) {
7342
+ fingerprint.openclaw_detected = true;
7343
+ fingerprint.openclaw_config = await auditOpenClawConfig(
7344
+ openclawConfigPath,
7345
+ openclawEnvPath,
7346
+ openclawMemoryPath,
7347
+ configExists,
7348
+ envExists,
7349
+ memoryExists
7350
+ );
7351
+ }
7352
+ return fingerprint;
7353
+ }
7354
+ async function auditOpenClawConfig(configPath, envPath, _memoryPath, configExists, envExists, memoryExists) {
7355
+ const audit = {
7356
+ config_path: configExists ? configPath : null,
7357
+ require_approval_enabled: false,
7358
+ sandbox_policy_active: false,
7359
+ sandbox_allow_list: [],
7360
+ sandbox_deny_list: [],
7361
+ memory_encrypted: false,
7362
+ // Stock OpenClaw never encrypts memory
7363
+ env_file_exposed: false,
7364
+ gateway_token_set: false,
7365
+ dm_pairing_enabled: false,
7366
+ mcp_bridge_active: false
7367
+ };
7368
+ if (configExists) {
7369
+ const raw = await safeReadFile(configPath);
7370
+ if (raw) {
7371
+ try {
7372
+ const parsed = lenientJsonParse(raw);
7373
+ const hooks = parsed.hooks;
7374
+ if (hooks) {
7375
+ const beforeToolCall = hooks.before_tool_call;
7376
+ if (beforeToolCall) {
7377
+ const hookStr = JSON.stringify(beforeToolCall);
7378
+ audit.require_approval_enabled = hookStr.includes("requireApproval");
7379
+ }
7380
+ }
7381
+ const tools = parsed.tools;
7382
+ if (tools) {
7383
+ const sandbox = tools.sandbox;
7384
+ if (sandbox) {
7385
+ const sandboxTools = sandbox.tools;
7386
+ if (sandboxTools) {
7387
+ audit.sandbox_policy_active = true;
7388
+ if (Array.isArray(sandboxTools.allow)) {
7389
+ audit.sandbox_allow_list = sandboxTools.allow.filter(
7390
+ (item) => typeof item === "string"
7391
+ );
7392
+ }
7393
+ if (Array.isArray(sandboxTools.alsoAllow)) {
7394
+ audit.sandbox_allow_list = [
7395
+ ...audit.sandbox_allow_list,
7396
+ ...sandboxTools.alsoAllow.filter(
7397
+ (item) => typeof item === "string"
7398
+ )
7399
+ ];
7400
+ }
7401
+ if (Array.isArray(sandboxTools.deny)) {
7402
+ audit.sandbox_deny_list = sandboxTools.deny.filter(
7403
+ (item) => typeof item === "string"
7404
+ );
7405
+ }
7406
+ }
7407
+ }
7408
+ }
7409
+ const mcpServers = parsed.mcpServers;
7410
+ if (mcpServers && Object.keys(mcpServers).length > 0) {
7411
+ audit.mcp_bridge_active = true;
7412
+ }
7413
+ } catch {
7414
+ }
7415
+ }
7416
+ }
7417
+ if (envExists) {
7418
+ const envContent = await safeReadFile(envPath);
7419
+ if (envContent) {
7420
+ const secretPatterns = [
7421
+ /[A-Z_]*API_KEY\s*=/,
7422
+ /[A-Z_]*TOKEN\s*=/,
7423
+ /[A-Z_]*SECRET\s*=/,
7424
+ /[A-Z_]*PASSWORD\s*=/,
7425
+ /[A-Z_]*PRIVATE_KEY\s*=/
7426
+ ];
7427
+ audit.env_file_exposed = secretPatterns.some((p) => p.test(envContent));
7428
+ audit.gateway_token_set = /OPENCLAW_GATEWAY_TOKEN\s*=/.test(envContent);
7429
+ }
7430
+ }
7431
+ if (memoryExists) {
7432
+ audit.memory_encrypted = false;
7433
+ }
7434
+ return audit;
7435
+ }
7436
+
7437
+ // src/audit/analyzer.ts
7438
+ var L1_ENCRYPTION_AT_REST = 10;
7439
+ var L1_IDENTITY_CRYPTOGRAPHIC = 10;
7440
+ var L1_INTEGRITY_VERIFICATION = 8;
7441
+ var L1_STATE_PORTABLE = 7;
7442
+ var L2_THREE_TIER_GATE = 10;
7443
+ var L2_BINARY_GATE = 3;
7444
+ var L2_ANOMALY_DETECTION = 5;
7445
+ var L2_ENCRYPTED_AUDIT = 4;
7446
+ var L2_TOOL_SANDBOXING = 2;
7447
+ var L2_CONTEXT_GATING = 4;
7448
+ var L2_PROCESS_HARDENING = 5;
7449
+ var L3_COMMITMENT_SCHEME = 8;
7450
+ var L3_ZK_PROOFS = 7;
7451
+ var L3_DISCLOSURE_POLICIES = 5;
7452
+ var L4_PORTABLE_REPUTATION = 6;
7453
+ var L4_SIGNED_ATTESTATIONS = 6;
7454
+ var L4_SYBIL_DETECTION = 4;
7455
+ var L4_SOVEREIGNTY_GATED = 4;
7456
+ var SEVERITY_ORDER = {
7457
+ critical: 0,
7458
+ high: 1,
7459
+ medium: 2,
7460
+ low: 3
7461
+ };
7462
+ var INCIDENT_META_SEV1 = {
7463
+ id: "META-SEV1-2026",
7464
+ name: "Meta Sev 1: Unauthorized autonomous data exposure",
7465
+ date: "2026-03-18",
7466
+ description: "AI agent autonomously posted proprietary code, business strategies, and user datasets to an internal forum without human approval. Two-hour exposure window."
7467
+ };
7468
+ var INCIDENT_OPENCLAW_SANDBOX = {
7469
+ id: "OPENCLAW-CVE-2026",
7470
+ name: "OpenClaw sandbox escape via privilege inheritance",
7471
+ date: "2026-03-18",
7472
+ 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.",
7473
+ cves: [
7474
+ "CVE-2026-32048",
7475
+ "CVE-2026-32915",
7476
+ "CVE-2026-32918"
7477
+ ]
7478
+ };
7479
+ var INCIDENT_CONTEXT_LEAKAGE = {
7480
+ id: "CONTEXT-LEAK-CLASS",
7481
+ name: "Context leakage: Full state exposure to inference providers",
7482
+ date: "2026-03",
7483
+ 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."
7484
+ };
7485
+ var INCIDENT_CLAUDE_CODE_LEAK = {
7486
+ id: "CLAUDE-CODE-LEAK-2026",
7487
+ name: "Claude Code source leak: 512K lines exposed via npm source map",
7488
+ date: "2026-03-31",
7489
+ 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."
7490
+ };
7491
+ function analyzeSovereignty(env, config) {
7492
+ const l1 = assessL1(env, config);
7493
+ const l2 = assessL2(env);
7494
+ const l3 = assessL3(env);
7495
+ const l4 = assessL4(env);
7496
+ const l1Score = scoreL1(l1);
7497
+ const l2Score = scoreL2(l2);
7498
+ const l3Score = scoreL3(l3);
7499
+ const l4Score = scoreL4(l4);
7500
+ const overallScore = l1Score + l2Score + l3Score + l4Score;
7501
+ const sovereigntyLevel = overallScore >= 80 ? "full" : overallScore >= 50 ? "partial" : overallScore >= 20 ? "minimal" : "none";
7502
+ const gaps = generateGaps(env, l1, l2, l3, l4);
7503
+ gaps.sort((a, b) => SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity]);
7504
+ const recommendations = generateRecommendations(env, l1, l2, l3, l4);
7505
+ return {
7506
+ version: "1.0",
7507
+ audited_at: (/* @__PURE__ */ new Date()).toISOString(),
7508
+ environment: env,
7509
+ layers: {
7510
+ l1_cognitive: l1,
7511
+ l2_operational: l2,
7512
+ l3_selective_disclosure: l3,
7513
+ l4_reputation: l4
7514
+ },
7515
+ overall_score: overallScore,
7516
+ sovereignty_level: sovereigntyLevel,
7517
+ gaps,
7518
+ recommendations
7519
+ };
7520
+ }
7521
+ function assessL1(env, config) {
7522
+ const findings = [];
7523
+ const sanctuaryActive = env.sanctuary_installed;
7524
+ const encryptionAtRest = sanctuaryActive;
7525
+ const keyCustody = sanctuaryActive ? "self" : "none";
7526
+ const integrityVerification = sanctuaryActive;
7527
+ const identityCryptographic = sanctuaryActive;
7528
+ const statePortable = sanctuaryActive;
7529
+ if (sanctuaryActive) {
7530
+ findings.push("AES-256-GCM encryption active for all state");
7531
+ findings.push(`Key derivation: ${config.state.key_derivation}`);
7532
+ findings.push(`Identity provider: ${config.state.identity_provider}`);
7533
+ findings.push("Merkle integrity verification enabled");
7534
+ findings.push("State export/import available");
7535
+ }
7536
+ if (env.openclaw_detected && env.openclaw_config) {
7537
+ if (!env.openclaw_config.memory_encrypted) {
7538
+ findings.push("OpenClaw agent memory (MEMORY.md, daily notes) stored in plaintext");
7539
+ }
7540
+ if (env.openclaw_config.env_file_exposed) {
7541
+ findings.push("OpenClaw .env file contains plaintext API keys/tokens");
7542
+ }
7543
+ }
7544
+ const status = encryptionAtRest && identityCryptographic ? "active" : encryptionAtRest || identityCryptographic ? "partial" : "inactive";
7545
+ return {
7546
+ status,
7547
+ encryption_at_rest: encryptionAtRest,
7548
+ key_custody: keyCustody,
7549
+ integrity_verification: integrityVerification,
7550
+ identity_cryptographic: identityCryptographic,
7551
+ state_portable: statePortable,
7552
+ findings
7553
+ };
7554
+ }
7555
+ function assessL2(env, _config) {
7556
+ const findings = [];
7557
+ const sanctuaryActive = env.sanctuary_installed;
7558
+ let approvalGate = "none";
7559
+ let behavioralAnomalyDetection = false;
7560
+ let auditTrailEncrypted = false;
7561
+ let auditTrailExists = false;
7562
+ let toolSandboxing = "none";
7563
+ let contextGating = false;
7564
+ let processIsolationHardening = "none";
7565
+ if (sanctuaryActive) {
7566
+ approvalGate = "three-tier";
7567
+ behavioralAnomalyDetection = true;
7568
+ auditTrailEncrypted = true;
7569
+ auditTrailExists = true;
7570
+ contextGating = true;
7571
+ findings.push("Three-tier Principal Policy gate active");
7572
+ findings.push("Behavioral anomaly detection (BaselineTracker) enabled");
7573
+ findings.push("Encrypted audit trail active");
7574
+ findings.push("Context gating available (sanctuary/context_gate_set_policy)");
7575
+ }
7576
+ if (env.openclaw_detected && env.openclaw_config) {
7577
+ if (env.openclaw_config.require_approval_enabled) {
7578
+ if (!sanctuaryActive) {
7579
+ approvalGate = "binary";
7580
+ }
7581
+ findings.push("OpenClaw requireApproval hook enabled (binary approve/deny)");
7582
+ }
7583
+ if (env.openclaw_config.sandbox_policy_active) {
7584
+ if (!sanctuaryActive) {
7585
+ toolSandboxing = "basic";
7586
+ }
7587
+ findings.push(
7588
+ `OpenClaw sandbox policy active (${env.openclaw_config.sandbox_allow_list.length} allowed, ${env.openclaw_config.sandbox_deny_list.length} denied)`
7589
+ );
7590
+ }
7591
+ }
7592
+ processIsolationHardening = "none";
7593
+ const status = approvalGate === "three-tier" && auditTrailEncrypted ? "active" : approvalGate !== "none" || auditTrailExists ? "partial" : "inactive";
7594
+ return {
7595
+ status,
7596
+ approval_gate: approvalGate,
7597
+ behavioral_anomaly_detection: behavioralAnomalyDetection,
7598
+ audit_trail_encrypted: auditTrailEncrypted,
7599
+ audit_trail_exists: auditTrailExists,
7600
+ tool_sandboxing: sanctuaryActive ? "policy-enforced" : toolSandboxing,
7601
+ context_gating: contextGating,
7602
+ process_isolation_hardening: processIsolationHardening,
7603
+ findings
7604
+ };
7605
+ }
7606
+ function assessL3(env, _config) {
7607
+ const findings = [];
7608
+ const sanctuaryActive = env.sanctuary_installed;
7609
+ let commitmentScheme = "none";
7610
+ let zkProofs = false;
7611
+ let selectiveDisclosurePolicy = false;
7612
+ if (sanctuaryActive) {
7613
+ commitmentScheme = "pedersen+sha256";
7614
+ zkProofs = true;
7615
+ selectiveDisclosurePolicy = true;
7616
+ findings.push("SHA-256 + Pedersen commitment schemes active");
7617
+ findings.push("Schnorr zero-knowledge proofs (Fiat-Shamir) enabled \u2014 genuine ZK proofs");
7618
+ findings.push("Range proofs (bit-decomposition + OR-proofs) enabled \u2014 genuine ZK proofs");
7619
+ findings.push("Selective disclosure policies configurable");
7620
+ findings.push("Non-interactive proofs with replay-resistant domain separation");
7621
+ }
7622
+ const status = commitmentScheme === "pedersen+sha256" && zkProofs ? "active" : commitmentScheme !== "none" ? "partial" : "inactive";
7623
+ return {
7624
+ status,
7625
+ commitment_scheme: commitmentScheme,
7626
+ zero_knowledge_proofs: zkProofs,
7627
+ selective_disclosure_policy: selectiveDisclosurePolicy,
7628
+ findings
7629
+ };
7630
+ }
7631
+ function assessL4(env, _config) {
7632
+ const findings = [];
7633
+ const sanctuaryActive = env.sanctuary_installed;
7634
+ const reputationPortable = sanctuaryActive;
7635
+ const reputationSigned = sanctuaryActive;
7636
+ const sybilDetection = sanctuaryActive;
7637
+ const sovereigntyGated = sanctuaryActive;
7638
+ if (sanctuaryActive) {
7639
+ findings.push("Signed EAS-compatible attestations active");
7640
+ findings.push("Reputation export/import available");
7641
+ findings.push("Sybil detection heuristics enabled");
7642
+ findings.push("Sovereignty-gated reputation tiers active");
7643
+ } else {
7644
+ findings.push("No portable reputation system detected");
7645
+ }
7646
+ const status = reputationPortable && reputationSigned && sovereigntyGated ? "active" : reputationPortable || reputationSigned ? "partial" : "inactive";
7647
+ return {
7648
+ status,
7649
+ reputation_portable: reputationPortable,
7650
+ reputation_signed: reputationSigned,
7651
+ reputation_sybil_detection: sybilDetection,
7652
+ sovereignty_gated_tiers: sovereigntyGated,
7653
+ findings
7654
+ };
7655
+ }
7656
+ function scoreL1(l1) {
7657
+ let score = 0;
7658
+ if (l1.encryption_at_rest) score += L1_ENCRYPTION_AT_REST;
7659
+ if (l1.identity_cryptographic) score += L1_IDENTITY_CRYPTOGRAPHIC;
7660
+ if (l1.integrity_verification) score += L1_INTEGRITY_VERIFICATION;
7661
+ if (l1.state_portable) score += L1_STATE_PORTABLE;
7662
+ return score;
7663
+ }
7664
+ function scoreL2(l2) {
7665
+ let score = 0;
7666
+ if (l2.approval_gate === "three-tier") score += L2_THREE_TIER_GATE;
7667
+ else if (l2.approval_gate === "binary") score += L2_BINARY_GATE;
7668
+ if (l2.behavioral_anomaly_detection) score += L2_ANOMALY_DETECTION;
7669
+ if (l2.audit_trail_encrypted) score += L2_ENCRYPTED_AUDIT;
7670
+ if (l2.tool_sandboxing === "policy-enforced") score += L2_TOOL_SANDBOXING;
7671
+ else if (l2.tool_sandboxing === "basic") score += 1;
7672
+ if (l2.context_gating) score += L2_CONTEXT_GATING;
7673
+ if (l2.process_isolation_hardening === "hardened") score += L2_PROCESS_HARDENING;
7674
+ else if (l2.process_isolation_hardening === "basic") score += 2;
7675
+ return score;
7676
+ }
7677
+ function scoreL3(l3) {
7678
+ let score = 0;
7679
+ if (l3.commitment_scheme === "pedersen+sha256") score += L3_COMMITMENT_SCHEME;
7680
+ else if (l3.commitment_scheme === "sha256-only") score += 4;
7681
+ if (l3.zero_knowledge_proofs) score += L3_ZK_PROOFS;
7682
+ if (l3.selective_disclosure_policy) score += L3_DISCLOSURE_POLICIES;
7683
+ return score;
7684
+ }
7685
+ function scoreL4(l4) {
7686
+ let score = 0;
7687
+ if (l4.reputation_portable) score += L4_PORTABLE_REPUTATION;
7688
+ if (l4.reputation_signed) score += L4_SIGNED_ATTESTATIONS;
7689
+ if (l4.reputation_sybil_detection) score += L4_SYBIL_DETECTION;
7690
+ if (l4.sovereignty_gated_tiers) score += L4_SOVEREIGNTY_GATED;
7691
+ return score;
7692
+ }
7693
+ function generateGaps(env, l1, l2, l3, l4) {
7694
+ const gaps = [];
7695
+ const oc = env.openclaw_config;
7696
+ if (oc && !oc.memory_encrypted) {
7697
+ gaps.push({
7698
+ id: "GAP-L1-001",
7699
+ layer: "L1",
7700
+ severity: "critical",
7701
+ title: "Agent memory stored in plaintext",
7702
+ 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.",
7703
+ openclaw_relevance: "Stock OpenClaw stores all agent memory in plaintext files. There is no built-in encryption for agent state.",
7704
+ 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.",
7705
+ incident_class: INCIDENT_META_SEV1
7706
+ });
7707
+ }
7708
+ if (oc && oc.env_file_exposed) {
7709
+ gaps.push({
7710
+ id: "GAP-L1-002",
7711
+ layer: "L1",
7712
+ severity: "critical",
7713
+ title: "Plaintext API keys in .env file",
7714
+ description: "Your .env file contains plaintext API keys and tokens. These secrets are readable by any process with filesystem access.",
7715
+ openclaw_relevance: "OpenClaw stores API keys (LLM providers, gateway tokens) in a plaintext .env file.",
7716
+ 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'."
7717
+ });
7718
+ }
7719
+ if (!l1.identity_cryptographic) {
7720
+ gaps.push({
7721
+ id: "GAP-L1-003",
7722
+ layer: "L1",
7723
+ severity: "critical",
7724
+ title: "No cryptographic agent identity",
7725
+ 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.",
7726
+ openclaw_relevance: env.openclaw_detected ? "OpenClaw has no cryptographic agent identity. Agent identity is implicit (tied to the process/session), not cryptographically verifiable." : null,
7727
+ sanctuary_solution: "Sanctuary provides Ed25519 self-custodied identity with key rotation and delegation. Use sanctuary/identity_create to establish your cryptographic identity."
7728
+ });
7729
+ }
7730
+ if (l2.approval_gate === "binary" && !l2.behavioral_anomaly_detection) {
7731
+ gaps.push({
7732
+ id: "GAP-L2-001",
7733
+ layer: "L2",
7734
+ severity: "high",
7735
+ title: "Binary approval gate (no anomaly detection)",
7736
+ description: "Your approval gate provides binary approve/deny gating without behavioral anomaly detection. Routine operations require the same manual approval as sensitive ones.",
7737
+ 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,
7738
+ 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.",
7739
+ incident_class: INCIDENT_META_SEV1
7740
+ });
7741
+ } else if (l2.approval_gate === "none") {
7742
+ gaps.push({
7743
+ id: "GAP-L2-001",
7744
+ layer: "L2",
7745
+ severity: "critical",
7746
+ title: "No approval gate",
7747
+ description: "No approval gate is configured. All tool calls execute without oversight.",
7748
+ openclaw_relevance: null,
7749
+ sanctuary_solution: "Sanctuary's Principal Policy evaluates every tool call before execution. Enable it to get three-tier approval gating with behavioral anomaly detection.",
7750
+ incident_class: INCIDENT_META_SEV1
7751
+ });
7752
+ }
7753
+ if (l2.tool_sandboxing === "basic") {
7754
+ gaps.push({
7755
+ id: "GAP-L2-002",
7756
+ layer: "L2",
7757
+ severity: "medium",
7758
+ title: "Basic tool sandboxing (no cryptographic attestation)",
7759
+ description: "Your tool sandbox enforces allow/deny lists but provides no cryptographic attestation of execution context.",
7760
+ 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,
7761
+ sanctuary_solution: "Sanctuary provides cryptographic execution attestation via sanctuary/exec_attest and policy-enforced sandboxing with encrypted audit trails.",
7762
+ incident_class: INCIDENT_OPENCLAW_SANDBOX
7763
+ });
7764
+ }
7765
+ if (!l2.context_gating) {
7766
+ gaps.push({
7767
+ id: "GAP-L2-003",
7768
+ layer: "L2",
7769
+ severity: "high",
7770
+ title: "No context gating for outbound inference calls",
7771
+ 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.",
7772
+ 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,
7773
+ 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.",
7774
+ incident_class: INCIDENT_CONTEXT_LEAKAGE
7775
+ });
7776
+ }
7777
+ if (!l2.audit_trail_exists) {
7778
+ gaps.push({
7779
+ id: "GAP-L2-004",
7780
+ layer: "L2",
7781
+ severity: "high",
7782
+ title: "No audit trail",
7783
+ description: "No audit trail exists for tool call history. There is no record of what operations were executed, when, or by whom.",
7784
+ openclaw_relevance: null,
7785
+ sanctuary_solution: "Sanctuary maintains an encrypted audit log of all operations, queryable via sanctuary/monitor_audit_log.",
7786
+ incident_class: INCIDENT_CLAUDE_CODE_LEAK
7787
+ });
7788
+ }
7789
+ if (l3.commitment_scheme === "none") {
7790
+ gaps.push({
7791
+ id: "GAP-L3-001",
7792
+ layer: "L3",
7793
+ severity: "high",
7794
+ title: "No selective disclosure capability",
7795
+ 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.",
7796
+ 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,
7797
+ 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.",
7798
+ incident_class: INCIDENT_META_SEV1
7799
+ });
7800
+ }
7801
+ if (!l4.reputation_portable) {
7802
+ gaps.push({
7803
+ id: "GAP-L4-001",
7804
+ layer: "L4",
7805
+ severity: "high",
7806
+ title: "No portable reputation",
7807
+ description: "Your agent's reputation is platform-locked. If you move to a different harness or platform, your track record doesn't follow.",
7808
+ 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,
7809
+ 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."
7810
+ });
7811
+ }
7812
+ return gaps;
7813
+ }
7814
+ function generateRecommendations(env, l1, l2, l3, l4) {
7815
+ const recs = [];
7816
+ if (!l1.identity_cryptographic) {
7817
+ recs.push({
7818
+ priority: 1,
7819
+ action: "Create a cryptographic identity \u2014 your agent's foundation for all sovereignty operations",
7820
+ tool: "sanctuary/identity_create",
7821
+ effort: "immediate",
7822
+ impact: "critical"
7823
+ });
7824
+ }
7825
+ if (!l1.encryption_at_rest || env.openclaw_config && !env.openclaw_config.memory_encrypted) {
7826
+ recs.push({
7827
+ priority: 2,
7828
+ action: "Migrate plaintext agent state to Sanctuary's encrypted store",
7829
+ tool: "sanctuary/state_write",
7830
+ effort: "minutes",
7831
+ impact: "critical"
7832
+ });
7833
+ }
7834
+ recs.push({
7835
+ priority: 3,
7836
+ action: "Generate a Sovereignty Health Report to present to counterparties",
7837
+ tool: "sanctuary/shr_generate",
7838
+ effort: "immediate",
7839
+ impact: "high"
7840
+ });
7841
+ if (l2.approval_gate !== "three-tier") {
7842
+ recs.push({
7843
+ priority: 4,
7844
+ action: "Enable the three-tier Principal Policy gate for graduated approval",
7845
+ tool: "sanctuary/principal_policy_view",
7846
+ effort: "minutes",
7847
+ impact: "high"
7848
+ });
7849
+ }
7850
+ if (!l2.context_gating) {
7851
+ recs.push({
7852
+ priority: 5,
7853
+ action: "Configure context gating to control what flows to LLM providers",
7854
+ tool: "sanctuary/context_gate_set_policy",
7855
+ effort: "minutes",
7856
+ impact: "high"
7857
+ });
7858
+ }
7859
+ if (!l4.reputation_signed) {
7860
+ recs.push({
7861
+ priority: 6,
7862
+ action: "Start recording reputation attestations from completed interactions",
7863
+ tool: "sanctuary/reputation_record",
7864
+ effort: "minutes",
7865
+ impact: "medium"
7866
+ });
7867
+ }
7868
+ if (!l3.selective_disclosure_policy) {
7869
+ recs.push({
7870
+ priority: 7,
7871
+ action: "Configure selective disclosure policies for data sharing",
7872
+ tool: "sanctuary/disclosure_set_policy",
7873
+ effort: "hours",
7874
+ impact: "medium"
7875
+ });
7876
+ }
7877
+ return recs;
7878
+ }
7879
+ function formatAuditReport(result) {
7880
+ const { environment: env, layers, overall_score, sovereignty_level, gaps, recommendations } = result;
7881
+ const scoreBar = formatScoreBar(overall_score);
7882
+ const levelLabel = sovereignty_level.toUpperCase();
7883
+ let report = "";
7884
+ 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";
7885
+ report += " SOVEREIGNTY AUDIT REPORT\n";
7886
+ report += ` Generated: ${result.audited_at}
7887
+ `;
7888
+ 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";
7889
+ report += "\n";
7890
+ report += ` Overall Score: ${overall_score} / 100 ${scoreBar} ${levelLabel}
7891
+ `;
7892
+ report += "\n";
7893
+ report += " Environment:\n";
7894
+ report += ` \u2022 Sanctuary v${env.sanctuary_version ?? "?"} ${padDots("Sanctuary v" + (env.sanctuary_version ?? "?"))} ${env.sanctuary_installed ? "\u2713 installed" : "\u2717 not found"}
7895
+ `;
7896
+ if (env.openclaw_detected) {
7897
+ report += ` \u2022 OpenClaw ${padDots("OpenClaw")} \u2713 detected
7898
+ `;
7899
+ if (env.openclaw_config) {
7900
+ report += ` \u2022 OpenClaw requireApproval ${padDots("OpenClaw requireApproval")} ${env.openclaw_config.require_approval_enabled ? "\u2713 enabled" : "\u2717 disabled"}
7901
+ `;
7902
+ report += ` \u2022 OpenClaw sandbox policy ${padDots("OpenClaw sandbox policy")} ${env.openclaw_config.sandbox_policy_active ? "\u2713 active" : "\u2717 inactive"}
7903
+ `;
7904
+ }
7905
+ }
7906
+ report += "\n";
7907
+ const l1Score = scoreL1(layers.l1_cognitive);
7908
+ const l2Score = scoreL2(layers.l2_operational);
7909
+ const l3Score = scoreL3(layers.l3_selective_disclosure);
7910
+ const l4Score = scoreL4(layers.l4_reputation);
7911
+ report += " Layer Assessment:\n";
7912
+ 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";
7913
+ report += " \u2502 Layer \u2502 Status \u2502 Score \u2502\n";
7914
+ 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";
7915
+ report += ` \u2502 L1 Cognitive Sovereignty \u2502 ${padStatus(layers.l1_cognitive.status)} \u2502 ${padScore(l1Score, 35)} \u2502
7916
+ `;
7917
+ report += ` \u2502 L2 Operational Isolation \u2502 ${padStatus(layers.l2_operational.status)} \u2502 ${padScore(l2Score, 25)} \u2502
7918
+ `;
7919
+ if (layers.l2_operational.context_gating) {
7920
+ report += ` \u2502 \u2514 Context Gating \u2502 ACTIVE \u2502 \u2502
7921
+ `;
7922
+ }
7923
+ report += ` \u2502 L3 Selective Disclosure \u2502 ${padStatus(layers.l3_selective_disclosure.status)} \u2502 ${padScore(l3Score, 20)} \u2502
7924
+ `;
7925
+ report += ` \u2502 L4 Verifiable Reputation \u2502 ${padStatus(layers.l4_reputation.status)} \u2502 ${padScore(l4Score, 20)} \u2502
7926
+ `;
7927
+ 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";
7928
+ report += "\n";
7929
+ if (gaps.length > 0) {
7930
+ report += ` \u26A0 ${gaps.length} SOVEREIGNTY GAP${gaps.length !== 1 ? "S" : ""} FOUND
7931
+ `;
7932
+ report += "\n";
7933
+ for (const gap of gaps) {
7934
+ const severityLabel = `[${gap.severity.toUpperCase()}]`;
7935
+ report += ` ${severityLabel} ${gap.id}: ${gap.title}
7936
+ `;
7937
+ const descLines = wordWrap(gap.description, 66);
7938
+ for (const line of descLines) {
7939
+ report += ` ${line}
7940
+ `;
7941
+ }
7942
+ if (gap.incident_class) {
7943
+ const ic = gap.incident_class;
7944
+ const cveStr = ic.cves?.length ? ` (${ic.cves.join(", ")})` : "";
7945
+ report += ` \u2192 Incident precedent: ${ic.name}${cveStr} [${ic.date}]
7946
+ `;
7947
+ }
7948
+ report += ` \u2192 Fix: ${gap.sanctuary_solution.split(".")[0]}.
7949
+ `;
7950
+ if (gap.openclaw_relevance) {
7951
+ report += ` \u2192 OpenClaw context: ${gap.openclaw_relevance.split(".")[0]}.
7952
+ `;
7953
+ }
7954
+ report += "\n";
7955
+ }
7956
+ } else {
7957
+ report += " \u2713 NO SOVEREIGNTY GAPS FOUND\n";
7958
+ report += "\n";
7959
+ }
7960
+ if (recommendations.length > 0) {
7961
+ report += " RECOMMENDED NEXT STEPS (in order):\n";
7962
+ for (const rec of recommendations) {
7963
+ const effortLabel = rec.effort === "immediate" ? "immediate" : rec.effort === "minutes" ? "5 min" : "30 min";
7964
+ report += ` ${rec.priority}. [${effortLabel}] ${rec.action}`;
7965
+ if (rec.tool) {
7966
+ report += `: ${rec.tool}`;
7967
+ }
7968
+ report += "\n";
7969
+ }
7970
+ report += "\n";
7971
+ }
7972
+ 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";
7973
+ return report;
7974
+ }
7975
+ function formatScoreBar(score) {
7976
+ const filled = Math.round(score / 10);
7977
+ return "[" + "\u25A0".repeat(filled) + "\u2591".repeat(10 - filled) + "]";
7978
+ }
7979
+ function padDots(label) {
7980
+ const totalWidth = 30;
7981
+ const dotsNeeded = Math.max(2, totalWidth - label.length - 4);
7982
+ return ".".repeat(dotsNeeded);
7983
+ }
7984
+ function padStatus(status) {
7985
+ const label = status.toUpperCase();
7986
+ return label + " ".repeat(Math.max(0, 8 - label.length));
7987
+ }
7988
+ function padScore(score, max) {
7989
+ const text = `${score}/${max}`;
7990
+ return " ".repeat(Math.max(0, 5 - text.length)) + text;
7991
+ }
7992
+ function wordWrap(text, maxWidth) {
7993
+ const words = text.split(" ");
7994
+ const lines = [];
7995
+ let current = "";
7996
+ for (const word of words) {
7997
+ if (current.length + word.length + 1 > maxWidth && current.length > 0) {
7998
+ lines.push(current);
7999
+ current = word;
8000
+ } else {
8001
+ current = current.length > 0 ? current + " " + word : word;
8002
+ }
8003
+ }
8004
+ if (current.length > 0) lines.push(current);
8005
+ return lines;
8006
+ }
8007
+
8008
+ // src/audit/tools.ts
8009
+ function createAuditTools(config) {
8010
+ const tools = [
8011
+ {
8012
+ name: "sanctuary/sovereignty_audit",
8013
+ 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.",
8014
+ inputSchema: {
8015
+ type: "object",
8016
+ properties: {
8017
+ deep_scan: {
8018
+ type: "boolean",
8019
+ description: "If true (default), also scans for OpenClaw config, .env files, and memory files. Set to false for a Sanctuary-only assessment."
8020
+ }
8021
+ }
8022
+ },
8023
+ handler: async (args) => {
8024
+ const deepScan = args.deep_scan !== false;
8025
+ const env = await detectEnvironment(config, deepScan);
8026
+ const result = analyzeSovereignty(env, config);
8027
+ const report = formatAuditReport(result);
8028
+ return {
8029
+ content: [
8030
+ { type: "text", text: report },
8031
+ { type: "text", text: JSON.stringify(result, null, 2) }
8032
+ ]
8033
+ };
8034
+ }
8035
+ }
8036
+ ];
8037
+ return { tools };
8038
+ }
8039
+
8040
+ // src/l2-operational/context-gate.ts
8041
+ init_encoding();
8042
+ init_hashing();
8043
+ var MAX_CONTEXT_FIELDS = 1e3;
8044
+ var MAX_POLICY_RULES = 50;
8045
+ var MAX_PATTERNS_PER_ARRAY = 500;
8046
+ function evaluateField(policy, provider, field) {
8047
+ const exactRule = policy.rules.find((r) => r.provider === provider);
8048
+ const wildcardRule = policy.rules.find((r) => r.provider === "*");
8049
+ const matchedRule = exactRule ?? wildcardRule;
8050
+ if (!matchedRule) {
8051
+ return {
8052
+ field,
8053
+ action: policy.default_action === "deny" ? "deny" : "redact",
8054
+ reason: `No rule matches provider "${provider}"; applying default (${policy.default_action})`
8055
+ };
8056
+ }
8057
+ if (matchesPattern(field, matchedRule.redact)) {
8058
+ return {
8059
+ field,
8060
+ action: "redact",
8061
+ reason: `Field "${field}" is explicitly redacted for ${matchedRule.provider} provider`
8062
+ };
8063
+ }
8064
+ if (matchesPattern(field, matchedRule.hash)) {
8065
+ return {
8066
+ field,
8067
+ action: "hash",
8068
+ reason: `Field "${field}" is hashed for ${matchedRule.provider} provider`
8069
+ };
8070
+ }
8071
+ if (matchesPattern(field, matchedRule.summarize)) {
8072
+ return {
8073
+ field,
8074
+ action: "summarize",
8075
+ reason: `Field "${field}" should be summarized for ${matchedRule.provider} provider`
8076
+ };
8077
+ }
8078
+ if (matchesPattern(field, matchedRule.allow)) {
8079
+ return {
8080
+ field,
8081
+ action: "allow",
8082
+ reason: `Field "${field}" is allowed for ${matchedRule.provider} provider`
8083
+ };
8084
+ }
8085
+ return {
8086
+ field,
8087
+ action: policy.default_action === "deny" ? "deny" : "redact",
8088
+ reason: `Field "${field}" not addressed in ${matchedRule.provider} rule; applying default (${policy.default_action})`
8089
+ };
8090
+ }
8091
+ function filterContext(policy, provider, context) {
8092
+ const fields = Object.keys(context);
8093
+ if (fields.length > MAX_CONTEXT_FIELDS) {
8094
+ throw new Error(
8095
+ `Context object has ${fields.length} fields, exceeding limit of ${MAX_CONTEXT_FIELDS}`
8096
+ );
8097
+ }
8098
+ const decisions = [];
8099
+ let allowed = 0;
8100
+ let redacted = 0;
8101
+ let hashed = 0;
8102
+ let summarized = 0;
8103
+ let denied = 0;
8104
+ for (const field of fields) {
8105
+ const result = evaluateField(policy, provider, field);
8106
+ if (result.action === "hash") {
8107
+ const value = typeof context[field] === "string" ? context[field] : JSON.stringify(context[field]);
8108
+ result.hash_value = hashToString(stringToBytes(value));
8109
+ }
8110
+ decisions.push(result);
8111
+ switch (result.action) {
8112
+ case "allow":
8113
+ allowed++;
8114
+ break;
8115
+ case "redact":
8116
+ redacted++;
8117
+ break;
8118
+ case "hash":
8119
+ hashed++;
8120
+ break;
8121
+ case "summarize":
8122
+ summarized++;
8123
+ break;
8124
+ case "deny":
8125
+ denied++;
8126
+ break;
8127
+ }
8128
+ }
8129
+ const originalHash = hashToString(
8130
+ stringToBytes(JSON.stringify(context))
8131
+ );
8132
+ const filteredOutput = {};
8133
+ for (const decision of decisions) {
8134
+ switch (decision.action) {
8135
+ case "allow":
8136
+ filteredOutput[decision.field] = context[decision.field];
8137
+ break;
8138
+ case "redact":
8139
+ filteredOutput[decision.field] = "[REDACTED]";
8140
+ break;
8141
+ case "hash":
8142
+ filteredOutput[decision.field] = `[HASH:${decision.hash_value}]`;
8143
+ break;
8144
+ case "summarize":
8145
+ filteredOutput[decision.field] = "[SUMMARIZE]";
8146
+ break;
8147
+ }
8148
+ }
8149
+ const filteredHash = hashToString(
8150
+ stringToBytes(JSON.stringify(filteredOutput))
8151
+ );
8152
+ return {
8153
+ policy_id: policy.policy_id,
8154
+ provider,
8155
+ fields_allowed: allowed,
8156
+ fields_redacted: redacted,
8157
+ fields_hashed: hashed,
8158
+ fields_summarized: summarized,
8159
+ fields_denied: denied,
8160
+ decisions,
8161
+ original_context_hash: originalHash,
8162
+ filtered_context_hash: filteredHash,
8163
+ filtered_at: (/* @__PURE__ */ new Date()).toISOString()
8164
+ };
8165
+ }
8166
+ function matchesPattern(field, patterns) {
8167
+ const normalizedField = field.toLowerCase();
8168
+ for (const pattern of patterns) {
8169
+ if (pattern === "*") return true;
8170
+ const normalizedPattern = pattern.toLowerCase();
8171
+ if (normalizedPattern === normalizedField) return true;
8172
+ if (normalizedPattern.endsWith("*") && normalizedField.startsWith(normalizedPattern.slice(0, -1))) return true;
8173
+ if (normalizedPattern.startsWith("*") && normalizedField.endsWith(normalizedPattern.slice(1))) return true;
8174
+ }
8175
+ return false;
8176
+ }
8177
+ var ContextGatePolicyStore = class {
8178
+ storage;
8179
+ encryptionKey;
8180
+ policies = /* @__PURE__ */ new Map();
8181
+ constructor(storage, masterKey) {
8182
+ this.storage = storage;
8183
+ this.encryptionKey = derivePurposeKey(masterKey, "l2-context-gate");
8184
+ }
8185
+ /**
8186
+ * Create and store a new context-gating policy.
8187
+ */
8188
+ async create(policyName, rules, defaultAction, identityId) {
8189
+ const policyId = `cg-${Date.now()}-${toBase64url(randomBytes(8))}`;
8190
+ const now = (/* @__PURE__ */ new Date()).toISOString();
8191
+ const policy = {
8192
+ policy_id: policyId,
8193
+ policy_name: policyName,
8194
+ rules,
8195
+ default_action: defaultAction,
8196
+ identity_id: identityId,
8197
+ created_at: now,
8198
+ updated_at: now
8199
+ };
8200
+ await this.persist(policy);
8201
+ this.policies.set(policyId, policy);
8202
+ return policy;
8203
+ }
8204
+ /**
8205
+ * Get a policy by ID.
8206
+ */
8207
+ async get(policyId) {
8208
+ if (this.policies.has(policyId)) {
8209
+ return this.policies.get(policyId);
8210
+ }
8211
+ const raw = await this.storage.read("_context_gate_policies", policyId);
8212
+ if (!raw) return null;
8213
+ try {
8214
+ const encrypted = JSON.parse(bytesToString(raw));
8215
+ const decrypted = decrypt(encrypted, this.encryptionKey);
8216
+ const policy = JSON.parse(bytesToString(decrypted));
8217
+ this.policies.set(policyId, policy);
8218
+ return policy;
8219
+ } catch {
8220
+ return null;
8221
+ }
8222
+ }
8223
+ /**
8224
+ * List all context-gating policies.
8225
+ */
8226
+ async list() {
8227
+ await this.loadAll();
8228
+ return Array.from(this.policies.values());
8229
+ }
8230
+ /**
8231
+ * Load all persisted policies into memory.
8232
+ */
8233
+ async loadAll() {
8234
+ try {
8235
+ const entries = await this.storage.list("_context_gate_policies");
8236
+ for (const meta of entries) {
8237
+ if (this.policies.has(meta.key)) continue;
8238
+ const raw = await this.storage.read("_context_gate_policies", meta.key);
8239
+ if (!raw) continue;
8240
+ try {
8241
+ const encrypted = JSON.parse(bytesToString(raw));
8242
+ const decrypted = decrypt(encrypted, this.encryptionKey);
8243
+ const policy = JSON.parse(bytesToString(decrypted));
8244
+ this.policies.set(policy.policy_id, policy);
8245
+ } catch {
8246
+ }
8247
+ }
8248
+ } catch {
8249
+ }
8250
+ }
8251
+ async persist(policy) {
8252
+ const serialized = stringToBytes(JSON.stringify(policy));
8253
+ const encrypted = encrypt(serialized, this.encryptionKey);
8254
+ await this.storage.write(
8255
+ "_context_gate_policies",
8256
+ policy.policy_id,
8257
+ stringToBytes(JSON.stringify(encrypted))
8258
+ );
8259
+ }
8260
+ };
8261
+
8262
+ // src/l2-operational/context-gate-templates.ts
8263
+ var ALWAYS_REDACT_SECRETS = [
8264
+ "api_key",
8265
+ "secret_*",
8266
+ "*_secret",
8267
+ "*_token",
8268
+ "*_key",
8269
+ "password",
8270
+ "*_password",
8271
+ "credential",
8272
+ "*_credential",
8273
+ "private_key",
8274
+ "recovery_key",
8275
+ "passphrase",
8276
+ "auth_*"
8277
+ ];
8278
+ var PII_PATTERNS = [
8279
+ "*_pii",
8280
+ "name",
8281
+ "full_name",
8282
+ "email",
8283
+ "email_address",
8284
+ "phone",
8285
+ "phone_number",
8286
+ "address",
8287
+ "ssn",
8288
+ "date_of_birth",
8289
+ "ip_address",
8290
+ "credit_card",
8291
+ "card_number",
8292
+ "cvv",
8293
+ "bank_account",
8294
+ "account_number",
8295
+ "routing_number"
8296
+ ];
8297
+ var INTERNAL_STATE_PATTERNS = [
8298
+ "memory",
8299
+ "agent_memory",
8300
+ "internal_reasoning",
8301
+ "internal_state",
8302
+ "reasoning_trace",
8303
+ "chain_of_thought",
8304
+ "private_notes",
8305
+ "soul",
8306
+ "personality",
8307
+ "system_prompt"
8308
+ ];
8309
+ var ID_PATTERNS = [
8310
+ "user_id",
8311
+ "session_id",
8312
+ "agent_id",
8313
+ "identity_id",
8314
+ "conversation_id",
8315
+ "thread_id"
8316
+ ];
8317
+ var HISTORY_PATTERNS = [
8318
+ "conversation_history",
8319
+ "message_history",
8320
+ "chat_history",
8321
+ "context_window",
8322
+ "previous_messages"
8323
+ ];
8324
+ var INFERENCE_MINIMAL = {
8325
+ id: "inference-minimal",
8326
+ name: "Inference Minimal",
8327
+ description: "Maximum privacy. Only the current task and query reach the LLM provider.",
8328
+ use_when: "You want the strictest possible context control for inference calls. The LLM sees only what it needs for the immediate task.",
8329
+ rules: [
8330
+ {
8331
+ provider: "inference",
8332
+ allow: [
8333
+ "task",
8334
+ "task_description",
8335
+ "current_query",
8336
+ "query",
8337
+ "prompt",
8338
+ "question",
8339
+ "instruction"
8340
+ ],
8341
+ redact: [
8342
+ ...ALWAYS_REDACT_SECRETS,
8343
+ ...PII_PATTERNS,
8344
+ ...INTERNAL_STATE_PATTERNS,
8345
+ ...HISTORY_PATTERNS,
8346
+ "tool_results",
8347
+ "previous_results"
8348
+ ],
8349
+ hash: [...ID_PATTERNS],
8350
+ summarize: []
8351
+ }
8352
+ ],
8353
+ default_action: "redact"
8354
+ };
8355
+ var INFERENCE_STANDARD = {
8356
+ id: "inference-standard",
8357
+ name: "Inference Standard",
8358
+ description: "Balanced privacy. Task, query, and tool results pass through. History flagged for summarization. Secrets and PII redacted.",
8359
+ use_when: "You need the LLM to have enough context for multi-step tasks while keeping secrets, PII, and internal reasoning private.",
8360
+ rules: [
8361
+ {
8362
+ provider: "inference",
8363
+ allow: [
8364
+ "task",
8365
+ "task_description",
8366
+ "current_query",
8367
+ "query",
8368
+ "prompt",
8369
+ "question",
8370
+ "instruction",
8371
+ "tool_results",
8372
+ "tool_output",
8373
+ "previous_results",
8374
+ "current_step",
8375
+ "remaining_steps",
8376
+ "objective",
8377
+ "constraints",
8378
+ "format",
8379
+ "output_format"
8380
+ ],
8381
+ redact: [
8382
+ ...ALWAYS_REDACT_SECRETS,
8383
+ ...PII_PATTERNS,
8384
+ ...INTERNAL_STATE_PATTERNS
8385
+ ],
8386
+ hash: [...ID_PATTERNS],
8387
+ summarize: [...HISTORY_PATTERNS]
8388
+ }
8389
+ ],
8390
+ default_action: "redact"
8391
+ };
8392
+ var LOGGING_STRICT = {
8393
+ id: "logging-strict",
8394
+ name: "Logging Strict",
8395
+ description: "Redacts all content for logging and analytics providers. Only operation metadata passes through.",
8396
+ use_when: "You send telemetry to logging or analytics services and want usage metrics without any content exposure.",
8397
+ rules: [
8398
+ {
8399
+ provider: "logging",
8400
+ allow: [
8401
+ "operation",
8402
+ "operation_name",
8403
+ "tool_name",
8404
+ "timestamp",
8405
+ "duration_ms",
8406
+ "status",
8407
+ "error_code",
8408
+ "event_type"
8409
+ ],
8410
+ redact: [
8411
+ ...ALWAYS_REDACT_SECRETS,
8412
+ ...PII_PATTERNS,
8413
+ ...INTERNAL_STATE_PATTERNS,
8414
+ ...HISTORY_PATTERNS
8415
+ ],
8416
+ hash: [...ID_PATTERNS],
8417
+ summarize: []
8418
+ },
8419
+ {
8420
+ provider: "analytics",
8421
+ allow: [
8422
+ "event_type",
8423
+ "timestamp",
8424
+ "duration_ms",
8425
+ "status",
8426
+ "tool_name"
8427
+ ],
8428
+ redact: [
8429
+ ...ALWAYS_REDACT_SECRETS,
8430
+ ...PII_PATTERNS,
8431
+ ...INTERNAL_STATE_PATTERNS,
8432
+ ...HISTORY_PATTERNS
8433
+ ],
8434
+ hash: [...ID_PATTERNS],
8435
+ summarize: []
8436
+ }
8437
+ ],
8438
+ default_action: "redact"
8439
+ };
8440
+ var TOOL_API_SCOPED = {
8441
+ id: "tool-api-scoped",
8442
+ name: "Tool API Scoped",
8443
+ description: "Allows tool-specific parameters for external API calls. Redacts memory, history, secrets, and PII.",
8444
+ 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.",
8445
+ rules: [
8446
+ {
8447
+ provider: "tool-api",
8448
+ allow: [
8449
+ "task",
8450
+ "task_description",
8451
+ "query",
8452
+ "search_query",
8453
+ "tool_input",
8454
+ "tool_parameters",
8455
+ "url",
8456
+ "endpoint",
8457
+ "method",
8458
+ "filter",
8459
+ "sort",
8460
+ "limit",
8461
+ "offset"
8462
+ ],
8463
+ redact: [
8464
+ ...ALWAYS_REDACT_SECRETS,
8465
+ ...PII_PATTERNS,
8466
+ ...INTERNAL_STATE_PATTERNS,
8467
+ ...HISTORY_PATTERNS
8468
+ ],
8469
+ hash: [...ID_PATTERNS],
8470
+ summarize: []
8471
+ }
8472
+ ],
8473
+ default_action: "redact"
8474
+ };
8475
+ var TEMPLATES = {
8476
+ "inference-minimal": INFERENCE_MINIMAL,
8477
+ "inference-standard": INFERENCE_STANDARD,
8478
+ "logging-strict": LOGGING_STRICT,
8479
+ "tool-api-scoped": TOOL_API_SCOPED
8480
+ };
8481
+ function listTemplateIds() {
8482
+ return Object.keys(TEMPLATES);
8483
+ }
8484
+ function getTemplate(id) {
8485
+ return TEMPLATES[id];
8486
+ }
8487
+
8488
+ // src/l2-operational/context-gate-recommend.ts
8489
+ var CLASSIFICATION_RULES = [
8490
+ // ── Secrets (always redact, high confidence) ─────────────────────
8491
+ {
8492
+ patterns: [
8493
+ "api_key",
8494
+ "apikey",
8495
+ "api_secret",
8496
+ "secret",
8497
+ "secret_key",
8498
+ "secret_token",
8499
+ "password",
8500
+ "passwd",
8501
+ "pass",
8502
+ "credential",
8503
+ "credentials",
8504
+ "private_key",
8505
+ "privkey",
8506
+ "recovery_key",
8507
+ "passphrase",
8508
+ "token",
8509
+ "access_token",
8510
+ "refresh_token",
8511
+ "bearer_token",
8512
+ "auth_token",
8513
+ "auth_header",
8514
+ "authorization",
8515
+ "encryption_key",
8516
+ "master_key",
8517
+ "signing_key",
8518
+ "webhook_secret",
8519
+ "client_secret",
8520
+ "connection_string"
8521
+ ],
8522
+ action: "redact",
8523
+ confidence: "high",
8524
+ reason: "Matches known secret/credential pattern"
8525
+ },
8526
+ // ── PII (always redact, high confidence) ─────────────────────────
8527
+ {
8528
+ patterns: [
8529
+ "name",
8530
+ "full_name",
8531
+ "first_name",
8532
+ "last_name",
8533
+ "display_name",
8534
+ "email",
8535
+ "email_address",
8536
+ "phone",
8537
+ "phone_number",
8538
+ "mobile",
8539
+ "address",
8540
+ "street_address",
8541
+ "mailing_address",
8542
+ "ssn",
8543
+ "social_security",
8544
+ "date_of_birth",
8545
+ "dob",
8546
+ "birthday",
8547
+ "ip_address",
8548
+ "ip",
8549
+ "location",
8550
+ "geolocation",
8551
+ "coordinates",
8552
+ "credit_card",
8553
+ "card_number",
8554
+ "cvv",
8555
+ "bank_account",
8556
+ "routing_number",
8557
+ "passport",
8558
+ "drivers_license",
8559
+ "license_number"
8560
+ ],
8561
+ action: "redact",
8562
+ confidence: "high",
8563
+ reason: "Matches known PII pattern"
8564
+ },
8565
+ // ── Internal agent state (redact, high confidence) ───────────────
8566
+ {
8567
+ patterns: [
8568
+ "memory",
8569
+ "agent_memory",
8570
+ "long_term_memory",
8571
+ "internal_reasoning",
8572
+ "reasoning_trace",
8573
+ "chain_of_thought",
8574
+ "internal_state",
8575
+ "agent_state",
8576
+ "private_notes",
8577
+ "scratchpad",
8578
+ "soul",
8579
+ "personality",
8580
+ "persona",
8581
+ "system_prompt",
8582
+ "system_message",
8583
+ "system_instruction",
8584
+ "preferences",
8585
+ "user_preferences",
8586
+ "agent_preferences",
8587
+ "beliefs",
8588
+ "goals",
8589
+ "motivations"
8590
+ ],
8591
+ action: "redact",
8592
+ confidence: "high",
8593
+ reason: "Matches known internal agent state pattern"
8594
+ },
8595
+ // ── IDs (hash, medium confidence) ────────────────────────────────
8596
+ {
8597
+ patterns: [
8598
+ "user_id",
8599
+ "userid",
8600
+ "session_id",
8601
+ "sessionid",
8602
+ "agent_id",
8603
+ "agentid",
8604
+ "identity_id",
8605
+ "conversation_id",
8606
+ "thread_id",
8607
+ "threadid",
8608
+ "request_id",
8609
+ "requestid",
8610
+ "correlation_id",
8611
+ "trace_id",
8612
+ "traceid",
8613
+ "account_id",
8614
+ "accountid"
8615
+ ],
8616
+ action: "hash",
8617
+ confidence: "medium",
8618
+ reason: "Matches known identifier pattern \u2014 hash preserves correlation without exposing value"
8619
+ },
8620
+ // ── History (summarize, medium confidence) ───────────────────────
8621
+ {
8622
+ patterns: [
8623
+ "conversation_history",
8624
+ "chat_history",
8625
+ "message_history",
8626
+ "messages",
8627
+ "previous_messages",
8628
+ "prior_messages",
8629
+ "context_window",
8630
+ "interaction_history",
8631
+ "audit_log",
8632
+ "event_log"
8633
+ ],
8634
+ action: "summarize",
8635
+ confidence: "medium",
8636
+ reason: "Matches known history/log pattern \u2014 summarize to reduce exposure"
8637
+ },
8638
+ // ── Task/query (allow, medium confidence) ────────────────────────
8639
+ {
8640
+ patterns: [
8641
+ "task",
8642
+ "task_description",
8643
+ "query",
8644
+ "current_query",
8645
+ "search_query",
8646
+ "prompt",
8647
+ "user_prompt",
8648
+ "question",
8649
+ "current_question",
8650
+ "instruction",
8651
+ "instructions",
8652
+ "objective",
8653
+ "goal",
8654
+ "current_step",
8655
+ "next_step",
8656
+ "remaining_steps",
8657
+ "constraints",
8658
+ "requirements",
8659
+ "output_format",
8660
+ "format",
8661
+ "tool_results",
8662
+ "tool_output",
8663
+ "tool_input",
8664
+ "tool_parameters"
8665
+ ],
8666
+ action: "allow",
8667
+ confidence: "medium",
8668
+ reason: "Matches known task/query pattern \u2014 likely needed for inference"
8669
+ }
8670
+ ];
8671
+ function classifyField(fieldName) {
8672
+ const normalized = fieldName.toLowerCase().trim();
8673
+ for (const rule of CLASSIFICATION_RULES) {
8674
+ for (const pattern of rule.patterns) {
8675
+ if (matchesFieldPattern(normalized, pattern)) {
8676
+ return {
8677
+ field: fieldName,
8678
+ recommended_action: rule.action,
8679
+ reason: rule.reason,
8680
+ confidence: rule.confidence,
8681
+ matched_pattern: pattern
8682
+ };
8683
+ }
8684
+ }
8685
+ }
8686
+ return {
8687
+ field: fieldName,
8688
+ recommended_action: "redact",
8689
+ reason: "No known pattern matched \u2014 defaulting to redact (conservative)",
8690
+ confidence: "low",
8691
+ matched_pattern: null
8692
+ };
8693
+ }
8694
+ function recommendPolicy(context, provider = "inference") {
8695
+ const fields = Object.keys(context);
8696
+ const classifications = fields.map(classifyField);
8697
+ const warnings = [];
8698
+ const allow = [];
8699
+ const redact = [];
8700
+ const hash2 = [];
8701
+ const summarize = [];
8702
+ for (const c of classifications) {
8703
+ switch (c.recommended_action) {
8704
+ case "allow":
8705
+ allow.push(c.field);
8706
+ break;
8707
+ case "redact":
8708
+ redact.push(c.field);
8709
+ break;
8710
+ case "hash":
8711
+ hash2.push(c.field);
8712
+ break;
8713
+ case "summarize":
8714
+ summarize.push(c.field);
8715
+ break;
8716
+ }
8717
+ }
8718
+ const lowConfidence = classifications.filter((c) => c.confidence === "low");
8719
+ if (lowConfidence.length > 0) {
8720
+ warnings.push(
8721
+ `${lowConfidence.length} field(s) could not be classified by pattern and will default to redact: ${lowConfidence.map((c) => c.field).join(", ")}. Review these manually.`
8722
+ );
8723
+ }
8724
+ for (const [key, value] of Object.entries(context)) {
8725
+ if (typeof value === "string" && value.length > 5e3) {
8726
+ const existing = classifications.find((c) => c.field === key);
8727
+ if (existing && existing.recommended_action === "allow") {
8728
+ warnings.push(
8729
+ `Field "${key}" is allowed but contains ${value.length} characters. Consider summarizing it to reduce context size and exposure.`
8730
+ );
8731
+ }
8732
+ }
8733
+ }
8734
+ return {
8735
+ provider,
8736
+ classifications,
8737
+ recommended_rules: { allow, redact, hash: hash2, summarize },
8738
+ default_action: "redact",
8739
+ summary: {
8740
+ total_fields: fields.length,
8741
+ allow: allow.length,
8742
+ redact: redact.length,
8743
+ hash: hash2.length,
8744
+ summarize: summarize.length
8745
+ },
8746
+ warnings
8747
+ };
8748
+ }
8749
+ function matchesFieldPattern(normalizedField, pattern) {
8750
+ if (normalizedField === pattern) return true;
8751
+ if (pattern.length >= 3 && normalizedField.includes(pattern)) {
8752
+ const idx = normalizedField.indexOf(pattern);
8753
+ const before = idx === 0 || normalizedField[idx - 1] === "_" || normalizedField[idx - 1] === "-";
8754
+ const after = idx + pattern.length === normalizedField.length || normalizedField[idx + pattern.length] === "_" || normalizedField[idx + pattern.length] === "-";
8755
+ return before && after;
8756
+ }
8757
+ return false;
8758
+ }
8759
+
8760
+ // src/l2-operational/context-gate-tools.ts
8761
+ function createContextGateTools(storage, masterKey, auditLog) {
8762
+ const policyStore = new ContextGatePolicyStore(storage, masterKey);
8763
+ const tools = [
8764
+ // ── Set Policy ──────────────────────────────────────────────────
8765
+ {
8766
+ name: "sanctuary/context_gate_set_policy",
8767
+ 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.",
8768
+ inputSchema: {
8769
+ type: "object",
8770
+ properties: {
8771
+ policy_name: {
8772
+ type: "string",
8773
+ description: "Human-readable name for this policy (e.g., 'inference-minimal', 'tool-api-strict')"
8774
+ },
8775
+ rules: {
8776
+ type: "array",
8777
+ 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).",
8778
+ items: {
8779
+ type: "object",
8780
+ properties: {
8781
+ provider: {
8782
+ type: "string",
8783
+ description: "Provider category: inference, tool-api, logging, analytics, peer-agent, custom, or * for all"
8784
+ },
8785
+ allow: {
8786
+ type: "array",
8787
+ items: { type: "string" },
8788
+ description: "Fields/patterns to allow through (e.g., 'task_description', 'current_query', 'tool_*')"
8789
+ },
8790
+ redact: {
8791
+ type: "array",
8792
+ items: { type: "string" },
8793
+ description: "Fields/patterns to redact (e.g., 'conversation_history', 'secret_*', '*_pii'). Takes absolute priority."
8794
+ },
8795
+ hash: {
8796
+ type: "array",
8797
+ items: { type: "string" },
8798
+ description: "Fields/patterns to replace with SHA-256 hash (e.g., 'user_id', 'session_id')"
8799
+ },
8800
+ summarize: {
8801
+ type: "array",
8802
+ items: { type: "string" },
8803
+ description: "Fields/patterns to flag for summarization (advisory \u2014 agent should compress these before sending)"
8804
+ }
8805
+ },
8806
+ required: ["provider", "allow", "redact"]
8807
+ }
8808
+ },
8809
+ default_action: {
8810
+ type: "string",
8811
+ enum: ["redact", "deny"],
8812
+ description: "Action for fields not matched by any rule. 'redact' removes the field value; 'deny' blocks the entire request. Default: 'redact'."
8813
+ },
8814
+ identity_id: {
8815
+ type: "string",
8816
+ description: "Bind this policy to a specific identity (optional)"
8817
+ }
8818
+ },
8819
+ required: ["policy_name", "rules"]
8820
+ },
8821
+ handler: async (args) => {
8822
+ const policyName = args.policy_name;
8823
+ const rawRules = args.rules;
8824
+ const defaultAction = args.default_action ?? "redact";
8825
+ const identityId = args.identity_id;
8826
+ if (!Array.isArray(rawRules)) {
8827
+ return toolResult({ error: "invalid_rules", message: "rules must be an array" });
8828
+ }
8829
+ if (rawRules.length > MAX_POLICY_RULES) {
8830
+ return toolResult({
8831
+ error: "too_many_rules",
8832
+ message: `Policy has ${rawRules.length} rules, exceeding limit of ${MAX_POLICY_RULES}`
8833
+ });
8834
+ }
8835
+ const rules = [];
8836
+ for (const r of rawRules) {
8837
+ const allow = Array.isArray(r.allow) ? r.allow : [];
8838
+ const redact = Array.isArray(r.redact) ? r.redact : [];
8839
+ const hash2 = Array.isArray(r.hash) ? r.hash : [];
8840
+ const summarize = Array.isArray(r.summarize) ? r.summarize : [];
8841
+ for (const [name, arr] of [["allow", allow], ["redact", redact], ["hash", hash2], ["summarize", summarize]]) {
8842
+ if (arr.length > MAX_PATTERNS_PER_ARRAY) {
8843
+ return toolResult({
8844
+ error: "too_many_patterns",
8845
+ message: `Rule ${name} array has ${arr.length} patterns, exceeding limit of ${MAX_PATTERNS_PER_ARRAY}`
8846
+ });
8847
+ }
8848
+ }
8849
+ rules.push({
8850
+ provider: r.provider ?? "*",
8851
+ allow,
8852
+ redact,
8853
+ hash: hash2,
8854
+ summarize
8855
+ });
8856
+ }
8857
+ const policy = await policyStore.create(
8858
+ policyName,
8859
+ rules,
8860
+ defaultAction,
8861
+ identityId
8862
+ );
8863
+ auditLog.append("l2", "context_gate_set_policy", identityId ?? "system", {
8864
+ policy_id: policy.policy_id,
8865
+ policy_name: policyName,
8866
+ rule_count: rules.length,
8867
+ default_action: defaultAction
8868
+ });
8869
+ return toolResult({
8870
+ policy_id: policy.policy_id,
8871
+ policy_name: policy.policy_name,
8872
+ rules: policy.rules,
8873
+ default_action: policy.default_action,
8874
+ created_at: policy.created_at,
8875
+ message: "Context-gating policy created. Use sanctuary/context_gate_filter to apply this policy before making outbound calls."
8876
+ });
8877
+ }
8878
+ },
8879
+ // ── Apply Template ───────────────────────────────────────────────
8880
+ {
8881
+ name: "sanctuary/context_gate_apply_template",
8882
+ 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.",
8883
+ inputSchema: {
8884
+ type: "object",
8885
+ properties: {
8886
+ template_id: {
8887
+ type: "string",
8888
+ description: "Template to apply: inference-minimal, inference-standard, logging-strict, or tool-api-scoped"
8889
+ },
8890
+ identity_id: {
8891
+ type: "string",
8892
+ description: "Bind this policy to a specific identity (optional)"
8893
+ }
8894
+ },
8895
+ required: ["template_id"]
8896
+ },
8897
+ handler: async (args) => {
8898
+ const templateId = args.template_id;
8899
+ const identityId = args.identity_id;
8900
+ const template = getTemplate(templateId);
8901
+ if (!template) {
8902
+ return toolResult({
8903
+ error: "template_not_found",
8904
+ message: `Unknown template "${templateId}"`,
8905
+ available_templates: listTemplateIds().map((id) => {
8906
+ const t = TEMPLATES[id];
8907
+ return { id, name: t.name, description: t.description };
8908
+ })
8909
+ });
8910
+ }
8911
+ const policy = await policyStore.create(
8912
+ template.name,
8913
+ template.rules,
8914
+ template.default_action,
8915
+ identityId
8916
+ );
8917
+ auditLog.append("l2", "context_gate_apply_template", identityId ?? "system", {
8918
+ policy_id: policy.policy_id,
8919
+ template_id: templateId
8920
+ });
8921
+ return toolResult({
8922
+ policy_id: policy.policy_id,
8923
+ template_applied: templateId,
8924
+ policy_name: template.name,
8925
+ description: template.description,
8926
+ use_when: template.use_when,
8927
+ rules: policy.rules,
8928
+ default_action: policy.default_action,
8929
+ created_at: policy.created_at,
8930
+ 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."
8931
+ });
8932
+ }
8933
+ },
8934
+ // ── Recommend Policy ────────────────────────────────────────────
8935
+ {
8936
+ name: "sanctuary/context_gate_recommend",
8937
+ 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.",
8938
+ inputSchema: {
8939
+ type: "object",
8940
+ properties: {
8941
+ context: {
8942
+ type: "object",
8943
+ description: "A sample context object to analyze. Each top-level key will be classified. Values are inspected for size warnings but not stored."
8944
+ },
8945
+ provider: {
8946
+ type: "string",
8947
+ description: "Provider category to generate rules for. Default: 'inference'."
8948
+ }
8949
+ },
8950
+ required: ["context"]
8951
+ },
8952
+ handler: async (args) => {
8953
+ const context = args.context;
8954
+ const provider = args.provider ?? "inference";
8955
+ const contextKeys = Object.keys(context);
8956
+ if (contextKeys.length > MAX_CONTEXT_FIELDS) {
8957
+ return toolResult({
8958
+ error: "context_too_large",
8959
+ message: `Context has ${contextKeys.length} fields, exceeding limit of ${MAX_CONTEXT_FIELDS}`
8960
+ });
8961
+ }
8962
+ const recommendation = recommendPolicy(context, provider);
8963
+ auditLog.append("l2", "context_gate_recommend", "system", {
8964
+ provider,
8965
+ fields_analyzed: recommendation.summary.total_fields,
8966
+ fields_allow: recommendation.summary.allow,
8967
+ fields_redact: recommendation.summary.redact,
8968
+ fields_hash: recommendation.summary.hash,
8969
+ fields_summarize: recommendation.summary.summarize
8970
+ });
8971
+ return toolResult({
8972
+ ...recommendation,
8973
+ 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.",
8974
+ available_templates: listTemplateIds().map((id) => {
8975
+ const t = TEMPLATES[id];
8976
+ return { id, name: t.name, description: t.description };
8977
+ })
8978
+ });
8979
+ }
8980
+ },
8981
+ // ── Filter Context ──────────────────────────────────────────────
8982
+ {
8983
+ name: "sanctuary/context_gate_filter",
8984
+ 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.",
8985
+ inputSchema: {
8986
+ type: "object",
8987
+ properties: {
8988
+ policy_id: {
8989
+ type: "string",
8990
+ description: "ID of the context-gating policy to apply"
8991
+ },
8992
+ provider: {
8993
+ type: "string",
8994
+ description: "Provider category for this call: inference, tool-api, logging, analytics, peer-agent, or custom"
8995
+ },
8996
+ context: {
8997
+ type: "object",
8998
+ 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"
8999
+ }
9000
+ },
9001
+ required: ["policy_id", "provider", "context"]
9002
+ },
9003
+ handler: async (args) => {
9004
+ const policyId = args.policy_id;
9005
+ const provider = args.provider;
9006
+ const context = args.context;
9007
+ const contextKeys = Object.keys(context);
9008
+ if (contextKeys.length > MAX_CONTEXT_FIELDS) {
9009
+ return toolResult({
9010
+ error: "context_too_large",
9011
+ message: `Context has ${contextKeys.length} fields, exceeding limit of ${MAX_CONTEXT_FIELDS}`
9012
+ });
9013
+ }
9014
+ const policy = await policyStore.get(policyId);
9015
+ if (!policy) {
9016
+ return toolResult({
9017
+ error: "policy_not_found",
9018
+ message: `No context-gating policy found with ID "${policyId}"`
9019
+ });
9020
+ }
9021
+ const result = filterContext(policy, provider, context);
9022
+ const deniedFields = result.decisions.filter((d) => d.action === "deny");
9023
+ if (deniedFields.length > 0) {
9024
+ auditLog.append("l2", "context_gate_deny", policy.identity_id ?? "system", {
9025
+ policy_id: policyId,
9026
+ provider,
9027
+ denied_fields: deniedFields.map((d) => d.field),
9028
+ original_context_hash: result.original_context_hash
9029
+ });
9030
+ return toolResult({
9031
+ blocked: true,
9032
+ reason: "Context contains fields that trigger deny action",
9033
+ denied_fields: deniedFields.map((d) => ({
9034
+ field: d.field,
9035
+ reason: d.reason
9036
+ })),
9037
+ recommendation: "Remove the denied fields from context before retrying, or update the policy to handle these fields differently."
9038
+ });
9039
+ }
9040
+ const safeContext = {};
9041
+ for (const decision of result.decisions) {
9042
+ switch (decision.action) {
9043
+ case "allow":
9044
+ safeContext[decision.field] = context[decision.field];
9045
+ break;
9046
+ case "redact":
9047
+ break;
9048
+ case "hash":
9049
+ safeContext[decision.field] = decision.hash_value;
9050
+ break;
9051
+ case "summarize":
9052
+ safeContext[decision.field] = context[decision.field];
9053
+ break;
9054
+ }
9055
+ }
9056
+ auditLog.append("l2", "context_gate_filter", policy.identity_id ?? "system", {
9057
+ policy_id: policyId,
9058
+ provider,
9059
+ fields_total: Object.keys(context).length,
9060
+ fields_allowed: result.fields_allowed,
9061
+ fields_redacted: result.fields_redacted,
9062
+ fields_hashed: result.fields_hashed,
9063
+ fields_summarized: result.fields_summarized,
9064
+ original_context_hash: result.original_context_hash,
9065
+ filtered_context_hash: result.filtered_context_hash
9066
+ });
9067
+ return toolResult({
9068
+ blocked: false,
9069
+ safe_context: safeContext,
9070
+ summary: {
9071
+ total_fields: Object.keys(context).length,
9072
+ allowed: result.fields_allowed,
9073
+ redacted: result.fields_redacted,
9074
+ hashed: result.fields_hashed,
9075
+ summarized: result.fields_summarized
9076
+ },
9077
+ decisions: result.decisions,
9078
+ audit: {
9079
+ original_context_hash: result.original_context_hash,
9080
+ filtered_context_hash: result.filtered_context_hash,
9081
+ filtered_at: result.filtered_at
9082
+ },
9083
+ 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
9084
+ });
9085
+ }
9086
+ },
9087
+ // ── List Policies ───────────────────────────────────────────────
9088
+ {
9089
+ name: "sanctuary/context_gate_list_policies",
9090
+ description: "List all configured context-gating policies. Returns policy IDs, names, rule summaries, and default actions.",
9091
+ inputSchema: {
9092
+ type: "object",
9093
+ properties: {}
9094
+ },
9095
+ handler: async () => {
9096
+ const policies = await policyStore.list();
9097
+ auditLog.append("l2", "context_gate_list_policies", "system", {
9098
+ policy_count: policies.length
9099
+ });
9100
+ return toolResult({
9101
+ policies: policies.map((p) => ({
9102
+ policy_id: p.policy_id,
9103
+ policy_name: p.policy_name,
9104
+ rule_count: p.rules.length,
9105
+ providers: p.rules.map((r) => r.provider),
9106
+ default_action: p.default_action,
9107
+ identity_id: p.identity_id ?? null,
9108
+ created_at: p.created_at,
9109
+ updated_at: p.updated_at
9110
+ })),
9111
+ count: policies.length,
9112
+ 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.`
9113
+ });
9114
+ }
9115
+ }
9116
+ ];
9117
+ return { tools, policyStore };
9118
+ }
9119
+ function checkMemoryProtection() {
9120
+ const checks = {
9121
+ aslr_enabled: checkASLR(),
9122
+ stack_canaries: true,
9123
+ // Enabled by default in Node.js runtime
9124
+ secure_buffer_zeros: true,
9125
+ // We use crypto.randomBytes and explicit zeroing
9126
+ argon2id_kdf: true
9127
+ // Master key derivation uses Argon2id
9128
+ };
9129
+ const activeCount = Object.values(checks).filter((v) => v).length;
9130
+ const overall = activeCount >= 4 ? "full" : activeCount >= 3 ? "partial" : "minimal";
9131
+ return {
9132
+ ...checks,
9133
+ overall
9134
+ };
9135
+ }
9136
+ function checkASLR() {
9137
+ if (process.platform === "linux") {
9138
+ try {
9139
+ const result = child_process.execSync("cat /proc/sys/kernel/randomize_va_space", {
9140
+ encoding: "utf-8",
9141
+ stdio: ["pipe", "pipe", "ignore"]
9142
+ }).trim();
9143
+ return result === "2";
9144
+ } catch {
9145
+ return false;
9146
+ }
9147
+ }
9148
+ if (process.platform === "darwin") {
9149
+ return true;
9150
+ }
9151
+ return false;
9152
+ }
9153
+ function checkProcessIsolation() {
9154
+ const isContainer = detectContainer();
9155
+ const isVM = detectVM();
9156
+ const isSandboxed = detectSandbox();
9157
+ let isolationLevel = "none";
9158
+ if (isContainer) isolationLevel = "hardened";
9159
+ else if (isVM) isolationLevel = "hardened";
9160
+ else if (isSandboxed) isolationLevel = "basic";
9161
+ const details = {};
9162
+ if (isContainer && isContainer !== true) details.container_type = isContainer;
9163
+ if (isVM && isVM !== true) details.vm_type = isVM;
9164
+ if (isSandboxed && isSandboxed !== true) details.sandbox_type = isSandboxed;
9165
+ return {
9166
+ isolation_level: isolationLevel,
9167
+ is_container: isContainer !== false,
9168
+ is_vm: isVM !== false,
9169
+ is_sandboxed: isSandboxed !== false,
9170
+ is_tee: false,
9171
+ details
9172
+ };
9173
+ }
9174
+ function detectContainer() {
9175
+ try {
9176
+ if (process.env.DOCKER_HOST) return "docker";
9177
+ try {
9178
+ fs.statSync("/.dockerenv");
9179
+ return "docker";
9180
+ } catch {
9181
+ }
9182
+ if (process.platform === "linux") {
9183
+ const cgroup = child_process.execSync("cat /proc/1/cgroup 2>/dev/null || echo ''", {
9184
+ encoding: "utf-8"
9185
+ });
9186
+ if (cgroup.includes("docker")) return "docker";
9187
+ if (cgroup.includes("lxc")) return "lxc";
9188
+ if (cgroup.includes("kubepods") || cgroup.includes("kubernetes")) return "kubernetes";
9189
+ }
9190
+ if (process.env.container === "podman") return "podman";
9191
+ if (process.env.CONTAINER_ID) return "oci";
9192
+ return false;
9193
+ } catch {
9194
+ return false;
9195
+ }
9196
+ }
9197
+ function detectVM() {
9198
+ if (process.platform === "linux") {
9199
+ try {
9200
+ const dmidecode = child_process.execSync("dmidecode -s system-product-name 2>/dev/null || echo ''", {
9201
+ encoding: "utf-8"
9202
+ }).toLowerCase();
9203
+ if (dmidecode.includes("vmware")) return "vmware";
9204
+ if (dmidecode.includes("virtualbox")) return "virtualbox";
9205
+ if (dmidecode.includes("kvm")) return "kvm";
9206
+ if (dmidecode.includes("xen")) return "xen";
9207
+ if (dmidecode.includes("hyper-v")) return "hyper-v";
9208
+ const cpuinfo = child_process.execSync("grep -i hypervisor /proc/cpuinfo || echo ''", {
9209
+ encoding: "utf-8"
9210
+ });
9211
+ if (cpuinfo.length > 0) return "detected";
9212
+ } catch {
9213
+ }
9214
+ }
9215
+ if (process.platform === "darwin") {
9216
+ try {
9217
+ const bootargs = child_process.execSync(
9218
+ "nvram boot-args 2>/dev/null | grep -i 'parallels\\|vmware\\|virtualbox' || echo ''",
9219
+ {
9220
+ encoding: "utf-8"
9221
+ }
9222
+ );
9223
+ if (bootargs.length > 0) return "detected";
9224
+ } catch {
9225
+ }
9226
+ }
9227
+ return false;
9228
+ }
9229
+ function detectSandbox() {
9230
+ if (process.platform === "darwin") {
9231
+ if (process.env.APP_SANDBOX_READ_ONLY_HOME === "1") return "app-sandbox";
9232
+ if (process.env.TMPDIR && process.env.TMPDIR.includes("AppSandbox")) return "app-sandbox";
9233
+ }
9234
+ if (process.platform === "openbsd") {
9235
+ try {
9236
+ const pledge = child_process.execSync("pledge -v 2>/dev/null || echo ''", {
9237
+ encoding: "utf-8"
9238
+ });
9239
+ if (pledge.length > 0) return "pledge";
9240
+ } catch {
9241
+ }
9242
+ }
9243
+ if (process.platform === "linux") {
9244
+ if (process.env.container === "lxc") return "lxc";
9245
+ try {
9246
+ const context = child_process.execSync("getenforce 2>/dev/null || echo ''", {
9247
+ encoding: "utf-8"
9248
+ }).trim();
9249
+ if (context === "Enforcing") return "selinux";
9250
+ } catch {
9251
+ }
9252
+ }
9253
+ return false;
9254
+ }
9255
+ function checkFilesystemPermissions(storagePath) {
9256
+ try {
9257
+ const stats = fs.statSync(storagePath);
9258
+ const mode = stats.mode & parseInt("777", 8);
9259
+ const modeString = mode.toString(8).padStart(3, "0");
9260
+ const isSecure = mode === parseInt("700", 8);
9261
+ const groupReadable = (mode & parseInt("040", 8)) !== 0;
9262
+ const othersReadable = (mode & parseInt("007", 8)) !== 0;
9263
+ const currentUid = process.getuid?.() || -1;
9264
+ const ownerIsCurrentUser = stats.uid === currentUid;
9265
+ let overall = "secure";
9266
+ if (groupReadable || othersReadable) overall = "insecure";
9267
+ else if (!ownerIsCurrentUser) overall = "warning";
9268
+ return {
9269
+ sanctuary_storage_protected: isSecure,
9270
+ sanctuary_storage_mode: modeString,
9271
+ owner_is_current_user: ownerIsCurrentUser,
9272
+ group_readable: groupReadable,
9273
+ others_readable: othersReadable,
9274
+ overall
9275
+ };
9276
+ } catch {
9277
+ return {
9278
+ sanctuary_storage_protected: false,
9279
+ sanctuary_storage_mode: "unknown",
9280
+ owner_is_current_user: false,
9281
+ group_readable: false,
9282
+ others_readable: false,
9283
+ overall: "warning"
9284
+ };
9285
+ }
9286
+ }
9287
+ function checkRuntimeIntegrity() {
9288
+ return {
9289
+ config_hash_stable: true,
9290
+ environment_state: "clean",
9291
+ discrepancies: []
9292
+ };
9293
+ }
9294
+ function assessL2Hardening(storagePath) {
9295
+ const memory = checkMemoryProtection();
9296
+ const isolation = checkProcessIsolation();
9297
+ const filesystem = checkFilesystemPermissions(storagePath);
9298
+ const integrity = checkRuntimeIntegrity();
9299
+ let checksPassed = 0;
9300
+ let checksTotal = 0;
9301
+ if (memory.aslr_enabled) checksPassed++;
9302
+ checksTotal++;
9303
+ if (memory.stack_canaries) checksPassed++;
9304
+ checksTotal++;
9305
+ if (memory.secure_buffer_zeros) checksPassed++;
9306
+ checksTotal++;
9307
+ if (memory.argon2id_kdf) checksPassed++;
9308
+ checksTotal++;
9309
+ if (isolation.is_container) checksPassed++;
9310
+ checksTotal++;
9311
+ if (isolation.is_vm) checksPassed++;
9312
+ checksTotal++;
9313
+ if (isolation.is_sandboxed) checksPassed++;
9314
+ checksTotal++;
9315
+ if (filesystem.sanctuary_storage_protected) checksPassed++;
9316
+ checksTotal++;
9317
+ {
9318
+ checksPassed++;
9319
+ }
9320
+ checksTotal++;
9321
+ let hardeningLevel = isolation.isolation_level;
9322
+ if (filesystem.overall === "insecure" || memory.overall === "none" || memory.overall === "minimal") {
9323
+ if (hardeningLevel === "hardened") {
9324
+ hardeningLevel = "basic";
9325
+ } else if (hardeningLevel === "basic") {
9326
+ hardeningLevel = "none";
9327
+ }
9328
+ }
9329
+ const summaryParts = [];
9330
+ if (isolation.is_container || isolation.is_vm) {
9331
+ summaryParts.push(`Running in ${isolation.details.container_type || isolation.details.vm_type || "isolated environment"}`);
9332
+ }
9333
+ if (memory.aslr_enabled) {
9334
+ summaryParts.push("ASLR enabled");
9335
+ }
9336
+ if (filesystem.sanctuary_storage_protected) {
9337
+ summaryParts.push("Storage permissions secured (0700)");
9338
+ }
9339
+ const summary = summaryParts.length > 0 ? summaryParts.join("; ") : "No process-level hardening detected";
9340
+ return {
9341
+ hardening_level: hardeningLevel,
9342
+ memory_protection: memory,
9343
+ process_isolation: isolation,
9344
+ filesystem_permissions: filesystem,
9345
+ runtime_integrity: integrity,
9346
+ checks_passed: checksPassed,
9347
+ checks_total: checksTotal,
9348
+ summary
9349
+ };
9350
+ }
9351
+
9352
+ // src/l2-operational/hardening-tools.ts
9353
+ function createL2HardeningTools(storagePath, auditLog) {
9354
+ return [
9355
+ {
9356
+ name: "sanctuary/l2_hardening_status",
9357
+ 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.",
9358
+ inputSchema: {
9359
+ type: "object",
9360
+ properties: {
9361
+ include_details: {
9362
+ type: "boolean",
9363
+ description: "If true, include detailed check results for memory, process, and filesystem. If false, show summary only.",
9364
+ default: false
9365
+ }
9366
+ }
9367
+ },
9368
+ handler: async (args) => {
9369
+ const includeDetails = args.include_details ?? false;
9370
+ const status = assessL2Hardening(storagePath);
9371
+ auditLog.append(
9372
+ "l2",
9373
+ "l2_hardening_status",
9374
+ "system",
9375
+ { include_details: includeDetails }
9376
+ );
9377
+ if (includeDetails) {
9378
+ return toolResult({
9379
+ hardening_level: status.hardening_level,
9380
+ summary: status.summary,
9381
+ checks_passed: status.checks_passed,
9382
+ checks_total: status.checks_total,
9383
+ memory_protection: {
9384
+ aslr_enabled: status.memory_protection.aslr_enabled,
9385
+ stack_canaries: status.memory_protection.stack_canaries,
9386
+ secure_buffer_zeros: status.memory_protection.secure_buffer_zeros,
9387
+ argon2id_kdf: status.memory_protection.argon2id_kdf,
9388
+ overall: status.memory_protection.overall
9389
+ },
9390
+ process_isolation: {
9391
+ isolation_level: status.process_isolation.isolation_level,
9392
+ is_container: status.process_isolation.is_container,
9393
+ is_vm: status.process_isolation.is_vm,
9394
+ is_sandboxed: status.process_isolation.is_sandboxed,
9395
+ is_tee: status.process_isolation.is_tee,
9396
+ details: status.process_isolation.details
9397
+ },
9398
+ filesystem_permissions: {
9399
+ sanctuary_storage_protected: status.filesystem_permissions.sanctuary_storage_protected,
9400
+ sanctuary_storage_mode: status.filesystem_permissions.sanctuary_storage_mode,
9401
+ owner_is_current_user: status.filesystem_permissions.owner_is_current_user,
9402
+ group_readable: status.filesystem_permissions.group_readable,
9403
+ others_readable: status.filesystem_permissions.others_readable,
9404
+ overall: status.filesystem_permissions.overall
9405
+ },
9406
+ runtime_integrity: {
9407
+ config_hash_stable: status.runtime_integrity.config_hash_stable,
9408
+ environment_state: status.runtime_integrity.environment_state,
9409
+ discrepancies: status.runtime_integrity.discrepancies
9410
+ }
9411
+ });
9412
+ } else {
9413
+ return toolResult({
9414
+ hardening_level: status.hardening_level,
9415
+ summary: status.summary,
9416
+ checks_passed: status.checks_passed,
9417
+ checks_total: status.checks_total,
9418
+ note: "Pass include_details: true to see full breakdown of memory, process isolation, and filesystem checks."
9419
+ });
9420
+ }
9421
+ }
9422
+ },
9423
+ {
9424
+ name: "sanctuary/l2_verify_isolation",
9425
+ 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.",
9426
+ inputSchema: {
9427
+ type: "object",
9428
+ properties: {
9429
+ check_filesystem: {
9430
+ type: "boolean",
9431
+ description: "If true, verify Sanctuary storage directory permissions.",
9432
+ default: true
9433
+ },
9434
+ check_memory: {
9435
+ type: "boolean",
9436
+ description: "If true, verify memory protection mechanisms (ASLR, etc.).",
9437
+ default: true
9438
+ },
9439
+ check_process: {
9440
+ type: "boolean",
9441
+ description: "If true, detect container, VM, or sandbox environment.",
9442
+ default: true
9443
+ }
9444
+ }
9445
+ },
9446
+ handler: async (args) => {
9447
+ const checkFilesystem = args.check_filesystem ?? true;
9448
+ const checkMemory = args.check_memory ?? true;
9449
+ const checkProcess = args.check_process ?? true;
9450
+ const status = assessL2Hardening(storagePath);
9451
+ auditLog.append(
9452
+ "l2",
9453
+ "l2_verify_isolation",
9454
+ "system",
9455
+ {
9456
+ check_filesystem: checkFilesystem,
9457
+ check_memory: checkMemory,
9458
+ check_process: checkProcess
9459
+ }
9460
+ );
9461
+ const results = {
9462
+ isolation_level: status.hardening_level,
9463
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
9464
+ };
9465
+ if (checkFilesystem) {
9466
+ const fs = status.filesystem_permissions;
9467
+ results.filesystem = {
9468
+ sanctuary_storage_protected: fs.sanctuary_storage_protected,
9469
+ storage_mode: fs.sanctuary_storage_mode,
9470
+ is_secure: fs.overall === "secure",
9471
+ issues: fs.overall === "insecure" ? [
9472
+ "Storage directory is readable by group or others. Recommend: chmod 700 on Sanctuary storage path."
9473
+ ] : fs.overall === "warning" ? [
9474
+ "Storage directory not owned by current user. Verify correct user is running Sanctuary."
9475
+ ] : []
9476
+ };
9477
+ }
9478
+ if (checkMemory) {
9479
+ const mem = status.memory_protection;
9480
+ const issues = [];
9481
+ if (!mem.aslr_enabled) {
9482
+ issues.push(
9483
+ "ASLR not detected. On Linux, enable with: echo 2 | sudo tee /proc/sys/kernel/randomize_va_space"
9484
+ );
9485
+ }
9486
+ results.memory = {
9487
+ aslr_enabled: mem.aslr_enabled,
9488
+ stack_canaries: mem.stack_canaries,
9489
+ secure_buffer_handling: mem.secure_buffer_zeros,
9490
+ argon2id_key_derivation: mem.argon2id_kdf,
9491
+ protection_level: mem.overall,
9492
+ issues
9493
+ };
9494
+ }
9495
+ if (checkProcess) {
9496
+ const iso = status.process_isolation;
9497
+ results.process = {
9498
+ isolation_level: iso.isolation_level,
9499
+ in_container: iso.is_container,
9500
+ in_vm: iso.is_vm,
9501
+ sandboxed: iso.is_sandboxed,
9502
+ has_tee: iso.is_tee,
9503
+ environment: iso.details,
9504
+ 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."
9505
+ };
9506
+ }
9507
+ return toolResult({
9508
+ status: "verified",
9509
+ results
9510
+ });
9511
+ }
9512
+ }
9513
+ ];
9514
+ }
9515
+
9516
+ // src/index.ts
9517
+ init_encoding();
9518
+
9519
+ // src/storage/memory.ts
9520
+ var MemoryStorage = class {
9521
+ store = /* @__PURE__ */ new Map();
9522
+ storageKey(namespace, key) {
9523
+ return `${namespace}/${key}`;
9524
+ }
9525
+ async write(namespace, key, data) {
9526
+ this.store.set(this.storageKey(namespace, key), {
9527
+ data: new Uint8Array(data),
9528
+ // Copy to prevent external mutation
9529
+ modified_at: (/* @__PURE__ */ new Date()).toISOString()
9530
+ });
9531
+ }
9532
+ async read(namespace, key) {
9533
+ const entry = this.store.get(this.storageKey(namespace, key));
9534
+ if (!entry) return null;
9535
+ return new Uint8Array(entry.data);
6675
9536
  }
6676
9537
  async delete(namespace, key, _secureOverwrite) {
6677
9538
  return this.store.delete(this.storageKey(namespace, key));
@@ -6742,15 +9603,51 @@ async function createSanctuaryServer(options) {
6742
9603
  }
6743
9604
  } else {
6744
9605
  keyProtection = "recovery-key";
6745
- const existing = await storage.read("_meta", "recovery-key-hash");
6746
- if (existing) {
6747
- masterKey = generateRandomKey();
6748
- recoveryKey = toBase64url(masterKey);
9606
+ const { hashToString: hashToString2 } = await Promise.resolve().then(() => (init_hashing(), hashing_exports));
9607
+ const { stringToBytes: stringToBytes2, bytesToString: bytesToString2 } = await Promise.resolve().then(() => (init_encoding(), encoding_exports));
9608
+ const { fromBase64url: fromBase64url2 } = await Promise.resolve().then(() => (init_encoding(), encoding_exports));
9609
+ const { constantTimeEqual: constantTimeEqual2 } = await Promise.resolve().then(() => (init_encoding(), encoding_exports));
9610
+ const existingHash = await storage.read("_meta", "recovery-key-hash");
9611
+ if (existingHash) {
9612
+ const envRecoveryKey = process.env.SANCTUARY_RECOVERY_KEY;
9613
+ if (!envRecoveryKey) {
9614
+ throw new Error(
9615
+ "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."
9616
+ );
9617
+ }
9618
+ let recoveryKeyBytes;
9619
+ try {
9620
+ recoveryKeyBytes = fromBase64url2(envRecoveryKey);
9621
+ } catch {
9622
+ throw new Error(
9623
+ "Sanctuary: SANCTUARY_RECOVERY_KEY is not valid base64url. The recovery key should be the exact string shown at first run."
9624
+ );
9625
+ }
9626
+ if (recoveryKeyBytes.length !== 32) {
9627
+ throw new Error(
9628
+ "Sanctuary: SANCTUARY_RECOVERY_KEY has incorrect length. The recovery key should be the exact string shown at first run."
9629
+ );
9630
+ }
9631
+ const providedHash = hashToString2(recoveryKeyBytes);
9632
+ const storedHash = bytesToString2(existingHash);
9633
+ const providedHashBytes = stringToBytes2(providedHash);
9634
+ const storedHashBytes = stringToBytes2(storedHash);
9635
+ if (!constantTimeEqual2(providedHashBytes, storedHashBytes)) {
9636
+ throw new Error(
9637
+ "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."
9638
+ );
9639
+ }
9640
+ masterKey = recoveryKeyBytes;
6749
9641
  } else {
9642
+ const existingNamespaces = await storage.list("_meta");
9643
+ const hasKeyParams = existingNamespaces.some((e) => e.key === "key-params");
9644
+ if (hasKeyParams) {
9645
+ throw new Error(
9646
+ "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."
9647
+ );
9648
+ }
6750
9649
  masterKey = generateRandomKey();
6751
9650
  recoveryKey = toBase64url(masterKey);
6752
- const { hashToString: hashToString2 } = await Promise.resolve().then(() => (init_hashing(), hashing_exports));
6753
- const { stringToBytes: stringToBytes2 } = await Promise.resolve().then(() => (init_encoding(), encoding_exports));
6754
9651
  const keyHash = hashToString2(masterKey);
6755
9652
  await storage.write(
6756
9653
  "_meta",
@@ -6837,7 +9734,7 @@ async function createSanctuaryServer(options) {
6837
9734
  layer: "l2",
6838
9735
  description: "Process-level isolation only (no TEE)",
6839
9736
  severity: "warning",
6840
- mitigation: "TEE support planned for v0.3.0"
9737
+ mitigation: "TEE support planned for a future release"
6841
9738
  });
6842
9739
  if (config.disclosure.proof_system === "commitment-only") {
6843
9740
  degradations.push({
@@ -6977,7 +9874,7 @@ async function createSanctuaryServer(options) {
6977
9874
  },
6978
9875
  limitations: [
6979
9876
  "L1 identity uses ed25519 only; KERI support planned for v0.2.0",
6980
- "L2 isolation is process-level only; TEE support planned for v0.3.0",
9877
+ "L2 isolation is process-level only; TEE support planned for a future release",
6981
9878
  "L3 uses commitment schemes only; ZK proofs planned for v0.2.0",
6982
9879
  "L4 Sybil resistance is escrow-based only",
6983
9880
  "Spec license: CC-BY-4.0 | Code license: Apache-2.0"
@@ -6998,7 +9895,7 @@ async function createSanctuaryServer(options) {
6998
9895
  masterKey,
6999
9896
  auditLog
7000
9897
  );
7001
- const { tools: l4Tools } = createL4Tools(
9898
+ const { tools: l4Tools} = createL4Tools(
7002
9899
  storage,
7003
9900
  masterKey,
7004
9901
  identityManager,
@@ -7016,6 +9913,13 @@ async function createSanctuaryServer(options) {
7016
9913
  auditLog,
7017
9914
  handshakeResults
7018
9915
  );
9916
+ const { tools: auditTools } = createAuditTools(config);
9917
+ const { tools: contextGateTools } = createContextGateTools(
9918
+ storage,
9919
+ masterKey,
9920
+ auditLog
9921
+ );
9922
+ const hardeningTools = createL2HardeningTools(config.storage_path, auditLog);
7019
9923
  const policy = await loadPrincipalPolicy(config.storage_path);
7020
9924
  const baseline = new BaselineTracker(storage, masterKey);
7021
9925
  await baseline.load();
@@ -7031,7 +9935,7 @@ async function createSanctuaryServer(options) {
7031
9935
  port: config.dashboard.port,
7032
9936
  host: config.dashboard.host,
7033
9937
  timeout_seconds: policy.approval_channel.timeout_seconds,
7034
- auto_deny: policy.approval_channel.auto_deny,
9938
+ // SEC-002: auto_deny removed — timeout always denies
7035
9939
  auth_token: authToken,
7036
9940
  tls: config.dashboard.tls
7037
9941
  });
@@ -7044,8 +9948,8 @@ async function createSanctuaryServer(options) {
7044
9948
  webhook_secret: config.webhook.secret,
7045
9949
  callback_port: config.webhook.callback_port,
7046
9950
  callback_host: config.webhook.callback_host,
7047
- timeout_seconds: policy.approval_channel.timeout_seconds,
7048
- auto_deny: policy.approval_channel.auto_deny
9951
+ timeout_seconds: policy.approval_channel.timeout_seconds
9952
+ // SEC-002: auto_deny removed — timeout always denies
7049
9953
  });
7050
9954
  await webhook.start();
7051
9955
  approvalChannel = webhook;
@@ -7064,6 +9968,9 @@ async function createSanctuaryServer(options) {
7064
9968
  ...handshakeTools,
7065
9969
  ...federationTools,
7066
9970
  ...bridgeTools,
9971
+ ...auditTools,
9972
+ ...contextGateTools,
9973
+ ...hardeningTools,
7067
9974
  manifestTool
7068
9975
  ];
7069
9976
  const server = createServer(allTools, { gate });
@@ -7093,8 +10000,10 @@ exports.ApprovalGate = ApprovalGate;
7093
10000
  exports.AuditLog = AuditLog;
7094
10001
  exports.AutoApproveChannel = AutoApproveChannel;
7095
10002
  exports.BaselineTracker = BaselineTracker;
10003
+ exports.CONTEXT_GATE_TEMPLATES = TEMPLATES;
7096
10004
  exports.CallbackApprovalChannel = CallbackApprovalChannel;
7097
10005
  exports.CommitmentStore = CommitmentStore;
10006
+ exports.ContextGatePolicyStore = ContextGatePolicyStore;
7098
10007
  exports.DashboardApprovalChannel = DashboardApprovalChannel;
7099
10008
  exports.FederationRegistry = FederationRegistry;
7100
10009
  exports.FilesystemStorage = FilesystemStorage;
@@ -7106,6 +10015,7 @@ exports.StderrApprovalChannel = StderrApprovalChannel;
7106
10015
  exports.TIER_WEIGHTS = TIER_WEIGHTS;
7107
10016
  exports.WebhookApprovalChannel = WebhookApprovalChannel;
7108
10017
  exports.canonicalize = canonicalize;
10018
+ exports.classifyField = classifyField;
7109
10019
  exports.completeHandshake = completeHandshake;
7110
10020
  exports.computeWeightedScore = computeWeightedScore;
7111
10021
  exports.createBridgeCommitment = createBridgeCommitment;
@@ -7113,10 +10023,15 @@ exports.createPedersenCommitment = createPedersenCommitment;
7113
10023
  exports.createProofOfKnowledge = createProofOfKnowledge;
7114
10024
  exports.createRangeProof = createRangeProof;
7115
10025
  exports.createSanctuaryServer = createSanctuaryServer;
10026
+ exports.evaluateField = evaluateField;
10027
+ exports.filterContext = filterContext;
7116
10028
  exports.generateSHR = generateSHR;
10029
+ exports.getTemplate = getTemplate;
7117
10030
  exports.initiateHandshake = initiateHandshake;
10031
+ exports.listTemplateIds = listTemplateIds;
7118
10032
  exports.loadConfig = loadConfig;
7119
10033
  exports.loadPrincipalPolicy = loadPrincipalPolicy;
10034
+ exports.recommendPolicy = recommendPolicy;
7120
10035
  exports.resolveTier = resolveTier;
7121
10036
  exports.respondToHandshake = respondToHandshake;
7122
10037
  exports.signPayload = signPayload;