@sanctuary-framework/mcp-server 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -14,6 +14,9 @@ var hashWasm = require('hash-wasm');
14
14
  var hkdf = require('@noble/hashes/hkdf');
15
15
  var index_js = require('@modelcontextprotocol/sdk/server/index.js');
16
16
  var types_js = require('@modelcontextprotocol/sdk/types.js');
17
+ var http = require('http');
18
+ var https = require('https');
19
+ var fs = require('fs');
17
20
 
18
21
  var __defProp = Object.defineProperty;
19
22
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -205,7 +208,7 @@ var init_hashing = __esm({
205
208
  });
206
209
  function defaultConfig() {
207
210
  return {
208
- version: "0.2.0",
211
+ version: "0.3.0",
209
212
  storage_path: path.join(os.homedir(), ".sanctuary"),
210
213
  state: {
211
214
  encryption: "aes-256-gcm",
@@ -234,7 +237,19 @@ function defaultConfig() {
234
237
  service_endpoints: []
235
238
  },
236
239
  transport: "stdio",
237
- http_port: 3500
240
+ http_port: 3500,
241
+ dashboard: {
242
+ enabled: false,
243
+ port: 3501,
244
+ host: "127.0.0.1"
245
+ },
246
+ webhook: {
247
+ enabled: false,
248
+ url: "",
249
+ secret: "",
250
+ callback_port: 3502,
251
+ callback_host: "127.0.0.1"
252
+ }
238
253
  };
239
254
  }
240
255
  async function loadConfig(configPath) {
@@ -248,6 +263,39 @@ async function loadConfig(configPath) {
248
263
  if (process.env.SANCTUARY_HTTP_PORT) {
249
264
  config.http_port = parseInt(process.env.SANCTUARY_HTTP_PORT, 10);
250
265
  }
266
+ if (process.env.SANCTUARY_DASHBOARD_ENABLED === "true") {
267
+ config.dashboard.enabled = true;
268
+ }
269
+ if (process.env.SANCTUARY_DASHBOARD_PORT) {
270
+ config.dashboard.port = parseInt(process.env.SANCTUARY_DASHBOARD_PORT, 10);
271
+ }
272
+ if (process.env.SANCTUARY_DASHBOARD_HOST) {
273
+ config.dashboard.host = process.env.SANCTUARY_DASHBOARD_HOST;
274
+ }
275
+ if (process.env.SANCTUARY_DASHBOARD_AUTH_TOKEN) {
276
+ config.dashboard.auth_token = process.env.SANCTUARY_DASHBOARD_AUTH_TOKEN;
277
+ }
278
+ if (process.env.SANCTUARY_DASHBOARD_TLS_CERT && process.env.SANCTUARY_DASHBOARD_TLS_KEY) {
279
+ config.dashboard.tls = {
280
+ cert_path: process.env.SANCTUARY_DASHBOARD_TLS_CERT,
281
+ key_path: process.env.SANCTUARY_DASHBOARD_TLS_KEY
282
+ };
283
+ }
284
+ if (process.env.SANCTUARY_WEBHOOK_ENABLED === "true") {
285
+ config.webhook.enabled = true;
286
+ }
287
+ if (process.env.SANCTUARY_WEBHOOK_URL) {
288
+ config.webhook.url = process.env.SANCTUARY_WEBHOOK_URL;
289
+ }
290
+ if (process.env.SANCTUARY_WEBHOOK_SECRET) {
291
+ config.webhook.secret = process.env.SANCTUARY_WEBHOOK_SECRET;
292
+ }
293
+ if (process.env.SANCTUARY_WEBHOOK_CALLBACK_PORT) {
294
+ config.webhook.callback_port = parseInt(process.env.SANCTUARY_WEBHOOK_CALLBACK_PORT, 10);
295
+ }
296
+ if (process.env.SANCTUARY_WEBHOOK_CALLBACK_HOST) {
297
+ config.webhook.callback_host = process.env.SANCTUARY_WEBHOOK_CALLBACK_HOST;
298
+ }
251
299
  const path$1 = configPath ?? path.join(config.storage_path, "sanctuary.json");
252
300
  try {
253
301
  const raw = await promises.readFile(path$1, "utf-8");
@@ -1013,7 +1061,7 @@ function createServer(tools, options) {
1013
1061
  const server = new index_js.Server(
1014
1062
  {
1015
1063
  name: "sanctuary-mcp-server",
1016
- version: "0.2.0"
1064
+ version: "0.3.0"
1017
1065
  },
1018
1066
  {
1019
1067
  capabilities: {
@@ -1887,6 +1935,267 @@ var PolicyStore = class {
1887
1935
  );
1888
1936
  }
1889
1937
  };
1938
+ init_encoding();
1939
+ var G = ed25519.RistrettoPoint.BASE;
1940
+ var H_INPUT = concatBytes(
1941
+ sha256.sha256(stringToBytes("sanctuary-pedersen-generator-H-v1-a")),
1942
+ sha256.sha256(stringToBytes("sanctuary-pedersen-generator-H-v1-b"))
1943
+ );
1944
+ var H = ed25519.RistrettoPoint.hashToCurve(H_INPUT);
1945
+ function bigintToBytes(n) {
1946
+ const hex = n.toString(16).padStart(64, "0");
1947
+ const bytes = new Uint8Array(32);
1948
+ for (let i = 0; i < 32; i++) {
1949
+ bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
1950
+ }
1951
+ return bytes;
1952
+ }
1953
+ function bytesToBigint(bytes) {
1954
+ let hex = "";
1955
+ for (const b of bytes) {
1956
+ hex += b.toString(16).padStart(2, "0");
1957
+ }
1958
+ return BigInt("0x" + hex);
1959
+ }
1960
+ var ORDER = BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989");
1961
+ function mod(n) {
1962
+ return (n % ORDER + ORDER) % ORDER;
1963
+ }
1964
+ function safeMultiply(point, scalar) {
1965
+ const s = mod(scalar);
1966
+ if (s === 0n) return ed25519.RistrettoPoint.ZERO;
1967
+ return point.multiply(s);
1968
+ }
1969
+ function randomScalar() {
1970
+ const bytes = randomBytes(64);
1971
+ return mod(bytesToBigint(bytes));
1972
+ }
1973
+ function fiatShamirChallenge(domain, ...points) {
1974
+ const domainBytes = stringToBytes(domain);
1975
+ const combined = concatBytes(domainBytes, ...points);
1976
+ const hash2 = sha256.sha256(combined);
1977
+ return mod(bytesToBigint(hash2));
1978
+ }
1979
+ function createPedersenCommitment(value) {
1980
+ const v = mod(BigInt(value));
1981
+ const b = randomScalar();
1982
+ const C = safeMultiply(G, v).add(safeMultiply(H, b));
1983
+ return {
1984
+ commitment: toBase64url(C.toRawBytes()),
1985
+ blinding_factor: toBase64url(bigintToBytes(b)),
1986
+ committed_at: (/* @__PURE__ */ new Date()).toISOString()
1987
+ };
1988
+ }
1989
+ function verifyPedersenCommitment(commitment, value, blindingFactor) {
1990
+ try {
1991
+ const C = ed25519.RistrettoPoint.fromHex(fromBase64url(commitment));
1992
+ const v = mod(BigInt(value));
1993
+ const b = bytesToBigint(fromBase64url(blindingFactor));
1994
+ const expected = safeMultiply(G, v).add(safeMultiply(H, b));
1995
+ return C.equals(expected);
1996
+ } catch {
1997
+ return false;
1998
+ }
1999
+ }
2000
+ function createProofOfKnowledge(value, blindingFactor, commitment) {
2001
+ const v = mod(BigInt(value));
2002
+ const b = bytesToBigint(fromBase64url(blindingFactor));
2003
+ const r_v = randomScalar();
2004
+ const r_b = randomScalar();
2005
+ const R = safeMultiply(G, r_v).add(safeMultiply(H, r_b));
2006
+ const C_bytes = fromBase64url(commitment);
2007
+ const R_bytes = R.toRawBytes();
2008
+ const e = fiatShamirChallenge("sanctuary-zk-pok-v1", C_bytes, R_bytes);
2009
+ const s_v = mod(r_v + e * v);
2010
+ const s_b = mod(r_b + e * b);
2011
+ return {
2012
+ type: "schnorr-pedersen-ristretto255",
2013
+ commitment,
2014
+ announcement: toBase64url(R_bytes),
2015
+ response_v: toBase64url(bigintToBytes(s_v)),
2016
+ response_b: toBase64url(bigintToBytes(s_b)),
2017
+ generated_at: (/* @__PURE__ */ new Date()).toISOString()
2018
+ };
2019
+ }
2020
+ function verifyProofOfKnowledge(proof) {
2021
+ try {
2022
+ const C = ed25519.RistrettoPoint.fromHex(fromBase64url(proof.commitment));
2023
+ const R = ed25519.RistrettoPoint.fromHex(fromBase64url(proof.announcement));
2024
+ const s_v = bytesToBigint(fromBase64url(proof.response_v));
2025
+ const s_b = bytesToBigint(fromBase64url(proof.response_b));
2026
+ const e = fiatShamirChallenge(
2027
+ "sanctuary-zk-pok-v1",
2028
+ fromBase64url(proof.commitment),
2029
+ fromBase64url(proof.announcement)
2030
+ );
2031
+ const lhs = safeMultiply(G, s_v).add(safeMultiply(H, s_b));
2032
+ const rhs = R.add(safeMultiply(C, e));
2033
+ return lhs.equals(rhs);
2034
+ } catch {
2035
+ return false;
2036
+ }
2037
+ }
2038
+ function createRangeProof(value, blindingFactor, commitment, min, max) {
2039
+ if (value < min || value > max) {
2040
+ return { error: `Value ${value} is not in range [${min}, ${max}]` };
2041
+ }
2042
+ const range = max - min;
2043
+ const numBits = Math.ceil(Math.log2(range + 1));
2044
+ const shifted = value - min;
2045
+ const b = bytesToBigint(fromBase64url(blindingFactor));
2046
+ const bits = [];
2047
+ for (let i = 0; i < numBits; i++) {
2048
+ bits.push(shifted >> i & 1);
2049
+ }
2050
+ const bitBlindings = [];
2051
+ const bitCommitments = [];
2052
+ const bitProofs = [];
2053
+ for (let i = 0; i < numBits; i++) {
2054
+ const bit_b = randomScalar();
2055
+ bitBlindings.push(bit_b);
2056
+ const C_i = safeMultiply(G, mod(BigInt(bits[i]))).add(safeMultiply(H, bit_b));
2057
+ bitCommitments.push(toBase64url(C_i.toRawBytes()));
2058
+ const bitProof = createBitProof(bits[i], bit_b, C_i);
2059
+ bitProofs.push(bitProof);
2060
+ }
2061
+ const sumBlinding = bitBlindings.reduce(
2062
+ (acc, bi, i) => mod(acc + mod(BigInt(1 << i)) * bi),
2063
+ 0n
2064
+ );
2065
+ const blindingDiff = mod(b - sumBlinding);
2066
+ const r_sum = randomScalar();
2067
+ const R_sum = safeMultiply(H, r_sum);
2068
+ const e_sum = fiatShamirChallenge(
2069
+ "sanctuary-zk-range-sum-v1",
2070
+ fromBase64url(commitment),
2071
+ R_sum.toRawBytes()
2072
+ );
2073
+ const s_sum = mod(r_sum + e_sum * blindingDiff);
2074
+ return {
2075
+ type: "range-pedersen-ristretto255",
2076
+ commitment,
2077
+ min,
2078
+ max,
2079
+ bit_commitments: bitCommitments,
2080
+ bit_proofs: bitProofs,
2081
+ sum_proof: {
2082
+ announcement: toBase64url(R_sum.toRawBytes()),
2083
+ response: toBase64url(bigintToBytes(s_sum))
2084
+ },
2085
+ generated_at: (/* @__PURE__ */ new Date()).toISOString()
2086
+ };
2087
+ }
2088
+ function verifyRangeProof(proof) {
2089
+ try {
2090
+ const C = ed25519.RistrettoPoint.fromHex(fromBase64url(proof.commitment));
2091
+ const range = proof.max - proof.min;
2092
+ const numBits = Math.ceil(Math.log2(range + 1));
2093
+ if (proof.bit_commitments.length !== numBits) return false;
2094
+ if (proof.bit_proofs.length !== numBits) return false;
2095
+ for (let i = 0; i < numBits; i++) {
2096
+ const C_i = ed25519.RistrettoPoint.fromHex(fromBase64url(proof.bit_commitments[i]));
2097
+ if (!verifyBitProof(proof.bit_proofs[i], C_i)) {
2098
+ return false;
2099
+ }
2100
+ }
2101
+ let reconstructed = ed25519.RistrettoPoint.ZERO;
2102
+ for (let i = 0; i < numBits; i++) {
2103
+ const C_i = ed25519.RistrettoPoint.fromHex(fromBase64url(proof.bit_commitments[i]));
2104
+ const weight = mod(BigInt(1 << i));
2105
+ reconstructed = reconstructed.add(safeMultiply(C_i, weight));
2106
+ }
2107
+ const diff = C.subtract(safeMultiply(G, mod(BigInt(proof.min)))).subtract(reconstructed);
2108
+ const R_sum = ed25519.RistrettoPoint.fromHex(fromBase64url(proof.sum_proof.announcement));
2109
+ const s_sum = bytesToBigint(fromBase64url(proof.sum_proof.response));
2110
+ const e_sum = fiatShamirChallenge(
2111
+ "sanctuary-zk-range-sum-v1",
2112
+ fromBase64url(proof.commitment),
2113
+ fromBase64url(proof.sum_proof.announcement)
2114
+ );
2115
+ const lhs = safeMultiply(H, s_sum);
2116
+ const rhs = R_sum.add(safeMultiply(diff, e_sum));
2117
+ return lhs.equals(rhs);
2118
+ } catch {
2119
+ return false;
2120
+ }
2121
+ }
2122
+ function createBitProof(bit, blinding, commitment) {
2123
+ const C_bytes = commitment.toRawBytes();
2124
+ if (bit === 0) {
2125
+ const C_minus_G = commitment.subtract(G);
2126
+ const e_1 = randomScalar();
2127
+ const s_1 = randomScalar();
2128
+ const R_1 = safeMultiply(H, s_1).subtract(safeMultiply(C_minus_G, e_1));
2129
+ const r_0 = randomScalar();
2130
+ const R_0 = safeMultiply(H, r_0);
2131
+ const e = fiatShamirChallenge(
2132
+ "sanctuary-zk-bit-v1",
2133
+ C_bytes,
2134
+ R_0.toRawBytes(),
2135
+ R_1.toRawBytes()
2136
+ );
2137
+ const e_0 = mod(e - e_1);
2138
+ const s_0 = mod(r_0 + e_0 * blinding);
2139
+ return {
2140
+ announcement_0: toBase64url(R_0.toRawBytes()),
2141
+ announcement_1: toBase64url(R_1.toRawBytes()),
2142
+ challenge_0: toBase64url(bigintToBytes(e_0)),
2143
+ challenge_1: toBase64url(bigintToBytes(e_1)),
2144
+ response_0: toBase64url(bigintToBytes(s_0)),
2145
+ response_1: toBase64url(bigintToBytes(s_1))
2146
+ };
2147
+ } else {
2148
+ const e_0 = randomScalar();
2149
+ const s_0 = randomScalar();
2150
+ const R_0 = safeMultiply(H, s_0).subtract(safeMultiply(commitment, e_0));
2151
+ const r_1 = randomScalar();
2152
+ const R_1 = safeMultiply(H, r_1);
2153
+ const e = fiatShamirChallenge(
2154
+ "sanctuary-zk-bit-v1",
2155
+ C_bytes,
2156
+ R_0.toRawBytes(),
2157
+ R_1.toRawBytes()
2158
+ );
2159
+ const e_1 = mod(e - e_0);
2160
+ const s_1 = mod(r_1 + e_1 * blinding);
2161
+ return {
2162
+ announcement_0: toBase64url(R_0.toRawBytes()),
2163
+ announcement_1: toBase64url(R_1.toRawBytes()),
2164
+ challenge_0: toBase64url(bigintToBytes(e_0)),
2165
+ challenge_1: toBase64url(bigintToBytes(e_1)),
2166
+ response_0: toBase64url(bigintToBytes(s_0)),
2167
+ response_1: toBase64url(bigintToBytes(s_1))
2168
+ };
2169
+ }
2170
+ }
2171
+ function verifyBitProof(proof, commitment) {
2172
+ try {
2173
+ const C_bytes = commitment.toRawBytes();
2174
+ const R_0 = ed25519.RistrettoPoint.fromHex(fromBase64url(proof.announcement_0));
2175
+ const R_1 = ed25519.RistrettoPoint.fromHex(fromBase64url(proof.announcement_1));
2176
+ const e_0 = bytesToBigint(fromBase64url(proof.challenge_0));
2177
+ const e_1 = bytesToBigint(fromBase64url(proof.challenge_1));
2178
+ const s_0 = bytesToBigint(fromBase64url(proof.response_0));
2179
+ const s_1 = bytesToBigint(fromBase64url(proof.response_1));
2180
+ const e = fiatShamirChallenge(
2181
+ "sanctuary-zk-bit-v1",
2182
+ C_bytes,
2183
+ R_0.toRawBytes(),
2184
+ R_1.toRawBytes()
2185
+ );
2186
+ if (mod(e_0 + e_1) !== e) return false;
2187
+ const lhs_0 = safeMultiply(H, s_0);
2188
+ const rhs_0 = R_0.add(safeMultiply(commitment, e_0));
2189
+ if (!lhs_0.equals(rhs_0)) return false;
2190
+ const C_minus_G = commitment.subtract(G);
2191
+ const lhs_1 = safeMultiply(H, s_1);
2192
+ const rhs_1 = R_1.add(safeMultiply(C_minus_G, e_1));
2193
+ if (!lhs_1.equals(rhs_1)) return false;
2194
+ return true;
2195
+ } catch {
2196
+ return false;
2197
+ }
2198
+ }
1890
2199
 
1891
2200
  // src/l3-disclosure/tools.ts
1892
2201
  function createL3Tools(storage, masterKey, auditLog) {
@@ -2116,6 +2425,187 @@ function createL3Tools(storage, masterKey, auditLog) {
2116
2425
  overall_recommendation: withholding > 0 ? `Withholding ${withholding} of ${requestedFields.length} requested fields per policy "${policy.policy_name}"` : `All ${requestedFields.length} fields may be disclosed per policy "${policy.policy_name}"`
2117
2426
  });
2118
2427
  }
2428
+ },
2429
+ // ─── ZK Proof Tools ───────────────────────────────────────────────────
2430
+ {
2431
+ name: "sanctuary/zk_commit",
2432
+ description: "Create a Pedersen commitment to a numeric value on Ristretto255. Unlike SHA-256 commitments, Pedersen commitments support zero-knowledge proofs: you can prove properties about the committed value without revealing it.",
2433
+ inputSchema: {
2434
+ type: "object",
2435
+ properties: {
2436
+ value: {
2437
+ type: "number",
2438
+ description: "The integer value to commit to"
2439
+ }
2440
+ },
2441
+ required: ["value"]
2442
+ },
2443
+ handler: async (args) => {
2444
+ const value = args.value;
2445
+ if (!Number.isInteger(value)) {
2446
+ return toolResult({ error: "Value must be an integer." });
2447
+ }
2448
+ const commitment = createPedersenCommitment(value);
2449
+ auditLog.append("l3", "zk_commit", "system", {
2450
+ commitment_hash: commitment.commitment.slice(0, 16) + "..."
2451
+ });
2452
+ return toolResult({
2453
+ commitment: commitment.commitment,
2454
+ blinding_factor: commitment.blinding_factor,
2455
+ committed_at: commitment.committed_at,
2456
+ proof_system: "pedersen-ristretto255",
2457
+ note: "Store the blinding_factor securely. Use zk_prove to create proofs about this commitment."
2458
+ });
2459
+ }
2460
+ },
2461
+ {
2462
+ name: "sanctuary/zk_prove",
2463
+ description: "Create a zero-knowledge proof of knowledge for a Pedersen commitment. Proves you know the value and blinding factor without revealing either. Uses a Schnorr sigma protocol with Fiat-Shamir transform.",
2464
+ inputSchema: {
2465
+ type: "object",
2466
+ properties: {
2467
+ value: {
2468
+ type: "number",
2469
+ description: "The committed value (integer)"
2470
+ },
2471
+ blinding_factor: {
2472
+ type: "string",
2473
+ description: "The blinding factor from zk_commit (base64url)"
2474
+ },
2475
+ commitment: {
2476
+ type: "string",
2477
+ description: "The Pedersen commitment (base64url)"
2478
+ }
2479
+ },
2480
+ required: ["value", "blinding_factor", "commitment"]
2481
+ },
2482
+ handler: async (args) => {
2483
+ const value = args.value;
2484
+ const blindingFactor = args.blinding_factor;
2485
+ const commitment = args.commitment;
2486
+ if (!verifyPedersenCommitment(commitment, value, blindingFactor)) {
2487
+ return toolResult({
2488
+ error: "The provided value and blinding factor do not match the commitment."
2489
+ });
2490
+ }
2491
+ const proof = createProofOfKnowledge(value, blindingFactor, commitment);
2492
+ auditLog.append("l3", "zk_prove", "system", {
2493
+ proof_type: proof.type,
2494
+ commitment: commitment.slice(0, 16) + "..."
2495
+ });
2496
+ return toolResult({
2497
+ proof,
2498
+ note: "This proof demonstrates knowledge of the commitment opening without revealing the value."
2499
+ });
2500
+ }
2501
+ },
2502
+ {
2503
+ name: "sanctuary/zk_verify",
2504
+ description: "Verify a zero-knowledge proof of knowledge for a Pedersen commitment. Checks that the prover knows the commitment's opening without learning anything.",
2505
+ inputSchema: {
2506
+ type: "object",
2507
+ properties: {
2508
+ proof: {
2509
+ type: "object",
2510
+ description: "The ZK proof object from zk_prove"
2511
+ }
2512
+ },
2513
+ required: ["proof"]
2514
+ },
2515
+ handler: async (args) => {
2516
+ const proof = args.proof;
2517
+ const valid = verifyProofOfKnowledge(proof);
2518
+ auditLog.append("l3", "zk_verify", "system", {
2519
+ proof_type: proof.type,
2520
+ valid
2521
+ });
2522
+ return toolResult({
2523
+ valid,
2524
+ proof_type: proof.type,
2525
+ commitment: proof.commitment,
2526
+ verified_at: (/* @__PURE__ */ new Date()).toISOString()
2527
+ });
2528
+ }
2529
+ },
2530
+ {
2531
+ name: "sanctuary/zk_range_prove",
2532
+ description: "Create a zero-knowledge range proof: prove that a committed value is within [min, max] without revealing the exact value. Uses bit-decomposition with OR-proofs on Ristretto255.",
2533
+ inputSchema: {
2534
+ type: "object",
2535
+ properties: {
2536
+ value: {
2537
+ type: "number",
2538
+ description: "The committed value (integer)"
2539
+ },
2540
+ blinding_factor: {
2541
+ type: "string",
2542
+ description: "The blinding factor from zk_commit (base64url)"
2543
+ },
2544
+ commitment: {
2545
+ type: "string",
2546
+ description: "The Pedersen commitment (base64url)"
2547
+ },
2548
+ min: {
2549
+ type: "number",
2550
+ description: "Minimum of the range (inclusive)"
2551
+ },
2552
+ max: {
2553
+ type: "number",
2554
+ description: "Maximum of the range (inclusive)"
2555
+ }
2556
+ },
2557
+ required: ["value", "blinding_factor", "commitment", "min", "max"]
2558
+ },
2559
+ handler: async (args) => {
2560
+ const value = args.value;
2561
+ const blindingFactor = args.blinding_factor;
2562
+ const commitment = args.commitment;
2563
+ const min = args.min;
2564
+ const max = args.max;
2565
+ const proof = createRangeProof(value, blindingFactor, commitment, min, max);
2566
+ if ("error" in proof) {
2567
+ return toolResult({ error: proof.error });
2568
+ }
2569
+ auditLog.append("l3", "zk_range_prove", "system", {
2570
+ proof_type: proof.type,
2571
+ range: `[${min}, ${max}]`,
2572
+ bits: proof.bit_commitments.length
2573
+ });
2574
+ return toolResult({
2575
+ proof,
2576
+ note: `This proof demonstrates the committed value is in [${min}, ${max}] without revealing it.`
2577
+ });
2578
+ }
2579
+ },
2580
+ {
2581
+ name: "sanctuary/zk_range_verify",
2582
+ description: "Verify a zero-knowledge range proof \u2014 confirms a committed value is within the claimed range without learning the value.",
2583
+ inputSchema: {
2584
+ type: "object",
2585
+ properties: {
2586
+ proof: {
2587
+ type: "object",
2588
+ description: "The range proof object from zk_range_prove"
2589
+ }
2590
+ },
2591
+ required: ["proof"]
2592
+ },
2593
+ handler: async (args) => {
2594
+ const proof = args.proof;
2595
+ const valid = verifyRangeProof(proof);
2596
+ auditLog.append("l3", "zk_range_verify", "system", {
2597
+ proof_type: proof.type,
2598
+ valid,
2599
+ range: `[${proof.min}, ${proof.max}]`
2600
+ });
2601
+ return toolResult({
2602
+ valid,
2603
+ proof_type: proof.type,
2604
+ range: { min: proof.min, max: proof.max },
2605
+ commitment: proof.commitment,
2606
+ verified_at: (/* @__PURE__ */ new Date()).toISOString()
2607
+ });
2608
+ }
2119
2609
  }
2120
2610
  ];
2121
2611
  return { tools, commitmentStore, policyStore };
@@ -2164,7 +2654,7 @@ var ReputationStore = class {
2164
2654
  /**
2165
2655
  * Record an interaction outcome as a signed attestation.
2166
2656
  */
2167
- async record(interactionId, counterpartyDid, outcome, context, identity, identityEncryptionKey, counterpartyAttestation) {
2657
+ async record(interactionId, counterpartyDid, outcome, context, identity, identityEncryptionKey, counterpartyAttestation, sovereigntyTier) {
2168
2658
  const attestationId = `att-${Date.now()}-${toBase64url(randomBytes(8))}`;
2169
2659
  const now = (/* @__PURE__ */ new Date()).toISOString();
2170
2660
  const attestationData = {
@@ -2175,7 +2665,8 @@ var ReputationStore = class {
2175
2665
  outcome_result: outcome.result,
2176
2666
  metrics: outcome.metrics ?? {},
2177
2667
  context,
2178
- timestamp: now
2668
+ timestamp: now,
2669
+ sovereignty_tier: sovereigntyTier
2179
2670
  };
2180
2671
  const dataBytes = stringToBytes(JSON.stringify(attestationData));
2181
2672
  const signature = sign(
@@ -2424,6 +2915,24 @@ var ReputationStore = class {
2424
2915
  );
2425
2916
  return guarantee;
2426
2917
  }
2918
+ // ─── Tier-Aware Access ───────────────────────────────────────────────
2919
+ /**
2920
+ * Load attestations for tier-weighted scoring.
2921
+ * Applies basic context/counterparty filtering, returns full StoredAttestations
2922
+ * so callers can access sovereignty_tier from attestation data.
2923
+ */
2924
+ async loadAllForTierScoring(options) {
2925
+ let all = await this.loadAll();
2926
+ if (options?.context) {
2927
+ all = all.filter((a) => a.attestation.data.context === options.context);
2928
+ }
2929
+ if (options?.counterparty_did) {
2930
+ all = all.filter(
2931
+ (a) => a.attestation.data.counterparty_did === options.counterparty_did
2932
+ );
2933
+ }
2934
+ return all;
2935
+ }
2427
2936
  // ─── Internal ─────────────────────────────────────────────────────────
2428
2937
  async loadAll() {
2429
2938
  const results = [];
@@ -2447,9 +2956,70 @@ var ReputationStore = class {
2447
2956
 
2448
2957
  // src/l4-reputation/tools.ts
2449
2958
  init_encoding();
2450
- function createL4Tools(storage, masterKey, identityManager, auditLog) {
2959
+
2960
+ // src/l4-reputation/tiers.ts
2961
+ var TIER_WEIGHTS = {
2962
+ "verified-sovereign": 1,
2963
+ "verified-degraded": 0.8,
2964
+ "self-attested": 0.5,
2965
+ "unverified": 0.2
2966
+ };
2967
+ function resolveTier(counterpartyId, handshakeResults, hasSanctuaryIdentity) {
2968
+ const handshake = handshakeResults.get(counterpartyId);
2969
+ if (handshake && handshake.verified) {
2970
+ const expiresAt = new Date(handshake.expires_at);
2971
+ if (expiresAt > /* @__PURE__ */ new Date()) {
2972
+ return {
2973
+ sovereignty_tier: handshake.trust_tier,
2974
+ handshake_completed_at: handshake.completed_at,
2975
+ verified_by: handshake.counterparty_id
2976
+ };
2977
+ }
2978
+ }
2979
+ if (hasSanctuaryIdentity) {
2980
+ return { sovereignty_tier: "self-attested" };
2981
+ }
2982
+ return { sovereignty_tier: "unverified" };
2983
+ }
2984
+ function trustTierToSovereigntyTier(trustTier) {
2985
+ switch (trustTier) {
2986
+ case "verified-sovereign":
2987
+ return "verified-sovereign";
2988
+ case "verified-degraded":
2989
+ return "verified-degraded";
2990
+ default:
2991
+ return "unverified";
2992
+ }
2993
+ }
2994
+ function computeWeightedScore(attestations) {
2995
+ if (attestations.length === 0) return null;
2996
+ let weightedSum = 0;
2997
+ let totalWeight = 0;
2998
+ for (const a of attestations) {
2999
+ const weight = TIER_WEIGHTS[a.tier];
3000
+ weightedSum += a.value * weight;
3001
+ totalWeight += weight;
3002
+ }
3003
+ return totalWeight > 0 ? weightedSum / totalWeight : null;
3004
+ }
3005
+ function tierDistribution(tiers) {
3006
+ const dist = {
3007
+ "verified-sovereign": 0,
3008
+ "verified-degraded": 0,
3009
+ "self-attested": 0,
3010
+ "unverified": 0
3011
+ };
3012
+ for (const tier of tiers) {
3013
+ dist[tier]++;
3014
+ }
3015
+ return dist;
3016
+ }
3017
+
3018
+ // src/l4-reputation/tools.ts
3019
+ function createL4Tools(storage, masterKey, identityManager, auditLog, handshakeResults) {
2451
3020
  const reputationStore = new ReputationStore(storage, masterKey);
2452
3021
  const identityEncryptionKey = derivePurposeKey(masterKey, "identity-encryption");
3022
+ const hsResults = handshakeResults ?? /* @__PURE__ */ new Map();
2453
3023
  const tools = [
2454
3024
  // ─── Reputation Recording ─────────────────────────────────────────
2455
3025
  {
@@ -2511,26 +3081,34 @@ function createL4Tools(storage, masterKey, identityManager, auditLog) {
2511
3081
  }
2512
3082
  const outcome = args.outcome;
2513
3083
  const context = args.context ?? "general";
3084
+ const counterpartyDid = args.counterparty_did;
3085
+ const hasSanctuaryIdentity = identityManager.list().some(
3086
+ (id) => identityManager.get(id.identity_id)?.did === counterpartyDid
3087
+ );
3088
+ const tierMeta = resolveTier(counterpartyDid, hsResults, hasSanctuaryIdentity);
2514
3089
  const stored = await reputationStore.record(
2515
3090
  args.interaction_id,
2516
- args.counterparty_did,
3091
+ counterpartyDid,
2517
3092
  outcome,
2518
3093
  context,
2519
3094
  identity,
2520
3095
  identityEncryptionKey,
2521
- args.counterparty_attestation
3096
+ args.counterparty_attestation,
3097
+ tierMeta.sovereignty_tier
2522
3098
  );
2523
3099
  auditLog.append("l4", "reputation_record", identity.identity_id, {
2524
3100
  interaction_id: args.interaction_id,
2525
3101
  outcome_type: outcome.type,
2526
3102
  outcome_result: outcome.result,
2527
- context
3103
+ context,
3104
+ sovereignty_tier: tierMeta.sovereignty_tier
2528
3105
  });
2529
3106
  return toolResult({
2530
3107
  attestation_id: stored.attestation.attestation_id,
2531
3108
  interaction_id: stored.attestation.data.interaction_id,
2532
3109
  self_attestation: stored.attestation.signature,
2533
3110
  counterparty_confirmed: stored.counterparty_confirmed,
3111
+ sovereignty_tier: tierMeta.sovereignty_tier,
2534
3112
  context,
2535
3113
  recorded_at: stored.recorded_at
2536
3114
  });
@@ -2693,6 +3271,62 @@ function createL4Tools(storage, masterKey, identityManager, auditLog) {
2693
3271
  });
2694
3272
  }
2695
3273
  },
3274
+ // ─── Sovereignty-Weighted Query ──────────────────────────────────
3275
+ {
3276
+ name: "sanctuary/reputation_query_weighted",
3277
+ description: "Query reputation with sovereignty-weighted scoring. Attestations from verified-sovereign agents carry full weight (1.0); unverified attestations carry reduced weight (0.2). Returns both the weighted score and tier distribution.",
3278
+ inputSchema: {
3279
+ type: "object",
3280
+ properties: {
3281
+ metric: {
3282
+ type: "string",
3283
+ description: "Which metric to compute the weighted score for"
3284
+ },
3285
+ context: {
3286
+ type: "string",
3287
+ description: "Filter by context/domain"
3288
+ },
3289
+ counterparty_did: {
3290
+ type: "string",
3291
+ description: "Filter by counterparty"
3292
+ }
3293
+ },
3294
+ required: ["metric"]
3295
+ },
3296
+ handler: async (args) => {
3297
+ const summary = await reputationStore.query({
3298
+ context: args.context,
3299
+ counterparty_did: args.counterparty_did
3300
+ });
3301
+ const allAttestations = await reputationStore.loadAllForTierScoring({
3302
+ context: args.context,
3303
+ counterparty_did: args.counterparty_did
3304
+ });
3305
+ const metric = args.metric;
3306
+ const tieredAttestations = allAttestations.filter((a) => a.attestation.data.metrics[metric] !== void 0).map((a) => ({
3307
+ value: a.attestation.data.metrics[metric],
3308
+ tier: a.attestation.data.sovereignty_tier ?? "unverified"
3309
+ }));
3310
+ const weightedScore = computeWeightedScore(tieredAttestations);
3311
+ const tiers = allAttestations.map(
3312
+ (a) => a.attestation.data.sovereignty_tier ?? "unverified"
3313
+ );
3314
+ const dist = tierDistribution(tiers);
3315
+ auditLog.append("l4", "reputation_query_weighted", "system", {
3316
+ metric,
3317
+ attestation_count: tieredAttestations.length,
3318
+ weighted_score: weightedScore
3319
+ });
3320
+ return toolResult({
3321
+ metric,
3322
+ weighted_score: weightedScore,
3323
+ attestation_count: tieredAttestations.length,
3324
+ tier_distribution: dist,
3325
+ tier_weights: TIER_WEIGHTS,
3326
+ unweighted_summary: summary
3327
+ });
3328
+ }
3329
+ },
2696
3330
  // ─── Trust Bootstrap: Escrow ──────────────────────────────────────
2697
3331
  {
2698
3332
  name: "sanctuary/bootstrap_create_escrow",
@@ -2878,7 +3512,22 @@ var DEFAULT_POLICY = {
2878
3512
  "monitor_audit_log",
2879
3513
  "manifest",
2880
3514
  "principal_policy_view",
2881
- "principal_baseline_view"
3515
+ "principal_baseline_view",
3516
+ "shr_generate",
3517
+ "shr_verify",
3518
+ "handshake_initiate",
3519
+ "handshake_respond",
3520
+ "handshake_complete",
3521
+ "handshake_status",
3522
+ "reputation_query_weighted",
3523
+ "federation_peers",
3524
+ "federation_trust_evaluate",
3525
+ "federation_status",
3526
+ "zk_commit",
3527
+ "zk_prove",
3528
+ "zk_verify",
3529
+ "zk_range_prove",
3530
+ "zk_range_verify"
2882
3531
  ],
2883
3532
  approval_channel: DEFAULT_CHANNEL
2884
3533
  };
@@ -3013,6 +3662,21 @@ tier3_always_allow:
3013
3662
  - manifest
3014
3663
  - principal_policy_view
3015
3664
  - principal_baseline_view
3665
+ - shr_generate
3666
+ - shr_verify
3667
+ - handshake_initiate
3668
+ - handshake_respond
3669
+ - handshake_complete
3670
+ - handshake_status
3671
+ - reputation_query_weighted
3672
+ - federation_peers
3673
+ - federation_trust_evaluate
3674
+ - federation_status
3675
+ - zk_commit
3676
+ - zk_prove
3677
+ - zk_verify
3678
+ - zk_range_prove
3679
+ - zk_range_verify
3016
3680
 
3017
3681
  # \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
3018
3682
  # How Sanctuary reaches you when approval is needed.
@@ -3242,20 +3906,1143 @@ var StderrApprovalChannel = class {
3242
3906
  }
3243
3907
  };
3244
3908
 
3245
- // src/principal-policy/gate.ts
3246
- var ApprovalGate = class {
3247
- policy;
3248
- baseline;
3249
- channel;
3250
- auditLog;
3251
- constructor(policy, baseline, channel, auditLog) {
3252
- this.policy = policy;
3253
- this.baseline = baseline;
3254
- this.channel = channel;
3255
- this.auditLog = auditLog;
3909
+ // src/principal-policy/dashboard-html.ts
3910
+ function generateDashboardHTML(options) {
3911
+ return `<!DOCTYPE html>
3912
+ <html lang="en">
3913
+ <head>
3914
+ <meta charset="utf-8">
3915
+ <meta name="viewport" content="width=device-width, initial-scale=1">
3916
+ <title>Sanctuary \u2014 Principal Dashboard</title>
3917
+ <style>
3918
+ :root {
3919
+ --bg: #0f1117;
3920
+ --bg-surface: #1a1d27;
3921
+ --bg-elevated: #242736;
3922
+ --border: #2e3244;
3923
+ --text: #e4e6f0;
3924
+ --text-muted: #8b8fa3;
3925
+ --accent: #6c8aff;
3926
+ --accent-hover: #839dff;
3927
+ --approve: #3ecf8e;
3928
+ --approve-hover: #5dd9a3;
3929
+ --deny: #f87171;
3930
+ --deny-hover: #fca5a5;
3931
+ --warning: #fbbf24;
3932
+ --tier1: #f87171;
3933
+ --tier2: #fbbf24;
3934
+ --tier3: #3ecf8e;
3935
+ --font: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
3936
+ --mono: "SF Mono", "Fira Code", "Cascadia Code", monospace;
3937
+ --radius: 8px;
3256
3938
  }
3257
- /**
3258
- * Evaluate a tool call against the Principal Policy.
3939
+
3940
+ * { box-sizing: border-box; margin: 0; padding: 0; }
3941
+ body {
3942
+ font-family: var(--font);
3943
+ background: var(--bg);
3944
+ color: var(--text);
3945
+ line-height: 1.5;
3946
+ min-height: 100vh;
3947
+ }
3948
+
3949
+ /* Layout */
3950
+ .container { max-width: 960px; margin: 0 auto; padding: 24px 16px; }
3951
+
3952
+ header {
3953
+ display: flex; align-items: center; justify-content: space-between;
3954
+ padding-bottom: 20px; border-bottom: 1px solid var(--border);
3955
+ margin-bottom: 24px;
3956
+ }
3957
+ header h1 { font-size: 20px; font-weight: 600; letter-spacing: -0.3px; }
3958
+ header h1 span { color: var(--accent); }
3959
+ .status-badge {
3960
+ display: inline-flex; align-items: center; gap: 6px;
3961
+ font-size: 12px; color: var(--text-muted);
3962
+ padding: 4px 10px; border-radius: 12px;
3963
+ background: var(--bg-surface); border: 1px solid var(--border);
3964
+ }
3965
+ .status-dot {
3966
+ width: 8px; height: 8px; border-radius: 50%;
3967
+ background: var(--approve); animation: pulse 2s infinite;
3968
+ }
3969
+ .status-dot.disconnected { background: var(--deny); animation: none; }
3970
+ @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }
3971
+
3972
+ /* Tabs */
3973
+ .tabs {
3974
+ display: flex; gap: 2px; margin-bottom: 20px;
3975
+ background: var(--bg-surface); border-radius: var(--radius);
3976
+ padding: 3px; border: 1px solid var(--border);
3977
+ }
3978
+ .tab {
3979
+ flex: 1; padding: 8px 12px; text-align: center;
3980
+ font-size: 13px; font-weight: 500; cursor: pointer;
3981
+ border-radius: 6px; border: none; color: var(--text-muted);
3982
+ background: transparent; transition: all 0.15s;
3983
+ }
3984
+ .tab:hover { color: var(--text); }
3985
+ .tab.active { background: var(--bg-elevated); color: var(--text); }
3986
+ .tab .count {
3987
+ display: inline-flex; align-items: center; justify-content: center;
3988
+ min-width: 18px; height: 18px; padding: 0 5px;
3989
+ font-size: 11px; font-weight: 600; border-radius: 9px;
3990
+ margin-left: 6px;
3991
+ }
3992
+ .tab .count.alert { background: var(--deny); color: white; }
3993
+ .tab .count.muted { background: var(--border); color: var(--text-muted); }
3994
+
3995
+ /* Tab Content */
3996
+ .tab-content { display: none; }
3997
+ .tab-content.active { display: block; }
3998
+
3999
+ /* Pending Requests */
4000
+ .pending-empty {
4001
+ text-align: center; padding: 60px 20px; color: var(--text-muted);
4002
+ }
4003
+ .pending-empty .icon { font-size: 32px; margin-bottom: 12px; }
4004
+ .pending-empty p { font-size: 14px; }
4005
+
4006
+ .request-card {
4007
+ background: var(--bg-surface); border: 1px solid var(--border);
4008
+ border-radius: var(--radius); padding: 16px; margin-bottom: 12px;
4009
+ animation: slideIn 0.2s ease-out;
4010
+ }
4011
+ @keyframes slideIn { from { opacity: 0; transform: translateY(-8px); } to { opacity: 1; transform: translateY(0); } }
4012
+ .request-card.tier1 { border-left: 3px solid var(--tier1); }
4013
+ .request-card.tier2 { border-left: 3px solid var(--tier2); }
4014
+ .request-header {
4015
+ display: flex; align-items: center; justify-content: space-between;
4016
+ margin-bottom: 10px;
4017
+ }
4018
+ .request-op {
4019
+ font-family: var(--mono); font-size: 14px; font-weight: 600;
4020
+ }
4021
+ .tier-badge {
4022
+ font-size: 11px; font-weight: 600; padding: 2px 8px;
4023
+ border-radius: 4px; text-transform: uppercase;
4024
+ }
4025
+ .tier-badge.tier1 { background: rgba(248,113,113,0.15); color: var(--tier1); }
4026
+ .tier-badge.tier2 { background: rgba(251,191,36,0.15); color: var(--tier2); }
4027
+ .request-reason {
4028
+ font-size: 13px; color: var(--text-muted); margin-bottom: 12px;
4029
+ }
4030
+ .request-context {
4031
+ font-family: var(--mono); font-size: 12px; color: var(--text-muted);
4032
+ background: var(--bg); border-radius: 4px; padding: 8px 10px;
4033
+ margin-bottom: 14px; white-space: pre-wrap; word-break: break-all;
4034
+ max-height: 120px; overflow-y: auto;
4035
+ }
4036
+ .request-actions {
4037
+ display: flex; align-items: center; gap: 10px;
4038
+ }
4039
+ .btn {
4040
+ padding: 7px 16px; border-radius: 6px; font-size: 13px;
4041
+ font-weight: 600; border: none; cursor: pointer;
4042
+ transition: all 0.15s;
4043
+ }
4044
+ .btn-approve { background: var(--approve); color: #0f1117; }
4045
+ .btn-approve:hover { background: var(--approve-hover); }
4046
+ .btn-deny { background: var(--deny); color: white; }
4047
+ .btn-deny:hover { background: var(--deny-hover); }
4048
+ .countdown {
4049
+ margin-left: auto; font-size: 12px; color: var(--text-muted);
4050
+ font-family: var(--mono);
4051
+ }
4052
+ .countdown.urgent { color: var(--deny); font-weight: 600; }
4053
+
4054
+ /* Audit Log */
4055
+ .audit-table { width: 100%; border-collapse: collapse; }
4056
+ .audit-table th {
4057
+ text-align: left; font-size: 11px; font-weight: 600;
4058
+ text-transform: uppercase; letter-spacing: 0.5px;
4059
+ color: var(--text-muted); padding: 8px 10px;
4060
+ border-bottom: 1px solid var(--border);
4061
+ }
4062
+ .audit-table td {
4063
+ font-size: 13px; padding: 8px 10px;
4064
+ border-bottom: 1px solid var(--border);
4065
+ }
4066
+ .audit-table tr { transition: background 0.1s; }
4067
+ .audit-table tr:hover { background: var(--bg-elevated); }
4068
+ .audit-table tr.new { animation: highlight 1s ease-out; }
4069
+ @keyframes highlight { from { background: rgba(108,138,255,0.15); } to { background: transparent; } }
4070
+ .audit-time { font-family: var(--mono); font-size: 12px; color: var(--text-muted); }
4071
+ .audit-op { font-family: var(--mono); font-size: 12px; }
4072
+ .audit-layer {
4073
+ font-size: 11px; font-weight: 600; padding: 1px 6px;
4074
+ border-radius: 3px; text-transform: uppercase;
4075
+ }
4076
+ .audit-layer.l1 { background: rgba(108,138,255,0.15); color: var(--accent); }
4077
+ .audit-layer.l2 { background: rgba(251,191,36,0.15); color: var(--tier2); }
4078
+ .audit-layer.l3 { background: rgba(62,207,142,0.15); color: var(--tier3); }
4079
+ .audit-layer.l4 { background: rgba(168,85,247,0.15); color: #a855f7; }
4080
+
4081
+ /* Baseline & Policy */
4082
+ .info-section {
4083
+ background: var(--bg-surface); border: 1px solid var(--border);
4084
+ border-radius: var(--radius); padding: 16px; margin-bottom: 16px;
4085
+ }
4086
+ .info-section h3 {
4087
+ font-size: 13px; font-weight: 600; text-transform: uppercase;
4088
+ letter-spacing: 0.5px; color: var(--text-muted); margin-bottom: 12px;
4089
+ }
4090
+ .info-row {
4091
+ display: flex; justify-content: space-between; align-items: center;
4092
+ padding: 6px 0; font-size: 13px;
4093
+ }
4094
+ .info-label { color: var(--text-muted); }
4095
+ .info-value { font-family: var(--mono); font-size: 12px; }
4096
+ .tag-list { display: flex; flex-wrap: wrap; gap: 4px; }
4097
+ .tag {
4098
+ font-family: var(--mono); font-size: 11px; padding: 2px 8px;
4099
+ background: var(--bg-elevated); border-radius: 4px;
4100
+ color: var(--text-muted); border: 1px solid var(--border);
4101
+ }
4102
+ .policy-op {
4103
+ font-family: var(--mono); font-size: 12px; padding: 3px 0;
4104
+ }
4105
+
4106
+ /* Footer */
4107
+ footer {
4108
+ margin-top: 32px; padding-top: 16px;
4109
+ border-top: 1px solid var(--border);
4110
+ font-size: 12px; color: var(--text-muted);
4111
+ text-align: center;
4112
+ }
4113
+ </style>
4114
+ </head>
4115
+ <body>
4116
+ <div class="container">
4117
+ <header>
4118
+ <h1><span>Sanctuary</span> Principal Dashboard</h1>
4119
+ <div class="status-badge">
4120
+ <div class="status-dot" id="statusDot"></div>
4121
+ <span id="statusText">Connected</span>
4122
+ </div>
4123
+ </header>
4124
+
4125
+ <div class="tabs">
4126
+ <button class="tab active" data-tab="pending">
4127
+ Pending<span class="count muted" id="pendingCount">0</span>
4128
+ </button>
4129
+ <button class="tab" data-tab="audit">
4130
+ Audit Log<span class="count muted" id="auditCount">0</span>
4131
+ </button>
4132
+ <button class="tab" data-tab="baseline">Baseline</button>
4133
+ <button class="tab" data-tab="policy">Policy</button>
4134
+ </div>
4135
+
4136
+ <!-- Pending Approvals -->
4137
+ <div class="tab-content active" id="tab-pending">
4138
+ <div class="pending-empty" id="pendingEmpty">
4139
+ <div class="icon">&#x2714;</div>
4140
+ <p>No pending approval requests.</p>
4141
+ <p style="font-size:12px; margin-top:4px;">Requests will appear here in real time.</p>
4142
+ </div>
4143
+ <div id="pendingList"></div>
4144
+ </div>
4145
+
4146
+ <!-- Audit Log -->
4147
+ <div class="tab-content" id="tab-audit">
4148
+ <table class="audit-table">
4149
+ <thead>
4150
+ <tr><th>Time</th><th>Layer</th><th>Operation</th><th>Identity</th></tr>
4151
+ </thead>
4152
+ <tbody id="auditBody"></tbody>
4153
+ </table>
4154
+ </div>
4155
+
4156
+ <!-- Baseline -->
4157
+ <div class="tab-content" id="tab-baseline">
4158
+ <div class="info-section">
4159
+ <h3>Session Info</h3>
4160
+ <div class="info-row"><span class="info-label">First session</span><span class="info-value" id="bFirstSession">\u2014</span></div>
4161
+ <div class="info-row"><span class="info-label">Started</span><span class="info-value" id="bStarted">\u2014</span></div>
4162
+ </div>
4163
+ <div class="info-section">
4164
+ <h3>Known Namespaces</h3>
4165
+ <div class="tag-list" id="bNamespaces"><span class="tag">\u2014</span></div>
4166
+ </div>
4167
+ <div class="info-section">
4168
+ <h3>Known Counterparties</h3>
4169
+ <div class="tag-list" id="bCounterparties"><span class="tag">\u2014</span></div>
4170
+ </div>
4171
+ <div class="info-section">
4172
+ <h3>Tool Call Counts</h3>
4173
+ <div id="bToolCalls"><span class="info-value">\u2014</span></div>
4174
+ </div>
4175
+ </div>
4176
+
4177
+ <!-- Policy -->
4178
+ <div class="tab-content" id="tab-policy">
4179
+ <div class="info-section">
4180
+ <h3>Tier 1 \u2014 Always Requires Approval</h3>
4181
+ <div id="pTier1"></div>
4182
+ </div>
4183
+ <div class="info-section">
4184
+ <h3>Tier 2 \u2014 Anomaly Detection</h3>
4185
+ <div id="pTier2"></div>
4186
+ </div>
4187
+ <div class="info-section">
4188
+ <h3>Tier 3 \u2014 Always Allowed</h3>
4189
+ <div class="info-row">
4190
+ <span class="info-label">Operations</span>
4191
+ <span class="info-value" id="pTier3Count">\u2014</span>
4192
+ </div>
4193
+ </div>
4194
+ <div class="info-section">
4195
+ <h3>Approval Channel</h3>
4196
+ <div id="pChannel"></div>
4197
+ </div>
4198
+ </div>
4199
+
4200
+ <footer>Sanctuary Framework v${options.serverVersion} \u2014 Principal Dashboard</footer>
4201
+ </div>
4202
+
4203
+ <script>
4204
+ (function() {
4205
+ const TIMEOUT = ${options.timeoutSeconds};
4206
+ const AUTH_TOKEN = ${options.authToken ? `'${options.authToken}'` : "null"};
4207
+ const pending = new Map();
4208
+ let auditCount = 0;
4209
+
4210
+ // Auth helpers
4211
+ function authHeaders() {
4212
+ const h = { 'Content-Type': 'application/json' };
4213
+ if (AUTH_TOKEN) h['Authorization'] = 'Bearer ' + AUTH_TOKEN;
4214
+ return h;
4215
+ }
4216
+ function authQuery(url) {
4217
+ if (!AUTH_TOKEN) return url;
4218
+ const sep = url.includes('?') ? '&' : '?';
4219
+ return url + sep + 'token=' + AUTH_TOKEN;
4220
+ }
4221
+
4222
+ // Tab switching
4223
+ document.querySelectorAll('.tab').forEach(tab => {
4224
+ tab.addEventListener('click', () => {
4225
+ document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
4226
+ document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
4227
+ tab.classList.add('active');
4228
+ document.getElementById('tab-' + tab.dataset.tab).classList.add('active');
4229
+ });
4230
+ });
4231
+
4232
+ // SSE Connection
4233
+ let evtSource;
4234
+ function connect() {
4235
+ evtSource = new EventSource(authQuery('/events'));
4236
+ evtSource.onopen = () => {
4237
+ document.getElementById('statusDot').classList.remove('disconnected');
4238
+ document.getElementById('statusText').textContent = 'Connected';
4239
+ };
4240
+ evtSource.onerror = () => {
4241
+ document.getElementById('statusDot').classList.add('disconnected');
4242
+ document.getElementById('statusText').textContent = 'Reconnecting...';
4243
+ };
4244
+ evtSource.addEventListener('pending-request', (e) => {
4245
+ const data = JSON.parse(e.data);
4246
+ addPendingRequest(data);
4247
+ });
4248
+ evtSource.addEventListener('request-resolved', (e) => {
4249
+ const data = JSON.parse(e.data);
4250
+ removePendingRequest(data.request_id);
4251
+ });
4252
+ evtSource.addEventListener('audit-entry', (e) => {
4253
+ const data = JSON.parse(e.data);
4254
+ addAuditEntry(data);
4255
+ });
4256
+ evtSource.addEventListener('baseline-update', (e) => {
4257
+ const data = JSON.parse(e.data);
4258
+ updateBaseline(data);
4259
+ });
4260
+ evtSource.addEventListener('policy-update', (e) => {
4261
+ const data = JSON.parse(e.data);
4262
+ updatePolicy(data);
4263
+ });
4264
+ evtSource.addEventListener('init', (e) => {
4265
+ const data = JSON.parse(e.data);
4266
+ if (data.baseline) updateBaseline(data.baseline);
4267
+ if (data.policy) updatePolicy(data.policy);
4268
+ if (data.pending) data.pending.forEach(addPendingRequest);
4269
+ if (data.audit) data.audit.forEach(addAuditEntry);
4270
+ });
4271
+ }
4272
+
4273
+ // Pending requests
4274
+ function addPendingRequest(req) {
4275
+ pending.set(req.request_id, { ...req, remaining: TIMEOUT });
4276
+ renderPending();
4277
+ updatePendingCount();
4278
+ flashTab('pending');
4279
+ }
4280
+
4281
+ function removePendingRequest(id) {
4282
+ pending.delete(id);
4283
+ renderPending();
4284
+ updatePendingCount();
4285
+ }
4286
+
4287
+ function renderPending() {
4288
+ const list = document.getElementById('pendingList');
4289
+ const empty = document.getElementById('pendingEmpty');
4290
+ if (pending.size === 0) {
4291
+ list.innerHTML = '';
4292
+ empty.style.display = 'block';
4293
+ return;
4294
+ }
4295
+ empty.style.display = 'none';
4296
+ list.innerHTML = '';
4297
+ for (const [id, req] of pending) {
4298
+ const card = document.createElement('div');
4299
+ card.className = 'request-card tier' + req.tier;
4300
+ card.id = 'req-' + id;
4301
+ const ctx = typeof req.context === 'string' ? req.context : JSON.stringify(req.context, null, 2);
4302
+ card.innerHTML =
4303
+ '<div class="request-header">' +
4304
+ '<span class="request-op">' + esc(req.operation) + '</span>' +
4305
+ '<span class="tier-badge tier' + req.tier + '">Tier ' + req.tier + '</span>' +
4306
+ '</div>' +
4307
+ '<div class="request-reason">' + esc(req.reason) + '</div>' +
4308
+ '<div class="request-context">' + esc(ctx) + '</div>' +
4309
+ '<div class="request-actions">' +
4310
+ '<button class="btn btn-approve" onclick="handleApprove(\\'' + id + '\\')">Approve</button>' +
4311
+ '<button class="btn btn-deny" onclick="handleDeny(\\'' + id + '\\')">Deny</button>' +
4312
+ '<span class="countdown" id="cd-' + id + '">' + req.remaining + 's</span>' +
4313
+ '</div>';
4314
+ list.appendChild(card);
4315
+ }
4316
+ }
4317
+
4318
+ function updatePendingCount() {
4319
+ const el = document.getElementById('pendingCount');
4320
+ el.textContent = pending.size;
4321
+ el.className = pending.size > 0 ? 'count alert' : 'count muted';
4322
+ }
4323
+
4324
+ function flashTab(name) {
4325
+ const tab = document.querySelector('[data-tab="' + name + '"]');
4326
+ if (!tab.classList.contains('active')) {
4327
+ tab.style.background = 'rgba(248,113,113,0.15)';
4328
+ setTimeout(() => { tab.style.background = ''; }, 1500);
4329
+ }
4330
+ }
4331
+
4332
+ // Countdown timer
4333
+ setInterval(() => {
4334
+ for (const [id, req] of pending) {
4335
+ req.remaining = Math.max(0, req.remaining - 1);
4336
+ const el = document.getElementById('cd-' + id);
4337
+ if (el) {
4338
+ el.textContent = req.remaining + 's';
4339
+ el.className = req.remaining <= 30 ? 'countdown urgent' : 'countdown';
4340
+ }
4341
+ }
4342
+ }, 1000);
4343
+
4344
+ // Approve / Deny handlers (global scope)
4345
+ window.handleApprove = function(id) {
4346
+ fetch('/api/approve/' + id, { method: 'POST', headers: authHeaders() }).then(() => {
4347
+ removePendingRequest(id);
4348
+ });
4349
+ };
4350
+ window.handleDeny = function(id) {
4351
+ fetch('/api/deny/' + id, { method: 'POST', headers: authHeaders() }).then(() => {
4352
+ removePendingRequest(id);
4353
+ });
4354
+ };
4355
+
4356
+ // Audit log
4357
+ function addAuditEntry(entry) {
4358
+ auditCount++;
4359
+ document.getElementById('auditCount').textContent = auditCount;
4360
+ const tbody = document.getElementById('auditBody');
4361
+ const tr = document.createElement('tr');
4362
+ tr.className = 'new';
4363
+ const time = entry.timestamp ? new Date(entry.timestamp).toLocaleTimeString() : '\u2014';
4364
+ const layer = entry.layer || '\u2014';
4365
+ tr.innerHTML =
4366
+ '<td class="audit-time">' + esc(time) + '</td>' +
4367
+ '<td><span class="audit-layer ' + layer + '">' + esc(layer) + '</span></td>' +
4368
+ '<td class="audit-op">' + esc(entry.operation || '\u2014') + '</td>' +
4369
+ '<td style="font-size:12px;color:var(--text-muted)">' + esc(entry.identity_id || '\u2014') + '</td>';
4370
+ tbody.insertBefore(tr, tbody.firstChild);
4371
+ // Keep last 100 entries
4372
+ while (tbody.children.length > 100) tbody.removeChild(tbody.lastChild);
4373
+ }
4374
+
4375
+ // Baseline
4376
+ function updateBaseline(b) {
4377
+ if (!b) return;
4378
+ document.getElementById('bFirstSession').textContent = b.is_first_session ? 'Yes' : 'No';
4379
+ document.getElementById('bStarted').textContent = b.started_at ? new Date(b.started_at).toLocaleString() : '\u2014';
4380
+ const ns = document.getElementById('bNamespaces');
4381
+ ns.innerHTML = (b.known_namespaces || []).length > 0
4382
+ ? (b.known_namespaces || []).map(n => '<span class="tag">' + esc(n) + '</span>').join('')
4383
+ : '<span class="tag">none</span>';
4384
+ const cp = document.getElementById('bCounterparties');
4385
+ cp.innerHTML = (b.known_counterparties || []).length > 0
4386
+ ? (b.known_counterparties || []).map(c => '<span class="tag">' + esc(c.slice(0,16)) + '...</span>').join('')
4387
+ : '<span class="tag">none</span>';
4388
+ const tc = document.getElementById('bToolCalls');
4389
+ const counts = b.tool_call_counts || {};
4390
+ const entries = Object.entries(counts).sort((a,b) => b[1] - a[1]);
4391
+ tc.innerHTML = entries.length > 0
4392
+ ? entries.map(([k,v]) => '<div class="info-row"><span class="info-label">' + esc(k) + '</span><span class="info-value">' + v + '</span></div>').join('')
4393
+ : '<span class="info-value">no calls yet</span>';
4394
+ }
4395
+
4396
+ // Policy
4397
+ function updatePolicy(p) {
4398
+ if (!p) return;
4399
+ const t1 = document.getElementById('pTier1');
4400
+ t1.innerHTML = (p.tier1_always_approve || []).map(op =>
4401
+ '<div class="policy-op">' + esc(op) + '</div>'
4402
+ ).join('');
4403
+ const t2 = document.getElementById('pTier2');
4404
+ const cfg = p.tier2_anomaly || {};
4405
+ t2.innerHTML = Object.entries(cfg).map(([k,v]) =>
4406
+ '<div class="info-row"><span class="info-label">' + esc(k) + '</span><span class="info-value">' + esc(String(v)) + '</span></div>'
4407
+ ).join('');
4408
+ document.getElementById('pTier3Count').textContent = (p.tier3_always_allow || []).length + ' operations';
4409
+ const ch = document.getElementById('pChannel');
4410
+ const chan = p.approval_channel || {};
4411
+ ch.innerHTML = Object.entries(chan).filter(([k]) => k !== 'webhook_secret').map(([k,v]) =>
4412
+ '<div class="info-row"><span class="info-label">' + esc(k) + '</span><span class="info-value">' + esc(String(v)) + '</span></div>'
4413
+ ).join('');
4414
+ }
4415
+
4416
+ function esc(s) {
4417
+ if (!s) return '';
4418
+ const d = document.createElement('div');
4419
+ d.textContent = String(s);
4420
+ return d.innerHTML;
4421
+ }
4422
+
4423
+ // Init
4424
+ connect();
4425
+ fetch('/api/status', { headers: authHeaders() }).then(r => r.json()).then(data => {
4426
+ if (data.baseline) updateBaseline(data.baseline);
4427
+ if (data.policy) updatePolicy(data.policy);
4428
+ }).catch(() => {});
4429
+ })();
4430
+ </script>
4431
+ </body>
4432
+ </html>`;
4433
+ }
4434
+
4435
+ // src/principal-policy/dashboard.ts
4436
+ var DashboardApprovalChannel = class {
4437
+ config;
4438
+ pending = /* @__PURE__ */ new Map();
4439
+ sseClients = /* @__PURE__ */ new Set();
4440
+ httpServer = null;
4441
+ policy = null;
4442
+ baseline = null;
4443
+ auditLog = null;
4444
+ dashboardHTML;
4445
+ authToken;
4446
+ useTLS;
4447
+ constructor(config) {
4448
+ this.config = config;
4449
+ this.authToken = config.auth_token;
4450
+ this.useTLS = !!(config.tls?.cert_path && config.tls?.key_path);
4451
+ this.dashboardHTML = generateDashboardHTML({
4452
+ timeoutSeconds: config.timeout_seconds,
4453
+ serverVersion: "0.3.0",
4454
+ authToken: this.authToken
4455
+ });
4456
+ }
4457
+ /**
4458
+ * Inject dependencies after construction.
4459
+ * Called from index.ts after all components are initialized.
4460
+ */
4461
+ setDependencies(deps) {
4462
+ this.policy = deps.policy;
4463
+ this.baseline = deps.baseline;
4464
+ this.auditLog = deps.auditLog;
4465
+ }
4466
+ /**
4467
+ * Start the HTTP(S) server for the dashboard.
4468
+ */
4469
+ async start() {
4470
+ return new Promise((resolve, reject) => {
4471
+ const handler = (req, res) => this.handleRequest(req, res);
4472
+ if (this.useTLS && this.config.tls) {
4473
+ const tlsOpts = {
4474
+ cert: fs.readFileSync(this.config.tls.cert_path),
4475
+ key: fs.readFileSync(this.config.tls.key_path)
4476
+ };
4477
+ this.httpServer = https.createServer(tlsOpts, handler);
4478
+ } else {
4479
+ this.httpServer = http.createServer(handler);
4480
+ }
4481
+ const protocol = this.useTLS ? "https" : "http";
4482
+ const baseUrl = `${protocol}://${this.config.host}:${this.config.port}`;
4483
+ this.httpServer.listen(this.config.port, this.config.host, () => {
4484
+ if (this.authToken) {
4485
+ process.stderr.write(
4486
+ `
4487
+ Sanctuary Principal Dashboard: ${baseUrl}/?token=${this.authToken}
4488
+ `
4489
+ );
4490
+ process.stderr.write(
4491
+ ` Auth token: ${this.authToken}
4492
+
4493
+ `
4494
+ );
4495
+ } else {
4496
+ process.stderr.write(
4497
+ `
4498
+ Sanctuary Principal Dashboard: ${baseUrl}
4499
+
4500
+ `
4501
+ );
4502
+ }
4503
+ resolve();
4504
+ });
4505
+ this.httpServer.on("error", reject);
4506
+ });
4507
+ }
4508
+ /**
4509
+ * Stop the HTTP server and clean up.
4510
+ */
4511
+ async stop() {
4512
+ for (const [, pending] of this.pending) {
4513
+ clearTimeout(pending.timer);
4514
+ pending.resolve({
4515
+ decision: "deny",
4516
+ decided_at: (/* @__PURE__ */ new Date()).toISOString(),
4517
+ decided_by: "auto"
4518
+ });
4519
+ }
4520
+ this.pending.clear();
4521
+ for (const client of this.sseClients) {
4522
+ client.end();
4523
+ }
4524
+ this.sseClients.clear();
4525
+ if (this.httpServer) {
4526
+ return new Promise((resolve) => {
4527
+ this.httpServer.close(() => resolve());
4528
+ });
4529
+ }
4530
+ }
4531
+ /**
4532
+ * Request approval from the human via the dashboard.
4533
+ * Blocks until the human approves/denies or timeout occurs.
4534
+ */
4535
+ async requestApproval(request) {
4536
+ const id = crypto.randomBytes(8).toString("hex");
4537
+ process.stderr.write(
4538
+ `[Sanctuary] Approval required: ${request.operation} (Tier ${request.tier}) \u2014 open dashboard to respond
4539
+ `
4540
+ );
4541
+ return new Promise((resolve) => {
4542
+ const timer = setTimeout(() => {
4543
+ this.pending.delete(id);
4544
+ const response = {
4545
+ decision: this.config.auto_deny ? "deny" : "approve",
4546
+ decided_at: (/* @__PURE__ */ new Date()).toISOString(),
4547
+ decided_by: "timeout"
4548
+ };
4549
+ this.broadcastSSE("request-resolved", {
4550
+ request_id: id,
4551
+ decision: response.decision,
4552
+ decided_by: "timeout"
4553
+ });
4554
+ resolve(response);
4555
+ }, this.config.timeout_seconds * 1e3);
4556
+ const pending = {
4557
+ id,
4558
+ request,
4559
+ resolve,
4560
+ timer,
4561
+ created_at: (/* @__PURE__ */ new Date()).toISOString()
4562
+ };
4563
+ this.pending.set(id, pending);
4564
+ this.broadcastSSE("pending-request", {
4565
+ request_id: id,
4566
+ operation: request.operation,
4567
+ tier: request.tier,
4568
+ reason: request.reason,
4569
+ context: request.context,
4570
+ timestamp: request.timestamp
4571
+ });
4572
+ });
4573
+ }
4574
+ // ── Authentication ──────────────────────────────────────────────────
4575
+ /**
4576
+ * Verify bearer token authentication.
4577
+ * Checks Authorization header first, falls back to ?token= query param.
4578
+ * Returns true if auth passes, false if blocked (response already sent).
4579
+ */
4580
+ checkAuth(req, url, res) {
4581
+ if (!this.authToken) return true;
4582
+ const authHeader = req.headers.authorization;
4583
+ if (authHeader) {
4584
+ const parts = authHeader.split(" ");
4585
+ if (parts.length === 2 && parts[0] === "Bearer" && parts[1] === this.authToken) {
4586
+ return true;
4587
+ }
4588
+ }
4589
+ const queryToken = url.searchParams.get("token");
4590
+ if (queryToken === this.authToken) {
4591
+ return true;
4592
+ }
4593
+ res.writeHead(401, { "Content-Type": "application/json" });
4594
+ res.end(JSON.stringify({ error: "Unauthorized \u2014 valid bearer token required" }));
4595
+ return false;
4596
+ }
4597
+ // ── HTTP Request Handler ────────────────────────────────────────────
4598
+ handleRequest(req, res) {
4599
+ const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
4600
+ const method = req.method ?? "GET";
4601
+ res.setHeader("Access-Control-Allow-Origin", "*");
4602
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
4603
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
4604
+ if (method === "OPTIONS") {
4605
+ res.writeHead(204);
4606
+ res.end();
4607
+ return;
4608
+ }
4609
+ if (!this.checkAuth(req, url, res)) return;
4610
+ try {
4611
+ if (method === "GET" && url.pathname === "/") {
4612
+ this.serveDashboard(res);
4613
+ } else if (method === "GET" && url.pathname === "/events") {
4614
+ this.handleSSE(req, res);
4615
+ } else if (method === "GET" && url.pathname === "/api/status") {
4616
+ this.handleStatus(res);
4617
+ } else if (method === "GET" && url.pathname === "/api/pending") {
4618
+ this.handlePendingList(res);
4619
+ } else if (method === "GET" && url.pathname === "/api/audit-log") {
4620
+ this.handleAuditLog(url, res);
4621
+ } else if (method === "POST" && url.pathname.startsWith("/api/approve/")) {
4622
+ const id = url.pathname.slice("/api/approve/".length);
4623
+ this.handleDecision(id, "approve", res);
4624
+ } else if (method === "POST" && url.pathname.startsWith("/api/deny/")) {
4625
+ const id = url.pathname.slice("/api/deny/".length);
4626
+ this.handleDecision(id, "deny", res);
4627
+ } else {
4628
+ res.writeHead(404, { "Content-Type": "application/json" });
4629
+ res.end(JSON.stringify({ error: "Not found" }));
4630
+ }
4631
+ } catch (err) {
4632
+ res.writeHead(500, { "Content-Type": "application/json" });
4633
+ res.end(JSON.stringify({ error: "Internal server error" }));
4634
+ }
4635
+ }
4636
+ // ── Route Handlers ──────────────────────────────────────────────────
4637
+ serveDashboard(res) {
4638
+ res.writeHead(200, {
4639
+ "Content-Type": "text/html; charset=utf-8",
4640
+ "Cache-Control": "no-cache"
4641
+ });
4642
+ res.end(this.dashboardHTML);
4643
+ }
4644
+ handleSSE(req, res) {
4645
+ res.writeHead(200, {
4646
+ "Content-Type": "text/event-stream",
4647
+ "Cache-Control": "no-cache",
4648
+ "Connection": "keep-alive"
4649
+ });
4650
+ const initData = {};
4651
+ if (this.baseline) {
4652
+ initData.baseline = this.baseline.getProfile();
4653
+ }
4654
+ if (this.policy) {
4655
+ initData.policy = {
4656
+ tier1_always_approve: this.policy.tier1_always_approve,
4657
+ tier2_anomaly: this.policy.tier2_anomaly,
4658
+ tier3_always_allow: this.policy.tier3_always_allow,
4659
+ approval_channel: {
4660
+ type: this.policy.approval_channel.type,
4661
+ timeout_seconds: this.policy.approval_channel.timeout_seconds,
4662
+ auto_deny: this.policy.approval_channel.auto_deny
4663
+ }
4664
+ };
4665
+ }
4666
+ const pendingList = Array.from(this.pending.values()).map((p) => ({
4667
+ request_id: p.id,
4668
+ operation: p.request.operation,
4669
+ tier: p.request.tier,
4670
+ reason: p.request.reason,
4671
+ context: p.request.context,
4672
+ timestamp: p.request.timestamp
4673
+ }));
4674
+ if (pendingList.length > 0) {
4675
+ initData.pending = pendingList;
4676
+ }
4677
+ res.write(`event: init
4678
+ data: ${JSON.stringify(initData)}
4679
+
4680
+ `);
4681
+ this.sseClients.add(res);
4682
+ req.on("close", () => {
4683
+ this.sseClients.delete(res);
4684
+ });
4685
+ }
4686
+ handleStatus(res) {
4687
+ const status = {
4688
+ pending_count: this.pending.size,
4689
+ connected_clients: this.sseClients.size
4690
+ };
4691
+ if (this.baseline) {
4692
+ status.baseline = this.baseline.getProfile();
4693
+ }
4694
+ if (this.policy) {
4695
+ status.policy = {
4696
+ version: this.policy.version,
4697
+ tier1_always_approve: this.policy.tier1_always_approve,
4698
+ tier2_anomaly: this.policy.tier2_anomaly,
4699
+ tier3_always_allow: this.policy.tier3_always_allow,
4700
+ approval_channel: {
4701
+ type: this.policy.approval_channel.type,
4702
+ timeout_seconds: this.policy.approval_channel.timeout_seconds,
4703
+ auto_deny: this.policy.approval_channel.auto_deny
4704
+ }
4705
+ };
4706
+ }
4707
+ res.writeHead(200, { "Content-Type": "application/json" });
4708
+ res.end(JSON.stringify(status));
4709
+ }
4710
+ handlePendingList(res) {
4711
+ const list = Array.from(this.pending.values()).map((p) => ({
4712
+ id: p.id,
4713
+ operation: p.request.operation,
4714
+ tier: p.request.tier,
4715
+ reason: p.request.reason,
4716
+ context: p.request.context,
4717
+ timestamp: p.request.timestamp,
4718
+ created_at: p.created_at
4719
+ }));
4720
+ res.writeHead(200, { "Content-Type": "application/json" });
4721
+ res.end(JSON.stringify(list));
4722
+ }
4723
+ handleAuditLog(url, res) {
4724
+ const limit = parseInt(url.searchParams.get("limit") ?? "50", 10);
4725
+ if (this.auditLog) {
4726
+ this.auditLog.query({ limit }).then((entries) => {
4727
+ res.writeHead(200, { "Content-Type": "application/json" });
4728
+ res.end(JSON.stringify(entries));
4729
+ }).catch(() => {
4730
+ res.writeHead(200, { "Content-Type": "application/json" });
4731
+ res.end(JSON.stringify([]));
4732
+ });
4733
+ } else {
4734
+ res.writeHead(200, { "Content-Type": "application/json" });
4735
+ res.end(JSON.stringify([]));
4736
+ }
4737
+ }
4738
+ handleDecision(id, decision, res) {
4739
+ const pending = this.pending.get(id);
4740
+ if (!pending) {
4741
+ res.writeHead(404, { "Content-Type": "application/json" });
4742
+ res.end(JSON.stringify({ error: "Request not found or already resolved" }));
4743
+ return;
4744
+ }
4745
+ clearTimeout(pending.timer);
4746
+ this.pending.delete(id);
4747
+ const response = {
4748
+ decision,
4749
+ decided_at: (/* @__PURE__ */ new Date()).toISOString(),
4750
+ decided_by: "human"
4751
+ };
4752
+ this.broadcastSSE("request-resolved", {
4753
+ request_id: id,
4754
+ decision,
4755
+ decided_by: "human"
4756
+ });
4757
+ pending.resolve(response);
4758
+ res.writeHead(200, { "Content-Type": "application/json" });
4759
+ res.end(JSON.stringify({ success: true, decision }));
4760
+ }
4761
+ // ── SSE Broadcasting ────────────────────────────────────────────────
4762
+ broadcastSSE(event, data) {
4763
+ const message = `event: ${event}
4764
+ data: ${JSON.stringify(data)}
4765
+
4766
+ `;
4767
+ for (const client of this.sseClients) {
4768
+ try {
4769
+ client.write(message);
4770
+ } catch {
4771
+ this.sseClients.delete(client);
4772
+ }
4773
+ }
4774
+ }
4775
+ /**
4776
+ * Broadcast an audit entry to connected dashboards.
4777
+ * Called externally when audit events happen.
4778
+ */
4779
+ broadcastAuditEntry(entry) {
4780
+ this.broadcastSSE("audit-entry", entry);
4781
+ }
4782
+ /**
4783
+ * Broadcast a baseline update to connected dashboards.
4784
+ * Called externally after baseline changes.
4785
+ */
4786
+ broadcastBaselineUpdate() {
4787
+ if (this.baseline) {
4788
+ this.broadcastSSE("baseline-update", this.baseline.getProfile());
4789
+ }
4790
+ }
4791
+ /** Get the number of pending requests */
4792
+ get pendingCount() {
4793
+ return this.pending.size;
4794
+ }
4795
+ /** Get the number of connected SSE clients */
4796
+ get clientCount() {
4797
+ return this.sseClients.size;
4798
+ }
4799
+ };
4800
+ function signPayload(body, secret) {
4801
+ return crypto.createHmac("sha256", secret).update(body).digest("hex");
4802
+ }
4803
+ function verifySignature(body, signature, secret) {
4804
+ const expected = signPayload(body, secret);
4805
+ if (expected.length !== signature.length) return false;
4806
+ let mismatch = 0;
4807
+ for (let i = 0; i < expected.length; i++) {
4808
+ mismatch |= expected.charCodeAt(i) ^ signature.charCodeAt(i);
4809
+ }
4810
+ return mismatch === 0;
4811
+ }
4812
+ var WebhookApprovalChannel = class {
4813
+ config;
4814
+ pending = /* @__PURE__ */ new Map();
4815
+ callbackServer = null;
4816
+ constructor(config) {
4817
+ this.config = config;
4818
+ }
4819
+ /**
4820
+ * Start the callback listener server.
4821
+ */
4822
+ async start() {
4823
+ return new Promise((resolve, reject) => {
4824
+ this.callbackServer = http.createServer(
4825
+ (req, res) => this.handleCallback(req, res)
4826
+ );
4827
+ this.callbackServer.listen(
4828
+ this.config.callback_port,
4829
+ this.config.callback_host,
4830
+ () => {
4831
+ process.stderr.write(
4832
+ `
4833
+ Sanctuary Webhook Callback: http://${this.config.callback_host}:${this.config.callback_port}
4834
+ Webhook target: ${this.config.webhook_url}
4835
+
4836
+ `
4837
+ );
4838
+ resolve();
4839
+ }
4840
+ );
4841
+ this.callbackServer.on("error", reject);
4842
+ });
4843
+ }
4844
+ /**
4845
+ * Stop the callback server and clean up pending requests.
4846
+ */
4847
+ async stop() {
4848
+ for (const [, pending] of this.pending) {
4849
+ clearTimeout(pending.timer);
4850
+ pending.resolve({
4851
+ decision: "deny",
4852
+ decided_at: (/* @__PURE__ */ new Date()).toISOString(),
4853
+ decided_by: "auto"
4854
+ });
4855
+ }
4856
+ this.pending.clear();
4857
+ if (this.callbackServer) {
4858
+ return new Promise((resolve) => {
4859
+ this.callbackServer.close(() => resolve());
4860
+ });
4861
+ }
4862
+ }
4863
+ /**
4864
+ * Request approval by POSTing to the webhook and waiting for a callback.
4865
+ */
4866
+ async requestApproval(request) {
4867
+ const id = crypto.randomBytes(8).toString("hex");
4868
+ process.stderr.write(
4869
+ `[Sanctuary] Webhook approval sent: ${request.operation} (Tier ${request.tier}) \u2014 awaiting callback
4870
+ `
4871
+ );
4872
+ return new Promise((resolve) => {
4873
+ const timer = setTimeout(() => {
4874
+ this.pending.delete(id);
4875
+ const response = {
4876
+ decision: this.config.auto_deny ? "deny" : "approve",
4877
+ decided_at: (/* @__PURE__ */ new Date()).toISOString(),
4878
+ decided_by: "timeout"
4879
+ };
4880
+ resolve(response);
4881
+ }, this.config.timeout_seconds * 1e3);
4882
+ const pending = {
4883
+ id,
4884
+ request,
4885
+ resolve,
4886
+ timer,
4887
+ created_at: (/* @__PURE__ */ new Date()).toISOString()
4888
+ };
4889
+ this.pending.set(id, pending);
4890
+ const callbackUrl = `http://${this.config.callback_host}:${this.config.callback_port}/webhook/respond/${id}`;
4891
+ const payload = {
4892
+ request_id: id,
4893
+ operation: request.operation,
4894
+ tier: request.tier,
4895
+ reason: request.reason,
4896
+ context: request.context,
4897
+ timestamp: request.timestamp,
4898
+ callback_url: callbackUrl,
4899
+ timeout_seconds: this.config.timeout_seconds
4900
+ };
4901
+ this.sendWebhook(payload).catch((err) => {
4902
+ process.stderr.write(
4903
+ `[Sanctuary] Webhook delivery failed: ${err instanceof Error ? err.message : String(err)}
4904
+ `
4905
+ );
4906
+ });
4907
+ });
4908
+ }
4909
+ // ── Outbound Webhook ──────────────────────────────────────────────────
4910
+ async sendWebhook(payload) {
4911
+ const body = JSON.stringify(payload);
4912
+ const signature = signPayload(body, this.config.webhook_secret);
4913
+ const response = await fetch(this.config.webhook_url, {
4914
+ method: "POST",
4915
+ headers: {
4916
+ "Content-Type": "application/json",
4917
+ "X-Sanctuary-Signature": signature,
4918
+ "X-Sanctuary-Request-Id": payload.request_id
4919
+ },
4920
+ body
4921
+ });
4922
+ if (!response.ok) {
4923
+ throw new Error(
4924
+ `Webhook returned ${response.status}: ${await response.text().catch(() => "")}`
4925
+ );
4926
+ }
4927
+ }
4928
+ // ── Inbound Callback Handler ──────────────────────────────────────────
4929
+ handleCallback(req, res) {
4930
+ const url = new URL(
4931
+ req.url ?? "/",
4932
+ `http://${req.headers.host ?? "localhost"}`
4933
+ );
4934
+ const method = req.method ?? "GET";
4935
+ res.setHeader("Access-Control-Allow-Origin", "*");
4936
+ res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
4937
+ res.setHeader(
4938
+ "Access-Control-Allow-Headers",
4939
+ "Content-Type, X-Sanctuary-Signature"
4940
+ );
4941
+ if (method === "OPTIONS") {
4942
+ res.writeHead(204);
4943
+ res.end();
4944
+ return;
4945
+ }
4946
+ if (method === "GET" && url.pathname === "/health") {
4947
+ res.writeHead(200, { "Content-Type": "application/json" });
4948
+ res.end(
4949
+ JSON.stringify({
4950
+ status: "ok",
4951
+ pending_count: this.pending.size
4952
+ })
4953
+ );
4954
+ return;
4955
+ }
4956
+ const match = url.pathname.match(/^\/webhook\/respond\/([a-f0-9]+)$/);
4957
+ if (method !== "POST" || !match) {
4958
+ res.writeHead(404, { "Content-Type": "application/json" });
4959
+ res.end(JSON.stringify({ error: "Not found" }));
4960
+ return;
4961
+ }
4962
+ const requestId = match[1];
4963
+ let bodyChunks = [];
4964
+ req.on("data", (chunk) => bodyChunks.push(chunk));
4965
+ req.on("end", () => {
4966
+ const body = Buffer.concat(bodyChunks).toString("utf-8");
4967
+ const signature = req.headers["x-sanctuary-signature"];
4968
+ if (typeof signature !== "string" || !verifySignature(body, signature, this.config.webhook_secret)) {
4969
+ res.writeHead(401, { "Content-Type": "application/json" });
4970
+ res.end(
4971
+ JSON.stringify({ error: "Invalid signature" })
4972
+ );
4973
+ return;
4974
+ }
4975
+ let callbackPayload;
4976
+ try {
4977
+ callbackPayload = JSON.parse(body);
4978
+ } catch {
4979
+ res.writeHead(400, { "Content-Type": "application/json" });
4980
+ res.end(JSON.stringify({ error: "Invalid JSON" }));
4981
+ return;
4982
+ }
4983
+ if (callbackPayload.decision !== "approve" && callbackPayload.decision !== "deny") {
4984
+ res.writeHead(400, { "Content-Type": "application/json" });
4985
+ res.end(
4986
+ JSON.stringify({
4987
+ error: 'Decision must be "approve" or "deny"'
4988
+ })
4989
+ );
4990
+ return;
4991
+ }
4992
+ if (callbackPayload.request_id !== requestId) {
4993
+ res.writeHead(400, { "Content-Type": "application/json" });
4994
+ res.end(
4995
+ JSON.stringify({ error: "Request ID mismatch" })
4996
+ );
4997
+ return;
4998
+ }
4999
+ const pending = this.pending.get(requestId);
5000
+ if (!pending) {
5001
+ res.writeHead(404, { "Content-Type": "application/json" });
5002
+ res.end(
5003
+ JSON.stringify({
5004
+ error: "Request not found or already resolved"
5005
+ })
5006
+ );
5007
+ return;
5008
+ }
5009
+ clearTimeout(pending.timer);
5010
+ this.pending.delete(requestId);
5011
+ const response = {
5012
+ decision: callbackPayload.decision,
5013
+ decided_at: (/* @__PURE__ */ new Date()).toISOString(),
5014
+ decided_by: "human"
5015
+ };
5016
+ pending.resolve(response);
5017
+ res.writeHead(200, { "Content-Type": "application/json" });
5018
+ res.end(
5019
+ JSON.stringify({
5020
+ success: true,
5021
+ decision: callbackPayload.decision
5022
+ })
5023
+ );
5024
+ });
5025
+ }
5026
+ /** Get the number of pending requests */
5027
+ get pendingCount() {
5028
+ return this.pending.size;
5029
+ }
5030
+ };
5031
+
5032
+ // src/principal-policy/gate.ts
5033
+ var ApprovalGate = class {
5034
+ policy;
5035
+ baseline;
5036
+ channel;
5037
+ auditLog;
5038
+ constructor(policy, baseline, channel, auditLog) {
5039
+ this.policy = policy;
5040
+ this.baseline = baseline;
5041
+ this.channel = channel;
5042
+ this.auditLog = auditLog;
5043
+ }
5044
+ /**
5045
+ * Evaluate a tool call against the Principal Policy.
3259
5046
  *
3260
5047
  * @param toolName - Full MCP tool name (e.g., "sanctuary/state_export")
3261
5048
  * @param args - Tool call arguments (for context extraction)
@@ -3914,6 +5701,7 @@ function deriveTrustTier(level) {
3914
5701
  // src/handshake/tools.ts
3915
5702
  function createHandshakeTools(config, identityManager, masterKey, auditLog) {
3916
5703
  const sessions = /* @__PURE__ */ new Map();
5704
+ const handshakeResults = /* @__PURE__ */ new Map();
3917
5705
  const shrOpts = {
3918
5706
  config,
3919
5707
  identityManager,
@@ -4034,6 +5822,7 @@ function createHandshakeTools(config, identityManager, masterKey, auditLog) {
4034
5822
  session.their_shr = response.shr;
4035
5823
  session.their_nonce = response.responder_nonce;
4036
5824
  session.result = result.result;
5825
+ handshakeResults.set(result.result.counterparty_id, result.result);
4037
5826
  auditLog.append("l4", "handshake_complete", session.our_shr.body.instance_id);
4038
5827
  return toolResult({
4039
5828
  completion: result.completion,
@@ -4070,6 +5859,9 @@ function createHandshakeTools(config, identityManager, masterKey, auditLog) {
4070
5859
  const result = verifyCompletion(completion, session);
4071
5860
  session.state = result.verified ? "completed" : "failed";
4072
5861
  session.result = result;
5862
+ if (result.verified) {
5863
+ handshakeResults.set(result.counterparty_id, result);
5864
+ }
4073
5865
  auditLog.append(
4074
5866
  "l4",
4075
5867
  "handshake_verify_completion",
@@ -4089,7 +5881,759 @@ function createHandshakeTools(config, identityManager, masterKey, auditLog) {
4089
5881
  }
4090
5882
  }
4091
5883
  ];
4092
- return { tools };
5884
+ return { tools, handshakeResults };
5885
+ }
5886
+
5887
+ // src/federation/registry.ts
5888
+ var DEFAULT_CAPABILITIES = {
5889
+ reputation_exchange: true,
5890
+ mutual_attestation: true,
5891
+ encrypted_channel: false,
5892
+ attestation_formats: ["sanctuary-interaction-v1"]
5893
+ };
5894
+ var FederationRegistry = class {
5895
+ peers = /* @__PURE__ */ new Map();
5896
+ /**
5897
+ * Register or update a peer from a completed handshake.
5898
+ * This is the ONLY way peers enter the registry.
5899
+ */
5900
+ registerFromHandshake(result, peerDid, capabilities) {
5901
+ const existing = this.peers.get(result.counterparty_id);
5902
+ const now = (/* @__PURE__ */ new Date()).toISOString();
5903
+ const peer = {
5904
+ peer_id: result.counterparty_id,
5905
+ peer_did: peerDid,
5906
+ first_seen: existing?.first_seen ?? now,
5907
+ last_handshake: result.completed_at,
5908
+ trust_tier: trustTierToSovereigntyTier(result.trust_tier),
5909
+ handshake_result: result,
5910
+ capabilities: {
5911
+ ...DEFAULT_CAPABILITIES,
5912
+ ...existing?.capabilities ?? {},
5913
+ ...capabilities ?? {}
5914
+ },
5915
+ active: result.verified && new Date(result.expires_at) > /* @__PURE__ */ new Date()
5916
+ };
5917
+ if (!peer.active) {
5918
+ peer.trust_tier = "self-attested";
5919
+ }
5920
+ this.peers.set(result.counterparty_id, peer);
5921
+ return peer;
5922
+ }
5923
+ /**
5924
+ * Get a peer by instance ID.
5925
+ * Automatically updates active status based on handshake expiry.
5926
+ */
5927
+ getPeer(peerId) {
5928
+ const peer = this.peers.get(peerId);
5929
+ if (!peer) return null;
5930
+ if (peer.active && new Date(peer.handshake_result.expires_at) <= /* @__PURE__ */ new Date()) {
5931
+ peer.active = false;
5932
+ peer.trust_tier = "self-attested";
5933
+ }
5934
+ return peer;
5935
+ }
5936
+ /**
5937
+ * List all known peers, optionally filtered by status.
5938
+ */
5939
+ listPeers(filter) {
5940
+ const peers = Array.from(this.peers.values());
5941
+ for (const peer of peers) {
5942
+ if (peer.active && new Date(peer.handshake_result.expires_at) <= /* @__PURE__ */ new Date()) {
5943
+ peer.active = false;
5944
+ peer.trust_tier = "self-attested";
5945
+ }
5946
+ }
5947
+ if (filter?.active_only) {
5948
+ return peers.filter((p) => p.active);
5949
+ }
5950
+ return peers;
5951
+ }
5952
+ /**
5953
+ * Evaluate trust for a federation peer.
5954
+ *
5955
+ * Trust assessment considers:
5956
+ * - Handshake status (current vs expired)
5957
+ * - Sovereignty tier (verified-sovereign vs degraded vs unverified)
5958
+ * - Reputation data (if available)
5959
+ * - Mutual attestation history
5960
+ */
5961
+ evaluateTrust(peerId, mutualAttestationCount = 0, reputationScore) {
5962
+ const peer = this.getPeer(peerId);
5963
+ const now = (/* @__PURE__ */ new Date()).toISOString();
5964
+ if (!peer) {
5965
+ return {
5966
+ peer_id: peerId,
5967
+ sovereignty_tier: "unverified",
5968
+ handshake_current: false,
5969
+ mutual_attestation_count: 0,
5970
+ trust_level: "none",
5971
+ factors: ["Peer not found in federation registry"],
5972
+ evaluated_at: now
5973
+ };
5974
+ }
5975
+ const factors = [];
5976
+ let score = 0;
5977
+ if (peer.active) {
5978
+ factors.push("Active handshake (trust current)");
5979
+ score += 3;
5980
+ } else {
5981
+ factors.push("Handshake expired (trust degraded)");
5982
+ score += 1;
5983
+ }
5984
+ switch (peer.trust_tier) {
5985
+ case "verified-sovereign":
5986
+ factors.push("Verified sovereign \u2014 full sovereignty posture");
5987
+ score += 4;
5988
+ break;
5989
+ case "verified-degraded":
5990
+ factors.push("Verified degraded \u2014 sovereignty with known limitations");
5991
+ score += 3;
5992
+ break;
5993
+ case "self-attested":
5994
+ factors.push("Self-attested \u2014 claims not independently verified");
5995
+ score += 1;
5996
+ break;
5997
+ case "unverified":
5998
+ factors.push("Unverified \u2014 no sovereignty proof");
5999
+ score += 0;
6000
+ break;
6001
+ }
6002
+ if (mutualAttestationCount > 10) {
6003
+ factors.push(`Strong attestation history (${mutualAttestationCount} mutual attestations)`);
6004
+ score += 3;
6005
+ } else if (mutualAttestationCount > 0) {
6006
+ factors.push(`Some attestation history (${mutualAttestationCount} mutual attestations)`);
6007
+ score += 1;
6008
+ } else {
6009
+ factors.push("No mutual attestation history");
6010
+ }
6011
+ if (reputationScore !== void 0) {
6012
+ if (reputationScore >= 80) {
6013
+ factors.push(`High reputation score (${reputationScore})`);
6014
+ score += 2;
6015
+ } else if (reputationScore >= 50) {
6016
+ factors.push(`Moderate reputation score (${reputationScore})`);
6017
+ score += 1;
6018
+ } else {
6019
+ factors.push(`Low reputation score (${reputationScore})`);
6020
+ }
6021
+ }
6022
+ let trust_level;
6023
+ if (score >= 9) trust_level = "high";
6024
+ else if (score >= 5) trust_level = "medium";
6025
+ else if (score >= 2) trust_level = "low";
6026
+ else trust_level = "none";
6027
+ return {
6028
+ peer_id: peerId,
6029
+ sovereignty_tier: peer.trust_tier,
6030
+ handshake_current: peer.active,
6031
+ reputation_score: reputationScore,
6032
+ mutual_attestation_count: mutualAttestationCount,
6033
+ trust_level,
6034
+ factors,
6035
+ evaluated_at: now
6036
+ };
6037
+ }
6038
+ /**
6039
+ * Remove a peer from the registry.
6040
+ */
6041
+ removePeer(peerId) {
6042
+ return this.peers.delete(peerId);
6043
+ }
6044
+ /**
6045
+ * Get the handshake results map (for tier resolution integration).
6046
+ */
6047
+ getHandshakeResults() {
6048
+ const results = /* @__PURE__ */ new Map();
6049
+ for (const [id, peer] of this.peers) {
6050
+ if (peer.active) {
6051
+ results.set(id, peer.handshake_result);
6052
+ }
6053
+ }
6054
+ return results;
6055
+ }
6056
+ };
6057
+
6058
+ // src/federation/tools.ts
6059
+ function createFederationTools(auditLog, handshakeResults) {
6060
+ const registry = new FederationRegistry();
6061
+ const tools = [
6062
+ // ─── Peer Management ──────────────────────────────────────────────
6063
+ {
6064
+ name: "sanctuary/federation_peers",
6065
+ description: "List known federation peers, register a peer from a completed handshake, or remove a peer. Every peer MUST enter through a verified handshake \u2014 no self-registration allowed.",
6066
+ inputSchema: {
6067
+ type: "object",
6068
+ properties: {
6069
+ action: {
6070
+ type: "string",
6071
+ enum: ["list", "register", "remove"],
6072
+ description: "Operation to perform on the peer registry"
6073
+ },
6074
+ peer_id: {
6075
+ type: "string",
6076
+ description: "Peer instance ID (required for register/remove)"
6077
+ },
6078
+ peer_did: {
6079
+ type: "string",
6080
+ description: "Peer DID (required for register)"
6081
+ },
6082
+ active_only: {
6083
+ type: "boolean",
6084
+ description: "When listing, only show peers with active handshakes"
6085
+ }
6086
+ },
6087
+ required: ["action"]
6088
+ },
6089
+ handler: async (args) => {
6090
+ const action = args.action;
6091
+ switch (action) {
6092
+ case "list": {
6093
+ const peers = registry.listPeers({
6094
+ active_only: args.active_only
6095
+ });
6096
+ auditLog.append("l4", "federation_peers_list", "system", {
6097
+ peer_count: peers.length
6098
+ });
6099
+ return toolResult({
6100
+ peers: peers.map((p) => ({
6101
+ peer_id: p.peer_id,
6102
+ peer_did: p.peer_did,
6103
+ trust_tier: p.trust_tier,
6104
+ active: p.active,
6105
+ first_seen: p.first_seen,
6106
+ last_handshake: p.last_handshake,
6107
+ capabilities: p.capabilities
6108
+ })),
6109
+ total: peers.length
6110
+ });
6111
+ }
6112
+ case "register": {
6113
+ const peerId = args.peer_id;
6114
+ const peerDid = args.peer_did;
6115
+ if (!peerId || !peerDid) {
6116
+ return toolResult({
6117
+ error: "Both peer_id and peer_did are required for registration."
6118
+ });
6119
+ }
6120
+ const hsResult = handshakeResults.get(peerId);
6121
+ if (!hsResult) {
6122
+ return toolResult({
6123
+ error: `No completed handshake found for peer "${peerId}". Complete a sovereignty handshake first using handshake_initiate.`
6124
+ });
6125
+ }
6126
+ if (!hsResult.verified) {
6127
+ return toolResult({
6128
+ error: `Handshake with "${peerId}" was not verified. Only verified handshakes can establish federation.`
6129
+ });
6130
+ }
6131
+ const peer = registry.registerFromHandshake(hsResult, peerDid);
6132
+ auditLog.append("l4", "federation_peer_register", "system", {
6133
+ peer_id: peerId,
6134
+ peer_did: peerDid,
6135
+ trust_tier: peer.trust_tier
6136
+ });
6137
+ return toolResult({
6138
+ registered: true,
6139
+ peer_id: peer.peer_id,
6140
+ trust_tier: peer.trust_tier,
6141
+ active: peer.active,
6142
+ capabilities: peer.capabilities
6143
+ });
6144
+ }
6145
+ case "remove": {
6146
+ const peerId = args.peer_id;
6147
+ if (!peerId) {
6148
+ return toolResult({ error: "peer_id is required for removal." });
6149
+ }
6150
+ const removed = registry.removePeer(peerId);
6151
+ auditLog.append("l4", "federation_peer_remove", "system", {
6152
+ peer_id: peerId,
6153
+ removed
6154
+ });
6155
+ return toolResult({
6156
+ removed,
6157
+ peer_id: peerId
6158
+ });
6159
+ }
6160
+ default:
6161
+ return toolResult({ error: `Unknown action: ${action}` });
6162
+ }
6163
+ }
6164
+ },
6165
+ // ─── Trust Evaluation ─────────────────────────────────────────────
6166
+ {
6167
+ name: "sanctuary/federation_trust_evaluate",
6168
+ description: "Evaluate the trust level of a federation peer. Considers handshake status, sovereignty tier, reputation score, and mutual attestation history. Returns a composite trust assessment.",
6169
+ inputSchema: {
6170
+ type: "object",
6171
+ properties: {
6172
+ peer_id: {
6173
+ type: "string",
6174
+ description: "Peer instance ID to evaluate"
6175
+ },
6176
+ mutual_attestation_count: {
6177
+ type: "number",
6178
+ description: "Number of mutual attestations with this peer (0 if unknown)"
6179
+ },
6180
+ reputation_score: {
6181
+ type: "number",
6182
+ description: "Peer's weighted reputation score (from reputation_query_weighted)"
6183
+ }
6184
+ },
6185
+ required: ["peer_id"]
6186
+ },
6187
+ handler: async (args) => {
6188
+ const peerId = args.peer_id;
6189
+ const mutualCount = args.mutual_attestation_count ?? 0;
6190
+ const repScore = args.reputation_score;
6191
+ const evaluation = registry.evaluateTrust(peerId, mutualCount, repScore);
6192
+ auditLog.append("l4", "federation_trust_evaluate", "system", {
6193
+ peer_id: peerId,
6194
+ trust_level: evaluation.trust_level,
6195
+ sovereignty_tier: evaluation.sovereignty_tier
6196
+ });
6197
+ return toolResult(evaluation);
6198
+ }
6199
+ },
6200
+ // ─── Federation Status ────────────────────────────────────────────
6201
+ {
6202
+ name: "sanctuary/federation_status",
6203
+ description: "Overview of federation state: total peers, active connections, trust distribution, and readiness for cross-instance operations.",
6204
+ inputSchema: {
6205
+ type: "object",
6206
+ properties: {}
6207
+ },
6208
+ handler: async () => {
6209
+ const allPeers = registry.listPeers();
6210
+ const activePeers = registry.listPeers({ active_only: true });
6211
+ const tierCounts = {
6212
+ "verified-sovereign": 0,
6213
+ "verified-degraded": 0,
6214
+ "self-attested": 0,
6215
+ "unverified": 0
6216
+ };
6217
+ for (const peer of allPeers) {
6218
+ tierCounts[peer.trust_tier] = (tierCounts[peer.trust_tier] ?? 0) + 1;
6219
+ }
6220
+ const capCounts = {
6221
+ reputation_exchange: activePeers.filter((p) => p.capabilities.reputation_exchange).length,
6222
+ mutual_attestation: activePeers.filter((p) => p.capabilities.mutual_attestation).length,
6223
+ encrypted_channel: activePeers.filter((p) => p.capabilities.encrypted_channel).length
6224
+ };
6225
+ auditLog.append("l4", "federation_status", "system", {
6226
+ total_peers: allPeers.length,
6227
+ active_peers: activePeers.length
6228
+ });
6229
+ return toolResult({
6230
+ total_peers: allPeers.length,
6231
+ active_peers: activePeers.length,
6232
+ expired_peers: allPeers.length - activePeers.length,
6233
+ trust_distribution: tierCounts,
6234
+ capability_coverage: capCounts,
6235
+ federation_ready: activePeers.length > 0,
6236
+ checked_at: (/* @__PURE__ */ new Date()).toISOString()
6237
+ });
6238
+ }
6239
+ }
6240
+ ];
6241
+ return { tools, registry };
6242
+ }
6243
+
6244
+ // src/bridge/tools.ts
6245
+ init_encoding();
6246
+ init_encoding();
6247
+
6248
+ // src/bridge/bridge.ts
6249
+ init_encoding();
6250
+ init_hashing();
6251
+ function canonicalize(outcome) {
6252
+ return stringToBytes(stableStringify(outcome));
6253
+ }
6254
+ function stableStringify(value) {
6255
+ if (value === null || value === void 0) return JSON.stringify(value);
6256
+ if (typeof value !== "object") return JSON.stringify(value);
6257
+ if (Array.isArray(value)) {
6258
+ return "[" + value.map((v) => stableStringify(v)).join(",") + "]";
6259
+ }
6260
+ const obj = value;
6261
+ const keys = Object.keys(obj).sort();
6262
+ const pairs = keys.map((k) => JSON.stringify(k) + ":" + stableStringify(obj[k]));
6263
+ return "{" + pairs.join(",") + "}";
6264
+ }
6265
+ function createBridgeCommitment(outcome, identity, identityEncryptionKey, includePedersen = false) {
6266
+ const commitmentId = `bridge-${Date.now()}-${toBase64url(randomBytes(8))}`;
6267
+ const now = (/* @__PURE__ */ new Date()).toISOString();
6268
+ const canonicalBytes = canonicalize(outcome);
6269
+ const canonicalString = new TextDecoder().decode(canonicalBytes);
6270
+ const sha2564 = createCommitment(canonicalString);
6271
+ let pedersenData;
6272
+ if (includePedersen && Number.isInteger(outcome.rounds) && outcome.rounds >= 0) {
6273
+ const pedersen = createPedersenCommitment(outcome.rounds);
6274
+ pedersenData = {
6275
+ commitment: pedersen.commitment,
6276
+ blinding_factor: pedersen.blinding_factor
6277
+ };
6278
+ }
6279
+ const commitmentPayload = {
6280
+ bridge_commitment_id: commitmentId,
6281
+ session_id: outcome.session_id,
6282
+ sha256_commitment: sha2564.commitment,
6283
+ committer_did: identity.did,
6284
+ committed_at: now,
6285
+ bridge_version: "sanctuary-concordia-bridge-v1"
6286
+ };
6287
+ const payloadBytes = stringToBytes(JSON.stringify(commitmentPayload));
6288
+ const signature = sign(payloadBytes, identity.encrypted_private_key, identityEncryptionKey);
6289
+ return {
6290
+ bridge_commitment_id: commitmentId,
6291
+ session_id: outcome.session_id,
6292
+ sha256_commitment: sha2564.commitment,
6293
+ blinding_factor: sha2564.blinding_factor,
6294
+ committer_did: identity.did,
6295
+ signature: toBase64url(signature),
6296
+ pedersen_commitment: pedersenData,
6297
+ committed_at: now,
6298
+ bridge_version: "sanctuary-concordia-bridge-v1"
6299
+ };
6300
+ }
6301
+ function verifyBridgeCommitment(commitment, outcome, committerPublicKey) {
6302
+ const now = (/* @__PURE__ */ new Date()).toISOString();
6303
+ const canonicalString = new TextDecoder().decode(canonicalize(outcome));
6304
+ const sha256Match = verifyCommitment(
6305
+ commitment.sha256_commitment,
6306
+ canonicalString,
6307
+ commitment.blinding_factor
6308
+ );
6309
+ const commitmentPayload = {
6310
+ bridge_commitment_id: commitment.bridge_commitment_id,
6311
+ session_id: commitment.session_id,
6312
+ sha256_commitment: commitment.sha256_commitment,
6313
+ committer_did: commitment.committer_did,
6314
+ committed_at: commitment.committed_at,
6315
+ bridge_version: commitment.bridge_version
6316
+ };
6317
+ const payloadBytes = stringToBytes(JSON.stringify(commitmentPayload));
6318
+ const sigBytes = fromBase64url(commitment.signature);
6319
+ const signatureValid = verify(payloadBytes, sigBytes, committerPublicKey);
6320
+ const sessionIdMatch = commitment.session_id === outcome.session_id;
6321
+ const termsBytes = stringToBytes(stableStringify(outcome.terms));
6322
+ const computedTermsHash = toBase64url(hash(termsBytes));
6323
+ const termsHashMatch = computedTermsHash === outcome.terms_hash;
6324
+ let pedersenMatch;
6325
+ if (commitment.pedersen_commitment) {
6326
+ pedersenMatch = verifyPedersenCommitment(
6327
+ commitment.pedersen_commitment.commitment,
6328
+ outcome.rounds,
6329
+ commitment.pedersen_commitment.blinding_factor
6330
+ );
6331
+ }
6332
+ const valid = sha256Match && signatureValid && sessionIdMatch && termsHashMatch && (pedersenMatch === void 0 || pedersenMatch);
6333
+ return {
6334
+ valid,
6335
+ checks: {
6336
+ sha256_match: sha256Match,
6337
+ signature_valid: signatureValid,
6338
+ session_id_match: sessionIdMatch,
6339
+ terms_hash_match: termsHashMatch,
6340
+ pedersen_match: pedersenMatch
6341
+ },
6342
+ bridge_commitment_id: commitment.bridge_commitment_id,
6343
+ verified_at: now
6344
+ };
6345
+ }
6346
+
6347
+ // src/bridge/tools.ts
6348
+ var BridgeStore = class {
6349
+ storage;
6350
+ encryptionKey;
6351
+ constructor(storage, masterKey) {
6352
+ this.storage = storage;
6353
+ this.encryptionKey = derivePurposeKey(masterKey, "bridge-commitments");
6354
+ }
6355
+ async save(commitment, outcome) {
6356
+ const record = { commitment, outcome };
6357
+ const serialized = stringToBytes(JSON.stringify(record));
6358
+ const encrypted = encrypt(serialized, this.encryptionKey);
6359
+ await this.storage.write(
6360
+ "_bridge",
6361
+ commitment.bridge_commitment_id,
6362
+ stringToBytes(JSON.stringify(encrypted))
6363
+ );
6364
+ }
6365
+ async get(commitmentId) {
6366
+ const raw = await this.storage.read("_bridge", commitmentId);
6367
+ if (!raw) return null;
6368
+ try {
6369
+ const encrypted = JSON.parse(bytesToString(raw));
6370
+ const decrypted = decrypt(encrypted, this.encryptionKey);
6371
+ return JSON.parse(bytesToString(decrypted));
6372
+ } catch {
6373
+ return null;
6374
+ }
6375
+ }
6376
+ };
6377
+ function createBridgeTools(storage, masterKey, identityManager, auditLog, handshakeResults) {
6378
+ const bridgeStore = new BridgeStore(storage, masterKey);
6379
+ const reputationStore = new ReputationStore(storage, masterKey);
6380
+ const identityEncryptionKey = derivePurposeKey(masterKey, "identity-encryption");
6381
+ const hsResults = handshakeResults ?? /* @__PURE__ */ new Map();
6382
+ function resolveIdentity(identityId) {
6383
+ const id = identityId ? identityManager.get(identityId) : identityManager.getDefault();
6384
+ if (!id) {
6385
+ throw new Error(
6386
+ identityId ? `Identity "${identityId}" not found` : "No identity available. Create one with identity_create first."
6387
+ );
6388
+ }
6389
+ return id;
6390
+ }
6391
+ const tools = [
6392
+ // ─── bridge_commit ─────────────────────────────────────────────────
6393
+ {
6394
+ name: "sanctuary/bridge_commit",
6395
+ description: "Create a cryptographic commitment binding a Concordia negotiation outcome to Sanctuary's L3 proof layer. The commitment includes a SHA-256 hash of the canonical outcome (hiding + binding), an Ed25519 signature by the committer's identity, and an optional Pedersen commitment on the round count for zero-knowledge range proofs. This is the Sanctuary side of the Concordia bridge \u2014 call this when a Concordia `accept` fires.",
6396
+ inputSchema: {
6397
+ type: "object",
6398
+ properties: {
6399
+ session_id: {
6400
+ type: "string",
6401
+ description: "Concordia session identifier"
6402
+ },
6403
+ protocol_version: {
6404
+ type: "string",
6405
+ description: 'Concordia protocol version (e.g., "concordia-v1")'
6406
+ },
6407
+ proposer_did: {
6408
+ type: "string",
6409
+ description: "DID of the party who proposed the accepted terms"
6410
+ },
6411
+ acceptor_did: {
6412
+ type: "string",
6413
+ description: "DID of the party who accepted"
6414
+ },
6415
+ terms: {
6416
+ type: "object",
6417
+ description: "The accepted terms (opaque to Sanctuary, meaningful to Concordia)"
6418
+ },
6419
+ terms_hash: {
6420
+ type: "string",
6421
+ description: "SHA-256 hash of the canonical terms serialization (computed by Concordia)"
6422
+ },
6423
+ rounds: {
6424
+ type: "number",
6425
+ description: "Number of negotiation rounds (propose/counter cycles)"
6426
+ },
6427
+ accepted_at: {
6428
+ type: "string",
6429
+ description: "ISO 8601 timestamp when accept was issued"
6430
+ },
6431
+ session_receipt: {
6432
+ type: "string",
6433
+ description: "Optional: signed Concordia session receipt"
6434
+ },
6435
+ identity_id: {
6436
+ type: "string",
6437
+ description: "Sanctuary identity to sign the commitment (uses default if omitted)"
6438
+ },
6439
+ include_pedersen: {
6440
+ type: "boolean",
6441
+ description: "Include a Pedersen commitment on round count for ZK range proofs"
6442
+ }
6443
+ },
6444
+ required: [
6445
+ "session_id",
6446
+ "protocol_version",
6447
+ "proposer_did",
6448
+ "acceptor_did",
6449
+ "terms",
6450
+ "terms_hash",
6451
+ "rounds",
6452
+ "accepted_at"
6453
+ ]
6454
+ },
6455
+ handler: async (args) => {
6456
+ const outcome = {
6457
+ session_id: args.session_id,
6458
+ protocol_version: args.protocol_version,
6459
+ proposer_did: args.proposer_did,
6460
+ acceptor_did: args.acceptor_did,
6461
+ terms: args.terms,
6462
+ terms_hash: args.terms_hash,
6463
+ rounds: args.rounds,
6464
+ accepted_at: args.accepted_at,
6465
+ session_receipt: args.session_receipt
6466
+ };
6467
+ const identity = resolveIdentity(args.identity_id);
6468
+ const includePedersen = args.include_pedersen ?? false;
6469
+ const bridgeCommitment = createBridgeCommitment(
6470
+ outcome,
6471
+ identity,
6472
+ identityEncryptionKey,
6473
+ includePedersen
6474
+ );
6475
+ await bridgeStore.save(bridgeCommitment, outcome);
6476
+ auditLog.append("l3", "bridge_commit", identity.identity_id, {
6477
+ bridge_commitment_id: bridgeCommitment.bridge_commitment_id,
6478
+ session_id: outcome.session_id,
6479
+ counterparty: outcome.proposer_did === identity.did ? outcome.acceptor_did : outcome.proposer_did
6480
+ });
6481
+ return toolResult({
6482
+ bridge_commitment_id: bridgeCommitment.bridge_commitment_id,
6483
+ session_id: bridgeCommitment.session_id,
6484
+ sha256_commitment: bridgeCommitment.sha256_commitment,
6485
+ committer_did: bridgeCommitment.committer_did,
6486
+ signature: bridgeCommitment.signature,
6487
+ pedersen_commitment: bridgeCommitment.pedersen_commitment ? { commitment: bridgeCommitment.pedersen_commitment.commitment } : void 0,
6488
+ committed_at: bridgeCommitment.committed_at,
6489
+ bridge_version: bridgeCommitment.bridge_version,
6490
+ note: "Bridge commitment created. The blinding factor is stored encrypted. Use bridge_verify to verify the commitment against the revealed outcome. Use bridge_attest to link this negotiation to your reputation."
6491
+ });
6492
+ }
6493
+ },
6494
+ // ─── bridge_verify ───────────────────────────────────────────────────
6495
+ {
6496
+ name: "sanctuary/bridge_verify",
6497
+ description: "Verify a bridge commitment against a revealed Concordia negotiation outcome. Checks SHA-256 commitment validity, Ed25519 signature, session ID match, terms hash integrity, and Pedersen commitment (if present). Use this to confirm that a counterparty's claimed negotiation outcome matches what was cryptographically committed.",
6498
+ inputSchema: {
6499
+ type: "object",
6500
+ properties: {
6501
+ bridge_commitment_id: {
6502
+ type: "string",
6503
+ description: "The bridge commitment ID to verify"
6504
+ },
6505
+ committer_public_key: {
6506
+ type: "string",
6507
+ description: "The committer's Ed25519 public key (base64url). Required if verifying a counterparty's commitment. Omit to auto-resolve from local identities."
6508
+ }
6509
+ },
6510
+ required: ["bridge_commitment_id"]
6511
+ },
6512
+ handler: async (args) => {
6513
+ const commitmentId = args.bridge_commitment_id;
6514
+ const externalPublicKey = args.committer_public_key;
6515
+ const record = await bridgeStore.get(commitmentId);
6516
+ if (!record) {
6517
+ return toolResult({
6518
+ error: `Bridge commitment "${commitmentId}" not found`
6519
+ });
6520
+ }
6521
+ const { commitment: storedCommitment, outcome } = record;
6522
+ let publicKey;
6523
+ if (externalPublicKey) {
6524
+ publicKey = fromBase64url(externalPublicKey);
6525
+ } else {
6526
+ const localIdentities = identityManager.list();
6527
+ const match = localIdentities.find((i) => i.did === storedCommitment.committer_did);
6528
+ if (!match) {
6529
+ return toolResult({
6530
+ error: `Cannot resolve public key for committer "${storedCommitment.committer_did}". Provide committer_public_key for external verification.`
6531
+ });
6532
+ }
6533
+ publicKey = fromBase64url(match.public_key);
6534
+ }
6535
+ const result = verifyBridgeCommitment(storedCommitment, outcome, publicKey);
6536
+ auditLog.append("l3", "bridge_verify", "system", {
6537
+ bridge_commitment_id: commitmentId,
6538
+ session_id: storedCommitment.session_id,
6539
+ valid: result.valid
6540
+ });
6541
+ return toolResult({
6542
+ ...result,
6543
+ session_id: storedCommitment.session_id,
6544
+ committer_did: storedCommitment.committer_did
6545
+ });
6546
+ }
6547
+ },
6548
+ // ─── bridge_attest ───────────────────────────────────────────────────
6549
+ {
6550
+ name: "sanctuary/bridge_attest",
6551
+ description: "Record a Concordia negotiation as a Sanctuary L4 reputation attestation, linked to a bridge commitment. This completes the bridge: the commitment (L3) proves the terms were agreed, and the attestation (L4) feeds the sovereignty-weighted reputation score. The attestation is automatically tagged with the counterparty's sovereignty tier from any completed handshake.",
6552
+ inputSchema: {
6553
+ type: "object",
6554
+ properties: {
6555
+ bridge_commitment_id: {
6556
+ type: "string",
6557
+ description: "The bridge commitment ID to link"
6558
+ },
6559
+ outcome_result: {
6560
+ type: "string",
6561
+ enum: ["completed", "partial", "failed", "disputed"],
6562
+ description: "Negotiation outcome for reputation scoring"
6563
+ },
6564
+ metrics: {
6565
+ type: "object",
6566
+ description: "Optional metrics (e.g., rounds, response_time_ms, terms_complexity)"
6567
+ },
6568
+ identity_id: {
6569
+ type: "string",
6570
+ description: "Identity to sign the attestation (uses default if omitted)"
6571
+ }
6572
+ },
6573
+ required: ["bridge_commitment_id", "outcome_result"]
6574
+ },
6575
+ handler: async (args) => {
6576
+ const commitmentId = args.bridge_commitment_id;
6577
+ const outcomeResult = args.outcome_result;
6578
+ const metrics = args.metrics ?? {};
6579
+ const identityId = args.identity_id;
6580
+ const record = await bridgeStore.get(commitmentId);
6581
+ if (!record) {
6582
+ return toolResult({
6583
+ error: `Bridge commitment "${commitmentId}" not found`
6584
+ });
6585
+ }
6586
+ const { outcome } = record;
6587
+ const identity = resolveIdentity(identityId);
6588
+ const counterpartyDid = outcome.proposer_did === identity.did ? outcome.acceptor_did : outcome.proposer_did;
6589
+ const hasSanctuaryIdentity = identityManager.list().some(
6590
+ (id) => identityManager.get(id.identity_id)?.did === counterpartyDid
6591
+ );
6592
+ const tierMeta = resolveTier(counterpartyDid, hsResults, hasSanctuaryIdentity);
6593
+ const tier = tierMeta.sovereignty_tier;
6594
+ const fullMetrics = {
6595
+ ...metrics,
6596
+ negotiation_rounds: outcome.rounds
6597
+ };
6598
+ const attestation = await reputationStore.record(
6599
+ outcome.session_id,
6600
+ // interaction_id = concordia session
6601
+ counterpartyDid,
6602
+ {
6603
+ type: "negotiation",
6604
+ result: outcomeResult,
6605
+ metrics: fullMetrics
6606
+ },
6607
+ "concordia-bridge",
6608
+ // context
6609
+ identity,
6610
+ identityEncryptionKey,
6611
+ void 0,
6612
+ // counterparty_attestation
6613
+ tier
6614
+ );
6615
+ auditLog.append("l4", "bridge_attest", identity.identity_id, {
6616
+ bridge_commitment_id: commitmentId,
6617
+ session_id: outcome.session_id,
6618
+ attestation_id: attestation.attestation.attestation_id,
6619
+ counterparty_did: counterpartyDid,
6620
+ sovereignty_tier: tier
6621
+ });
6622
+ const weight = TIER_WEIGHTS[tier];
6623
+ return toolResult({
6624
+ attestation_id: attestation.attestation.attestation_id,
6625
+ bridge_commitment_id: commitmentId,
6626
+ session_id: outcome.session_id,
6627
+ counterparty_did: counterpartyDid,
6628
+ outcome_result: outcomeResult,
6629
+ sovereignty_tier: tier,
6630
+ attested_at: attestation.recorded_at,
6631
+ note: `Negotiation recorded as reputation attestation. Counterparty sovereignty tier: ${tier} (weight: ${weight}).`
6632
+ });
6633
+ }
6634
+ }
6635
+ ];
6636
+ return { tools };
4093
6637
  }
4094
6638
 
4095
6639
  // src/index.ts
@@ -4371,30 +6915,74 @@ async function createSanctuaryServer(options) {
4371
6915
  }
4372
6916
  };
4373
6917
  const { tools: l3Tools } = createL3Tools(storage, masterKey, auditLog);
4374
- const { tools: l4Tools } = createL4Tools(
4375
- storage,
4376
- masterKey,
4377
- identityManager,
4378
- auditLog
4379
- );
4380
- const policy = await loadPrincipalPolicy(config.storage_path);
4381
- const baseline = new BaselineTracker(storage, masterKey);
4382
- await baseline.load();
4383
- const approvalChannel = new StderrApprovalChannel(policy.approval_channel);
4384
- const gate = new ApprovalGate(policy, baseline, approvalChannel, auditLog);
4385
- const policyTools = createPrincipalPolicyTools(policy, baseline, auditLog);
4386
6918
  const { tools: shrTools } = createSHRTools(
4387
6919
  config,
4388
6920
  identityManager,
4389
6921
  masterKey,
4390
6922
  auditLog
4391
6923
  );
4392
- const { tools: handshakeTools } = createHandshakeTools(
6924
+ const { tools: handshakeTools, handshakeResults } = createHandshakeTools(
4393
6925
  config,
4394
6926
  identityManager,
4395
6927
  masterKey,
4396
6928
  auditLog
4397
6929
  );
6930
+ const { tools: l4Tools } = createL4Tools(
6931
+ storage,
6932
+ masterKey,
6933
+ identityManager,
6934
+ auditLog,
6935
+ handshakeResults
6936
+ );
6937
+ const { tools: federationTools } = createFederationTools(
6938
+ auditLog,
6939
+ handshakeResults
6940
+ );
6941
+ const { tools: bridgeTools } = createBridgeTools(
6942
+ storage,
6943
+ masterKey,
6944
+ identityManager,
6945
+ auditLog,
6946
+ handshakeResults
6947
+ );
6948
+ const policy = await loadPrincipalPolicy(config.storage_path);
6949
+ const baseline = new BaselineTracker(storage, masterKey);
6950
+ await baseline.load();
6951
+ let approvalChannel;
6952
+ let dashboard;
6953
+ if (config.dashboard.enabled) {
6954
+ let authToken = config.dashboard.auth_token;
6955
+ if (authToken === "auto") {
6956
+ const { randomBytes: rb } = await import('crypto');
6957
+ authToken = rb(32).toString("hex");
6958
+ }
6959
+ dashboard = new DashboardApprovalChannel({
6960
+ port: config.dashboard.port,
6961
+ host: config.dashboard.host,
6962
+ timeout_seconds: policy.approval_channel.timeout_seconds,
6963
+ auto_deny: policy.approval_channel.auto_deny,
6964
+ auth_token: authToken,
6965
+ tls: config.dashboard.tls
6966
+ });
6967
+ dashboard.setDependencies({ policy, baseline, auditLog });
6968
+ await dashboard.start();
6969
+ approvalChannel = dashboard;
6970
+ } else if (config.webhook.enabled && config.webhook.url && config.webhook.secret) {
6971
+ const webhook = new WebhookApprovalChannel({
6972
+ webhook_url: config.webhook.url,
6973
+ webhook_secret: config.webhook.secret,
6974
+ callback_port: config.webhook.callback_port,
6975
+ callback_host: config.webhook.callback_host,
6976
+ timeout_seconds: policy.approval_channel.timeout_seconds,
6977
+ auto_deny: policy.approval_channel.auto_deny
6978
+ });
6979
+ await webhook.start();
6980
+ approvalChannel = webhook;
6981
+ } else {
6982
+ approvalChannel = new StderrApprovalChannel(policy.approval_channel);
6983
+ }
6984
+ const gate = new ApprovalGate(policy, baseline, approvalChannel, auditLog);
6985
+ const policyTools = createPrincipalPolicyTools(policy, baseline, auditLog);
4398
6986
  const allTools = [
4399
6987
  ...l1Tools,
4400
6988
  ...l2Tools,
@@ -4403,6 +6991,8 @@ async function createSanctuaryServer(options) {
4403
6991
  ...policyTools,
4404
6992
  ...shrTools,
4405
6993
  ...handshakeTools,
6994
+ ...federationTools,
6995
+ ...bridgeTools,
4406
6996
  manifestTool
4407
6997
  ];
4408
6998
  const server = createServer(allTools, { gate });
@@ -4430,7 +7020,21 @@ async function createSanctuaryServer(options) {
4430
7020
 
4431
7021
  // src/cli.ts
4432
7022
  async function main() {
4433
- const passphrase = process.env.SANCTUARY_PASSPHRASE;
7023
+ const args = process.argv.slice(2);
7024
+ let passphrase = process.env.SANCTUARY_PASSPHRASE;
7025
+ for (let i = 0; i < args.length; i++) {
7026
+ if (args[i] === "--dashboard") {
7027
+ process.env.SANCTUARY_DASHBOARD_ENABLED = "true";
7028
+ } else if (args[i] === "--passphrase" && args[i + 1]) {
7029
+ passphrase = args[++i];
7030
+ } else if (args[i] === "--help" || args[i] === "-h") {
7031
+ printHelp();
7032
+ process.exit(0);
7033
+ } else if (args[i] === "--version" || args[i] === "-v") {
7034
+ console.log("@sanctuary-framework/mcp-server 0.3.0");
7035
+ process.exit(0);
7036
+ }
7037
+ }
4434
7038
  const { server, config } = await createSanctuaryServer({ passphrase });
4435
7039
  if (config.transport === "stdio") {
4436
7040
  const transport = new stdio_js.StdioServerTransport();
@@ -4443,6 +7047,34 @@ async function main() {
4443
7047
  process.exit(1);
4444
7048
  }
4445
7049
  }
7050
+ function printHelp() {
7051
+ console.log(`
7052
+ @sanctuary-framework/mcp-server v0.3.0
7053
+
7054
+ Sovereignty infrastructure for agents in the agentic economy.
7055
+
7056
+ Usage:
7057
+ sanctuary-mcp-server [options]
7058
+
7059
+ Options:
7060
+ --dashboard Enable the Principal Dashboard (web UI)
7061
+ --passphrase <pass> Derive encryption key from passphrase
7062
+ --help, -h Show this help
7063
+ --version, -v Show version
7064
+
7065
+ Environment variables:
7066
+ SANCTUARY_STORAGE_PATH State directory (default: ~/.sanctuary)
7067
+ SANCTUARY_PASSPHRASE Key derivation passphrase
7068
+ SANCTUARY_DASHBOARD_ENABLED "true" to enable dashboard
7069
+ SANCTUARY_DASHBOARD_PORT Dashboard port (default: 3501)
7070
+ SANCTUARY_DASHBOARD_AUTH_TOKEN Bearer token or "auto"
7071
+ SANCTUARY_WEBHOOK_ENABLED "true" to enable webhook approvals
7072
+ SANCTUARY_WEBHOOK_URL Webhook target URL
7073
+ SANCTUARY_WEBHOOK_SECRET HMAC-SHA256 shared secret
7074
+
7075
+ For more info: https://github.com/eriknewton/sanctuary-framework
7076
+ `);
7077
+ }
4446
7078
  main().catch((err) => {
4447
7079
  console.error("Sanctuary MCP Server failed to start:", err);
4448
7080
  process.exit(1);