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