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