@sanctuary-framework/mcp-server 0.3.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -7,6 +7,7 @@ var stdio_js = require('@modelcontextprotocol/sdk/server/stdio.js');
7
7
  var promises = require('fs/promises');
8
8
  var path = require('path');
9
9
  var os = require('os');
10
+ var module$1 = require('module');
10
11
  var crypto = require('crypto');
11
12
  var aes_js = require('@noble/ciphers/aes.js');
12
13
  var ed25519 = require('@noble/curves/ed25519');
@@ -17,7 +18,9 @@ var types_js = require('@modelcontextprotocol/sdk/types.js');
17
18
  var http = require('http');
18
19
  var https = require('https');
19
20
  var fs = require('fs');
21
+ var child_process = require('child_process');
20
22
 
23
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
21
24
  var __defProp = Object.defineProperty;
22
25
  var __getOwnPropNames = Object.getOwnPropertyNames;
23
26
  var __esm = (fn, res) => function __init() {
@@ -206,9 +209,12 @@ var init_hashing = __esm({
206
209
  init_encoding();
207
210
  }
208
211
  });
212
+ var require2 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli.cjs', document.baseURI).href)));
213
+ var { version: PKG_VERSION } = require2("../package.json");
214
+ var SANCTUARY_VERSION = PKG_VERSION;
209
215
  function defaultConfig() {
210
216
  return {
211
- version: "0.3.0",
217
+ version: PKG_VERSION,
212
218
  storage_path: path.join(os.homedir(), ".sanctuary"),
213
219
  state: {
214
220
  encryption: "aes-256-gcm",
@@ -334,6 +340,18 @@ function validateConfig(config) {
334
340
  `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.`
335
341
  );
336
342
  }
343
+ const implementedDisclosurePolicy = /* @__PURE__ */ new Set(["minimum-necessary"]);
344
+ if (!implementedDisclosurePolicy.has(config.disclosure.default_policy)) {
345
+ errors.push(
346
+ `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.`
347
+ );
348
+ }
349
+ const implementedReputationMode = /* @__PURE__ */ new Set(["self-custodied"]);
350
+ if (!implementedReputationMode.has(config.reputation.mode)) {
351
+ errors.push(
352
+ `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.`
353
+ );
354
+ }
337
355
  if (errors.length > 0) {
338
356
  throw new Error(
339
357
  `Sanctuary configuration references unimplemented features:
@@ -1039,6 +1057,8 @@ var StateStore = class {
1039
1057
  };
1040
1058
  }
1041
1059
  };
1060
+ var require3 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli.cjs', document.baseURI).href)));
1061
+ var { version: PKG_VERSION2 } = require3("../package.json");
1042
1062
  var MAX_STRING_BYTES = 1048576;
1043
1063
  var MAX_BUNDLE_BYTES = 5242880;
1044
1064
  var BUNDLE_FIELDS = /* @__PURE__ */ new Set(["bundle"]);
@@ -1121,7 +1141,7 @@ function createServer(tools, options) {
1121
1141
  const server = new index_js.Server(
1122
1142
  {
1123
1143
  name: "sanctuary-mcp-server",
1124
- version: "0.3.0"
1144
+ version: PKG_VERSION2
1125
1145
  },
1126
1146
  {
1127
1147
  capabilities: {
@@ -3575,7 +3595,9 @@ var DEFAULT_POLICY = {
3575
3595
  "state_delete",
3576
3596
  "identity_rotate",
3577
3597
  "reputation_import",
3578
- "bootstrap_provide_guarantee"
3598
+ "reputation_export",
3599
+ "bootstrap_provide_guarantee",
3600
+ "decommission_certificate"
3579
3601
  ],
3580
3602
  tier2_anomaly: DEFAULT_TIER2,
3581
3603
  tier3_always_allow: [
@@ -3592,7 +3614,6 @@ var DEFAULT_POLICY = {
3592
3614
  "disclosure_evaluate",
3593
3615
  "reputation_record",
3594
3616
  "reputation_query",
3595
- "reputation_export",
3596
3617
  "bootstrap_create_escrow",
3597
3618
  "exec_attest",
3598
3619
  "monitor_health",
@@ -3614,7 +3635,19 @@ var DEFAULT_POLICY = {
3614
3635
  "zk_prove",
3615
3636
  "zk_verify",
3616
3637
  "zk_range_prove",
3617
- "zk_range_verify"
3638
+ "zk_range_verify",
3639
+ "context_gate_set_policy",
3640
+ "context_gate_apply_template",
3641
+ "context_gate_recommend",
3642
+ "context_gate_filter",
3643
+ "context_gate_list_policies",
3644
+ "l2_hardening_status",
3645
+ "l2_verify_isolation",
3646
+ "sovereignty_audit",
3647
+ "shr_gateway_export",
3648
+ "bridge_commit",
3649
+ "bridge_verify",
3650
+ "bridge_attest"
3618
3651
  ],
3619
3652
  approval_channel: DEFAULT_CHANNEL
3620
3653
  };
@@ -3716,6 +3749,7 @@ tier1_always_approve:
3716
3749
  - state_delete
3717
3750
  - identity_rotate
3718
3751
  - reputation_import
3752
+ - reputation_export
3719
3753
  - bootstrap_provide_guarantee
3720
3754
 
3721
3755
  # \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
@@ -3745,7 +3779,6 @@ tier3_always_allow:
3745
3779
  - disclosure_evaluate
3746
3780
  - reputation_record
3747
3781
  - reputation_query
3748
- - reputation_export
3749
3782
  - bootstrap_create_escrow
3750
3783
  - exec_attest
3751
3784
  - monitor_health
@@ -3768,6 +3801,16 @@ tier3_always_allow:
3768
3801
  - zk_verify
3769
3802
  - zk_range_prove
3770
3803
  - zk_range_verify
3804
+ - context_gate_set_policy
3805
+ - context_gate_apply_template
3806
+ - context_gate_recommend
3807
+ - context_gate_filter
3808
+ - context_gate_list_policies
3809
+ - sovereignty_audit
3810
+ - shr_gateway_export
3811
+ - bridge_commit
3812
+ - bridge_verify
3813
+ - bridge_attest
3771
3814
 
3772
3815
  # \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
3773
3816
  # How Sanctuary reaches you when approval is needed.
@@ -4546,6 +4589,10 @@ function generateDashboardHTML(options) {
4546
4589
  // src/principal-policy/dashboard.ts
4547
4590
  var SESSION_TTL_MS = 5 * 60 * 1e3;
4548
4591
  var MAX_SESSIONS = 1e3;
4592
+ var RATE_LIMIT_WINDOW_MS = 6e4;
4593
+ var RATE_LIMIT_GENERAL = 120;
4594
+ var RATE_LIMIT_DECISIONS = 20;
4595
+ var MAX_RATE_LIMIT_ENTRIES = 1e4;
4549
4596
  var DashboardApprovalChannel = class {
4550
4597
  config;
4551
4598
  pending = /* @__PURE__ */ new Map();
@@ -4560,13 +4607,15 @@ var DashboardApprovalChannel = class {
4560
4607
  /** SEC-012: Short-lived session store. Sessions replace URL query tokens. */
4561
4608
  sessions = /* @__PURE__ */ new Map();
4562
4609
  sessionCleanupTimer = null;
4610
+ /** Rate limiting: per-IP request tracking */
4611
+ rateLimits = /* @__PURE__ */ new Map();
4563
4612
  constructor(config) {
4564
4613
  this.config = config;
4565
4614
  this.authToken = config.auth_token;
4566
4615
  this.useTLS = !!(config.tls?.cert_path && config.tls?.key_path);
4567
4616
  this.dashboardHTML = generateDashboardHTML({
4568
4617
  timeoutSeconds: config.timeout_seconds,
4569
- serverVersion: "0.3.0",
4618
+ serverVersion: SANCTUARY_VERSION,
4570
4619
  authToken: this.authToken
4571
4620
  });
4572
4621
  this.sessionCleanupTimer = setInterval(() => this.cleanupSessions(), 6e4);
@@ -4645,6 +4694,7 @@ var DashboardApprovalChannel = class {
4645
4694
  clearInterval(this.sessionCleanupTimer);
4646
4695
  this.sessionCleanupTimer = null;
4647
4696
  }
4697
+ this.rateLimits.clear();
4648
4698
  if (this.httpServer) {
4649
4699
  return new Promise((resolve) => {
4650
4700
  this.httpServer.close(() => resolve());
@@ -4770,6 +4820,61 @@ var DashboardApprovalChannel = class {
4770
4820
  }
4771
4821
  }
4772
4822
  }
4823
+ // ── Rate Limiting ─────────────────────────────────────────────────
4824
+ /**
4825
+ * Get the remote address from a request, normalizing IPv6-mapped IPv4.
4826
+ */
4827
+ getRemoteAddr(req) {
4828
+ const addr = req.socket.remoteAddress ?? "unknown";
4829
+ return addr.startsWith("::ffff:") ? addr.slice(7) : addr;
4830
+ }
4831
+ /**
4832
+ * Check rate limit for a request. Returns true if allowed, false if rate-limited.
4833
+ * When rate-limited, sends a 429 response.
4834
+ */
4835
+ checkRateLimit(req, res, type) {
4836
+ const addr = this.getRemoteAddr(req);
4837
+ const now = Date.now();
4838
+ const windowStart = now - RATE_LIMIT_WINDOW_MS;
4839
+ let entry = this.rateLimits.get(addr);
4840
+ if (!entry) {
4841
+ if (this.rateLimits.size >= MAX_RATE_LIMIT_ENTRIES) {
4842
+ this.pruneRateLimits(now);
4843
+ }
4844
+ entry = { general: [], decisions: [] };
4845
+ this.rateLimits.set(addr, entry);
4846
+ }
4847
+ entry.general = entry.general.filter((t) => t > windowStart);
4848
+ entry.decisions = entry.decisions.filter((t) => t > windowStart);
4849
+ const limit = type === "decisions" ? RATE_LIMIT_DECISIONS : RATE_LIMIT_GENERAL;
4850
+ const timestamps = entry[type];
4851
+ if (timestamps.length >= limit) {
4852
+ const retryAfter = Math.ceil((timestamps[0] + RATE_LIMIT_WINDOW_MS - now) / 1e3);
4853
+ res.writeHead(429, {
4854
+ "Content-Type": "application/json",
4855
+ "Retry-After": String(Math.max(1, retryAfter))
4856
+ });
4857
+ res.end(JSON.stringify({
4858
+ error: "Rate limit exceeded",
4859
+ retry_after_seconds: Math.max(1, retryAfter)
4860
+ }));
4861
+ return false;
4862
+ }
4863
+ timestamps.push(now);
4864
+ return true;
4865
+ }
4866
+ /**
4867
+ * Remove stale entries from the rate limit map.
4868
+ */
4869
+ pruneRateLimits(now) {
4870
+ const windowStart = now - RATE_LIMIT_WINDOW_MS;
4871
+ for (const [addr, entry] of this.rateLimits) {
4872
+ const hasRecent = entry.general.some((t) => t > windowStart) || entry.decisions.some((t) => t > windowStart);
4873
+ if (!hasRecent) {
4874
+ this.rateLimits.delete(addr);
4875
+ }
4876
+ }
4877
+ }
4773
4878
  // ── HTTP Request Handler ────────────────────────────────────────────
4774
4879
  handleRequest(req, res) {
4775
4880
  const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
@@ -4788,6 +4893,7 @@ var DashboardApprovalChannel = class {
4788
4893
  return;
4789
4894
  }
4790
4895
  if (!this.checkAuth(req, url, res)) return;
4896
+ if (!this.checkRateLimit(req, res, "general")) return;
4791
4897
  try {
4792
4898
  if (method === "POST" && url.pathname === "/auth/session") {
4793
4899
  this.handleSessionExchange(req, res);
@@ -4804,9 +4910,11 @@ var DashboardApprovalChannel = class {
4804
4910
  } else if (method === "GET" && url.pathname === "/api/audit-log") {
4805
4911
  this.handleAuditLog(url, res);
4806
4912
  } else if (method === "POST" && url.pathname.startsWith("/api/approve/")) {
4913
+ if (!this.checkRateLimit(req, res, "decisions")) return;
4807
4914
  const id = url.pathname.slice("/api/approve/".length);
4808
4915
  this.handleDecision(id, "approve", res);
4809
4916
  } else if (method === "POST" && url.pathname.startsWith("/api/deny/")) {
4917
+ if (!this.checkRateLimit(req, res, "decisions")) return;
4810
4918
  const id = url.pathname.slice("/api/deny/".length);
4811
4919
  this.handleDecision(id, "deny", res);
4812
4920
  } else {
@@ -5549,14 +5657,14 @@ function generateSHR(identityId, opts) {
5549
5657
  code: "PROCESS_ISOLATION_ONLY",
5550
5658
  severity: "warning",
5551
5659
  description: "Process-level isolation only (no TEE)",
5552
- mitigation: "TEE support planned for v0.3.0"
5660
+ mitigation: "TEE support planned for a future release"
5553
5661
  });
5554
5662
  degradations.push({
5555
5663
  layer: "l2",
5556
5664
  code: "SELF_REPORTED_ATTESTATION",
5557
5665
  severity: "warning",
5558
5666
  description: "Attestation is self-reported (no hardware root of trust)",
5559
- mitigation: "TEE attestation planned for v0.3.0"
5667
+ mitigation: "TEE attestation planned for a future release"
5560
5668
  });
5561
5669
  }
5562
5670
  if (config.disclosure.proof_system === "commitment-only") {
@@ -5570,6 +5678,11 @@ function generateSHR(identityId, opts) {
5570
5678
  }
5571
5679
  const body = {
5572
5680
  shr_version: "1.0",
5681
+ implementation: {
5682
+ sanctuary_version: config.version,
5683
+ node_version: process.versions.node,
5684
+ generated_by: "sanctuary-mcp-server"
5685
+ },
5573
5686
  instance_id: identity.identity_id,
5574
5687
  generated_at: now.toISOString(),
5575
5688
  expires_at: expiresAt.toISOString(),
@@ -5700,6 +5813,245 @@ function assessSovereigntyLevel(body) {
5700
5813
  return "minimal";
5701
5814
  }
5702
5815
 
5816
+ // src/shr/gateway-adapter.ts
5817
+ var LAYER_WEIGHTS = {
5818
+ l1: 100,
5819
+ l2: 100,
5820
+ l3: 100,
5821
+ l4: 100
5822
+ };
5823
+ var DEGRADATION_IMPACT = {
5824
+ critical: 40,
5825
+ warning: 25,
5826
+ info: 10
5827
+ };
5828
+ function transformSHRForGateway(shr) {
5829
+ const { body, signed_by, signature } = shr;
5830
+ const layerScores = calculateLayerScores(body);
5831
+ const overallScore = calculateOverallScore(layerScores);
5832
+ const trustLevel = determineTrustLevel(overallScore);
5833
+ const signals = extractAuthorizationSignals(body);
5834
+ const degradations = transformDegradations(body.degradations);
5835
+ const constraints = generateAuthorizationConstraints(body);
5836
+ return {
5837
+ shr_version: body.shr_version,
5838
+ agent_identity: signed_by,
5839
+ generated_at: (/* @__PURE__ */ new Date()).toISOString(),
5840
+ context_expires_at: body.expires_at,
5841
+ overall_score: overallScore,
5842
+ recommended_trust_level: trustLevel,
5843
+ layer_scores: {
5844
+ l1_cognitive: layerScores.l1,
5845
+ l2_operational: layerScores.l2,
5846
+ l3_disclosure: layerScores.l3,
5847
+ l4_reputation: layerScores.l4
5848
+ },
5849
+ layer_status: {
5850
+ l1_cognitive: body.layers.l1.status,
5851
+ l2_operational: body.layers.l2.status,
5852
+ l3_disclosure: body.layers.l3.status,
5853
+ l4_reputation: body.layers.l4.status
5854
+ },
5855
+ authorization_signals: signals,
5856
+ degradations,
5857
+ recommended_constraints: constraints,
5858
+ shr_signature: signature,
5859
+ shr_signed_by: signed_by
5860
+ };
5861
+ }
5862
+ function calculateLayerScores(body) {
5863
+ const layers = body.layers;
5864
+ const degradations = body.degradations;
5865
+ let l1Score = LAYER_WEIGHTS.l1;
5866
+ let l2Score = LAYER_WEIGHTS.l2;
5867
+ let l3Score = LAYER_WEIGHTS.l3;
5868
+ let l4Score = LAYER_WEIGHTS.l4;
5869
+ for (const deg of degradations) {
5870
+ const impact = DEGRADATION_IMPACT[deg.severity] || 10;
5871
+ if (deg.layer === "l1") {
5872
+ l1Score = Math.max(0, l1Score - impact);
5873
+ } else if (deg.layer === "l2") {
5874
+ l2Score = Math.max(0, l2Score - impact);
5875
+ } else if (deg.layer === "l3") {
5876
+ l3Score = Math.max(0, l3Score - impact);
5877
+ } else if (deg.layer === "l4") {
5878
+ l4Score = Math.max(0, l4Score - impact);
5879
+ }
5880
+ }
5881
+ if (layers.l1.status === "active" && l1Score > 50) l1Score = Math.min(100, l1Score + 5);
5882
+ if (layers.l2.status === "active" && l2Score > 50) l2Score = Math.min(100, l2Score + 5);
5883
+ if (layers.l3.status === "active" && l3Score > 50) l3Score = Math.min(100, l3Score + 5);
5884
+ if (layers.l4.status === "active" && l4Score > 50) l4Score = Math.min(100, l4Score + 5);
5885
+ if (layers.l1.status === "inactive") l1Score = 0;
5886
+ if (layers.l2.status === "inactive") l2Score = 0;
5887
+ if (layers.l3.status === "inactive") l3Score = 0;
5888
+ if (layers.l4.status === "inactive") l4Score = 0;
5889
+ return {
5890
+ l1: Math.round(l1Score),
5891
+ l2: Math.round(l2Score),
5892
+ l3: Math.round(l3Score),
5893
+ l4: Math.round(l4Score)
5894
+ };
5895
+ }
5896
+ function calculateOverallScore(layerScores) {
5897
+ const average = (layerScores.l1 + layerScores.l2 + layerScores.l3 + layerScores.l4) / 4;
5898
+ return Math.round(average);
5899
+ }
5900
+ function determineTrustLevel(score) {
5901
+ if (score >= 80) return "full";
5902
+ if (score >= 60) return "elevated";
5903
+ if (score >= 40) return "standard";
5904
+ return "restricted";
5905
+ }
5906
+ function extractAuthorizationSignals(body) {
5907
+ const l1 = body.layers.l1;
5908
+ const l3 = body.layers.l3;
5909
+ const l4 = body.layers.l4;
5910
+ return {
5911
+ approval_gate_active: body.capabilities.handshake,
5912
+ // Handshake implies human loop capability
5913
+ context_gating_active: body.capabilities.encrypted_channel,
5914
+ // Proxy for gating capability
5915
+ encryption_at_rest: l1.encryption !== "none" && l1.encryption !== "unencrypted",
5916
+ behavioral_baseline_active: false,
5917
+ // Would need explicit field in SHR v1.1
5918
+ identity_verified: l1.identity_type === "ed25519" || l1.identity_type !== "none",
5919
+ zero_knowledge_capable: l3.status === "active" && l3.proof_system !== "commitment-only",
5920
+ selective_disclosure_active: l3.selective_disclosure,
5921
+ reputation_portable: l4.reputation_portable,
5922
+ handshake_capable: body.capabilities.handshake
5923
+ };
5924
+ }
5925
+ function transformDegradations(degradations) {
5926
+ return degradations.map((deg) => {
5927
+ let authzImpact = "";
5928
+ if (deg.code === "NO_TEE") {
5929
+ authzImpact = "Restricted to read-only operations until TEE available";
5930
+ } else if (deg.code === "PROCESS_ISOLATION_ONLY") {
5931
+ authzImpact = "Requires additional identity verification";
5932
+ } else if (deg.code === "COMMITMENT_ONLY") {
5933
+ authzImpact = "Limited data sharing scope \u2014 no zero-knowledge proofs";
5934
+ } else if (deg.code === "NO_ZK_PROOFS") {
5935
+ authzImpact = "Cannot perform confidential disclosures";
5936
+ } else if (deg.code === "SELF_REPORTED_ATTESTATION") {
5937
+ authzImpact = "Attestation trust degraded \u2014 human verification recommended";
5938
+ } else if (deg.code === "NO_SELECTIVE_DISCLOSURE") {
5939
+ authzImpact = "Must share entire data context, cannot redact";
5940
+ } else if (deg.code === "BASIC_SYBIL_ONLY") {
5941
+ authzImpact = "Restrict to interactions with known agents only";
5942
+ } else {
5943
+ authzImpact = "Unknown authorization impact";
5944
+ }
5945
+ return {
5946
+ layer: deg.layer,
5947
+ code: deg.code,
5948
+ severity: deg.severity,
5949
+ description: deg.description,
5950
+ authorization_impact: authzImpact
5951
+ };
5952
+ });
5953
+ }
5954
+ function generateAuthorizationConstraints(body, _degradations) {
5955
+ const constraints = [];
5956
+ const layers = body.layers;
5957
+ if (layers.l1.status === "degraded" || layers.l1.key_custody !== "self") {
5958
+ constraints.push({
5959
+ type: "identity_verification_required",
5960
+ description: "Additional identity verification required for sensitive operations",
5961
+ rationale: "L1 is degraded or key custody is not self-managed",
5962
+ priority: "high"
5963
+ });
5964
+ }
5965
+ if (!layers.l1.state_portable) {
5966
+ constraints.push({
5967
+ type: "location_bound",
5968
+ description: "Agent state is not portable \u2014 restrict to home environment",
5969
+ rationale: "State cannot be safely migrated across boundaries",
5970
+ priority: "medium"
5971
+ });
5972
+ }
5973
+ if (layers.l2.status === "degraded" || layers.l2.isolation_type === "local-process") {
5974
+ constraints.push({
5975
+ type: "read_only",
5976
+ description: "Restrict to read-only operations until operational isolation improves",
5977
+ rationale: "L2 isolation is process-level only (no TEE)",
5978
+ priority: "high"
5979
+ });
5980
+ }
5981
+ if (!layers.l2.attestation_available) {
5982
+ constraints.push({
5983
+ type: "requires_approval",
5984
+ description: "Human approval required for writes and sensitive reads",
5985
+ rationale: "No attestation available \u2014 self-reported integrity only",
5986
+ priority: "high"
5987
+ });
5988
+ }
5989
+ if (layers.l3.status === "degraded" || !layers.l3.selective_disclosure) {
5990
+ constraints.push({
5991
+ type: "restricted_scope",
5992
+ description: "Limit data sharing to minimal required scope \u2014 no selective disclosure",
5993
+ rationale: "Agent cannot redact data or prove predicates without revealing all context",
5994
+ priority: "high"
5995
+ });
5996
+ }
5997
+ if (layers.l3.proof_system === "commitment-only") {
5998
+ constraints.push({
5999
+ type: "restricted_scope",
6000
+ description: "No zero-knowledge proofs available \u2014 entire state context may be visible",
6001
+ rationale: "Proof system is commitment-only (no ZK)",
6002
+ priority: "medium"
6003
+ });
6004
+ }
6005
+ if (layers.l4.status === "degraded") {
6006
+ constraints.push({
6007
+ type: "known_agents_only",
6008
+ description: "Restrict interactions to known, pre-approved agents",
6009
+ rationale: "Reputation layer is degraded",
6010
+ priority: "medium"
6011
+ });
6012
+ }
6013
+ if (!layers.l4.reputation_portable) {
6014
+ constraints.push({
6015
+ type: "location_bound",
6016
+ description: "Reputation is not portable \u2014 restrict to home environment",
6017
+ rationale: "Cannot present reputation to external parties",
6018
+ priority: "low"
6019
+ });
6020
+ }
6021
+ const layerScores = calculateLayerScores(body);
6022
+ const overallScore = calculateOverallScore(layerScores);
6023
+ if (overallScore < 40) {
6024
+ constraints.push({
6025
+ type: "restricted_scope",
6026
+ description: "Overall sovereignty score below threshold \u2014 restrict to non-sensitive operations",
6027
+ rationale: `Overall sovereignty score is ${overallScore}/100`,
6028
+ priority: "high"
6029
+ });
6030
+ }
6031
+ return constraints;
6032
+ }
6033
+ function transformSHRGeneric(shr) {
6034
+ const context = transformSHRForGateway(shr);
6035
+ return {
6036
+ agent_id: context.agent_identity,
6037
+ sovereignty_score: context.overall_score,
6038
+ trust_level: context.recommended_trust_level,
6039
+ layer_scores: {
6040
+ l1: context.layer_scores.l1_cognitive,
6041
+ l2: context.layer_scores.l2_operational,
6042
+ l3: context.layer_scores.l3_disclosure,
6043
+ l4: context.layer_scores.l4_reputation
6044
+ },
6045
+ capabilities: context.authorization_signals,
6046
+ constraints: context.recommended_constraints.map((c) => ({
6047
+ type: c.type,
6048
+ description: c.description
6049
+ })),
6050
+ expires_at: context.context_expires_at,
6051
+ signature: context.shr_signature
6052
+ };
6053
+ }
6054
+
5703
6055
  // src/shr/tools.ts
5704
6056
  function createSHRTools(config, identityManager, masterKey, auditLog) {
5705
6057
  const generatorOpts = {
@@ -5762,6 +6114,53 @@ function createSHRTools(config, identityManager, masterKey, auditLog) {
5762
6114
  );
5763
6115
  return toolResult(result);
5764
6116
  }
6117
+ },
6118
+ {
6119
+ name: "sanctuary/shr_gateway_export",
6120
+ 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.",
6121
+ inputSchema: {
6122
+ type: "object",
6123
+ properties: {
6124
+ format: {
6125
+ type: "string",
6126
+ enum: ["ping", "generic"],
6127
+ description: "Output format: 'ping' (Ping Identity Gateway format) or 'generic' (format-agnostic). Default: 'ping'."
6128
+ },
6129
+ identity_id: {
6130
+ type: "string",
6131
+ description: "Identity to sign the SHR with. Defaults to primary identity."
6132
+ },
6133
+ validity_minutes: {
6134
+ type: "number",
6135
+ description: "How long the SHR is valid (minutes). Default: 60."
6136
+ }
6137
+ }
6138
+ },
6139
+ handler: async (args) => {
6140
+ const format = args.format || "ping";
6141
+ const validityMs = args.validity_minutes ? args.validity_minutes * 60 * 1e3 : void 0;
6142
+ const shrResult = generateSHR(args.identity_id, {
6143
+ ...generatorOpts,
6144
+ validityMs
6145
+ });
6146
+ if (typeof shrResult === "string") {
6147
+ return toolResult({ error: shrResult });
6148
+ }
6149
+ let context;
6150
+ if (format === "generic") {
6151
+ context = transformSHRGeneric(shrResult);
6152
+ } else {
6153
+ context = transformSHRForGateway(shrResult);
6154
+ }
6155
+ auditLog.append(
6156
+ "l2",
6157
+ "shr_gateway_export",
6158
+ shrResult.body.instance_id,
6159
+ void 0,
6160
+ "success"
6161
+ );
6162
+ return toolResult(context);
6163
+ }
5765
6164
  }
5766
6165
  ];
5767
6166
  return { tools };
@@ -7040,9 +7439,11 @@ var L1_INTEGRITY_VERIFICATION = 8;
7040
7439
  var L1_STATE_PORTABLE = 7;
7041
7440
  var L2_THREE_TIER_GATE = 10;
7042
7441
  var L2_BINARY_GATE = 3;
7043
- var L2_ANOMALY_DETECTION = 7;
7044
- var L2_ENCRYPTED_AUDIT = 5;
7045
- var L2_TOOL_SANDBOXING = 3;
7442
+ var L2_ANOMALY_DETECTION = 5;
7443
+ var L2_ENCRYPTED_AUDIT = 4;
7444
+ var L2_TOOL_SANDBOXING = 2;
7445
+ var L2_CONTEXT_GATING = 4;
7446
+ var L2_PROCESS_HARDENING = 5;
7046
7447
  var L3_COMMITMENT_SCHEME = 8;
7047
7448
  var L3_ZK_PROOFS = 7;
7048
7449
  var L3_DISCLOSURE_POLICIES = 5;
@@ -7056,6 +7457,35 @@ var SEVERITY_ORDER = {
7056
7457
  medium: 2,
7057
7458
  low: 3
7058
7459
  };
7460
+ var INCIDENT_META_SEV1 = {
7461
+ id: "META-SEV1-2026",
7462
+ name: "Meta Sev 1: Unauthorized autonomous data exposure",
7463
+ date: "2026-03-18",
7464
+ description: "AI agent autonomously posted proprietary code, business strategies, and user datasets to an internal forum without human approval. Two-hour exposure window."
7465
+ };
7466
+ var INCIDENT_OPENCLAW_SANDBOX = {
7467
+ id: "OPENCLAW-CVE-2026",
7468
+ name: "OpenClaw sandbox escape via privilege inheritance",
7469
+ date: "2026-03-18",
7470
+ 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.",
7471
+ cves: [
7472
+ "CVE-2026-32048",
7473
+ "CVE-2026-32915",
7474
+ "CVE-2026-32918"
7475
+ ]
7476
+ };
7477
+ var INCIDENT_CONTEXT_LEAKAGE = {
7478
+ id: "CONTEXT-LEAK-CLASS",
7479
+ name: "Context leakage: Full state exposure to inference providers",
7480
+ date: "2026-03",
7481
+ 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."
7482
+ };
7483
+ var INCIDENT_CLAUDE_CODE_LEAK = {
7484
+ id: "CLAUDE-CODE-LEAK-2026",
7485
+ name: "Claude Code source leak: 512K lines exposed via npm source map",
7486
+ date: "2026-03-31",
7487
+ 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."
7488
+ };
7059
7489
  function analyzeSovereignty(env, config) {
7060
7490
  const l1 = assessL1(env, config);
7061
7491
  const l2 = assessL2(env);
@@ -7128,14 +7558,18 @@ function assessL2(env, _config) {
7128
7558
  let auditTrailEncrypted = false;
7129
7559
  let auditTrailExists = false;
7130
7560
  let toolSandboxing = "none";
7561
+ let contextGating = false;
7562
+ let processIsolationHardening = "none";
7131
7563
  if (sanctuaryActive) {
7132
7564
  approvalGate = "three-tier";
7133
7565
  behavioralAnomalyDetection = true;
7134
7566
  auditTrailEncrypted = true;
7135
7567
  auditTrailExists = true;
7568
+ contextGating = true;
7136
7569
  findings.push("Three-tier Principal Policy gate active");
7137
7570
  findings.push("Behavioral anomaly detection (BaselineTracker) enabled");
7138
7571
  findings.push("Encrypted audit trail active");
7572
+ findings.push("Context gating available (sanctuary/context_gate_set_policy)");
7139
7573
  }
7140
7574
  if (env.openclaw_detected && env.openclaw_config) {
7141
7575
  if (env.openclaw_config.require_approval_enabled) {
@@ -7153,6 +7587,7 @@ function assessL2(env, _config) {
7153
7587
  );
7154
7588
  }
7155
7589
  }
7590
+ processIsolationHardening = "none";
7156
7591
  const status = approvalGate === "three-tier" && auditTrailEncrypted ? "active" : approvalGate !== "none" || auditTrailExists ? "partial" : "inactive";
7157
7592
  return {
7158
7593
  status,
@@ -7161,6 +7596,8 @@ function assessL2(env, _config) {
7161
7596
  audit_trail_encrypted: auditTrailEncrypted,
7162
7597
  audit_trail_exists: auditTrailExists,
7163
7598
  tool_sandboxing: sanctuaryActive ? "policy-enforced" : toolSandboxing,
7599
+ context_gating: contextGating,
7600
+ process_isolation_hardening: processIsolationHardening,
7164
7601
  findings
7165
7602
  };
7166
7603
  }
@@ -7175,8 +7612,10 @@ function assessL3(env, _config) {
7175
7612
  zkProofs = true;
7176
7613
  selectiveDisclosurePolicy = true;
7177
7614
  findings.push("SHA-256 + Pedersen commitment schemes active");
7178
- findings.push("Schnorr ZK proofs and range proofs available");
7615
+ findings.push("Schnorr zero-knowledge proofs (Fiat-Shamir) enabled \u2014 genuine ZK proofs");
7616
+ findings.push("Range proofs (bit-decomposition + OR-proofs) enabled \u2014 genuine ZK proofs");
7179
7617
  findings.push("Selective disclosure policies configurable");
7618
+ findings.push("Non-interactive proofs with replay-resistant domain separation");
7180
7619
  }
7181
7620
  const status = commitmentScheme === "pedersen+sha256" && zkProofs ? "active" : commitmentScheme !== "none" ? "partial" : "inactive";
7182
7621
  return {
@@ -7228,6 +7667,9 @@ function scoreL2(l2) {
7228
7667
  if (l2.audit_trail_encrypted) score += L2_ENCRYPTED_AUDIT;
7229
7668
  if (l2.tool_sandboxing === "policy-enforced") score += L2_TOOL_SANDBOXING;
7230
7669
  else if (l2.tool_sandboxing === "basic") score += 1;
7670
+ if (l2.context_gating) score += L2_CONTEXT_GATING;
7671
+ if (l2.process_isolation_hardening === "hardened") score += L2_PROCESS_HARDENING;
7672
+ else if (l2.process_isolation_hardening === "basic") score += 2;
7231
7673
  return score;
7232
7674
  }
7233
7675
  function scoreL3(l3) {
@@ -7257,7 +7699,8 @@ function generateGaps(env, l1, l2, l3, l4) {
7257
7699
  title: "Agent memory stored in plaintext",
7258
7700
  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.",
7259
7701
  openclaw_relevance: "Stock OpenClaw stores all agent memory in plaintext files. There is no built-in encryption for agent state.",
7260
- 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."
7702
+ 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.",
7703
+ incident_class: INCIDENT_META_SEV1
7261
7704
  });
7262
7705
  }
7263
7706
  if (oc && oc.env_file_exposed) {
@@ -7290,7 +7733,8 @@ function generateGaps(env, l1, l2, l3, l4) {
7290
7733
  title: "Binary approval gate (no anomaly detection)",
7291
7734
  description: "Your approval gate provides binary approve/deny gating without behavioral anomaly detection. Routine operations require the same manual approval as sensitive ones.",
7292
7735
  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,
7293
- 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."
7736
+ 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.",
7737
+ incident_class: INCIDENT_META_SEV1
7294
7738
  });
7295
7739
  } else if (l2.approval_gate === "none") {
7296
7740
  gaps.push({
@@ -7300,7 +7744,8 @@ function generateGaps(env, l1, l2, l3, l4) {
7300
7744
  title: "No approval gate",
7301
7745
  description: "No approval gate is configured. All tool calls execute without oversight.",
7302
7746
  openclaw_relevance: null,
7303
- sanctuary_solution: "Sanctuary's Principal Policy evaluates every tool call before execution. Enable it to get three-tier approval gating with behavioral anomaly detection."
7747
+ sanctuary_solution: "Sanctuary's Principal Policy evaluates every tool call before execution. Enable it to get three-tier approval gating with behavioral anomaly detection.",
7748
+ incident_class: INCIDENT_META_SEV1
7304
7749
  });
7305
7750
  }
7306
7751
  if (l2.tool_sandboxing === "basic") {
@@ -7311,18 +7756,32 @@ function generateGaps(env, l1, l2, l3, l4) {
7311
7756
  title: "Basic tool sandboxing (no cryptographic attestation)",
7312
7757
  description: "Your tool sandbox enforces allow/deny lists but provides no cryptographic attestation of execution context.",
7313
7758
  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,
7314
- sanctuary_solution: "Sanctuary provides cryptographic execution attestation via sanctuary/exec_attest and policy-enforced sandboxing with encrypted audit trails."
7759
+ sanctuary_solution: "Sanctuary provides cryptographic execution attestation via sanctuary/exec_attest and policy-enforced sandboxing with encrypted audit trails.",
7760
+ incident_class: INCIDENT_OPENCLAW_SANDBOX
7315
7761
  });
7316
7762
  }
7317
- if (!l2.audit_trail_exists) {
7763
+ if (!l2.context_gating) {
7318
7764
  gaps.push({
7319
7765
  id: "GAP-L2-003",
7320
7766
  layer: "L2",
7321
7767
  severity: "high",
7768
+ title: "No context gating for outbound inference calls",
7769
+ 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.",
7770
+ 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,
7771
+ 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.",
7772
+ incident_class: INCIDENT_CONTEXT_LEAKAGE
7773
+ });
7774
+ }
7775
+ if (!l2.audit_trail_exists) {
7776
+ gaps.push({
7777
+ id: "GAP-L2-004",
7778
+ layer: "L2",
7779
+ severity: "high",
7322
7780
  title: "No audit trail",
7323
7781
  description: "No audit trail exists for tool call history. There is no record of what operations were executed, when, or by whom.",
7324
7782
  openclaw_relevance: null,
7325
- sanctuary_solution: "Sanctuary maintains an encrypted audit log of all operations, queryable via sanctuary/monitor_audit_log."
7783
+ sanctuary_solution: "Sanctuary maintains an encrypted audit log of all operations, queryable via sanctuary/monitor_audit_log.",
7784
+ incident_class: INCIDENT_CLAUDE_CODE_LEAK
7326
7785
  });
7327
7786
  }
7328
7787
  if (l3.commitment_scheme === "none") {
@@ -7331,9 +7790,10 @@ function generateGaps(env, l1, l2, l3, l4) {
7331
7790
  layer: "L3",
7332
7791
  severity: "high",
7333
7792
  title: "No selective disclosure capability",
7334
- description: "Your agent has no way to prove facts about its state without revealing the state itself. Every disclosure is all-or-nothing.",
7793
+ 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.",
7335
7794
  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,
7336
- sanctuary_solution: "Sanctuary's L3 provides SHA-256 + Pedersen commitments and Schnorr zero-knowledge proofs. Your agent can prove it has a valid credential, sufficient reputation, or a completed transaction without exposing the underlying data. Use sanctuary/zk_commit and sanctuary/zk_prove."
7795
+ 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.",
7796
+ incident_class: INCIDENT_META_SEV1
7337
7797
  });
7338
7798
  }
7339
7799
  if (!l4.reputation_portable) {
@@ -7385,9 +7845,18 @@ function generateRecommendations(env, l1, l2, l3, l4) {
7385
7845
  impact: "high"
7386
7846
  });
7387
7847
  }
7388
- if (!l4.reputation_signed) {
7848
+ if (!l2.context_gating) {
7389
7849
  recs.push({
7390
7850
  priority: 5,
7851
+ action: "Configure context gating to control what flows to LLM providers",
7852
+ tool: "sanctuary/context_gate_set_policy",
7853
+ effort: "minutes",
7854
+ impact: "high"
7855
+ });
7856
+ }
7857
+ if (!l4.reputation_signed) {
7858
+ recs.push({
7859
+ priority: 6,
7391
7860
  action: "Start recording reputation attestations from completed interactions",
7392
7861
  tool: "sanctuary/reputation_record",
7393
7862
  effort: "minutes",
@@ -7396,7 +7865,7 @@ function generateRecommendations(env, l1, l2, l3, l4) {
7396
7865
  }
7397
7866
  if (!l3.selective_disclosure_policy) {
7398
7867
  recs.push({
7399
- priority: 6,
7868
+ priority: 7,
7400
7869
  action: "Configure selective disclosure policies for data sharing",
7401
7870
  tool: "sanctuary/disclosure_set_policy",
7402
7871
  effort: "hours",
@@ -7445,6 +7914,10 @@ function formatAuditReport(result) {
7445
7914
  `;
7446
7915
  report += ` \u2502 L2 Operational Isolation \u2502 ${padStatus(layers.l2_operational.status)} \u2502 ${padScore(l2Score, 25)} \u2502
7447
7916
  `;
7917
+ if (layers.l2_operational.context_gating) {
7918
+ report += ` \u2502 \u2514 Context Gating \u2502 ACTIVE \u2502 \u2502
7919
+ `;
7920
+ }
7448
7921
  report += ` \u2502 L3 Selective Disclosure \u2502 ${padStatus(layers.l3_selective_disclosure.status)} \u2502 ${padScore(l3Score, 20)} \u2502
7449
7922
  `;
7450
7923
  report += ` \u2502 L4 Verifiable Reputation \u2502 ${padStatus(layers.l4_reputation.status)} \u2502 ${padScore(l4Score, 20)} \u2502
@@ -7462,6 +7935,12 @@ function formatAuditReport(result) {
7462
7935
  const descLines = wordWrap(gap.description, 66);
7463
7936
  for (const line of descLines) {
7464
7937
  report += ` ${line}
7938
+ `;
7939
+ }
7940
+ if (gap.incident_class) {
7941
+ const ic = gap.incident_class;
7942
+ const cveStr = ic.cves?.length ? ` (${ic.cves.join(", ")})` : "";
7943
+ report += ` \u2192 Incident precedent: ${ic.name}${cveStr} [${ic.date}]
7465
7944
  `;
7466
7945
  }
7467
7946
  report += ` \u2192 Fix: ${gap.sanctuary_solution.split(".")[0]}.
@@ -7556,32 +8035,1508 @@ function createAuditTools(config) {
7556
8035
  return { tools };
7557
8036
  }
7558
8037
 
7559
- // src/index.ts
8038
+ // src/l2-operational/context-gate.ts
7560
8039
  init_encoding();
7561
- async function createSanctuaryServer(options) {
7562
- const config = await loadConfig(options?.configPath);
7563
- await promises.mkdir(config.storage_path, { recursive: true, mode: 448 });
7564
- const storage = options?.storage ?? new FilesystemStorage(
7565
- `${config.storage_path}/state`
8040
+ init_hashing();
8041
+ var MAX_CONTEXT_FIELDS = 1e3;
8042
+ var MAX_POLICY_RULES = 50;
8043
+ var MAX_PATTERNS_PER_ARRAY = 500;
8044
+ function evaluateField(policy, provider, field) {
8045
+ const exactRule = policy.rules.find((r) => r.provider === provider);
8046
+ const wildcardRule = policy.rules.find((r) => r.provider === "*");
8047
+ const matchedRule = exactRule ?? wildcardRule;
8048
+ if (!matchedRule) {
8049
+ return {
8050
+ field,
8051
+ action: policy.default_action === "deny" ? "deny" : "redact",
8052
+ reason: `No rule matches provider "${provider}"; applying default (${policy.default_action})`
8053
+ };
8054
+ }
8055
+ if (matchesPattern(field, matchedRule.redact)) {
8056
+ return {
8057
+ field,
8058
+ action: "redact",
8059
+ reason: `Field "${field}" is explicitly redacted for ${matchedRule.provider} provider`
8060
+ };
8061
+ }
8062
+ if (matchesPattern(field, matchedRule.hash)) {
8063
+ return {
8064
+ field,
8065
+ action: "hash",
8066
+ reason: `Field "${field}" is hashed for ${matchedRule.provider} provider`
8067
+ };
8068
+ }
8069
+ if (matchesPattern(field, matchedRule.summarize)) {
8070
+ return {
8071
+ field,
8072
+ action: "summarize",
8073
+ reason: `Field "${field}" should be summarized for ${matchedRule.provider} provider`
8074
+ };
8075
+ }
8076
+ if (matchesPattern(field, matchedRule.allow)) {
8077
+ return {
8078
+ field,
8079
+ action: "allow",
8080
+ reason: `Field "${field}" is allowed for ${matchedRule.provider} provider`
8081
+ };
8082
+ }
8083
+ return {
8084
+ field,
8085
+ action: policy.default_action === "deny" ? "deny" : "redact",
8086
+ reason: `Field "${field}" not addressed in ${matchedRule.provider} rule; applying default (${policy.default_action})`
8087
+ };
8088
+ }
8089
+ function filterContext(policy, provider, context) {
8090
+ const fields = Object.keys(context);
8091
+ if (fields.length > MAX_CONTEXT_FIELDS) {
8092
+ throw new Error(
8093
+ `Context object has ${fields.length} fields, exceeding limit of ${MAX_CONTEXT_FIELDS}`
8094
+ );
8095
+ }
8096
+ const decisions = [];
8097
+ let allowed = 0;
8098
+ let redacted = 0;
8099
+ let hashed = 0;
8100
+ let summarized = 0;
8101
+ let denied = 0;
8102
+ for (const field of fields) {
8103
+ const result = evaluateField(policy, provider, field);
8104
+ if (result.action === "hash") {
8105
+ const value = typeof context[field] === "string" ? context[field] : JSON.stringify(context[field]);
8106
+ result.hash_value = hashToString(stringToBytes(value));
8107
+ }
8108
+ decisions.push(result);
8109
+ switch (result.action) {
8110
+ case "allow":
8111
+ allowed++;
8112
+ break;
8113
+ case "redact":
8114
+ redacted++;
8115
+ break;
8116
+ case "hash":
8117
+ hashed++;
8118
+ break;
8119
+ case "summarize":
8120
+ summarized++;
8121
+ break;
8122
+ case "deny":
8123
+ denied++;
8124
+ break;
8125
+ }
8126
+ }
8127
+ const originalHash = hashToString(
8128
+ stringToBytes(JSON.stringify(context))
7566
8129
  );
7567
- let masterKey;
7568
- let keyProtection;
7569
- let recoveryKey;
7570
- const passphrase = options?.passphrase ?? process.env.SANCTUARY_PASSPHRASE;
7571
- if (passphrase) {
7572
- keyProtection = "passphrase";
7573
- let existingParams;
8130
+ const filteredOutput = {};
8131
+ for (const decision of decisions) {
8132
+ switch (decision.action) {
8133
+ case "allow":
8134
+ filteredOutput[decision.field] = context[decision.field];
8135
+ break;
8136
+ case "redact":
8137
+ filteredOutput[decision.field] = "[REDACTED]";
8138
+ break;
8139
+ case "hash":
8140
+ filteredOutput[decision.field] = `[HASH:${decision.hash_value}]`;
8141
+ break;
8142
+ case "summarize":
8143
+ filteredOutput[decision.field] = "[SUMMARIZE]";
8144
+ break;
8145
+ }
8146
+ }
8147
+ const filteredHash = hashToString(
8148
+ stringToBytes(JSON.stringify(filteredOutput))
8149
+ );
8150
+ return {
8151
+ policy_id: policy.policy_id,
8152
+ provider,
8153
+ fields_allowed: allowed,
8154
+ fields_redacted: redacted,
8155
+ fields_hashed: hashed,
8156
+ fields_summarized: summarized,
8157
+ fields_denied: denied,
8158
+ decisions,
8159
+ original_context_hash: originalHash,
8160
+ filtered_context_hash: filteredHash,
8161
+ filtered_at: (/* @__PURE__ */ new Date()).toISOString()
8162
+ };
8163
+ }
8164
+ function matchesPattern(field, patterns) {
8165
+ const normalizedField = field.toLowerCase();
8166
+ for (const pattern of patterns) {
8167
+ if (pattern === "*") return true;
8168
+ const normalizedPattern = pattern.toLowerCase();
8169
+ if (normalizedPattern === normalizedField) return true;
8170
+ if (normalizedPattern.endsWith("*") && normalizedField.startsWith(normalizedPattern.slice(0, -1))) return true;
8171
+ if (normalizedPattern.startsWith("*") && normalizedField.endsWith(normalizedPattern.slice(1))) return true;
8172
+ }
8173
+ return false;
8174
+ }
8175
+ var ContextGatePolicyStore = class {
8176
+ storage;
8177
+ encryptionKey;
8178
+ policies = /* @__PURE__ */ new Map();
8179
+ constructor(storage, masterKey) {
8180
+ this.storage = storage;
8181
+ this.encryptionKey = derivePurposeKey(masterKey, "l2-context-gate");
8182
+ }
8183
+ /**
8184
+ * Create and store a new context-gating policy.
8185
+ */
8186
+ async create(policyName, rules, defaultAction, identityId) {
8187
+ const policyId = `cg-${Date.now()}-${toBase64url(randomBytes(8))}`;
8188
+ const now = (/* @__PURE__ */ new Date()).toISOString();
8189
+ const policy = {
8190
+ policy_id: policyId,
8191
+ policy_name: policyName,
8192
+ rules,
8193
+ default_action: defaultAction,
8194
+ identity_id: identityId,
8195
+ created_at: now,
8196
+ updated_at: now
8197
+ };
8198
+ await this.persist(policy);
8199
+ this.policies.set(policyId, policy);
8200
+ return policy;
8201
+ }
8202
+ /**
8203
+ * Get a policy by ID.
8204
+ */
8205
+ async get(policyId) {
8206
+ if (this.policies.has(policyId)) {
8207
+ return this.policies.get(policyId);
8208
+ }
8209
+ const raw = await this.storage.read("_context_gate_policies", policyId);
8210
+ if (!raw) return null;
7574
8211
  try {
7575
- const raw = await storage.read("_meta", "key-params");
7576
- if (raw) {
7577
- const { bytesToString: bytesToString2 } = await Promise.resolve().then(() => (init_encoding(), encoding_exports));
7578
- existingParams = JSON.parse(bytesToString2(raw));
8212
+ const encrypted = JSON.parse(bytesToString(raw));
8213
+ const decrypted = decrypt(encrypted, this.encryptionKey);
8214
+ const policy = JSON.parse(bytesToString(decrypted));
8215
+ this.policies.set(policyId, policy);
8216
+ return policy;
8217
+ } catch {
8218
+ return null;
8219
+ }
8220
+ }
8221
+ /**
8222
+ * List all context-gating policies.
8223
+ */
8224
+ async list() {
8225
+ await this.loadAll();
8226
+ return Array.from(this.policies.values());
8227
+ }
8228
+ /**
8229
+ * Load all persisted policies into memory.
8230
+ */
8231
+ async loadAll() {
8232
+ try {
8233
+ const entries = await this.storage.list("_context_gate_policies");
8234
+ for (const meta of entries) {
8235
+ if (this.policies.has(meta.key)) continue;
8236
+ const raw = await this.storage.read("_context_gate_policies", meta.key);
8237
+ if (!raw) continue;
8238
+ try {
8239
+ const encrypted = JSON.parse(bytesToString(raw));
8240
+ const decrypted = decrypt(encrypted, this.encryptionKey);
8241
+ const policy = JSON.parse(bytesToString(decrypted));
8242
+ this.policies.set(policy.policy_id, policy);
8243
+ } catch {
8244
+ }
7579
8245
  }
7580
8246
  } catch {
7581
8247
  }
7582
- const result = await deriveMasterKey(passphrase, existingParams);
7583
- masterKey = result.key;
7584
- if (!existingParams) {
8248
+ }
8249
+ async persist(policy) {
8250
+ const serialized = stringToBytes(JSON.stringify(policy));
8251
+ const encrypted = encrypt(serialized, this.encryptionKey);
8252
+ await this.storage.write(
8253
+ "_context_gate_policies",
8254
+ policy.policy_id,
8255
+ stringToBytes(JSON.stringify(encrypted))
8256
+ );
8257
+ }
8258
+ };
8259
+
8260
+ // src/l2-operational/context-gate-templates.ts
8261
+ var ALWAYS_REDACT_SECRETS = [
8262
+ "api_key",
8263
+ "secret_*",
8264
+ "*_secret",
8265
+ "*_token",
8266
+ "*_key",
8267
+ "password",
8268
+ "*_password",
8269
+ "credential",
8270
+ "*_credential",
8271
+ "private_key",
8272
+ "recovery_key",
8273
+ "passphrase",
8274
+ "auth_*"
8275
+ ];
8276
+ var PII_PATTERNS = [
8277
+ "*_pii",
8278
+ "name",
8279
+ "full_name",
8280
+ "email",
8281
+ "email_address",
8282
+ "phone",
8283
+ "phone_number",
8284
+ "address",
8285
+ "ssn",
8286
+ "date_of_birth",
8287
+ "ip_address",
8288
+ "credit_card",
8289
+ "card_number",
8290
+ "cvv",
8291
+ "bank_account",
8292
+ "account_number",
8293
+ "routing_number"
8294
+ ];
8295
+ var INTERNAL_STATE_PATTERNS = [
8296
+ "memory",
8297
+ "agent_memory",
8298
+ "internal_reasoning",
8299
+ "internal_state",
8300
+ "reasoning_trace",
8301
+ "chain_of_thought",
8302
+ "private_notes",
8303
+ "soul",
8304
+ "personality",
8305
+ "system_prompt"
8306
+ ];
8307
+ var ID_PATTERNS = [
8308
+ "user_id",
8309
+ "session_id",
8310
+ "agent_id",
8311
+ "identity_id",
8312
+ "conversation_id",
8313
+ "thread_id"
8314
+ ];
8315
+ var HISTORY_PATTERNS = [
8316
+ "conversation_history",
8317
+ "message_history",
8318
+ "chat_history",
8319
+ "context_window",
8320
+ "previous_messages"
8321
+ ];
8322
+ var INFERENCE_MINIMAL = {
8323
+ id: "inference-minimal",
8324
+ name: "Inference Minimal",
8325
+ description: "Maximum privacy. Only the current task and query reach the LLM provider.",
8326
+ use_when: "You want the strictest possible context control for inference calls. The LLM sees only what it needs for the immediate task.",
8327
+ rules: [
8328
+ {
8329
+ provider: "inference",
8330
+ allow: [
8331
+ "task",
8332
+ "task_description",
8333
+ "current_query",
8334
+ "query",
8335
+ "prompt",
8336
+ "question",
8337
+ "instruction"
8338
+ ],
8339
+ redact: [
8340
+ ...ALWAYS_REDACT_SECRETS,
8341
+ ...PII_PATTERNS,
8342
+ ...INTERNAL_STATE_PATTERNS,
8343
+ ...HISTORY_PATTERNS,
8344
+ "tool_results",
8345
+ "previous_results"
8346
+ ],
8347
+ hash: [...ID_PATTERNS],
8348
+ summarize: []
8349
+ }
8350
+ ],
8351
+ default_action: "redact"
8352
+ };
8353
+ var INFERENCE_STANDARD = {
8354
+ id: "inference-standard",
8355
+ name: "Inference Standard",
8356
+ description: "Balanced privacy. Task, query, and tool results pass through. History flagged for summarization. Secrets and PII redacted.",
8357
+ use_when: "You need the LLM to have enough context for multi-step tasks while keeping secrets, PII, and internal reasoning private.",
8358
+ rules: [
8359
+ {
8360
+ provider: "inference",
8361
+ allow: [
8362
+ "task",
8363
+ "task_description",
8364
+ "current_query",
8365
+ "query",
8366
+ "prompt",
8367
+ "question",
8368
+ "instruction",
8369
+ "tool_results",
8370
+ "tool_output",
8371
+ "previous_results",
8372
+ "current_step",
8373
+ "remaining_steps",
8374
+ "objective",
8375
+ "constraints",
8376
+ "format",
8377
+ "output_format"
8378
+ ],
8379
+ redact: [
8380
+ ...ALWAYS_REDACT_SECRETS,
8381
+ ...PII_PATTERNS,
8382
+ ...INTERNAL_STATE_PATTERNS
8383
+ ],
8384
+ hash: [...ID_PATTERNS],
8385
+ summarize: [...HISTORY_PATTERNS]
8386
+ }
8387
+ ],
8388
+ default_action: "redact"
8389
+ };
8390
+ var LOGGING_STRICT = {
8391
+ id: "logging-strict",
8392
+ name: "Logging Strict",
8393
+ description: "Redacts all content for logging and analytics providers. Only operation metadata passes through.",
8394
+ use_when: "You send telemetry to logging or analytics services and want usage metrics without any content exposure.",
8395
+ rules: [
8396
+ {
8397
+ provider: "logging",
8398
+ allow: [
8399
+ "operation",
8400
+ "operation_name",
8401
+ "tool_name",
8402
+ "timestamp",
8403
+ "duration_ms",
8404
+ "status",
8405
+ "error_code",
8406
+ "event_type"
8407
+ ],
8408
+ redact: [
8409
+ ...ALWAYS_REDACT_SECRETS,
8410
+ ...PII_PATTERNS,
8411
+ ...INTERNAL_STATE_PATTERNS,
8412
+ ...HISTORY_PATTERNS
8413
+ ],
8414
+ hash: [...ID_PATTERNS],
8415
+ summarize: []
8416
+ },
8417
+ {
8418
+ provider: "analytics",
8419
+ allow: [
8420
+ "event_type",
8421
+ "timestamp",
8422
+ "duration_ms",
8423
+ "status",
8424
+ "tool_name"
8425
+ ],
8426
+ redact: [
8427
+ ...ALWAYS_REDACT_SECRETS,
8428
+ ...PII_PATTERNS,
8429
+ ...INTERNAL_STATE_PATTERNS,
8430
+ ...HISTORY_PATTERNS
8431
+ ],
8432
+ hash: [...ID_PATTERNS],
8433
+ summarize: []
8434
+ }
8435
+ ],
8436
+ default_action: "redact"
8437
+ };
8438
+ var TOOL_API_SCOPED = {
8439
+ id: "tool-api-scoped",
8440
+ name: "Tool API Scoped",
8441
+ description: "Allows tool-specific parameters for external API calls. Redacts memory, history, secrets, and PII.",
8442
+ 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.",
8443
+ rules: [
8444
+ {
8445
+ provider: "tool-api",
8446
+ allow: [
8447
+ "task",
8448
+ "task_description",
8449
+ "query",
8450
+ "search_query",
8451
+ "tool_input",
8452
+ "tool_parameters",
8453
+ "url",
8454
+ "endpoint",
8455
+ "method",
8456
+ "filter",
8457
+ "sort",
8458
+ "limit",
8459
+ "offset"
8460
+ ],
8461
+ redact: [
8462
+ ...ALWAYS_REDACT_SECRETS,
8463
+ ...PII_PATTERNS,
8464
+ ...INTERNAL_STATE_PATTERNS,
8465
+ ...HISTORY_PATTERNS
8466
+ ],
8467
+ hash: [...ID_PATTERNS],
8468
+ summarize: []
8469
+ }
8470
+ ],
8471
+ default_action: "redact"
8472
+ };
8473
+ var TEMPLATES = {
8474
+ "inference-minimal": INFERENCE_MINIMAL,
8475
+ "inference-standard": INFERENCE_STANDARD,
8476
+ "logging-strict": LOGGING_STRICT,
8477
+ "tool-api-scoped": TOOL_API_SCOPED
8478
+ };
8479
+ function listTemplateIds() {
8480
+ return Object.keys(TEMPLATES);
8481
+ }
8482
+ function getTemplate(id) {
8483
+ return TEMPLATES[id];
8484
+ }
8485
+
8486
+ // src/l2-operational/context-gate-recommend.ts
8487
+ var CLASSIFICATION_RULES = [
8488
+ // ── Secrets (always redact, high confidence) ─────────────────────
8489
+ {
8490
+ patterns: [
8491
+ "api_key",
8492
+ "apikey",
8493
+ "api_secret",
8494
+ "secret",
8495
+ "secret_key",
8496
+ "secret_token",
8497
+ "password",
8498
+ "passwd",
8499
+ "pass",
8500
+ "credential",
8501
+ "credentials",
8502
+ "private_key",
8503
+ "privkey",
8504
+ "recovery_key",
8505
+ "passphrase",
8506
+ "token",
8507
+ "access_token",
8508
+ "refresh_token",
8509
+ "bearer_token",
8510
+ "auth_token",
8511
+ "auth_header",
8512
+ "authorization",
8513
+ "encryption_key",
8514
+ "master_key",
8515
+ "signing_key",
8516
+ "webhook_secret",
8517
+ "client_secret",
8518
+ "connection_string"
8519
+ ],
8520
+ action: "redact",
8521
+ confidence: "high",
8522
+ reason: "Matches known secret/credential pattern"
8523
+ },
8524
+ // ── PII (always redact, high confidence) ─────────────────────────
8525
+ {
8526
+ patterns: [
8527
+ "name",
8528
+ "full_name",
8529
+ "first_name",
8530
+ "last_name",
8531
+ "display_name",
8532
+ "email",
8533
+ "email_address",
8534
+ "phone",
8535
+ "phone_number",
8536
+ "mobile",
8537
+ "address",
8538
+ "street_address",
8539
+ "mailing_address",
8540
+ "ssn",
8541
+ "social_security",
8542
+ "date_of_birth",
8543
+ "dob",
8544
+ "birthday",
8545
+ "ip_address",
8546
+ "ip",
8547
+ "location",
8548
+ "geolocation",
8549
+ "coordinates",
8550
+ "credit_card",
8551
+ "card_number",
8552
+ "cvv",
8553
+ "bank_account",
8554
+ "routing_number",
8555
+ "passport",
8556
+ "drivers_license",
8557
+ "license_number"
8558
+ ],
8559
+ action: "redact",
8560
+ confidence: "high",
8561
+ reason: "Matches known PII pattern"
8562
+ },
8563
+ // ── Internal agent state (redact, high confidence) ───────────────
8564
+ {
8565
+ patterns: [
8566
+ "memory",
8567
+ "agent_memory",
8568
+ "long_term_memory",
8569
+ "internal_reasoning",
8570
+ "reasoning_trace",
8571
+ "chain_of_thought",
8572
+ "internal_state",
8573
+ "agent_state",
8574
+ "private_notes",
8575
+ "scratchpad",
8576
+ "soul",
8577
+ "personality",
8578
+ "persona",
8579
+ "system_prompt",
8580
+ "system_message",
8581
+ "system_instruction",
8582
+ "preferences",
8583
+ "user_preferences",
8584
+ "agent_preferences",
8585
+ "beliefs",
8586
+ "goals",
8587
+ "motivations"
8588
+ ],
8589
+ action: "redact",
8590
+ confidence: "high",
8591
+ reason: "Matches known internal agent state pattern"
8592
+ },
8593
+ // ── IDs (hash, medium confidence) ────────────────────────────────
8594
+ {
8595
+ patterns: [
8596
+ "user_id",
8597
+ "userid",
8598
+ "session_id",
8599
+ "sessionid",
8600
+ "agent_id",
8601
+ "agentid",
8602
+ "identity_id",
8603
+ "conversation_id",
8604
+ "thread_id",
8605
+ "threadid",
8606
+ "request_id",
8607
+ "requestid",
8608
+ "correlation_id",
8609
+ "trace_id",
8610
+ "traceid",
8611
+ "account_id",
8612
+ "accountid"
8613
+ ],
8614
+ action: "hash",
8615
+ confidence: "medium",
8616
+ reason: "Matches known identifier pattern \u2014 hash preserves correlation without exposing value"
8617
+ },
8618
+ // ── History (summarize, medium confidence) ───────────────────────
8619
+ {
8620
+ patterns: [
8621
+ "conversation_history",
8622
+ "chat_history",
8623
+ "message_history",
8624
+ "messages",
8625
+ "previous_messages",
8626
+ "prior_messages",
8627
+ "context_window",
8628
+ "interaction_history",
8629
+ "audit_log",
8630
+ "event_log"
8631
+ ],
8632
+ action: "summarize",
8633
+ confidence: "medium",
8634
+ reason: "Matches known history/log pattern \u2014 summarize to reduce exposure"
8635
+ },
8636
+ // ── Task/query (allow, medium confidence) ────────────────────────
8637
+ {
8638
+ patterns: [
8639
+ "task",
8640
+ "task_description",
8641
+ "query",
8642
+ "current_query",
8643
+ "search_query",
8644
+ "prompt",
8645
+ "user_prompt",
8646
+ "question",
8647
+ "current_question",
8648
+ "instruction",
8649
+ "instructions",
8650
+ "objective",
8651
+ "goal",
8652
+ "current_step",
8653
+ "next_step",
8654
+ "remaining_steps",
8655
+ "constraints",
8656
+ "requirements",
8657
+ "output_format",
8658
+ "format",
8659
+ "tool_results",
8660
+ "tool_output",
8661
+ "tool_input",
8662
+ "tool_parameters"
8663
+ ],
8664
+ action: "allow",
8665
+ confidence: "medium",
8666
+ reason: "Matches known task/query pattern \u2014 likely needed for inference"
8667
+ }
8668
+ ];
8669
+ function classifyField(fieldName) {
8670
+ const normalized = fieldName.toLowerCase().trim();
8671
+ for (const rule of CLASSIFICATION_RULES) {
8672
+ for (const pattern of rule.patterns) {
8673
+ if (matchesFieldPattern(normalized, pattern)) {
8674
+ return {
8675
+ field: fieldName,
8676
+ recommended_action: rule.action,
8677
+ reason: rule.reason,
8678
+ confidence: rule.confidence,
8679
+ matched_pattern: pattern
8680
+ };
8681
+ }
8682
+ }
8683
+ }
8684
+ return {
8685
+ field: fieldName,
8686
+ recommended_action: "redact",
8687
+ reason: "No known pattern matched \u2014 defaulting to redact (conservative)",
8688
+ confidence: "low",
8689
+ matched_pattern: null
8690
+ };
8691
+ }
8692
+ function recommendPolicy(context, provider = "inference") {
8693
+ const fields = Object.keys(context);
8694
+ const classifications = fields.map(classifyField);
8695
+ const warnings = [];
8696
+ const allow = [];
8697
+ const redact = [];
8698
+ const hash2 = [];
8699
+ const summarize = [];
8700
+ for (const c of classifications) {
8701
+ switch (c.recommended_action) {
8702
+ case "allow":
8703
+ allow.push(c.field);
8704
+ break;
8705
+ case "redact":
8706
+ redact.push(c.field);
8707
+ break;
8708
+ case "hash":
8709
+ hash2.push(c.field);
8710
+ break;
8711
+ case "summarize":
8712
+ summarize.push(c.field);
8713
+ break;
8714
+ }
8715
+ }
8716
+ const lowConfidence = classifications.filter((c) => c.confidence === "low");
8717
+ if (lowConfidence.length > 0) {
8718
+ warnings.push(
8719
+ `${lowConfidence.length} field(s) could not be classified by pattern and will default to redact: ${lowConfidence.map((c) => c.field).join(", ")}. Review these manually.`
8720
+ );
8721
+ }
8722
+ for (const [key, value] of Object.entries(context)) {
8723
+ if (typeof value === "string" && value.length > 5e3) {
8724
+ const existing = classifications.find((c) => c.field === key);
8725
+ if (existing && existing.recommended_action === "allow") {
8726
+ warnings.push(
8727
+ `Field "${key}" is allowed but contains ${value.length} characters. Consider summarizing it to reduce context size and exposure.`
8728
+ );
8729
+ }
8730
+ }
8731
+ }
8732
+ return {
8733
+ provider,
8734
+ classifications,
8735
+ recommended_rules: { allow, redact, hash: hash2, summarize },
8736
+ default_action: "redact",
8737
+ summary: {
8738
+ total_fields: fields.length,
8739
+ allow: allow.length,
8740
+ redact: redact.length,
8741
+ hash: hash2.length,
8742
+ summarize: summarize.length
8743
+ },
8744
+ warnings
8745
+ };
8746
+ }
8747
+ function matchesFieldPattern(normalizedField, pattern) {
8748
+ if (normalizedField === pattern) return true;
8749
+ if (pattern.length >= 3 && normalizedField.includes(pattern)) {
8750
+ const idx = normalizedField.indexOf(pattern);
8751
+ const before = idx === 0 || normalizedField[idx - 1] === "_" || normalizedField[idx - 1] === "-";
8752
+ const after = idx + pattern.length === normalizedField.length || normalizedField[idx + pattern.length] === "_" || normalizedField[idx + pattern.length] === "-";
8753
+ return before && after;
8754
+ }
8755
+ return false;
8756
+ }
8757
+
8758
+ // src/l2-operational/context-gate-tools.ts
8759
+ function createContextGateTools(storage, masterKey, auditLog) {
8760
+ const policyStore = new ContextGatePolicyStore(storage, masterKey);
8761
+ const tools = [
8762
+ // ── Set Policy ──────────────────────────────────────────────────
8763
+ {
8764
+ name: "sanctuary/context_gate_set_policy",
8765
+ 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.",
8766
+ inputSchema: {
8767
+ type: "object",
8768
+ properties: {
8769
+ policy_name: {
8770
+ type: "string",
8771
+ description: "Human-readable name for this policy (e.g., 'inference-minimal', 'tool-api-strict')"
8772
+ },
8773
+ rules: {
8774
+ type: "array",
8775
+ 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).",
8776
+ items: {
8777
+ type: "object",
8778
+ properties: {
8779
+ provider: {
8780
+ type: "string",
8781
+ description: "Provider category: inference, tool-api, logging, analytics, peer-agent, custom, or * for all"
8782
+ },
8783
+ allow: {
8784
+ type: "array",
8785
+ items: { type: "string" },
8786
+ description: "Fields/patterns to allow through (e.g., 'task_description', 'current_query', 'tool_*')"
8787
+ },
8788
+ redact: {
8789
+ type: "array",
8790
+ items: { type: "string" },
8791
+ description: "Fields/patterns to redact (e.g., 'conversation_history', 'secret_*', '*_pii'). Takes absolute priority."
8792
+ },
8793
+ hash: {
8794
+ type: "array",
8795
+ items: { type: "string" },
8796
+ description: "Fields/patterns to replace with SHA-256 hash (e.g., 'user_id', 'session_id')"
8797
+ },
8798
+ summarize: {
8799
+ type: "array",
8800
+ items: { type: "string" },
8801
+ description: "Fields/patterns to flag for summarization (advisory \u2014 agent should compress these before sending)"
8802
+ }
8803
+ },
8804
+ required: ["provider", "allow", "redact"]
8805
+ }
8806
+ },
8807
+ default_action: {
8808
+ type: "string",
8809
+ enum: ["redact", "deny"],
8810
+ description: "Action for fields not matched by any rule. 'redact' removes the field value; 'deny' blocks the entire request. Default: 'redact'."
8811
+ },
8812
+ identity_id: {
8813
+ type: "string",
8814
+ description: "Bind this policy to a specific identity (optional)"
8815
+ }
8816
+ },
8817
+ required: ["policy_name", "rules"]
8818
+ },
8819
+ handler: async (args) => {
8820
+ const policyName = args.policy_name;
8821
+ const rawRules = args.rules;
8822
+ const defaultAction = args.default_action ?? "redact";
8823
+ const identityId = args.identity_id;
8824
+ if (!Array.isArray(rawRules)) {
8825
+ return toolResult({ error: "invalid_rules", message: "rules must be an array" });
8826
+ }
8827
+ if (rawRules.length > MAX_POLICY_RULES) {
8828
+ return toolResult({
8829
+ error: "too_many_rules",
8830
+ message: `Policy has ${rawRules.length} rules, exceeding limit of ${MAX_POLICY_RULES}`
8831
+ });
8832
+ }
8833
+ const rules = [];
8834
+ for (const r of rawRules) {
8835
+ const allow = Array.isArray(r.allow) ? r.allow : [];
8836
+ const redact = Array.isArray(r.redact) ? r.redact : [];
8837
+ const hash2 = Array.isArray(r.hash) ? r.hash : [];
8838
+ const summarize = Array.isArray(r.summarize) ? r.summarize : [];
8839
+ for (const [name, arr] of [["allow", allow], ["redact", redact], ["hash", hash2], ["summarize", summarize]]) {
8840
+ if (arr.length > MAX_PATTERNS_PER_ARRAY) {
8841
+ return toolResult({
8842
+ error: "too_many_patterns",
8843
+ message: `Rule ${name} array has ${arr.length} patterns, exceeding limit of ${MAX_PATTERNS_PER_ARRAY}`
8844
+ });
8845
+ }
8846
+ }
8847
+ rules.push({
8848
+ provider: r.provider ?? "*",
8849
+ allow,
8850
+ redact,
8851
+ hash: hash2,
8852
+ summarize
8853
+ });
8854
+ }
8855
+ const policy = await policyStore.create(
8856
+ policyName,
8857
+ rules,
8858
+ defaultAction,
8859
+ identityId
8860
+ );
8861
+ auditLog.append("l2", "context_gate_set_policy", identityId ?? "system", {
8862
+ policy_id: policy.policy_id,
8863
+ policy_name: policyName,
8864
+ rule_count: rules.length,
8865
+ default_action: defaultAction
8866
+ });
8867
+ return toolResult({
8868
+ policy_id: policy.policy_id,
8869
+ policy_name: policy.policy_name,
8870
+ rules: policy.rules,
8871
+ default_action: policy.default_action,
8872
+ created_at: policy.created_at,
8873
+ message: "Context-gating policy created. Use sanctuary/context_gate_filter to apply this policy before making outbound calls."
8874
+ });
8875
+ }
8876
+ },
8877
+ // ── Apply Template ───────────────────────────────────────────────
8878
+ {
8879
+ name: "sanctuary/context_gate_apply_template",
8880
+ 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.",
8881
+ inputSchema: {
8882
+ type: "object",
8883
+ properties: {
8884
+ template_id: {
8885
+ type: "string",
8886
+ description: "Template to apply: inference-minimal, inference-standard, logging-strict, or tool-api-scoped"
8887
+ },
8888
+ identity_id: {
8889
+ type: "string",
8890
+ description: "Bind this policy to a specific identity (optional)"
8891
+ }
8892
+ },
8893
+ required: ["template_id"]
8894
+ },
8895
+ handler: async (args) => {
8896
+ const templateId = args.template_id;
8897
+ const identityId = args.identity_id;
8898
+ const template = getTemplate(templateId);
8899
+ if (!template) {
8900
+ return toolResult({
8901
+ error: "template_not_found",
8902
+ message: `Unknown template "${templateId}"`,
8903
+ available_templates: listTemplateIds().map((id) => {
8904
+ const t = TEMPLATES[id];
8905
+ return { id, name: t.name, description: t.description };
8906
+ })
8907
+ });
8908
+ }
8909
+ const policy = await policyStore.create(
8910
+ template.name,
8911
+ template.rules,
8912
+ template.default_action,
8913
+ identityId
8914
+ );
8915
+ auditLog.append("l2", "context_gate_apply_template", identityId ?? "system", {
8916
+ policy_id: policy.policy_id,
8917
+ template_id: templateId
8918
+ });
8919
+ return toolResult({
8920
+ policy_id: policy.policy_id,
8921
+ template_applied: templateId,
8922
+ policy_name: template.name,
8923
+ description: template.description,
8924
+ use_when: template.use_when,
8925
+ rules: policy.rules,
8926
+ default_action: policy.default_action,
8927
+ created_at: policy.created_at,
8928
+ 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."
8929
+ });
8930
+ }
8931
+ },
8932
+ // ── Recommend Policy ────────────────────────────────────────────
8933
+ {
8934
+ name: "sanctuary/context_gate_recommend",
8935
+ 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.",
8936
+ inputSchema: {
8937
+ type: "object",
8938
+ properties: {
8939
+ context: {
8940
+ type: "object",
8941
+ description: "A sample context object to analyze. Each top-level key will be classified. Values are inspected for size warnings but not stored."
8942
+ },
8943
+ provider: {
8944
+ type: "string",
8945
+ description: "Provider category to generate rules for. Default: 'inference'."
8946
+ }
8947
+ },
8948
+ required: ["context"]
8949
+ },
8950
+ handler: async (args) => {
8951
+ const context = args.context;
8952
+ const provider = args.provider ?? "inference";
8953
+ const contextKeys = Object.keys(context);
8954
+ if (contextKeys.length > MAX_CONTEXT_FIELDS) {
8955
+ return toolResult({
8956
+ error: "context_too_large",
8957
+ message: `Context has ${contextKeys.length} fields, exceeding limit of ${MAX_CONTEXT_FIELDS}`
8958
+ });
8959
+ }
8960
+ const recommendation = recommendPolicy(context, provider);
8961
+ auditLog.append("l2", "context_gate_recommend", "system", {
8962
+ provider,
8963
+ fields_analyzed: recommendation.summary.total_fields,
8964
+ fields_allow: recommendation.summary.allow,
8965
+ fields_redact: recommendation.summary.redact,
8966
+ fields_hash: recommendation.summary.hash,
8967
+ fields_summarize: recommendation.summary.summarize
8968
+ });
8969
+ return toolResult({
8970
+ ...recommendation,
8971
+ 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.",
8972
+ available_templates: listTemplateIds().map((id) => {
8973
+ const t = TEMPLATES[id];
8974
+ return { id, name: t.name, description: t.description };
8975
+ })
8976
+ });
8977
+ }
8978
+ },
8979
+ // ── Filter Context ──────────────────────────────────────────────
8980
+ {
8981
+ name: "sanctuary/context_gate_filter",
8982
+ 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.",
8983
+ inputSchema: {
8984
+ type: "object",
8985
+ properties: {
8986
+ policy_id: {
8987
+ type: "string",
8988
+ description: "ID of the context-gating policy to apply"
8989
+ },
8990
+ provider: {
8991
+ type: "string",
8992
+ description: "Provider category for this call: inference, tool-api, logging, analytics, peer-agent, or custom"
8993
+ },
8994
+ context: {
8995
+ type: "object",
8996
+ 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"
8997
+ }
8998
+ },
8999
+ required: ["policy_id", "provider", "context"]
9000
+ },
9001
+ handler: async (args) => {
9002
+ const policyId = args.policy_id;
9003
+ const provider = args.provider;
9004
+ const context = args.context;
9005
+ const contextKeys = Object.keys(context);
9006
+ if (contextKeys.length > MAX_CONTEXT_FIELDS) {
9007
+ return toolResult({
9008
+ error: "context_too_large",
9009
+ message: `Context has ${contextKeys.length} fields, exceeding limit of ${MAX_CONTEXT_FIELDS}`
9010
+ });
9011
+ }
9012
+ const policy = await policyStore.get(policyId);
9013
+ if (!policy) {
9014
+ return toolResult({
9015
+ error: "policy_not_found",
9016
+ message: `No context-gating policy found with ID "${policyId}"`
9017
+ });
9018
+ }
9019
+ const result = filterContext(policy, provider, context);
9020
+ const deniedFields = result.decisions.filter((d) => d.action === "deny");
9021
+ if (deniedFields.length > 0) {
9022
+ auditLog.append("l2", "context_gate_deny", policy.identity_id ?? "system", {
9023
+ policy_id: policyId,
9024
+ provider,
9025
+ denied_fields: deniedFields.map((d) => d.field),
9026
+ original_context_hash: result.original_context_hash
9027
+ });
9028
+ return toolResult({
9029
+ blocked: true,
9030
+ reason: "Context contains fields that trigger deny action",
9031
+ denied_fields: deniedFields.map((d) => ({
9032
+ field: d.field,
9033
+ reason: d.reason
9034
+ })),
9035
+ recommendation: "Remove the denied fields from context before retrying, or update the policy to handle these fields differently."
9036
+ });
9037
+ }
9038
+ const safeContext = {};
9039
+ for (const decision of result.decisions) {
9040
+ switch (decision.action) {
9041
+ case "allow":
9042
+ safeContext[decision.field] = context[decision.field];
9043
+ break;
9044
+ case "redact":
9045
+ break;
9046
+ case "hash":
9047
+ safeContext[decision.field] = decision.hash_value;
9048
+ break;
9049
+ case "summarize":
9050
+ safeContext[decision.field] = context[decision.field];
9051
+ break;
9052
+ }
9053
+ }
9054
+ auditLog.append("l2", "context_gate_filter", policy.identity_id ?? "system", {
9055
+ policy_id: policyId,
9056
+ provider,
9057
+ fields_total: Object.keys(context).length,
9058
+ fields_allowed: result.fields_allowed,
9059
+ fields_redacted: result.fields_redacted,
9060
+ fields_hashed: result.fields_hashed,
9061
+ fields_summarized: result.fields_summarized,
9062
+ original_context_hash: result.original_context_hash,
9063
+ filtered_context_hash: result.filtered_context_hash
9064
+ });
9065
+ return toolResult({
9066
+ blocked: false,
9067
+ safe_context: safeContext,
9068
+ summary: {
9069
+ total_fields: Object.keys(context).length,
9070
+ allowed: result.fields_allowed,
9071
+ redacted: result.fields_redacted,
9072
+ hashed: result.fields_hashed,
9073
+ summarized: result.fields_summarized
9074
+ },
9075
+ decisions: result.decisions,
9076
+ audit: {
9077
+ original_context_hash: result.original_context_hash,
9078
+ filtered_context_hash: result.filtered_context_hash,
9079
+ filtered_at: result.filtered_at
9080
+ },
9081
+ 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
9082
+ });
9083
+ }
9084
+ },
9085
+ // ── List Policies ───────────────────────────────────────────────
9086
+ {
9087
+ name: "sanctuary/context_gate_list_policies",
9088
+ description: "List all configured context-gating policies. Returns policy IDs, names, rule summaries, and default actions.",
9089
+ inputSchema: {
9090
+ type: "object",
9091
+ properties: {}
9092
+ },
9093
+ handler: async () => {
9094
+ const policies = await policyStore.list();
9095
+ auditLog.append("l2", "context_gate_list_policies", "system", {
9096
+ policy_count: policies.length
9097
+ });
9098
+ return toolResult({
9099
+ policies: policies.map((p) => ({
9100
+ policy_id: p.policy_id,
9101
+ policy_name: p.policy_name,
9102
+ rule_count: p.rules.length,
9103
+ providers: p.rules.map((r) => r.provider),
9104
+ default_action: p.default_action,
9105
+ identity_id: p.identity_id ?? null,
9106
+ created_at: p.created_at,
9107
+ updated_at: p.updated_at
9108
+ })),
9109
+ count: policies.length,
9110
+ 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.`
9111
+ });
9112
+ }
9113
+ }
9114
+ ];
9115
+ return { tools, policyStore };
9116
+ }
9117
+ function checkMemoryProtection() {
9118
+ const checks = {
9119
+ aslr_enabled: checkASLR(),
9120
+ stack_canaries: true,
9121
+ // Enabled by default in Node.js runtime
9122
+ secure_buffer_zeros: true,
9123
+ // We use crypto.randomBytes and explicit zeroing
9124
+ argon2id_kdf: true
9125
+ // Master key derivation uses Argon2id
9126
+ };
9127
+ const activeCount = Object.values(checks).filter((v) => v).length;
9128
+ const overall = activeCount >= 4 ? "full" : activeCount >= 3 ? "partial" : "minimal";
9129
+ return {
9130
+ ...checks,
9131
+ overall
9132
+ };
9133
+ }
9134
+ function checkASLR() {
9135
+ if (process.platform === "linux") {
9136
+ try {
9137
+ const result = child_process.execSync("cat /proc/sys/kernel/randomize_va_space", {
9138
+ encoding: "utf-8",
9139
+ stdio: ["pipe", "pipe", "ignore"]
9140
+ }).trim();
9141
+ return result === "2";
9142
+ } catch {
9143
+ return false;
9144
+ }
9145
+ }
9146
+ if (process.platform === "darwin") {
9147
+ return true;
9148
+ }
9149
+ return false;
9150
+ }
9151
+ function checkProcessIsolation() {
9152
+ const isContainer = detectContainer();
9153
+ const isVM = detectVM();
9154
+ const isSandboxed = detectSandbox();
9155
+ let isolationLevel = "none";
9156
+ if (isContainer) isolationLevel = "hardened";
9157
+ else if (isVM) isolationLevel = "hardened";
9158
+ else if (isSandboxed) isolationLevel = "basic";
9159
+ const details = {};
9160
+ if (isContainer && isContainer !== true) details.container_type = isContainer;
9161
+ if (isVM && isVM !== true) details.vm_type = isVM;
9162
+ if (isSandboxed && isSandboxed !== true) details.sandbox_type = isSandboxed;
9163
+ return {
9164
+ isolation_level: isolationLevel,
9165
+ is_container: isContainer !== false,
9166
+ is_vm: isVM !== false,
9167
+ is_sandboxed: isSandboxed !== false,
9168
+ is_tee: false,
9169
+ details
9170
+ };
9171
+ }
9172
+ function detectContainer() {
9173
+ try {
9174
+ if (process.env.DOCKER_HOST) return "docker";
9175
+ try {
9176
+ fs.statSync("/.dockerenv");
9177
+ return "docker";
9178
+ } catch {
9179
+ }
9180
+ if (process.platform === "linux") {
9181
+ const cgroup = child_process.execSync("cat /proc/1/cgroup 2>/dev/null || echo ''", {
9182
+ encoding: "utf-8"
9183
+ });
9184
+ if (cgroup.includes("docker")) return "docker";
9185
+ if (cgroup.includes("lxc")) return "lxc";
9186
+ if (cgroup.includes("kubepods") || cgroup.includes("kubernetes")) return "kubernetes";
9187
+ }
9188
+ if (process.env.container === "podman") return "podman";
9189
+ if (process.env.CONTAINER_ID) return "oci";
9190
+ return false;
9191
+ } catch {
9192
+ return false;
9193
+ }
9194
+ }
9195
+ function detectVM() {
9196
+ if (process.platform === "linux") {
9197
+ try {
9198
+ const dmidecode = child_process.execSync("dmidecode -s system-product-name 2>/dev/null || echo ''", {
9199
+ encoding: "utf-8"
9200
+ }).toLowerCase();
9201
+ if (dmidecode.includes("vmware")) return "vmware";
9202
+ if (dmidecode.includes("virtualbox")) return "virtualbox";
9203
+ if (dmidecode.includes("kvm")) return "kvm";
9204
+ if (dmidecode.includes("xen")) return "xen";
9205
+ if (dmidecode.includes("hyper-v")) return "hyper-v";
9206
+ const cpuinfo = child_process.execSync("grep -i hypervisor /proc/cpuinfo || echo ''", {
9207
+ encoding: "utf-8"
9208
+ });
9209
+ if (cpuinfo.length > 0) return "detected";
9210
+ } catch {
9211
+ }
9212
+ }
9213
+ if (process.platform === "darwin") {
9214
+ try {
9215
+ const bootargs = child_process.execSync(
9216
+ "nvram boot-args 2>/dev/null | grep -i 'parallels\\|vmware\\|virtualbox' || echo ''",
9217
+ {
9218
+ encoding: "utf-8"
9219
+ }
9220
+ );
9221
+ if (bootargs.length > 0) return "detected";
9222
+ } catch {
9223
+ }
9224
+ }
9225
+ return false;
9226
+ }
9227
+ function detectSandbox() {
9228
+ if (process.platform === "darwin") {
9229
+ if (process.env.APP_SANDBOX_READ_ONLY_HOME === "1") return "app-sandbox";
9230
+ if (process.env.TMPDIR && process.env.TMPDIR.includes("AppSandbox")) return "app-sandbox";
9231
+ }
9232
+ if (process.platform === "openbsd") {
9233
+ try {
9234
+ const pledge = child_process.execSync("pledge -v 2>/dev/null || echo ''", {
9235
+ encoding: "utf-8"
9236
+ });
9237
+ if (pledge.length > 0) return "pledge";
9238
+ } catch {
9239
+ }
9240
+ }
9241
+ if (process.platform === "linux") {
9242
+ if (process.env.container === "lxc") return "lxc";
9243
+ try {
9244
+ const context = child_process.execSync("getenforce 2>/dev/null || echo ''", {
9245
+ encoding: "utf-8"
9246
+ }).trim();
9247
+ if (context === "Enforcing") return "selinux";
9248
+ } catch {
9249
+ }
9250
+ }
9251
+ return false;
9252
+ }
9253
+ function checkFilesystemPermissions(storagePath) {
9254
+ try {
9255
+ const stats = fs.statSync(storagePath);
9256
+ const mode = stats.mode & parseInt("777", 8);
9257
+ const modeString = mode.toString(8).padStart(3, "0");
9258
+ const isSecure = mode === parseInt("700", 8);
9259
+ const groupReadable = (mode & parseInt("040", 8)) !== 0;
9260
+ const othersReadable = (mode & parseInt("007", 8)) !== 0;
9261
+ const currentUid = process.getuid?.() || -1;
9262
+ const ownerIsCurrentUser = stats.uid === currentUid;
9263
+ let overall = "secure";
9264
+ if (groupReadable || othersReadable) overall = "insecure";
9265
+ else if (!ownerIsCurrentUser) overall = "warning";
9266
+ return {
9267
+ sanctuary_storage_protected: isSecure,
9268
+ sanctuary_storage_mode: modeString,
9269
+ owner_is_current_user: ownerIsCurrentUser,
9270
+ group_readable: groupReadable,
9271
+ others_readable: othersReadable,
9272
+ overall
9273
+ };
9274
+ } catch {
9275
+ return {
9276
+ sanctuary_storage_protected: false,
9277
+ sanctuary_storage_mode: "unknown",
9278
+ owner_is_current_user: false,
9279
+ group_readable: false,
9280
+ others_readable: false,
9281
+ overall: "warning"
9282
+ };
9283
+ }
9284
+ }
9285
+ function checkRuntimeIntegrity() {
9286
+ return {
9287
+ config_hash_stable: true,
9288
+ environment_state: "clean",
9289
+ discrepancies: []
9290
+ };
9291
+ }
9292
+ function assessL2Hardening(storagePath) {
9293
+ const memory = checkMemoryProtection();
9294
+ const isolation = checkProcessIsolation();
9295
+ const filesystem = checkFilesystemPermissions(storagePath);
9296
+ const integrity = checkRuntimeIntegrity();
9297
+ let checksPassed = 0;
9298
+ let checksTotal = 0;
9299
+ if (memory.aslr_enabled) checksPassed++;
9300
+ checksTotal++;
9301
+ if (memory.stack_canaries) checksPassed++;
9302
+ checksTotal++;
9303
+ if (memory.secure_buffer_zeros) checksPassed++;
9304
+ checksTotal++;
9305
+ if (memory.argon2id_kdf) checksPassed++;
9306
+ checksTotal++;
9307
+ if (isolation.is_container) checksPassed++;
9308
+ checksTotal++;
9309
+ if (isolation.is_vm) checksPassed++;
9310
+ checksTotal++;
9311
+ if (isolation.is_sandboxed) checksPassed++;
9312
+ checksTotal++;
9313
+ if (filesystem.sanctuary_storage_protected) checksPassed++;
9314
+ checksTotal++;
9315
+ {
9316
+ checksPassed++;
9317
+ }
9318
+ checksTotal++;
9319
+ let hardeningLevel = isolation.isolation_level;
9320
+ if (filesystem.overall === "insecure" || memory.overall === "none" || memory.overall === "minimal") {
9321
+ if (hardeningLevel === "hardened") {
9322
+ hardeningLevel = "basic";
9323
+ } else if (hardeningLevel === "basic") {
9324
+ hardeningLevel = "none";
9325
+ }
9326
+ }
9327
+ const summaryParts = [];
9328
+ if (isolation.is_container || isolation.is_vm) {
9329
+ summaryParts.push(`Running in ${isolation.details.container_type || isolation.details.vm_type || "isolated environment"}`);
9330
+ }
9331
+ if (memory.aslr_enabled) {
9332
+ summaryParts.push("ASLR enabled");
9333
+ }
9334
+ if (filesystem.sanctuary_storage_protected) {
9335
+ summaryParts.push("Storage permissions secured (0700)");
9336
+ }
9337
+ const summary = summaryParts.length > 0 ? summaryParts.join("; ") : "No process-level hardening detected";
9338
+ return {
9339
+ hardening_level: hardeningLevel,
9340
+ memory_protection: memory,
9341
+ process_isolation: isolation,
9342
+ filesystem_permissions: filesystem,
9343
+ runtime_integrity: integrity,
9344
+ checks_passed: checksPassed,
9345
+ checks_total: checksTotal,
9346
+ summary
9347
+ };
9348
+ }
9349
+
9350
+ // src/l2-operational/hardening-tools.ts
9351
+ function createL2HardeningTools(storagePath, auditLog) {
9352
+ return [
9353
+ {
9354
+ name: "sanctuary/l2_hardening_status",
9355
+ 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.",
9356
+ inputSchema: {
9357
+ type: "object",
9358
+ properties: {
9359
+ include_details: {
9360
+ type: "boolean",
9361
+ description: "If true, include detailed check results for memory, process, and filesystem. If false, show summary only.",
9362
+ default: false
9363
+ }
9364
+ }
9365
+ },
9366
+ handler: async (args) => {
9367
+ const includeDetails = args.include_details ?? false;
9368
+ const status = assessL2Hardening(storagePath);
9369
+ auditLog.append(
9370
+ "l2",
9371
+ "l2_hardening_status",
9372
+ "system",
9373
+ { include_details: includeDetails }
9374
+ );
9375
+ if (includeDetails) {
9376
+ return toolResult({
9377
+ hardening_level: status.hardening_level,
9378
+ summary: status.summary,
9379
+ checks_passed: status.checks_passed,
9380
+ checks_total: status.checks_total,
9381
+ memory_protection: {
9382
+ aslr_enabled: status.memory_protection.aslr_enabled,
9383
+ stack_canaries: status.memory_protection.stack_canaries,
9384
+ secure_buffer_zeros: status.memory_protection.secure_buffer_zeros,
9385
+ argon2id_kdf: status.memory_protection.argon2id_kdf,
9386
+ overall: status.memory_protection.overall
9387
+ },
9388
+ process_isolation: {
9389
+ isolation_level: status.process_isolation.isolation_level,
9390
+ is_container: status.process_isolation.is_container,
9391
+ is_vm: status.process_isolation.is_vm,
9392
+ is_sandboxed: status.process_isolation.is_sandboxed,
9393
+ is_tee: status.process_isolation.is_tee,
9394
+ details: status.process_isolation.details
9395
+ },
9396
+ filesystem_permissions: {
9397
+ sanctuary_storage_protected: status.filesystem_permissions.sanctuary_storage_protected,
9398
+ sanctuary_storage_mode: status.filesystem_permissions.sanctuary_storage_mode,
9399
+ owner_is_current_user: status.filesystem_permissions.owner_is_current_user,
9400
+ group_readable: status.filesystem_permissions.group_readable,
9401
+ others_readable: status.filesystem_permissions.others_readable,
9402
+ overall: status.filesystem_permissions.overall
9403
+ },
9404
+ runtime_integrity: {
9405
+ config_hash_stable: status.runtime_integrity.config_hash_stable,
9406
+ environment_state: status.runtime_integrity.environment_state,
9407
+ discrepancies: status.runtime_integrity.discrepancies
9408
+ }
9409
+ });
9410
+ } else {
9411
+ return toolResult({
9412
+ hardening_level: status.hardening_level,
9413
+ summary: status.summary,
9414
+ checks_passed: status.checks_passed,
9415
+ checks_total: status.checks_total,
9416
+ note: "Pass include_details: true to see full breakdown of memory, process isolation, and filesystem checks."
9417
+ });
9418
+ }
9419
+ }
9420
+ },
9421
+ {
9422
+ name: "sanctuary/l2_verify_isolation",
9423
+ 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.",
9424
+ inputSchema: {
9425
+ type: "object",
9426
+ properties: {
9427
+ check_filesystem: {
9428
+ type: "boolean",
9429
+ description: "If true, verify Sanctuary storage directory permissions.",
9430
+ default: true
9431
+ },
9432
+ check_memory: {
9433
+ type: "boolean",
9434
+ description: "If true, verify memory protection mechanisms (ASLR, etc.).",
9435
+ default: true
9436
+ },
9437
+ check_process: {
9438
+ type: "boolean",
9439
+ description: "If true, detect container, VM, or sandbox environment.",
9440
+ default: true
9441
+ }
9442
+ }
9443
+ },
9444
+ handler: async (args) => {
9445
+ const checkFilesystem = args.check_filesystem ?? true;
9446
+ const checkMemory = args.check_memory ?? true;
9447
+ const checkProcess = args.check_process ?? true;
9448
+ const status = assessL2Hardening(storagePath);
9449
+ auditLog.append(
9450
+ "l2",
9451
+ "l2_verify_isolation",
9452
+ "system",
9453
+ {
9454
+ check_filesystem: checkFilesystem,
9455
+ check_memory: checkMemory,
9456
+ check_process: checkProcess
9457
+ }
9458
+ );
9459
+ const results = {
9460
+ isolation_level: status.hardening_level,
9461
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
9462
+ };
9463
+ if (checkFilesystem) {
9464
+ const fs = status.filesystem_permissions;
9465
+ results.filesystem = {
9466
+ sanctuary_storage_protected: fs.sanctuary_storage_protected,
9467
+ storage_mode: fs.sanctuary_storage_mode,
9468
+ is_secure: fs.overall === "secure",
9469
+ issues: fs.overall === "insecure" ? [
9470
+ "Storage directory is readable by group or others. Recommend: chmod 700 on Sanctuary storage path."
9471
+ ] : fs.overall === "warning" ? [
9472
+ "Storage directory not owned by current user. Verify correct user is running Sanctuary."
9473
+ ] : []
9474
+ };
9475
+ }
9476
+ if (checkMemory) {
9477
+ const mem = status.memory_protection;
9478
+ const issues = [];
9479
+ if (!mem.aslr_enabled) {
9480
+ issues.push(
9481
+ "ASLR not detected. On Linux, enable with: echo 2 | sudo tee /proc/sys/kernel/randomize_va_space"
9482
+ );
9483
+ }
9484
+ results.memory = {
9485
+ aslr_enabled: mem.aslr_enabled,
9486
+ stack_canaries: mem.stack_canaries,
9487
+ secure_buffer_handling: mem.secure_buffer_zeros,
9488
+ argon2id_key_derivation: mem.argon2id_kdf,
9489
+ protection_level: mem.overall,
9490
+ issues
9491
+ };
9492
+ }
9493
+ if (checkProcess) {
9494
+ const iso = status.process_isolation;
9495
+ results.process = {
9496
+ isolation_level: iso.isolation_level,
9497
+ in_container: iso.is_container,
9498
+ in_vm: iso.is_vm,
9499
+ sandboxed: iso.is_sandboxed,
9500
+ has_tee: iso.is_tee,
9501
+ environment: iso.details,
9502
+ 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."
9503
+ };
9504
+ }
9505
+ return toolResult({
9506
+ status: "verified",
9507
+ results
9508
+ });
9509
+ }
9510
+ }
9511
+ ];
9512
+ }
9513
+
9514
+ // src/index.ts
9515
+ init_encoding();
9516
+ async function createSanctuaryServer(options) {
9517
+ const config = await loadConfig(options?.configPath);
9518
+ await promises.mkdir(config.storage_path, { recursive: true, mode: 448 });
9519
+ const storage = options?.storage ?? new FilesystemStorage(
9520
+ `${config.storage_path}/state`
9521
+ );
9522
+ let masterKey;
9523
+ let keyProtection;
9524
+ let recoveryKey;
9525
+ const passphrase = options?.passphrase ?? process.env.SANCTUARY_PASSPHRASE;
9526
+ if (passphrase) {
9527
+ keyProtection = "passphrase";
9528
+ let existingParams;
9529
+ try {
9530
+ const raw = await storage.read("_meta", "key-params");
9531
+ if (raw) {
9532
+ const { bytesToString: bytesToString2 } = await Promise.resolve().then(() => (init_encoding(), encoding_exports));
9533
+ existingParams = JSON.parse(bytesToString2(raw));
9534
+ }
9535
+ } catch {
9536
+ }
9537
+ const result = await deriveMasterKey(passphrase, existingParams);
9538
+ masterKey = result.key;
9539
+ if (!existingParams) {
7585
9540
  const { stringToBytes: stringToBytes2 } = await Promise.resolve().then(() => (init_encoding(), encoding_exports));
7586
9541
  await storage.write(
7587
9542
  "_meta",
@@ -7722,7 +9677,7 @@ async function createSanctuaryServer(options) {
7722
9677
  layer: "l2",
7723
9678
  description: "Process-level isolation only (no TEE)",
7724
9679
  severity: "warning",
7725
- mitigation: "TEE support planned for v0.3.0"
9680
+ mitigation: "TEE support planned for a future release"
7726
9681
  });
7727
9682
  if (config.disclosure.proof_system === "commitment-only") {
7728
9683
  degradations.push({
@@ -7862,7 +9817,7 @@ async function createSanctuaryServer(options) {
7862
9817
  },
7863
9818
  limitations: [
7864
9819
  "L1 identity uses ed25519 only; KERI support planned for v0.2.0",
7865
- "L2 isolation is process-level only; TEE support planned for v0.3.0",
9820
+ "L2 isolation is process-level only; TEE support planned for a future release",
7866
9821
  "L3 uses commitment schemes only; ZK proofs planned for v0.2.0",
7867
9822
  "L4 Sybil resistance is escrow-based only",
7868
9823
  "Spec license: CC-BY-4.0 | Code license: Apache-2.0"
@@ -7883,7 +9838,7 @@ async function createSanctuaryServer(options) {
7883
9838
  masterKey,
7884
9839
  auditLog
7885
9840
  );
7886
- const { tools: l4Tools } = createL4Tools(
9841
+ const { tools: l4Tools} = createL4Tools(
7887
9842
  storage,
7888
9843
  masterKey,
7889
9844
  identityManager,
@@ -7902,6 +9857,12 @@ async function createSanctuaryServer(options) {
7902
9857
  handshakeResults
7903
9858
  );
7904
9859
  const { tools: auditTools } = createAuditTools(config);
9860
+ const { tools: contextGateTools } = createContextGateTools(
9861
+ storage,
9862
+ masterKey,
9863
+ auditLog
9864
+ );
9865
+ const hardeningTools = createL2HardeningTools(config.storage_path, auditLog);
7905
9866
  const policy = await loadPrincipalPolicy(config.storage_path);
7906
9867
  const baseline = new BaselineTracker(storage, masterKey);
7907
9868
  await baseline.load();
@@ -7951,6 +9912,8 @@ async function createSanctuaryServer(options) {
7951
9912
  ...federationTools,
7952
9913
  ...bridgeTools,
7953
9914
  ...auditTools,
9915
+ ...contextGateTools,
9916
+ ...hardeningTools,
7954
9917
  manifestTool
7955
9918
  ];
7956
9919
  const server = createServer(allTools, { gate });
@@ -7975,8 +9938,78 @@ async function createSanctuaryServer(options) {
7975
9938
  }
7976
9939
  return { server, config };
7977
9940
  }
7978
-
7979
- // src/cli.ts
9941
+ var REGISTRY_URL = "https://registry.npmjs.org/@sanctuary-framework/mcp-server/latest";
9942
+ var TIMEOUT_MS = 3e3;
9943
+ function isNewerVersion(current, latest) {
9944
+ const parse = (v) => v.replace(/^v/, "").split(".").map(Number);
9945
+ const [curMajor = 0, curMinor = 0, curPatch = 0] = parse(current);
9946
+ const [latMajor = 0, latMinor = 0, latPatch = 0] = parse(latest);
9947
+ if (latMajor !== curMajor) return latMajor > curMajor;
9948
+ if (latMinor !== curMinor) return latMinor > curMinor;
9949
+ return latPatch > curPatch;
9950
+ }
9951
+ function formatUpdateMessage(current, latest) {
9952
+ return `[Sanctuary] Update available: ${current} \u2192 ${latest} \u2014 run: npx @sanctuary-framework/mcp-server@latest`;
9953
+ }
9954
+ function fetchLatestVersion(currentVersion) {
9955
+ return new Promise((resolve) => {
9956
+ const req = https.get(
9957
+ REGISTRY_URL,
9958
+ {
9959
+ headers: { Accept: "application/json" },
9960
+ timeout: TIMEOUT_MS
9961
+ },
9962
+ (res) => {
9963
+ if (res.statusCode !== 200) {
9964
+ res.resume();
9965
+ resolve(null);
9966
+ return;
9967
+ }
9968
+ let data = "";
9969
+ res.setEncoding("utf-8");
9970
+ res.on("data", (chunk) => {
9971
+ data += chunk;
9972
+ if (data.length > 32768) {
9973
+ res.destroy();
9974
+ resolve(null);
9975
+ }
9976
+ });
9977
+ res.on("end", () => {
9978
+ try {
9979
+ const json = JSON.parse(data);
9980
+ const latest = json.version;
9981
+ if (typeof latest === "string" && isNewerVersion(currentVersion, latest)) {
9982
+ resolve(latest);
9983
+ } else {
9984
+ resolve(null);
9985
+ }
9986
+ } catch {
9987
+ resolve(null);
9988
+ }
9989
+ });
9990
+ }
9991
+ );
9992
+ req.on("error", () => resolve(null));
9993
+ req.on("timeout", () => {
9994
+ req.destroy();
9995
+ resolve(null);
9996
+ });
9997
+ });
9998
+ }
9999
+ async function checkForUpdate(currentVersion) {
10000
+ if (process.env.SANCTUARY_NO_UPDATE_CHECK === "1") {
10001
+ return;
10002
+ }
10003
+ try {
10004
+ const latest = await fetchLatestVersion(currentVersion);
10005
+ if (latest) {
10006
+ console.error(formatUpdateMessage(currentVersion, latest));
10007
+ }
10008
+ } catch {
10009
+ }
10010
+ }
10011
+ var require4 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli.cjs', document.baseURI).href)));
10012
+ var { version: PKG_VERSION3 } = require4("../package.json");
7980
10013
  async function main() {
7981
10014
  const args = process.argv.slice(2);
7982
10015
  let passphrase = process.env.SANCTUARY_PASSPHRASE;
@@ -7989,7 +10022,7 @@ async function main() {
7989
10022
  printHelp();
7990
10023
  process.exit(0);
7991
10024
  } else if (args[i] === "--version" || args[i] === "-v") {
7992
- console.log("@sanctuary-framework/mcp-server 0.3.0");
10025
+ console.log(`@sanctuary-framework/mcp-server ${PKG_VERSION3}`);
7993
10026
  process.exit(0);
7994
10027
  }
7995
10028
  }
@@ -8000,6 +10033,7 @@ async function main() {
8000
10033
  console.error(`Sanctuary MCP Server v${config.version} running (stdio)`);
8001
10034
  console.error(`Storage: ${config.storage_path}`);
8002
10035
  console.error("Tools: all registered");
10036
+ checkForUpdate(PKG_VERSION3);
8003
10037
  } else {
8004
10038
  console.error("HTTP transport not yet implemented. Use stdio.");
8005
10039
  process.exit(1);
@@ -8007,7 +10041,7 @@ async function main() {
8007
10041
  }
8008
10042
  function printHelp() {
8009
10043
  console.log(`
8010
- @sanctuary-framework/mcp-server v0.3.0
10044
+ @sanctuary-framework/mcp-server v${PKG_VERSION3}
8011
10045
 
8012
10046
  Sovereignty infrastructure for agents in the agentic economy.
8013
10047
 
@@ -8029,6 +10063,7 @@ Environment variables:
8029
10063
  SANCTUARY_WEBHOOK_ENABLED "true" to enable webhook approvals
8030
10064
  SANCTUARY_WEBHOOK_URL Webhook target URL
8031
10065
  SANCTUARY_WEBHOOK_SECRET HMAC-SHA256 shared secret
10066
+ SANCTUARY_NO_UPDATE_CHECK "1" to disable startup update check
8032
10067
 
8033
10068
  For more info: https://github.com/eriknewton/sanctuary-framework
8034
10069
  `);