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