saktum 0.10.0 → 0.12.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.
Files changed (3) hide show
  1. package/README.md +12 -1
  2. package/package.json +1 -1
  3. package/saktum.mjs +614 -100
package/README.md CHANGED
@@ -11,6 +11,17 @@ npx saktum check https://your-server.example/mcp # a remote server (sign-in
11
11
 
12
12
  Runs on your machine. Nothing is uploaded. Your own environment variables are never passed to the server.
13
13
 
14
+ ## Trust you can verify (v0.12)
15
+
16
+ Saktum holds itself to the standard it asks of others. Revocations are signed and stick (receipt chain, optional remote
17
+ list); wallets and receipts are chained and signed, with checkpoints that detect deletion; approvals are single use,
18
+ per request and can require a **passkey**; proxies **pin tools** against rug pulls and **fail closed**; argument
19
+ digests are keyed; organisations **verify their domain**; keys can live in the OS keychain or any key service through an
20
+ external signer; the ledger records key rotations and revocations, with checkpoints and witnesses; canonical JSON is
21
+ RFC 8785-compatible. Releases are Sigstore-signed (`saktum self-verify`), actions are pinned, and CodeQL, Dependabot and
22
+ the OpenSSF Scorecard run on the repository. See [threat model v2](docs/THREAT-MODEL.md),
23
+ [security architecture](docs/SECURITY-ARCHITECTURE.md) and the [hardening guide](docs/HARDENING.md).
24
+
14
25
  ## Enterprise pilot-ready (v0.10)
15
26
 
16
27
  - **Remote MCP servers:** `saktum proxy --mandate m.json --enforce -- saktum bridge https://host/mcp` governs a remote
@@ -234,7 +245,7 @@ servers not on your allowlist, and the weakest grades. Configured secrets are ne
234
245
 
235
246
  ```yaml
236
247
  - uses: actions/checkout@v4
237
- - uses: soodhere/saktum-check@v0.10.0
248
+ - uses: soodhere/saktum-check@v0.12.0
238
249
  with:
239
250
  target: "-- node build/index.js" # or an https URL
240
251
  args: "--active --tests saktum.tests.yaml" # optional; --active only for your own server
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "saktum",
3
- "version": "0.10.0",
3
+ "version": "0.12.0",
4
4
  "description": "Test MCP servers in one command: conformance, sign-in, security (OWASP MCP Top 10), agent experience, context cost and performance.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
package/saktum.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // Saktum Check 0.10.0 (private beta). Licensed Apache-2.0; bundled dependencies keep their own licences.
2
+ // Saktum Check 0.12.0 (private beta). Licensed Apache-2.0; bundled dependencies keep their own licences.
3
3
  import { createRequire as __saktumCreateRequire } from "node:module";
4
4
  const require = __saktumCreateRequire(import.meta.url);
5
5
  var __create = Object.create;
@@ -10533,6 +10533,17 @@ function loadOrCreateKey(path = defaultKeyPath()) {
10533
10533
  }
10534
10534
  if (path.startsWith("keychain:"))
10535
10535
  return keychain(path.slice(9));
10536
+ if (path.startsWith("exec:")) {
10537
+ const prog = path.slice(5);
10538
+ const publicKey = createPublicKey({ key: JSON.parse(execFileSync(prog, ["public"], { encoding: "utf8" })), format: "jwk" });
10539
+ const signer = (data) => {
10540
+ const sig = Buffer.from(execFileSync(prog, ["sign"], { encoding: "utf8", input: data.toString("base64") }).trim(), "base64");
10541
+ if (!verify(null, data, publicKey, sig))
10542
+ throw new Error("The external signer returned an invalid signature.");
10543
+ return sig;
10544
+ };
10545
+ return { privateKey: publicKey, publicKey, kid: didKeyFromPublicKey(publicKey), signer };
10546
+ }
10536
10547
  if (existsSync(path)) {
10537
10548
  const jwk = JSON.parse(readFileSync(path, "utf8"));
10538
10549
  const privateKey = createPrivateKey({ key: jwk, format: "jwk" });
@@ -10552,7 +10563,7 @@ function signDocument(doc, key) {
10552
10563
  const { signature: _ignored, ...body2 } = doc;
10553
10564
  const header = b64u(Buffer.from(JSON.stringify({ alg: "EdDSA", kid: key.kid })));
10554
10565
  const payload = b64u(Buffer.from(canonicalize(body2)));
10555
- const sig = sign(null, Buffer.from(`${header}.${payload}`), key.privateKey);
10566
+ const sig = key.signer ? key.signer(Buffer.from(`${header}.${payload}`)) : sign(null, Buffer.from(`${header}.${payload}`), key.privateKey);
10556
10567
  return { ...body2, signature: { alg: "EdDSA", kid: key.kid, jws: `${header}..${b64u(sig)}` } };
10557
10568
  }
10558
10569
  function verifyDocument(doc) {
@@ -34046,7 +34057,7 @@ var init_dist3 = __esm({
34046
34057
  init_stdio2();
34047
34058
  init_streamableHttp();
34048
34059
  init_types2();
34049
- USER_AGENT = "saktum-check/0.10.0 (+https://saktum.dev/check)";
34060
+ USER_AGENT = "saktum-check/0.12.0 (+https://saktum.dev/check)";
34050
34061
  LIMITS = { requestTimeoutMs: 1e4, connectTimeoutMs: 6e4, maxResponseChars: 5e6 };
34051
34062
  LimitError = class extends Error {
34052
34063
  };
@@ -34084,7 +34095,7 @@ var init_dist3 = __esm({
34084
34095
  jsonrpc: "2.0",
34085
34096
  id: 1,
34086
34097
  method: "initialize",
34087
- params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "saktum-trust-check-probe", version: "0.10.0" } }
34098
+ params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "saktum-trust-check-probe", version: "0.12.0" } }
34088
34099
  });
34089
34100
  }
34090
34101
  });
@@ -35456,7 +35467,7 @@ var init_engine = __esm({
35456
35467
  init_runner();
35457
35468
  init_safe();
35458
35469
  init_scoring();
35459
- ENGINE_VERSION = "0.10.0";
35470
+ ENGINE_VERSION = "0.12.0";
35460
35471
  UNKNOWN_TOOL = "saktum_trust_check_no_such_tool";
35461
35472
  INVALID_TOKEN = "saktum-check-deliberately-invalid-token";
35462
35473
  baseOf = (pack, check) => ({
@@ -35840,6 +35851,51 @@ var init_fleet = __esm({
35840
35851
  });
35841
35852
 
35842
35853
  // packages/testkit-core/dist/ledger.js
35854
+ function checkStatement(s) {
35855
+ const st = s;
35856
+ if (!st || st.statementFormat !== "0.1" || !["key-rotation", "revocation"].includes(st.type))
35857
+ return { ok: false, reason: "not a Saktum statement" };
35858
+ if (JSON.stringify(st).length > MAX_ATTESTATION_BYTES)
35859
+ return { ok: false, reason: "statement too large" };
35860
+ const v = verifyDocument(st);
35861
+ if (!v.valid)
35862
+ return { ok: false, reason: `signature not valid (${v.reason})` };
35863
+ if (st.type === "key-rotation") {
35864
+ if (v.kid !== st.oldKey || !st.newKey)
35865
+ return { ok: false, reason: "a rotation must be signed by the old key and name the new key" };
35866
+ const pv = verifyDocument(st.newKeyProof);
35867
+ if (!pv.valid || pv.kid !== st.newKey || st.newKeyProof.rotates !== st.oldKey)
35868
+ return { ok: false, reason: "missing proof of possession of the new key" };
35869
+ } else if (!st.target)
35870
+ return { ok: false, reason: "a revocation must name its target" };
35871
+ return { ok: true, st, signer: v.kid };
35872
+ }
35873
+ function appendStatement(ledgerText, statement, source, now = /* @__PURE__ */ new Date()) {
35874
+ const c = checkStatement(statement);
35875
+ if (!c.ok)
35876
+ throw new Error(`Refused: ${c.reason}`);
35877
+ const entries = parseLedger(ledgerText);
35878
+ const check = verifyLedger(entries);
35879
+ if (!check.ok)
35880
+ throw new Error(`Refused: the existing ledger does not verify (${check.errors[0]})`);
35881
+ if (c.st.type === "revocation" && !entries.some((e) => e.signer === c.signer && (e.attestation?.resultDigest === c.st.target || e.signer === c.st.target)) && c.st.target !== c.signer)
35882
+ throw new Error("Refused: a revocation must come from the key that signed the target");
35883
+ const prev = entries[entries.length - 1];
35884
+ const base = { ledgerFormat: "0.1", seq: (prev?.seq ?? 0) + 1, recordedAt: now.toISOString(), source, subject: { server: `${c.st.type}:${c.signer.slice(0, 32)}` }, signer: c.signer, statement: c.st, prevHash: prev?.entryHash ?? GENESIS };
35885
+ const entry = { ...base, entryHash: hashOf(base) };
35886
+ return { text: `${ledgerText.replace(/\n*$/, ledgerText.trim() ? "\n" : "")}${JSON.stringify(entry)}
35887
+ `, entry };
35888
+ }
35889
+ function ledgerStatus(entries) {
35890
+ const rotated = /* @__PURE__ */ new Map(), revoked = /* @__PURE__ */ new Set();
35891
+ for (const e of entries) {
35892
+ if (e.statement?.type === "key-rotation")
35893
+ rotated.set(e.statement.oldKey, e.statement.newKey);
35894
+ if (e.statement?.type === "revocation")
35895
+ revoked.add(e.statement.target);
35896
+ }
35897
+ return { rotated, revoked };
35898
+ }
35843
35899
  function parseLedger(text2) {
35844
35900
  return text2.split("\n").map((l) => l.trim()).filter(Boolean).map((l, i) => {
35845
35901
  try {
@@ -35878,7 +35934,7 @@ function appendToLedger(ledgerText, attestation, source, now = /* @__PURE__ */ n
35878
35934
  const check = verifyLedger(entries);
35879
35935
  if (!check.ok)
35880
35936
  throw new Error(`Refused: the existing ledger does not verify (${check.errors[0]})`);
35881
- if (entries.some((e) => e.signer === c.signer && e.attestation.resultDigest === c.att.resultDigest))
35937
+ if (entries.some((e) => e.signer === c.signer && e.attestation?.resultDigest === c.att.resultDigest))
35882
35938
  throw new Error("Refused: this attestation is already in the ledger");
35883
35939
  const prev = entries[entries.length - 1];
35884
35940
  const base = {
@@ -35906,16 +35962,17 @@ function verifyLedger(entries) {
35906
35962
  const { entryHash, ...base } = e;
35907
35963
  if (hashOf(base) !== entryHash)
35908
35964
  errors.push(`entry ${e.seq}: contents changed after it was recorded`);
35909
- const c = checkAttestation(e.attestation);
35965
+ const c = e.statement ? checkStatement(e.statement) : checkAttestation(e.attestation);
35910
35966
  if (!c.ok)
35911
35967
  errors.push(`entry ${e.seq}: ${c.reason}`);
35912
35968
  else if (c.signer !== e.signer)
35913
- errors.push(`entry ${e.seq}: signer does not match the attestation`);
35969
+ errors.push(`entry ${e.seq}: signer does not match`);
35914
35970
  prev = entryHash;
35915
35971
  });
35916
35972
  return { ok: errors.length === 0, count: entries.length, errors };
35917
35973
  }
35918
35974
  function findInLedger(entries, query) {
35975
+ entries = entries.filter((e) => e.attestation);
35919
35976
  const q = query.toLowerCase();
35920
35977
  return entries.filter((e) => e.subject.server.toLowerCase().includes(q) || e.subject.toolsFingerprint === query);
35921
35978
  }
@@ -35925,6 +35982,8 @@ function allowlistFromLedger(entries, c) {
35925
35982
  latest.set(`${e.subject.server}|${e.subject.toolsFingerprint}`, e);
35926
35983
  const allowed = [], excluded = [];
35927
35984
  for (const e of latest.values()) {
35985
+ if (!e.attestation)
35986
+ continue;
35928
35987
  const cl = e.attestation.claims, why = [];
35929
35988
  if (c.trustedSigners && !c.trustedSigners.has(e.signer))
35930
35989
  why.push("signer is not on your trusted list");
@@ -36404,17 +36463,27 @@ function checkOperator(m) {
36404
36463
  return { present: true, valid: false, reason: "operator signed a different mandate" };
36405
36464
  return { present: true, valid: true, id: v.kid, name: cs.name };
36406
36465
  }
36407
- function revokeMandate(m, reason, path = DEFAULT_REVOCATIONS()) {
36466
+ function revokeMandate(m, reason, path = DEFAULT_REVOCATIONS(), key) {
36408
36467
  const r = readRevocations(path), d = mandateDigest(m);
36468
+ const entry = { revocationFormat: "0.1", mandate: d, agent: m.agent.id, at: (/* @__PURE__ */ new Date()).toISOString(), ...reason ? { reason } : {} };
36409
36469
  if (!r.revoked.some((x) => x.mandate === d))
36410
- r.revoked.push({ mandate: d, agent: m.agent.id, at: (/* @__PURE__ */ new Date()).toISOString(), ...reason ? { reason } : {} });
36470
+ r.revoked.push(key ? signDocument(entry, key) : entry);
36411
36471
  _mkdir(_dirname(path), { recursive: true });
36412
36472
  _write(path, JSON.stringify(r, null, 2) + "\n");
36413
36473
  return r.revoked.find((x) => x.mandate === d);
36414
36474
  }
36415
36475
  function revocationOf(m, path = DEFAULT_REVOCATIONS()) {
36416
36476
  const d = mandateDigest(m);
36417
- return readRevocations(path).revoked.find((x) => x.mandate === d);
36477
+ const op = m.operatorCountersign?.signature?.kid;
36478
+ return readRevocations(path).revoked.find((x) => {
36479
+ if (x.mandate !== d)
36480
+ return false;
36481
+ const sx = x;
36482
+ if (!sx.signature)
36483
+ return true;
36484
+ const v = verifyDocument(x);
36485
+ return v.valid && (v.kid === m.owner.id || Boolean(op) && v.kid === op);
36486
+ });
36418
36487
  }
36419
36488
  function trustStatement(entries, verified) {
36420
36489
  const allowed = entries.filter((e) => e.receipt.outcome === "allow" && e.result.status === "ok").length;
@@ -36806,21 +36875,47 @@ function verifyAgreement(a, today = nowIso().slice(0, 10)) {
36806
36875
  return { valid: false, reason: `expired on ${a.validUntil}` };
36807
36876
  return { valid: true };
36808
36877
  }
36878
+ function sealEntry(w, e, key) {
36879
+ const prev = w.entries[w.entries.length - 1]?.hash ?? "sha256:genesis";
36880
+ const body2 = { at: e.at, from: e.from, to: e.to, tokens: e.tokens, ref: e.ref, prev };
36881
+ const hash = argumentsHash(body2);
36882
+ return key ? signDocument({ ...body2, hash }, key) : { ...body2, hash };
36883
+ }
36884
+ function verifyWallet(path) {
36885
+ const errors = [];
36886
+ let prev = "sha256:genesis";
36887
+ readWallet(path).entries.forEach((e, i) => {
36888
+ if (!e.hash)
36889
+ return;
36890
+ const { signature: _s, hash, ...body2 } = e;
36891
+ if (body2.prev !== prev)
36892
+ errors.push(`entry ${i + 1}: chain broken`);
36893
+ if (argumentsHash({ at: body2.at, from: body2.from, to: body2.to, tokens: body2.tokens, ref: body2.ref, prev: body2.prev }) !== hash)
36894
+ errors.push(`entry ${i + 1}: changed after it was written`);
36895
+ if (e.signature && !verifyDocument(e).valid)
36896
+ errors.push(`entry ${i + 1}: signature not valid`);
36897
+ prev = hash;
36898
+ });
36899
+ return { ok: errors.length === 0, errors };
36900
+ }
36809
36901
  function walletBalance(path, account) {
36810
36902
  return readWallet(path).entries.reduce((b, e) => b + (e.to === account ? e.tokens : 0) - (e.from === account ? e.tokens : 0), 0);
36811
36903
  }
36812
- function topUp(path, account, tokens, ref = "top-up") {
36904
+ function topUp(path, account, tokens, ref = "top-up", key) {
36813
36905
  const w = readWallet(path);
36814
- w.entries.push({ at: nowIso(), from: PREPAID, to: account, tokens, ref });
36906
+ w.entries.push(sealEntry(w, { at: nowIso(), from: PREPAID, to: account, tokens, ref }, key));
36815
36907
  writeWallet(path, w);
36816
36908
  return walletBalance(path, account);
36817
36909
  }
36818
- function chargeCall(path, a, tool, ref) {
36819
- const cost = tokensFor(a, tool), bal = walletBalance(path, a.invoker.id);
36910
+ function chargeCall(path, a, tool, ref, key) {
36911
+ const cost = tokensFor(a, tool);
36912
+ if (!verifyWallet(path).ok)
36913
+ return { ok: false, tokens: cost, balance: 0 };
36914
+ const bal = walletBalance(path, a.invoker.id);
36820
36915
  if (bal < cost)
36821
36916
  return { ok: false, tokens: cost, balance: bal };
36822
36917
  const w = readWallet(path);
36823
- w.entries.push({ at: nowIso(), from: a.invoker.id, to: a.provider.id, tokens: cost, ref });
36918
+ w.entries.push(sealEntry(w, { at: nowIso(), from: a.invoker.id, to: a.provider.id, tokens: cost, ref }, key));
36824
36919
  writeWallet(path, w);
36825
36920
  return { ok: true, tokens: cost, balance: bal - cost };
36826
36921
  }
@@ -37039,6 +37134,197 @@ var init_agents = __esm({
37039
37134
  }
37040
37135
  });
37041
37136
 
37137
+ // packages/testkit-core/dist/trust.js
37138
+ import { createHmac } from "node:crypto";
37139
+ function signRevocation(m, key, reason) {
37140
+ return signDocument({ revocationFormat: "0.1", mandate: mandateDigest(m), agent: m.agent.id, at: (/* @__PURE__ */ new Date()).toISOString(), ...reason ? { reason } : {} }, key);
37141
+ }
37142
+ function validRevocation(r, m) {
37143
+ const x = r;
37144
+ if (!x || x.mandate !== mandateDigest(m))
37145
+ return false;
37146
+ if (!x.signature)
37147
+ return true;
37148
+ const v = verifyDocument(x);
37149
+ const op = m.operatorCountersign?.signature?.kid;
37150
+ return v.valid && (v.kid === m.owner.id || Boolean(op) && v.kid === op);
37151
+ }
37152
+ function makeCheckpoint(entries, key, log = "receipts") {
37153
+ const last = entries[entries.length - 1];
37154
+ return signDocument({ checkpointFormat: "0.1", log, seq: last?.seq ?? 0, head: last?.entryHash ?? "sha256:genesis", at: (/* @__PURE__ */ new Date()).toISOString() }, key);
37155
+ }
37156
+ function verifyAgainstCheckpoint(entries, cp, trustedSigners) {
37157
+ const v = verifyDocument(cpCore(cp));
37158
+ if (!v.valid)
37159
+ return { ok: false, reason: "checkpoint signature not valid" };
37160
+ if (trustedSigners?.length && !trustedSigners.includes(v.kid))
37161
+ return { ok: false, reason: "checkpoint signed by an untrusted key" };
37162
+ if (entries.length < cp.seq)
37163
+ return { ok: false, reason: `the log has ${entries.length} entries but the checkpoint covers ${cp.seq}: entries were deleted` };
37164
+ const head = cp.seq === 0 ? "sha256:genesis" : entries[cp.seq - 1]?.entryHash;
37165
+ if (head !== cp.head)
37166
+ return { ok: false, reason: `entry ${cp.seq} differs from the checkpoint: the log was rewritten` };
37167
+ return { ok: true };
37168
+ }
37169
+ function witnessCheckpoint(cp, entries, key) {
37170
+ const ok = verifyAgainstCheckpoint(entries, cp);
37171
+ if (!ok.ok)
37172
+ throw new Error(`Not witnessing: ${ok.reason}`);
37173
+ return { ...cp, witnesses: [...cp.witnesses ?? [], signDocument({ witnessFormat: "0.1", checkpoint: sha256Tag(canonicalize(cpCore(cp))), at: (/* @__PURE__ */ new Date()).toISOString() }, key)] };
37174
+ }
37175
+ function validWitnesses(cp) {
37176
+ const d = sha256Tag(canonicalize(cpCore(cp)));
37177
+ return (cp.witnesses ?? []).flatMap((w) => {
37178
+ const x = w;
37179
+ const v = verifyDocument(w);
37180
+ return v.valid && x.checkpoint === d ? [v.kid] : [];
37181
+ });
37182
+ }
37183
+ async function verifyDomain(domain, did, o = {}) {
37184
+ if (!/^[a-z0-9.-]{3,253}$/i.test(domain))
37185
+ return { verified: false };
37186
+ try {
37187
+ const rt = o.resolveTxt ?? (await import("node:dns/promises")).resolveTxt;
37188
+ const recs = await rt(`_saktum.${domain}`);
37189
+ if (recs.flat().some((t) => t.trim() === `saktum-did=${did}`))
37190
+ return { verified: true, method: "dns" };
37191
+ } catch {
37192
+ }
37193
+ try {
37194
+ const r = await (o.fetchImpl ?? fetch)(`https://${domain}/.well-known/saktum.json`);
37195
+ if (r.ok) {
37196
+ const j = await r.json();
37197
+ if (j.did === did || j.dids?.includes(did))
37198
+ return { verified: true, method: "well-known" };
37199
+ }
37200
+ } catch {
37201
+ }
37202
+ return { verified: false };
37203
+ }
37204
+ var keyedDigest, revokedInChain, approvalUsedInChain, cpCore;
37205
+ var init_trust = __esm({
37206
+ "packages/testkit-core/dist/trust.js"() {
37207
+ "use strict";
37208
+ init_dist();
37209
+ init_agentid();
37210
+ keyedDigest = (args, key) => "hmac-sha256:" + createHmac("sha256", key).update(canonicalize(JSON.parse(JSON.stringify(args ?? {})))).digest("hex");
37211
+ revokedInChain = (entries) => entries.some((e) => e.result.code === "revoked");
37212
+ approvalUsedInChain = (entries, rid) => entries.some((e) => /approved by/.test(String(e.receipt.reason ?? "")) && String(e.receipt.reason ?? "").includes(`(${rid})`));
37213
+ cpCore = (cp) => {
37214
+ const { witnesses: _w, ...rest } = cp;
37215
+ return rest;
37216
+ };
37217
+ }
37218
+ });
37219
+
37220
+ // packages/testkit-core/dist/webauthn.js
37221
+ import { createHash as createHash3, createPublicKey as createPublicKey2, verify as verify2 } from "node:crypto";
37222
+ function decodeCbor(buf) {
37223
+ let i = 0;
37224
+ const read = () => {
37225
+ const ib = buf[i++], mt = ib >> 5, ai = ib & 31;
37226
+ let len = ai;
37227
+ if (ai === 24)
37228
+ len = buf[i++];
37229
+ else if (ai === 25) {
37230
+ len = buf[i] << 8 | buf[i + 1];
37231
+ i += 2;
37232
+ } else if (ai === 26) {
37233
+ len = (buf[i] << 24 >>> 0) + (buf[i + 1] << 16) + (buf[i + 2] << 8) + buf[i + 3];
37234
+ i += 4;
37235
+ } else if (ai > 26)
37236
+ throw new Error("unsupported CBOR length");
37237
+ switch (mt) {
37238
+ case 0:
37239
+ return len;
37240
+ case 1:
37241
+ return -1 - len;
37242
+ case 2: {
37243
+ const v = buf.slice(i, i + len);
37244
+ i += len;
37245
+ return v;
37246
+ }
37247
+ case 3: {
37248
+ const v = new TextDecoder().decode(buf.slice(i, i + len));
37249
+ i += len;
37250
+ return v;
37251
+ }
37252
+ case 4: {
37253
+ const a = [];
37254
+ for (let k = 0; k < len; k++)
37255
+ a.push(read());
37256
+ return a;
37257
+ }
37258
+ case 5: {
37259
+ const m = /* @__PURE__ */ new Map();
37260
+ for (let k = 0; k < len; k++) {
37261
+ const key = read();
37262
+ m.set(key, read());
37263
+ }
37264
+ return m;
37265
+ }
37266
+ case 7:
37267
+ return ai === 20 ? false : ai === 21 ? true : null;
37268
+ default:
37269
+ throw new Error("unsupported CBOR type");
37270
+ }
37271
+ };
37272
+ const value = read();
37273
+ return { value, length: i };
37274
+ }
37275
+ function coseToJwk(m) {
37276
+ const kty = m.get(1), alg = m.get(3);
37277
+ if (kty === 2 && alg === -7)
37278
+ return { kty: "EC", crv: "P-256", x: b64u3(m.get(-2)), y: b64u3(m.get(-3)) };
37279
+ if (kty === 1 && alg === -8)
37280
+ return { kty: "OKP", crv: "Ed25519", x: b64u3(m.get(-2)) };
37281
+ throw new Error("unsupported passkey algorithm (ES256 and EdDSA are supported)");
37282
+ }
37283
+ function checkClientData(clientDataJSON, type, challenge, origin) {
37284
+ const c = JSON.parse(Buffer.from(clientDataJSON, "base64url").toString("utf8"));
37285
+ if (c.type !== type)
37286
+ throw new Error("wrong client data type");
37287
+ if (c.challenge !== b64u3(Buffer.from(challenge)))
37288
+ throw new Error("challenge does not match");
37289
+ if (c.origin !== origin)
37290
+ throw new Error("origin does not match");
37291
+ }
37292
+ function verifyPasskeyRegistration(r, expected) {
37293
+ checkClientData(r.clientDataJSON, "webauthn.create", expected.challenge, expected.origin);
37294
+ const att = decodeCbor(Buffer.from(r.attestationObject, "base64url")).value;
37295
+ const ad = att.get("authData");
37296
+ if (!Buffer.from(ad.slice(0, 32)).equals(sha256(expected.rpId)))
37297
+ throw new Error("relying party does not match");
37298
+ const flags = ad[32];
37299
+ if (!(flags & 1))
37300
+ throw new Error("user presence not confirmed");
37301
+ if (!(flags & 64))
37302
+ throw new Error("no credential data");
37303
+ const idLen = ad[53] << 8 | ad[54];
37304
+ const credentialId = b64u3(ad.slice(55, 55 + idLen));
37305
+ const jwk = coseToJwk(decodeCbor(ad.slice(55 + idLen)).value);
37306
+ return { credentialId, jwk };
37307
+ }
37308
+ function verifyPasskeyAssertion(a, jwk, expected) {
37309
+ checkClientData(a.clientDataJSON, "webauthn.get", expected.challenge, expected.origin);
37310
+ const ad = Buffer.from(a.authenticatorData, "base64url");
37311
+ if (!ad.slice(0, 32).equals(sha256(expected.rpId)))
37312
+ throw new Error("relying party does not match");
37313
+ if (!(ad[32] & 1))
37314
+ throw new Error("user presence not confirmed");
37315
+ const data = Buffer.concat([ad, sha256(Buffer.from(a.clientDataJSON, "base64url"))]);
37316
+ const key = createPublicKey2({ key: jwk, format: "jwk" });
37317
+ return jwk.kty === "OKP" ? verify2(null, data, key, Buffer.from(a.signature, "base64url")) : verify2("sha256", data, key, Buffer.from(a.signature, "base64url"));
37318
+ }
37319
+ var sha256, b64u3;
37320
+ var init_webauthn = __esm({
37321
+ "packages/testkit-core/dist/webauthn.js"() {
37322
+ "use strict";
37323
+ sha256 = (b) => createHash3("sha256").update(b).digest();
37324
+ b64u3 = (b) => Buffer.from(b).toString("base64url");
37325
+ }
37326
+ });
37327
+
37042
37328
  // packages/testkit-core/dist/index.js
37043
37329
  var dist_exports = {};
37044
37330
  __export(dist_exports, {
@@ -37085,9 +37371,11 @@ __export(dist_exports, {
37085
37371
  allowlistFromLedger: () => allowlistFromLedger,
37086
37372
  analyseSetup: () => analyseSetup,
37087
37373
  analysers: () => analysers,
37374
+ appendStatement: () => appendStatement,
37088
37375
  appendTestCase: () => appendTestCase,
37089
37376
  appendToLedger: () => appendToLedger,
37090
37377
  approvalRequestId: () => approvalRequestId,
37378
+ approvalUsedInChain: () => approvalUsedInChain,
37091
37379
  approveAction: () => approveAction,
37092
37380
  argumentsHash: () => argumentsHash,
37093
37381
  attestationToCredential: () => attestationToCredential,
@@ -37104,6 +37392,7 @@ __export(dist_exports, {
37104
37392
  checkMandate: () => checkMandate,
37105
37393
  checkNeedsSession: () => checkNeedsSession,
37106
37394
  checkOperator: () => checkOperator,
37395
+ checkStatement: () => checkStatement,
37107
37396
  clientCompatibility: () => clientCompatibility,
37108
37397
  compileContract: () => compileContract,
37109
37398
  compileUntrustedSchema: () => compileUntrustedSchema,
@@ -37135,8 +37424,10 @@ __export(dist_exports, {
37135
37424
  invalidArgProblems: () => invalidArgProblems,
37136
37425
  invalidArgsFor: () => invalidArgsFor,
37137
37426
  issueCredential: () => issueCredential,
37427
+ keyedDigest: () => keyedDigest,
37138
37428
  kpis: () => kpis,
37139
37429
  leakageAnalysers: () => leakageAnalysers,
37430
+ ledgerStatus: () => ledgerStatus,
37140
37431
  lintPaths: () => lintPaths,
37141
37432
  lintSarif: () => lintSarif,
37142
37433
  lintSource: () => lintSource,
@@ -37145,6 +37436,7 @@ __export(dist_exports, {
37145
37436
  loadPack: () => loadPack,
37146
37437
  loadPackDir: () => loadPackDir,
37147
37438
  loadPackText: () => loadPackText,
37439
+ makeCheckpoint: () => makeCheckpoint,
37148
37440
  mandateDecision: () => mandateDecision,
37149
37441
  mandateDigest: () => mandateDigest,
37150
37442
  maxDepth: () => maxDepth,
@@ -37172,6 +37464,7 @@ __export(dist_exports, {
37172
37464
  resultProblems: () => resultProblems,
37173
37465
  revocationOf: () => revocationOf,
37174
37466
  revokeMandate: () => revokeMandate,
37467
+ revokedInChain: () => revokedInChain,
37175
37468
  riskTier: () => riskTier,
37176
37469
  roiEstimate: () => roiEstimate,
37177
37470
  runCheck: () => runCheck,
@@ -37186,6 +37479,7 @@ __export(dist_exports, {
37186
37479
  semanticValues: () => semanticValues,
37187
37480
  signCredentialJwt: () => signCredentialJwt,
37188
37481
  signReceipt: () => signReceipt,
37482
+ signRevocation: () => signRevocation,
37189
37483
  sourceFiles: () => sourceFiles,
37190
37484
  splitCommand: () => splitCommand,
37191
37485
  subjectFromResult: () => subjectFromResult,
@@ -37199,15 +37493,23 @@ __export(dist_exports, {
37199
37493
  topUp: () => topUp,
37200
37494
  trustStatement: () => trustStatement,
37201
37495
  usageStatement: () => usageStatement,
37496
+ validRevocation: () => validRevocation,
37497
+ validWitnesses: () => validWitnesses,
37498
+ verifyAgainstCheckpoint: () => verifyAgainstCheckpoint,
37202
37499
  verifyAgreement: () => verifyAgreement,
37203
37500
  verifyChain: () => verifyChain,
37204
37501
  verifyCredentialJwt: () => verifyCredentialJwt,
37502
+ verifyDomain: () => verifyDomain,
37205
37503
  verifyLedger: () => verifyLedger,
37504
+ verifyPasskeyAssertion: () => verifyPasskeyAssertion,
37505
+ verifyPasskeyRegistration: () => verifyPasskeyRegistration,
37206
37506
  verifyReceipt: () => verifyReceipt,
37207
37507
  verifyReceiptLog: () => verifyReceiptLog,
37508
+ verifyWallet: () => verifyWallet,
37208
37509
  walletBalance: () => walletBalance,
37209
37510
  watchAllowlist: () => watchAllowlist,
37210
- wellKnownUrls: () => wellKnownUrls
37511
+ wellKnownUrls: () => wellKnownUrls,
37512
+ witnessCheckpoint: () => witnessCheckpoint
37211
37513
  });
37212
37514
  var init_dist4 = __esm({
37213
37515
  "packages/testkit-core/dist/index.js"() {
@@ -37244,6 +37546,8 @@ var init_dist4 = __esm({
37244
37546
  init_market();
37245
37547
  init_crosswalk();
37246
37548
  init_agents();
37549
+ init_trust();
37550
+ init_webauthn();
37247
37551
  }
37248
37552
  });
37249
37553
 
@@ -37899,6 +38203,7 @@ var proxy_exports = {};
37899
38203
  __export(proxy_exports, {
37900
38204
  runProxy: () => runProxy
37901
38205
  });
38206
+ import { createHmac as createHmac2 } from "node:crypto";
37902
38207
  import { spawn as spawn3 } from "node:child_process";
37903
38208
  import { appendFileSync, existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync7 } from "node:fs";
37904
38209
  import { dirname as dirname3 } from "node:path";
@@ -37923,6 +38228,25 @@ async function runProxy(o) {
37923
38228
  const bare = !/[\\/]/.test(o.command);
37924
38229
  const child = spawn3(o.command, o.args, { stdio: ["pipe", "pipe", "inherit"], shell: process.platform === "win32" && (bare || /\.(cmd|bat)$/i.test(o.command)) });
37925
38230
  let service = o.command.split(/[\\/]/).pop() ?? o.command, version2;
38231
+ let remoteRevoked = false, toolsChanged = false;
38232
+ const pollRevocations = async () => {
38233
+ if (!o.revocationsUrl || !o.mandate)
38234
+ return;
38235
+ try {
38236
+ const r = await fetch(o.revocationsUrl);
38237
+ if (r.ok) {
38238
+ const j = await r.json();
38239
+ const list = Array.isArray(j) ? j : j.revoked ?? [];
38240
+ if (list.some((e) => validRevocation(e, o.mandate)))
38241
+ remoteRevoked = true;
38242
+ }
38243
+ } catch {
38244
+ }
38245
+ };
38246
+ await pollRevocations();
38247
+ if (o.revocationsUrl)
38248
+ setInterval(pollRevocations, 5 * 6e4).unref();
38249
+ const digest = (args) => o.digestKey ? keyedDigest(args, o.digestKey) : argumentsHash(args);
37926
38250
  const annotations = /* @__PURE__ */ new Map();
37927
38251
  const toolDefs = /* @__PURE__ */ new Map();
37928
38252
  const pendingKinds = /* @__PURE__ */ new Map();
@@ -37954,6 +38278,12 @@ async function runProxy(o) {
37954
38278
  appendFileSync(o.receiptsPath, JSON.stringify(entry) + "\n");
37955
38279
  last = entry;
37956
38280
  history.push(entry);
38281
+ if (o.checkpointEvery && o.checkpointFile && entry.seq % o.checkpointEvery === 0) {
38282
+ try {
38283
+ appendFileSync(o.checkpointFile, JSON.stringify(makeCheckpoint(history, o.agentKey)) + "\n");
38284
+ } catch {
38285
+ }
38286
+ }
37957
38287
  };
37958
38288
  createInterface({ input: process.stdin }).on("line", (line) => {
37959
38289
  let msg;
@@ -37968,68 +38298,74 @@ async function runProxy(o) {
37968
38298
  if (msg.method === "tools/call" && msg.id !== void 0) {
37969
38299
  const tool = String(msg.params?.name ?? "");
37970
38300
  const args = msg.params?.arguments ?? {};
37971
- const argsHash = argumentsHash(args);
38301
+ const argsHash = digest(args);
37972
38302
  const ann = annotations.get(tool);
37973
38303
  const def = toolDefs.get(tool);
37974
38304
  const isMoney = def ? capabilityProfile([def]).capabilities.some((c) => c.capability === "money") : false;
37975
38305
  const values = Object.fromEntries([...governed].filter((k) => args[k] !== void 0 && (typeof args[k] === "number" || typeof args[k] === "string")).map((k) => [k, args[k]]));
37976
- const rev = o.mandate ? revocationOf(o.mandate, o.revocationsPath) : void 0;
37977
- let d = rev ? { allow: false, code: "revoked", reason: `the mandate was revoked on ${rev.at.slice(0, 10)}${rev.reason ? ` (${rev.reason})` : ""}` } : o.mandate ? decideCall(o.mandate, { tool, server: service, args, annotations: ann, isMoney, usage: usage() }) : { allow: true, code: "ok", reason: "no mandate: observed" };
38306
+ let d;
37978
38307
  let rationale;
37979
- if (d.allow && o.mandate && hasIntent(o.mandate)) {
37980
- const di = decideIntent(o.mandate, def ?? { name: tool }, args, { server: service });
37981
- rationale = di.rationale;
37982
- for (const [k, val] of Object.entries(di.values))
37983
- if (typeof val === "number" || typeof val === "string" || typeof val === "boolean")
37984
- values[k] = val;
37985
- if (!di.allow)
37986
- d = { allow: false, code: di.code, reason: di.reason };
37987
- else if (di.reason !== "within the mandate")
37988
- d = { allow: true, code: "ok", reason: di.reason };
37989
- }
37990
- if (!d.allow && d.code === "approval-needed" && o.mandate) {
37991
- const rid = approvalRequestId(o.mandate, tool, args);
37992
- const ap = consumeApproval(o.mandate, rid, o.approvalsPath);
37993
- if (ap.ok)
37994
- d = { allow: true, code: "ok", reason: `approved by ${ap.by} (${rid}), after: ${d.reason}` };
37995
- else {
37996
- d = { ...d, reason: `${d.reason} [approval request ${rid}]` };
37997
- try {
37998
- recordPending(o.approvalsPath ?? DEFAULT_APPROVALS(), { id: rid, tool, reason: d.reason, agent: o.mandate.agent.name });
37999
- } catch {
38000
- }
38001
- if (o.approvalWebhook) {
38002
- const link = o.approvalUrl ? `${o.approvalUrl}${o.approvalUrl.includes("?") ? "&" : "?"}id=${rid}` : "";
38003
- const text2 = `Approval needed: ${o.mandate.agent.name} wants to run ${tool}. ${d.reason.replace(/ \[approval request [^\]]+\]/, "")}. Request ${rid}. ${link ? `Approve: ${link}` : `Approve with: npx saktum agent approve ${rid} --mandate <mandate>`}`;
38004
- fetch(o.approvalWebhook, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ text: text2, requestId: rid, tool, agent: o.mandate.agent.name, ...link ? { approveUrl: link } : {} }) }).catch(() => void 0);
38308
+ let metering;
38309
+ try {
38310
+ const rev = o.mandate ? revocationOf(o.mandate, o.revocationsPath) : void 0;
38311
+ d = rev ? { allow: false, code: "revoked", reason: `the mandate was revoked on ${rev.at.slice(0, 10)}${rev.reason ? ` (${rev.reason})` : ""}` } : o.mandate && (remoteRevoked || revokedInChain(history)) ? { allow: false, code: "revoked", reason: "the mandate was revoked (recorded in the ledger or in this receipt chain)" } : toolsChanged ? { allow: false, code: "tools-changed", reason: "the server's tools differ from the pinned, approved fingerprint" } : o.mandate ? decideCall(o.mandate, { tool, server: service, args, annotations: ann, isMoney, usage: usage() }) : { allow: true, code: "ok", reason: "no mandate: observed" };
38312
+ if (d.allow && o.mandate && hasIntent(o.mandate)) {
38313
+ const di = decideIntent(o.mandate, def ?? { name: tool }, args, { server: service });
38314
+ rationale = di.rationale;
38315
+ for (const [k, val] of Object.entries(di.values))
38316
+ if (typeof val === "number" || typeof val === "string" || typeof val === "boolean")
38317
+ values[k] = val;
38318
+ if (!di.allow)
38319
+ d = { allow: false, code: di.code, reason: di.reason };
38320
+ else if (di.reason !== "within the mandate")
38321
+ d = { allow: true, code: "ok", reason: di.reason };
38322
+ }
38323
+ if (!d.allow && d.code === "approval-needed" && o.mandate) {
38324
+ const rid = approvalRequestId(o.mandate, tool, args);
38325
+ const ap = approvalUsedInChain(history, rid) ? { ok: false } : consumeApproval(o.mandate, rid, o.approvalsPath);
38326
+ if (ap.ok)
38327
+ d = { allow: true, code: "ok", reason: `approved by ${ap.by} (${rid}), after: ${d.reason}` };
38328
+ else {
38329
+ d = { ...d, reason: `${d.reason} [approval request ${rid}]` };
38330
+ try {
38331
+ recordPending(o.approvalsPath ?? DEFAULT_APPROVALS(), { id: rid, tool, reason: d.reason, agent: o.mandate.agent.name });
38332
+ } catch {
38333
+ }
38334
+ if (o.approvalWebhook) {
38335
+ const t = o.approvalSecret ? createHmac2("sha256", o.approvalSecret).update(rid).digest("hex").slice(0, 32) : "";
38336
+ const link = o.approvalUrl ? `${o.approvalUrl}${o.approvalUrl.includes("?") ? "&" : "?"}id=${rid}${t ? `&t=${t}` : ""}` : "";
38337
+ const text2 = `Approval needed: ${o.mandate.agent.name} wants to run ${tool}. ${d.reason.replace(/ \[approval request [^\]]+\]/, "")}. Request ${rid}. ${link ? `Approve: ${link}` : `Approve with: npx saktum agent approve ${rid} --mandate <mandate>`}`;
38338
+ fetch(o.approvalWebhook, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ text: text2, requestId: rid, tool, agent: o.mandate.agent.name, ...link ? { approveUrl: link } : {} }) }).catch(() => void 0);
38339
+ }
38005
38340
  }
38006
38341
  }
38342
+ if (d.allow && o.credential) {
38343
+ const vc = verifyChain(o.credential, { revoked: o.revokedCredentials });
38344
+ const root = [...o.credential.chain ?? [], o.credential][0].subject.id;
38345
+ if (!vc.valid)
38346
+ d = { allow: false, code: "identity-chain", reason: `the agent's accountability chain is broken: ${vc.reason}` };
38347
+ else if (o.agreement && root !== o.agreement.invoker.id)
38348
+ d = { allow: false, code: "identity-chain", reason: "the agent's organisation is not the party to the agreement" };
38349
+ }
38350
+ if (d.allow && o.agreement) {
38351
+ const va = verifyAgreement(o.agreement);
38352
+ if (!va.valid)
38353
+ d = { allow: false, code: "no-valid-agreement", reason: `no valid agreement with the provider: ${va.reason}` };
38354
+ else if (o.agreement.scope.tools && !o.agreement.scope.tools.includes(tool))
38355
+ d = { allow: false, code: "outside-agreement", reason: `${tool} is outside the agreement ${o.agreement.id}` };
38356
+ else if (o.walletPath) {
38357
+ const ch = chargeCall(o.walletPath, o.agreement, tool, `${o.agreement.id}:${tool}`, o.agentKey);
38358
+ if (!ch.ok)
38359
+ d = { allow: false, code: "insufficient-credit", reason: `${tool} costs ${ch.tokens} tokens; the prepaid balance is ${ch.balance}` };
38360
+ else
38361
+ metering = { agreement: o.agreement.id, tokens: ch.tokens, balance: ch.balance };
38362
+ } else
38363
+ metering = { agreement: o.agreement.id, tokens: o.agreement.rates.perTool?.[tool] ?? o.agreement.rates.perCall, balance: -1 };
38364
+ }
38365
+ } catch (err) {
38366
+ d = { allow: false, code: "error-fail-closed", reason: `the decision could not be completed, so the call is refused (${String(err.message).slice(0, 120)})` };
38007
38367
  }
38008
- if (d.allow && o.credential) {
38009
- const vc = verifyChain(o.credential, { revoked: o.revokedCredentials });
38010
- const root = [...o.credential.chain ?? [], o.credential][0].subject.id;
38011
- if (!vc.valid)
38012
- d = { allow: false, code: "identity-chain", reason: `the agent's accountability chain is broken: ${vc.reason}` };
38013
- else if (o.agreement && root !== o.agreement.invoker.id)
38014
- d = { allow: false, code: "identity-chain", reason: "the agent's organisation is not the party to the agreement" };
38015
- }
38016
- let metering;
38017
- if (d.allow && o.agreement) {
38018
- const va = verifyAgreement(o.agreement);
38019
- if (!va.valid)
38020
- d = { allow: false, code: "no-valid-agreement", reason: `no valid agreement with the provider: ${va.reason}` };
38021
- else if (o.agreement.scope.tools && !o.agreement.scope.tools.includes(tool))
38022
- d = { allow: false, code: "outside-agreement", reason: `${tool} is outside the agreement ${o.agreement.id}` };
38023
- else if (o.walletPath) {
38024
- const ch = chargeCall(o.walletPath, o.agreement, tool, `${o.agreement.id}:${tool}`);
38025
- if (!ch.ok)
38026
- d = { allow: false, code: "insufficient-credit", reason: `${tool} costs ${ch.tokens} tokens; the prepaid balance is ${ch.balance}` };
38027
- else
38028
- metering = { agreement: o.agreement.id, tokens: ch.tokens, balance: ch.balance };
38029
- } else
38030
- metering = { agreement: o.agreement.id, tokens: o.agreement.rates.perTool?.[tool] ?? o.agreement.rates.perCall, balance: -1 };
38031
- }
38032
- if (!d.allow && o.enforce) {
38368
+ if (!d.allow && (o.enforce || d.code === "error-fail-closed")) {
38033
38369
  const hint = d.code === "revoked" ? " The agent's owner stopped it; do not retry." : d.code === "approval-needed" ? " Ask your user to approve it (saktum agent approve with the request id), then retry the same action once." : d.code === "notify-only" ? " Tell your user what you found instead." : " Ask the agent's owner to change the mandate if this action is needed.";
38034
38370
  process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: msg.id, result: { isError: true, content: [{ type: "text", text: `Blocked by Saktum (${d.code}): ${d.reason}.${hint}` }] } }) + "\n");
38035
38371
  record2(tool, argsHash, "deny", d.reason, { status: "blocked", destructive: isDestructive(ann), code: d.code, values, ...rationale ? { rationale } : {} });
@@ -38075,6 +38411,12 @@ async function runProxy(o) {
38075
38411
  annotations.set(t.name, t.annotations);
38076
38412
  toolDefs.set(t.name, def);
38077
38413
  }
38414
+ if (o.pin) {
38415
+ const fp = sha256Tag(canonicalize([...msg.result.tools].sort((a, b) => String(a.name).localeCompare(String(b.name)))));
38416
+ toolsChanged = fp !== o.pin;
38417
+ if (toolsChanged)
38418
+ o.log?.(`tools changed: ${fp} differs from the pinned ${o.pin}`);
38419
+ }
38078
38420
  pendingKinds.delete(k);
38079
38421
  }
38080
38422
  const c = calls.get(k);
@@ -38094,6 +38436,7 @@ async function runProxy(o) {
38094
38436
  var init_proxy = __esm({
38095
38437
  "packages/cli/dist/proxy.js"() {
38096
38438
  "use strict";
38439
+ init_dist();
38097
38440
  init_dist4();
38098
38441
  }
38099
38442
  });
@@ -39738,6 +40081,15 @@ What would you like to do?
39738
40081
  All commands: npx saktum --help \xB7 Guide: https://github.com/soodhere/saktum-check
39739
40082
  `;
39740
40083
  var bundledPacks = fileURLToPath2(new URL("../../../packs/", import.meta.url));
40084
+ var secretFrom = (spec) => {
40085
+ if (spec.startsWith("env:")) {
40086
+ const v = process.env[spec.slice(4)];
40087
+ if (!v)
40088
+ throw new Error(`Environment variable ${spec.slice(4)} is not set.`);
40089
+ return v;
40090
+ }
40091
+ return spec;
40092
+ };
39741
40093
  var collect = (v, acc) => [...acc, v];
39742
40094
  var parseHeaders = (hs) => Object.fromEntries(hs.map((h) => {
39743
40095
  const i = h.indexOf(":");
@@ -40143,15 +40495,15 @@ ${r.errors.slice(0, 10).map((e) => ` ${sanitizeText(e, 200)}`).join("\n")}
40143
40495
  const latest = /* @__PURE__ */ new Map();
40144
40496
  for (const e of entries)
40145
40497
  latest.set(e.subject.server, e);
40146
- for (const e of latest.values())
40498
+ for (const e of [...latest.values()].filter((x) => x.attestation))
40147
40499
  writeFileSync5(`${o.out}/${passportSlug(e.subject.server)}.html`, renderLedgerPassport(e));
40148
- writeFileSync5(`${o.out}/index.html`, renderPassportGallery(entries));
40500
+ writeFileSync5(`${o.out}/index.html`, renderPassportGallery(entries.filter((x) => x.attestation)));
40149
40501
  process.stdout.write(`Wrote ${latest.size} passport page(s) and the gallery to ${sanitizeText(o.out)}.
40150
40502
  `);
40151
40503
  });
40152
40504
  ledger.command("append").description("Append a signed attestation to a ledger file after verifying it (used by the ledger bot)").argument("<input>", "attestation JSON, or a text file (such as an issue body) containing it").requiredOption("--ledger <file>", "ledger file to append to").option("--issue <n>", "issue number that requested it").action((input, o) => {
40153
40505
  const att = extractJson(readFileSync10(input, "utf8"));
40154
- const { text: text2, entry } = appendToLedger(existsSync7(o.ledger) ? readFileSync10(o.ledger, "utf8") : "", att, { via: "saktum-index issue", ...o.issue ? { issue: Number(o.issue) } : {} });
40506
+ const { text: text2, entry } = (att?.statementFormat ? appendStatement : appendToLedger)(existsSync7(o.ledger) ? readFileSync10(o.ledger, "utf8") : "", att, { via: "saktum-index issue", ...o.issue ? { issue: Number(o.issue) } : {} });
40155
40507
  writeFileSync5(o.ledger, text2);
40156
40508
  process.stdout.write(`Recorded entry #${entry.seq} for ${sanitizeText(entry.subject.server, 80)} (signed by ${entry.signer}); entry hash ${entry.entryHash}.
40157
40509
  `);
@@ -40247,13 +40599,16 @@ Wrote ${sanitizeText(o.out)} and the agent key ${sanitizeText(o.agentKey)} (keep
40247
40599
  process.stdout.write(`Approved ${sanitizeText(rid, 40)} for ${sanitizeText(m.agent.name, 80)}, valid until ${a.expires}, once. The agent can now retry exactly that action.
40248
40600
  `);
40249
40601
  });
40250
- agent.command("revoke").description("Stop an agent now: every Saktum proxy on this machine refuses calls under this mandate").argument("<mandate>", "mandate file").option("--reason <text>", "why").action((f, o) => {
40602
+ agent.command("revoke").description("Stop an agent now: every Saktum proxy on this machine refuses calls under this mandate").argument("<mandate>", "mandate file").option("--reason <text>", "why").option("--key <spec>", "sign the revocation as the owner or operator (file, env:VAR, keychain:NAME or exec:PROGRAM)").option("--out <file>", "also write the signed revocation (for a remote list or the ledger)").action((f, o) => {
40251
40603
  const m = JSON.parse(readFileSync10(f, "utf8"));
40252
- const r = revokeMandate(m, o.reason);
40604
+ const key = o.key ? loadOrCreateKey(o.key) : void 0;
40605
+ const r = revokeMandate(m, o.reason, void 0, key);
40606
+ if (o.out && key)
40607
+ writeFileSync5(o.out, JSON.stringify(signRevocation(m, key, o.reason), null, 2) + "\n");
40253
40608
  process.stdout.write(`Revoked the mandate for ${sanitizeText(m.agent.name, 80)} at ${r.at}. Its calls are now refused (code: revoked).
40254
40609
  `);
40255
40610
  });
40256
- program2.command("proxy").description("Put Saktum between an agent and a local MCP server: signed receipts for every tool call, and the agent's mandate observed or enforced (preview)").argument("<command...>", "the server command, after --").option("--mandate <file>", "the agent's mandate (from saktum agent create)").option("--agent-key <file>", "the agent's key, which signs receipts", "agent-key.json").option("--enforce", "block calls outside the mandate (default: observe and record only)", false).option("--receipts <file>", "receipt log (append-only, hash-chained)").option("--revocations <file>", "revocation list to honour (default ~/.saktum/revocations.json)").option("--approvals <file>", "signed approvals to honour (default ~/.saktum/approvals.json)").option("--credential <file>", "the agent's credential: its accountability chain is verified on every call").option("--revoked-credentials <file>", "JSON list of revoked credential ids").option("--agreement <file>", "the signed agreement with the provider: calls outside it are refused and every call is metered").option("--wallet <file>", "prepaid token wallet charged per call under the agreement").option("--approval-webhook <url>", "post approval requests to this webhook (Slack, Teams or an email relay)").option("--approval-url <url>", "base link of saktum approvals serve, included in approval requests").option("--bindings <file>", "bindings override: JSON { tool: { action, bindings: { arg: field } } } for tools that declare nothing").action(async (parts, o) => {
40611
+ program2.command("proxy").description("Put Saktum between an agent and a local MCP server: signed receipts for every tool call, and the agent's mandate observed or enforced (preview)").argument("<command...>", "the server command, after --").option("--mandate <file>", "the agent's mandate (from saktum agent create)").option("--agent-key <file>", "the agent's key, which signs receipts", "agent-key.json").option("--enforce", "block calls outside the mandate (default: observe and record only)", false).option("--receipts <file>", "receipt log (append-only, hash-chained)").option("--revocations <file>", "revocation list to honour (default ~/.saktum/revocations.json)").option("--approvals <file>", "signed approvals to honour (default ~/.saktum/approvals.json)").option("--credential <file>", "the agent's credential: its accountability chain is verified on every call").option("--revoked-credentials <file>", "JSON list of revoked credential ids").option("--agreement <file>", "the signed agreement with the provider: calls outside it are refused and every call is metered").option("--wallet <file>", "prepaid token wallet charged per call under the agreement").option("--approval-webhook <url>", "post approval requests to this webhook (Slack, Teams or an email relay)").option("--approval-url <url>", "base link of saktum approvals serve, included in approval requests").option("--bindings <file>", "bindings override: JSON { tool: { action, bindings: { arg: field } } } for tools that declare nothing").option("--revocations-url <url>", "a remote revocation list (for example in the ledger) the agent cannot edit").option("--digest-key <spec>", "keyed digests of arguments in receipts: env:VAR (recommended)").option("--pin <fingerprint>", "refuse calls if the server's tools differ from this approved fingerprint (sha256:...)").option("--checkpoint-every <n>", "write a signed checkpoint every n receipts").option("--checkpoint-file <file>", "where checkpoints go (keep it off the agent's machine or ship it)").option("--approval-secret <spec>", "secret shared with approvals serve for single-use, per-request links: env:VAR").action(async (parts, o) => {
40257
40612
  const { homedir: homedir2 } = await import("node:os");
40258
40613
  const { join: join7 } = await import("node:path");
40259
40614
  let mandate;
@@ -40283,6 +40638,11 @@ Wrote ${sanitizeText(o.out)} and the agent key ${sanitizeText(o.agentKey)} (keep
40283
40638
  ...o.approvalWebhook ? { approvalWebhook: o.approvalWebhook } : {},
40284
40639
  ...o.approvalUrl ? { approvalUrl: o.approvalUrl } : {},
40285
40640
  ...o.bindings ? { bindingsOverride: JSON.parse(readFileSync10(o.bindings, "utf8")) } : {},
40641
+ ...o.revocationsUrl ? { revocationsUrl: o.revocationsUrl } : {},
40642
+ ...o.digestKey ? { digestKey: secretFrom(o.digestKey) } : {},
40643
+ ...o.pin ? { pin: o.pin } : {},
40644
+ ...o.checkpointEvery && o.checkpointFile ? { checkpointEvery: Number(o.checkpointEvery), checkpointFile: o.checkpointFile } : {},
40645
+ ...o.approvalSecret ? { approvalSecret: secretFrom(o.approvalSecret) } : {},
40286
40646
  log: (m) => process.stderr.write(`saktum: ${m}
40287
40647
  `)
40288
40648
  });
@@ -40326,6 +40686,14 @@ ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
40326
40686
  `);
40327
40687
  exitCode = logs.every((l) => l.verified) ? 0 : 1;
40328
40688
  });
40689
+ receipts.command("checkpoint").description("Write a signed checkpoint of a receipt log (keep it elsewhere, so deletions are detectable)").argument("[file]", "receipt log").option("--key <spec>", "signing key").option("--out <file>", "checkpoint file", "saktum-checkpoint.json").action(async (f, o) => {
40690
+ const { homedir: homedir2 } = await import("node:os");
40691
+ const { join: join7 } = await import("node:path");
40692
+ const cp = makeCheckpoint(parseReceiptLog(readFileSync10(f ?? join7(homedir2(), ".saktum", "receipts.jsonl"), "utf8")), loadOrCreateKey(o.key));
40693
+ writeFileSync5(o.out, JSON.stringify(cp, null, 2) + "\n");
40694
+ process.stdout.write(`Checkpoint at receipt ${cp.seq} (${cp.head.slice(0, 20)}...) written to ${sanitizeText(o.out)}.
40695
+ `);
40696
+ });
40329
40697
  receipts.command("summary").description("The path, not the answer: which tools were called, how often, in what order, retries, denials, destructive actions").argument("[file]", "receipt log").option("--json", "print JSON", false).action(async (f, o) => {
40330
40698
  const { homedir: homedir2 } = await import("node:os");
40331
40699
  const { join: join7 } = await import("node:path");
@@ -40641,11 +41009,19 @@ ${" ".repeat(36)}${i.evidence}${i.commands.length ? ` (${i.commands.join("; ")})
40641
41009
  ${DISCLAIMER}
40642
41010
  `);
40643
41011
  });
40644
- program2.command("bridge").description("Present a remote MCP server (Streamable HTTP) as a local one, so saktum proxy can govern it: saktum proxy ... -- saktum bridge https://host/mcp").argument("<url>", "the remote server's URL").option("--header <Name: value>", "HTTP header to send, for example Authorization (repeatable; never logged)", collect, []).action(async (url2, o) => {
41012
+ program2.command("bridge").description("Present a remote MCP server (Streamable HTTP) as a local one, so saktum proxy can govern it: saktum proxy ... -- saktum bridge https://host/mcp").argument("<url>", "the remote server's URL").option("--header <Name: value>", "HTTP header to send (repeatable; never logged). Prefer --header-env for secrets", collect, []).option("--header-env <Name=VAR>", "HTTP header whose value comes from an environment variable, e.g. Authorization=MCP_TOKEN (keeps secrets out of the process list)", collect, []).action(async (url2, o) => {
40645
41013
  if (!/^https?:\/\//.test(url2))
40646
41014
  throw new Error("Give the remote server's http(s) URL.");
41015
+ const h = parseHeaders(o.header);
41016
+ for (const x of o.headerEnv) {
41017
+ const i = x.indexOf("=");
41018
+ const v = process.env[x.slice(i + 1)];
41019
+ if (i < 1 || v === void 0)
41020
+ throw new Error(`--header-env ${x}: use Name=VAR with VAR set`);
41021
+ h[x.slice(0, i)] = v;
41022
+ }
40647
41023
  const { runBridge: runBridge2 } = await Promise.resolve().then(() => (init_bridge(), bridge_exports));
40648
- exitCode = await runBridge2(url2, parseHeaders(o.header));
41024
+ exitCode = await runBridge2(url2, h);
40649
41025
  });
40650
41026
  const approvals = program2.command("approvals").description("Approvals by link (v0.10)");
40651
41027
  approvals.command("list").option("--approvals <file>", "approvals file").action((o) => {
@@ -40656,50 +41032,112 @@ ${DISCLAIMER}
40656
41032
  process.stdout.write(`${p.length} waiting.
40657
41033
  `);
40658
41034
  });
40659
- approvals.command("serve").description("A local page where the mandate's owner approves exactly one pending action with their key").requiredOption("--mandate <file>").option("--key <path>", "the owner's key (file, env:VAR or keychain:NAME)").option("--approvals <file>", "approvals file shared with the proxy").option("--port <n>", "port", "8787").option("--host <host>", "interface to listen on", "127.0.0.1").option("--minutes <n>", "approval validity", "60").action(async (o) => {
41035
+ approvals.command("serve").description("A local page where the mandate's owner approves exactly one pending action (optionally with a passkey)").requiredOption("--mandate <file>").option("--key <spec>", "the owner's key (file, env:VAR, keychain:NAME or exec:PROGRAM)").option("--approvals <file>", "approvals file shared with the proxy").option("--port <n>", "port", "8787").option("--host <host>", "interface (localhost is required for passkeys)", "localhost").option("--minutes <n>", "approval validity", "60").option("--secret <spec>", "secret shared with the proxy (--approval-secret) for single-use, per-request links: env:VAR").option("--passkey", "require a passkey (Face ID, Touch ID, Windows Hello or a security key) for every approval (beta)", false).option("--passkeys <file>", "registered passkeys", "saktum-passkeys.json").action(async (o) => {
40660
41036
  const http = await import("node:http");
40661
- const { randomBytes } = await import("node:crypto");
41037
+ const { randomBytes, createHmac: createHmac3 } = await import("node:crypto");
40662
41038
  const m = JSON.parse(readFileSync10(o.mandate, "utf8"));
40663
41039
  const key = loadOrCreateKey(o.key);
40664
41040
  const token = randomBytes(16).toString("hex");
40665
41041
  if (key.kid !== m.owner.id)
40666
41042
  throw new Error("This key is not the mandate owner's key.");
41043
+ const secret = o.secret ? secretFrom(o.secret) : "";
41044
+ const origin = `http://${o.host}:${o.port}`, rpId = o.host;
41045
+ const nonces = /* @__PURE__ */ new Map();
41046
+ const pks = () => existsSync7(o.passkeys) ? JSON.parse(readFileSync10(o.passkeys, "utf8")) : [];
40667
41047
  const esc22 = (x) => String(x).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
40668
- const pageOf = (body2) => `<!doctype html><meta name="viewport" content="width=device-width, initial-scale=1"><title>Saktum approvals</title><body style="font:15px system-ui;max-width:760px;margin:24px auto;padding:0 16px"><h1>Approvals for ${esc22(m.agent.name)}</h1>${body2}</body>`;
41048
+ const js = `const b=s=>Uint8Array.from(atob(s.replace(/-/g,'+').replace(/_/g,'/')),c=>c.charCodeAt(0)),u=a=>btoa(String.fromCharCode(...new Uint8Array(a))).replace(/\\+/g,'-').replace(/\\//g,'_').replace(/=+$/,'');`;
41049
+ const pageOf = (body2) => `<!doctype html><meta name="viewport" content="width=device-width, initial-scale=1"><title>Saktum approvals</title><body style="font:15px system-ui;max-width:760px;margin:24px auto;padding:0 16px"><h1>Approvals for ${esc22(m.agent.name)}</h1>${body2}<script>${js}</script></body>`;
41050
+ const okToken = (u, id) => u.searchParams.get("token") === token || Boolean(secret) && Boolean(id) && u.searchParams.get("t") === createHmac3("sha256", secret).update(id).digest("hex").slice(0, 32);
41051
+ const item = (x, q) => {
41052
+ const n = randomBytes(12).toString("hex");
41053
+ nonces.set(x.id, n);
41054
+ const ch = `${x.id}:${n}`;
41055
+ return `<form data-id="${esc22(x.id)}" data-ch="${esc22(ch)}" method="post" action="/approve?${q}" style="border:1px solid #ddd;border-radius:12px;padding:12px;margin:10px 0"><b>${esc22(x.tool)}</b> <code>${esc22(x.id)}</code><p>${esc22(x.reason)}</p><small>${esc22(x.at)}</small><input type="hidden" name="id" value="${esc22(x.id)}"><p><button type="submit">Approve exactly this action, once${o.passkey ? " (with your passkey)" : ""}</button></p></form>`;
41056
+ };
41057
+ const pkScript = o.passkey ? `<script>document.querySelectorAll('form[data-ch]').forEach(f=>f.addEventListener('submit',async e=>{e.preventDefault();const ids=${JSON.stringify(pks().map((p) => p.credentialId))};const c=await navigator.credentials.get({publicKey:{challenge:new TextEncoder().encode(f.dataset.ch),rpId:${JSON.stringify(rpId)},allowCredentials:ids.map(i=>({type:'public-key',id:b(i)})),userVerification:'required'}});const r=c.response;const res=await fetch(f.action,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id:f.dataset.id,credentialId:u(c.rawId),authenticatorData:u(r.authenticatorData),clientDataJSON:u(r.clientDataJSON),signature:u(r.signature)})});document.body.insertAdjacentHTML('beforeend',await res.text());}));</script>` : "";
40669
41058
  const server = http.createServer((req, res) => {
40670
- const u = new URL(req.url ?? "/", `http://${req.headers.host}`);
40671
- if (u.searchParams.get("token") !== token) {
40672
- res.writeHead(403);
40673
- res.end("Forbidden");
41059
+ const u = new URL(req.url ?? "/", origin);
41060
+ const send = (code, html) => {
41061
+ res.writeHead(code, { "Content-Type": "text/html", "X-Frame-Options": "DENY", "Content-Security-Policy": "default-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; frame-ancestors 'none'" });
41062
+ res.end(html);
41063
+ };
41064
+ if (u.pathname === "/passkey/register") {
41065
+ if (u.searchParams.get("token") !== token)
41066
+ return send(403, "Forbidden");
41067
+ if (req.method === "GET") {
41068
+ const ch = randomBytes(16).toString("hex");
41069
+ nonces.set("register", ch);
41070
+ return send(200, pageOf(`<p>Register a passkey for approving ${esc22(m.agent.name)}'s actions.</p><button id="r">Register a passkey</button><p id="o"></p><script>document.getElementById('r').onclick=async()=>{const c=await navigator.credentials.create({publicKey:{challenge:new TextEncoder().encode(${JSON.stringify(ch)}),rp:{name:'Saktum approvals',id:${JSON.stringify(rpId)}},user:{id:new TextEncoder().encode(${JSON.stringify(m.owner.id.slice(-32))}),name:${JSON.stringify(m.owner.name ?? "owner")},displayName:${JSON.stringify(m.owner.name ?? "owner")}},pubKeyCredParams:[{type:'public-key',alg:-7},{type:'public-key',alg:-8}],authenticatorSelection:{userVerification:'required'},attestation:'none'}});const res=await fetch(location.href,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({attestationObject:u(c.response.attestationObject),clientDataJSON:u(c.response.clientDataJSON)})});document.getElementById('o').textContent=await res.text();};</script>`));
41071
+ }
41072
+ let b = "";
41073
+ req.on("data", (c) => {
41074
+ b += c;
41075
+ if (b.length > 2e4)
41076
+ req.destroy();
41077
+ });
41078
+ req.on("end", () => {
41079
+ try {
41080
+ const r = verifyPasskeyRegistration(JSON.parse(b), { challenge: nonces.get("register") ?? "", origin, rpId });
41081
+ writeFileSync5(o.passkeys, JSON.stringify([...pks(), { ...r, binding: signDocument({ credentialId: r.credentialId, owner: m.owner.id, at: (/* @__PURE__ */ new Date()).toISOString() }, key) }], null, 2));
41082
+ nonces.delete("register");
41083
+ res.writeHead(200);
41084
+ res.end("Passkey registered. Restart approvals serve to use it.");
41085
+ } catch (e) {
41086
+ res.writeHead(400);
41087
+ res.end(`Registration failed: ${e.message}`);
41088
+ }
41089
+ });
40674
41090
  return;
40675
41091
  }
40676
- if (req.method === "POST") {
41092
+ if (req.method === "POST" && u.pathname === "/approve") {
40677
41093
  let b = "";
40678
41094
  req.on("data", (c) => {
40679
41095
  b += c;
40680
- if (b.length > 2e3)
41096
+ if (b.length > 2e4)
40681
41097
  req.destroy();
40682
41098
  });
40683
41099
  req.on("end", () => {
40684
- const id = new URLSearchParams(b).get("id") ?? "";
40685
- if (!listPending(o.approvals).some((p2) => p2.id === id)) {
40686
- res.writeHead(400, { "Content-Type": "text/html" });
40687
- res.end(pageOf(`<p>No pending request ${esc22(id)}.</p>`));
40688
- return;
41100
+ let id = "", assertion = {};
41101
+ try {
41102
+ if ((req.headers["content-type"] ?? "").includes("json")) {
41103
+ const j = JSON.parse(b);
41104
+ id = j.id;
41105
+ assertion = j;
41106
+ } else
41107
+ id = new URLSearchParams(b).get("id") ?? "";
41108
+ } catch {
41109
+ }
41110
+ if (!okToken(u, id))
41111
+ return send(403, "Forbidden");
41112
+ if (!listPending(o.approvals).some((p2) => p2.id === id))
41113
+ return send(400, `<p>No pending request ${esc22(id)}.</p>`);
41114
+ if (o.passkey) {
41115
+ const pk = pks().find((p2) => p2.credentialId === assertion.credentialId && verifyDocument(p2.binding).kid === m.owner.id);
41116
+ let ok = false;
41117
+ try {
41118
+ ok = Boolean(pk) && verifyPasskeyAssertion(assertion, pk.jwk, { challenge: `${id}:${nonces.get(id) ?? ""}`, origin, rpId });
41119
+ } catch {
41120
+ ok = false;
41121
+ }
41122
+ if (!ok)
41123
+ return send(403, "<p>\u2717 Passkey check failed. Nothing was approved.</p>");
41124
+ nonces.delete(id);
40689
41125
  }
40690
41126
  approveAction(m, id, key, Number(o.minutes), o.approvals);
40691
- res.writeHead(200, { "Content-Type": "text/html" });
40692
- res.end(pageOf(`<p>\u2713 Approved <code>${esc22(id)}</code>, once, for ${esc22(o.minutes)} minutes. The agent can retry exactly that action.</p><p><a href="/?token=${token}">Back</a></p>`));
41127
+ send(200, `<p>\u2713 Approved <code>${esc22(id)}</code>, once, for ${esc22(o.minutes)} minutes${o.passkey ? ", confirmed with your passkey" : ""}. The agent can retry exactly that action.</p>`);
40693
41128
  });
40694
41129
  return;
40695
41130
  }
40696
- const only = u.searchParams.get("id");
41131
+ const only = u.searchParams.get("id") ?? void 0;
41132
+ if (!okToken(u, only))
41133
+ return send(403, "Forbidden");
41134
+ const q = u.searchParams.get("token") ? `token=${token}` : `t=${u.searchParams.get("t")}`;
40697
41135
  const p = listPending(o.approvals).filter((x) => !only || x.id === only);
40698
- res.writeHead(200, { "Content-Type": "text/html" });
40699
- res.end(pageOf(p.length ? p.map((x) => `<form method="post" action="/?token=${token}" style="border:1px solid #ddd;border-radius:12px;padding:12px;margin:10px 0"><b>${esc22(x.tool)}</b> <code>${esc22(x.id)}</code><p>${esc22(x.reason)}</p><small>${esc22(x.at)}</small><input type="hidden" name="id" value="${esc22(x.id)}"><p><button type="submit">Approve exactly this action, once</button></p></form>`).join("") : "<p>Nothing is waiting for approval.</p>"));
41136
+ send(200, pageOf((o.passkey && !pks().length ? `<p>No passkey registered yet: <a href="/passkey/register?token=${token}">register one</a> (owner only).</p>` : "") + (p.length ? p.map((x) => item(x, q)).join("") : "<p>Nothing is waiting for approval.</p>") + pkScript));
40700
41137
  });
40701
- server.listen(Number(o.port), o.host, () => process.stdout.write(`Approvals page: http://${o.host}:${o.port}/?token=${token}
40702
- Give the proxy --approval-url "http://${o.host}:${o.port}/?token=${token}" so requests carry a one-click link. Ctrl+C to stop.
41138
+ server.listen(Number(o.port), o.host, () => process.stdout.write(`Approvals page (owner): ${origin}/?token=${token}
41139
+ ${secret ? "Per-request links: give the proxy the same --approval-secret and --approval-url " + origin + "\n" : ""}${o.passkey ? `Passkeys: register at ${origin}/passkey/register?token=${token}
41140
+ ` : ""}Ctrl+C to stop.
40703
41141
  `));
40704
41142
  await new Promise(() => void 0);
40705
41143
  });
@@ -40715,6 +41153,82 @@ Give the proxy --approval-url "http://${o.host}:${o.port}/?token=${token}" so re
40715
41153
  if (o.out)
40716
41154
  writeFileSync5(o.out, JSON.stringify(a, null, 2) + "\n");
40717
41155
  });
41156
+ const ledger2 = program2.commands.find((c) => c.name() === "ledger");
41157
+ ledger2.command("rotate").description("Record a key rotation: signed by the old key, with proof of possession of the new key").requiredOption("--old-key <spec>").requiredOption("--new-key <spec>").option("--out <file>", "statement file", "saktum-rotation.json").action((o) => {
41158
+ const ok = loadOrCreateKey(o.oldKey), nk = loadOrCreateKey(o.newKey);
41159
+ const st = signDocument({ statementFormat: "0.1", type: "key-rotation", oldKey: ok.kid, newKey: nk.kid, newKeyProof: signDocument({ rotates: ok.kid, at: (/* @__PURE__ */ new Date()).toISOString() }, nk), at: (/* @__PURE__ */ new Date()).toISOString() }, ok);
41160
+ writeFileSync5(o.out, JSON.stringify(st, null, 2) + "\n");
41161
+ process.stdout.write(`Rotation statement written to ${sanitizeText(o.out)}. Publish it to the ledger like an attestation (saktum ledger append, or the attest issue).
41162
+ `);
41163
+ });
41164
+ ledger2.command("revoke-entry").description("Revoke one of your attestations (by its result digest) or your key, as a ledger statement").requiredOption("--key <spec>").requiredOption("--target <digest-or-did>").option("--reason <text>").option("--out <file>", "statement file", "saktum-revocation.json").action((o) => {
41165
+ const k = loadOrCreateKey(o.key);
41166
+ writeFileSync5(o.out, JSON.stringify(signDocument({ statementFormat: "0.1", type: "revocation", target: o.target, ...o.reason ? { reason: o.reason } : {}, at: (/* @__PURE__ */ new Date()).toISOString() }, k), null, 2) + "\n");
41167
+ process.stdout.write(`Revocation statement written to ${sanitizeText(o.out)}.
41168
+ `);
41169
+ });
41170
+ ledger2.command("checkpoint").description("Sign a checkpoint of the ledger's current head").argument("[source]", "ledger file or URL", DEFAULT_LEDGER_URL).option("--key <spec>").option("--out <file>", "checkpoint file", "ledger-checkpoint.json").action(async (src, o) => {
41171
+ const e = parseLedger(await readLedgerText(src));
41172
+ const cp = makeCheckpoint(e, loadOrCreateKey(o.key), "saktum-ledger");
41173
+ writeFileSync5(o.out, JSON.stringify(cp, null, 2) + "\n");
41174
+ process.stdout.write(`Checkpoint at entry ${cp.seq} written to ${sanitizeText(o.out)}.
41175
+ `);
41176
+ });
41177
+ ledger2.command("witness").description("Independently check the ledger against a checkpoint and add your witness signature").argument("<checkpoint>").option("--ledger <source>", "ledger file or URL", DEFAULT_LEDGER_URL).option("--key <spec>").action(async (f, o) => {
41178
+ const cp = JSON.parse(readFileSync10(f, "utf8"));
41179
+ const e = parseLedger(await readLedgerText(o.ledger));
41180
+ if (!verifyLedger(e).ok)
41181
+ throw new Error("The ledger does not verify.");
41182
+ const w = witnessCheckpoint(cp, e, loadOrCreateKey(o.key));
41183
+ writeFileSync5(f, JSON.stringify(w, null, 2) + "\n");
41184
+ process.stdout.write(`Witnessed. Valid witnesses: ${validWitnesses(w).length}.
41185
+ `);
41186
+ });
41187
+ ledger2.command("check").description("Check a ledger or receipt log against a checkpoint (detects deletion and rewriting)").argument("<checkpoint>").option("--ledger <source>").option("--receipts <file>").action(async (f, o) => {
41188
+ const cp = JSON.parse(readFileSync10(f, "utf8"));
41189
+ const e = o.receipts ? parseReceiptLog(readFileSync10(o.receipts, "utf8")) : parseLedger(await readLedgerText(o.ledger ?? DEFAULT_LEDGER_URL));
41190
+ const r = verifyAgainstCheckpoint(e, cp);
41191
+ process.stdout.write(r.ok ? `\u2713 Consistent with the checkpoint at ${cp.seq} (${validWitnesses(cp).length} witness signature(s)).
41192
+ ` : `\u2717 ${r.reason}
41193
+ `);
41194
+ exitCode = r.ok ? 0 : 1;
41195
+ });
41196
+ org.command("verify-domain").description("Verify that an organisation controls its domain (DNS TXT _saktum.<domain> or https://<domain>/.well-known/saktum.json)").argument("<credential>", "the organisation's credential").action(async (f) => {
41197
+ const c = JSON.parse(readFileSync10(f, "utf8"));
41198
+ const d = c.issuer.domain;
41199
+ if (!d)
41200
+ throw new Error("This credential names no domain (org init --domain).");
41201
+ const r = await verifyDomain(d, c.subject.id);
41202
+ process.stdout.write(r.verified ? `\u2713 ${d} is verified for ${sanitizeText(c.subject.name, 80)} (${r.method}).
41203
+ ` : `\u2717 Not verified. Add a DNS TXT record:
41204
+ _saktum.${d} "saktum-did=${c.subject.id}"
41205
+ or publish https://${d}/.well-known/saktum.json containing {"did":"${c.subject.id}"}.
41206
+ `);
41207
+ exitCode = r.verified ? 0 : 1;
41208
+ });
41209
+ wallet.command("verify").option("--wallet <file>", "wallet file", "saktum-wallet.json").action((o) => {
41210
+ const r = verifyWallet(o.wallet);
41211
+ process.stdout.write(r.ok ? "\u2713 Wallet entries intact (chained and, where signed, signatures valid).\n" : `\u2717 ${r.errors.join("; ")}
41212
+ `);
41213
+ exitCode = r.ok ? 0 : 1;
41214
+ });
41215
+ program2.command("self-verify").description("Check that the saktum you are running matches the published, signed release").action(async () => {
41216
+ const { createHash: createHash4 } = await import("node:crypto");
41217
+ const self = process.argv[1];
41218
+ const mine = createHash4("sha256").update(readFileSync10(self)).digest("hex");
41219
+ let published = "";
41220
+ try {
41221
+ const r = await fetch(`https://github.com/soodhere/saktum-check/releases/download/v${ENGINE_VERSION}/saktum.mjs.sha256`);
41222
+ if (r.ok)
41223
+ published = (await r.text()).trim().split(/\s+/)[0] ?? "";
41224
+ } catch {
41225
+ }
41226
+ process.stdout.write(`This copy (${sanitizeText(self, 120)}): sha256 ${mine}
41227
+ Published v${ENGINE_VERSION}: ${published || "(not reachable)"}
41228
+ ${published ? published === mine ? "\u2713 Matches the published release.\n" : "\u2717 Does not match the published bundle (npm installs add a wrapper; compare the release asset saktum.mjs).\n" : ""}Signature: cosign verify-blob --bundle saktum.mjs.sigstore.json --certificate-identity-regexp "https://github.com/soodhere/saktum-check/" --certificate-oidc-issuer https://token.actions.githubusercontent.com saktum.mjs
41229
+ npm provenance: npm audit signatures
41230
+ `);
41231
+ });
40718
41232
  program2.command("demo").description("See permissions, autonomy, risk and receipts in 60 seconds: one shopping agent under three mandates").option("--out <dir>", "folder for the demo's mandates, receipts and passports", "saktum-demo").option("--story <name>", "grocery, travel, finance, coding, marketplace, autonomy, or all (grocery, travel, finance, coding and marketplace)", "all").action(async (o) => {
40719
41233
  const { runDemo: runDemo2 } = await Promise.resolve().then(() => (init_demo(), demo_exports));
40720
41234
  await runDemo2(o.out, (l) => process.stdout.write(l + "\n"), o.story);