saktum 0.10.0 → 0.13.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/README.md +23 -1
- package/package.json +1 -1
- package/saktum.mjs +745 -111
package/saktum.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// Saktum Check 0.
|
|
2
|
+
// Saktum Check 0.13.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.
|
|
34060
|
+
USER_AGENT = "saktum-check/0.13.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.
|
|
34098
|
+
params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "saktum-trust-check-probe", version: "0.13.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.
|
|
35470
|
+
ENGINE_VERSION = "0.13.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
|
|
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
|
|
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");
|
|
@@ -36052,6 +36111,10 @@ var init_vocab = __esm({
|
|
|
36052
36111
|
{ path: "code.repository", type: "string", description: "The code repository" },
|
|
36053
36112
|
{ path: "code.environment", type: "string", description: "The deployment environment (for example staging, production)" }
|
|
36054
36113
|
] };
|
|
36114
|
+
VOCABULARIES.support = { version: "0.1", fields: [
|
|
36115
|
+
{ path: "support.customer_id", type: "string", description: "The customer a support case is about" },
|
|
36116
|
+
{ path: "support.amount", type: "number", description: "A refund or credit amount" }
|
|
36117
|
+
] };
|
|
36055
36118
|
KNOWN_FIELDS = new Set(Object.values(VOCABULARIES).flatMap((v) => v.fields.map((f) => f.path)));
|
|
36056
36119
|
NAME_RULES = [
|
|
36057
36120
|
[/(^|[_-])(search|find|list|get|lookup|deals|browse)([_-]|$)/i, "search"],
|
|
@@ -36404,17 +36467,27 @@ function checkOperator(m) {
|
|
|
36404
36467
|
return { present: true, valid: false, reason: "operator signed a different mandate" };
|
|
36405
36468
|
return { present: true, valid: true, id: v.kid, name: cs.name };
|
|
36406
36469
|
}
|
|
36407
|
-
function revokeMandate(m, reason, path = DEFAULT_REVOCATIONS()) {
|
|
36470
|
+
function revokeMandate(m, reason, path = DEFAULT_REVOCATIONS(), key) {
|
|
36408
36471
|
const r = readRevocations(path), d = mandateDigest(m);
|
|
36472
|
+
const entry = { revocationFormat: "0.1", mandate: d, agent: m.agent.id, at: (/* @__PURE__ */ new Date()).toISOString(), ...reason ? { reason } : {} };
|
|
36409
36473
|
if (!r.revoked.some((x) => x.mandate === d))
|
|
36410
|
-
r.revoked.push(
|
|
36474
|
+
r.revoked.push(key ? signDocument(entry, key) : entry);
|
|
36411
36475
|
_mkdir(_dirname(path), { recursive: true });
|
|
36412
36476
|
_write(path, JSON.stringify(r, null, 2) + "\n");
|
|
36413
36477
|
return r.revoked.find((x) => x.mandate === d);
|
|
36414
36478
|
}
|
|
36415
36479
|
function revocationOf(m, path = DEFAULT_REVOCATIONS()) {
|
|
36416
36480
|
const d = mandateDigest(m);
|
|
36417
|
-
|
|
36481
|
+
const op = m.operatorCountersign?.signature?.kid;
|
|
36482
|
+
return readRevocations(path).revoked.find((x) => {
|
|
36483
|
+
if (x.mandate !== d)
|
|
36484
|
+
return false;
|
|
36485
|
+
const sx = x;
|
|
36486
|
+
if (!sx.signature)
|
|
36487
|
+
return true;
|
|
36488
|
+
const v = verifyDocument(x);
|
|
36489
|
+
return v.valid && (v.kid === m.owner.id || Boolean(op) && v.kid === op);
|
|
36490
|
+
});
|
|
36418
36491
|
}
|
|
36419
36492
|
function trustStatement(entries, verified) {
|
|
36420
36493
|
const allowed = entries.filter((e) => e.receipt.outcome === "allow" && e.result.status === "ok").length;
|
|
@@ -36695,8 +36768,17 @@ function issueCredential(issuerCred, issuerKey, s) {
|
|
|
36695
36768
|
throw new Error("The signing key does not belong to the issuer's credential.");
|
|
36696
36769
|
if (issuerCred.type === "agent")
|
|
36697
36770
|
throw new Error("Agents cannot issue credentials.");
|
|
36771
|
+
const parentTools = issuerCred.scope?.tools;
|
|
36772
|
+
if (parentTools && s.tools?.some((t) => !parentTools.includes(t)))
|
|
36773
|
+
throw new Error(`The issuer may only grant tools it holds: ${parentTools.join(", ")}.`);
|
|
36774
|
+
if (s.expires > issuerCred.expires)
|
|
36775
|
+
throw new Error(`A credential cannot outlive its issuer's (${issuerCred.expires}).`);
|
|
36776
|
+
if (issuerCred.maxDepth !== void 0 && issuerCred.maxDepth < 1)
|
|
36777
|
+
throw new Error("The issuer's credential does not allow further delegation.");
|
|
36778
|
+
const tools = s.tools ?? parentTools;
|
|
36779
|
+
const maxDepth2 = issuerCred.maxDepth !== void 0 ? Math.min(s.maxDepth ?? issuerCred.maxDepth - 1, issuerCred.maxDepth - 1) : s.maxDepth;
|
|
36698
36780
|
const chain = [...issuerCred.chain ?? [], { ...issuerCred, chain: void 0 }].map((c2) => JSON.parse(JSON.stringify(c2)));
|
|
36699
|
-
const c = { credentialFormat: "0.1", type: s.type, subject: { id: s.id, name: s.name, ...s.role ? { role: s.role } : {} }, issuer: { id: issuerKey.kid, name: issuerCred.subject.name, ...issuerCred.issuer.domain ? { domain: issuerCred.issuer.domain } : {} }, issuedAt: nowIso(), expires: s.expires };
|
|
36781
|
+
const c = { credentialFormat: "0.1", type: s.type, ...tools ? { scope: { tools } } : {}, ...maxDepth2 !== void 0 ? { maxDepth: maxDepth2 } : {}, subject: { id: s.id, name: s.name, ...s.role ? { role: s.role } : {} }, issuer: { id: issuerKey.kid, name: issuerCred.subject.name, ...issuerCred.issuer.domain ? { domain: issuerCred.issuer.domain } : {} }, issuedAt: nowIso(), expires: s.expires };
|
|
36700
36782
|
return { ...signDocument({ ...c, id: short("cred_", c) }, issuerKey), chain };
|
|
36701
36783
|
}
|
|
36702
36784
|
function verifyChain(c, o = {}) {
|
|
@@ -36718,9 +36800,18 @@ function verifyChain(c, o = {}) {
|
|
|
36718
36800
|
return { valid: false, path, reason: "the chain does not start at an organisation" };
|
|
36719
36801
|
if (i > 0 && l.issuer.id !== links[i - 1].subject.id)
|
|
36720
36802
|
return { valid: false, path, reason: `${l.subject.name}'s issuer is not the previous link in the chain` };
|
|
36803
|
+
if (i > 0) {
|
|
36804
|
+
const p = links[i - 1];
|
|
36805
|
+
if (p.scope?.tools && (!l.scope?.tools || l.scope.tools.some((t) => !p.scope.tools.includes(t))))
|
|
36806
|
+
return { valid: false, path, reason: `${l.subject.name}'s credential grants more than its issuer holds` };
|
|
36807
|
+
if (l.expires > p.expires)
|
|
36808
|
+
return { valid: false, path, reason: `${l.subject.name}'s credential outlives its issuer's` };
|
|
36809
|
+
}
|
|
36810
|
+
if (l.maxDepth !== void 0 && links.length - 1 - i > l.maxDepth)
|
|
36811
|
+
return { valid: false, path, reason: `the chain delegates deeper than ${l.subject.name}'s credential allows (${l.maxDepth})` };
|
|
36721
36812
|
path.push(`${l.subject.name}${l.subject.role ? ` (${l.subject.role})` : ""}`);
|
|
36722
36813
|
}
|
|
36723
|
-
return { valid: true, path, organisation: links[0].subject.name + (links[0].issuer.domain ? ` (${links[0].issuer.domain})` : "") };
|
|
36814
|
+
return { valid: true, path, organisation: links[0].subject.name + (links[0].issuer.domain ? ` (${links[0].issuer.domain})` : ""), ...links[links.length - 1].scope?.tools ? { tools: links[links.length - 1].scope.tools } : {} };
|
|
36724
36815
|
}
|
|
36725
36816
|
function findOrphans(creds, o = {}) {
|
|
36726
36817
|
return creds.filter((c) => c.type === "agent").map((c) => ({ agent: c.subject.name, id: c.subject.id, ...verifyChain(c, o) })).filter((x) => !x.valid);
|
|
@@ -36806,21 +36897,47 @@ function verifyAgreement(a, today = nowIso().slice(0, 10)) {
|
|
|
36806
36897
|
return { valid: false, reason: `expired on ${a.validUntil}` };
|
|
36807
36898
|
return { valid: true };
|
|
36808
36899
|
}
|
|
36900
|
+
function sealEntry(w, e, key) {
|
|
36901
|
+
const prev = w.entries[w.entries.length - 1]?.hash ?? "sha256:genesis";
|
|
36902
|
+
const body2 = { at: e.at, from: e.from, to: e.to, tokens: e.tokens, ref: e.ref, prev };
|
|
36903
|
+
const hash = argumentsHash(body2);
|
|
36904
|
+
return key ? signDocument({ ...body2, hash }, key) : { ...body2, hash };
|
|
36905
|
+
}
|
|
36906
|
+
function verifyWallet(path) {
|
|
36907
|
+
const errors = [];
|
|
36908
|
+
let prev = "sha256:genesis";
|
|
36909
|
+
readWallet(path).entries.forEach((e, i) => {
|
|
36910
|
+
if (!e.hash)
|
|
36911
|
+
return;
|
|
36912
|
+
const { signature: _s, hash, ...body2 } = e;
|
|
36913
|
+
if (body2.prev !== prev)
|
|
36914
|
+
errors.push(`entry ${i + 1}: chain broken`);
|
|
36915
|
+
if (argumentsHash({ at: body2.at, from: body2.from, to: body2.to, tokens: body2.tokens, ref: body2.ref, prev: body2.prev }) !== hash)
|
|
36916
|
+
errors.push(`entry ${i + 1}: changed after it was written`);
|
|
36917
|
+
if (e.signature && !verifyDocument(e).valid)
|
|
36918
|
+
errors.push(`entry ${i + 1}: signature not valid`);
|
|
36919
|
+
prev = hash;
|
|
36920
|
+
});
|
|
36921
|
+
return { ok: errors.length === 0, errors };
|
|
36922
|
+
}
|
|
36809
36923
|
function walletBalance(path, account) {
|
|
36810
36924
|
return readWallet(path).entries.reduce((b, e) => b + (e.to === account ? e.tokens : 0) - (e.from === account ? e.tokens : 0), 0);
|
|
36811
36925
|
}
|
|
36812
|
-
function topUp(path, account, tokens, ref = "top-up") {
|
|
36926
|
+
function topUp(path, account, tokens, ref = "top-up", key) {
|
|
36813
36927
|
const w = readWallet(path);
|
|
36814
|
-
w.entries.push({ at: nowIso(), from: PREPAID, to: account, tokens, ref });
|
|
36928
|
+
w.entries.push(sealEntry(w, { at: nowIso(), from: PREPAID, to: account, tokens, ref }, key));
|
|
36815
36929
|
writeWallet(path, w);
|
|
36816
36930
|
return walletBalance(path, account);
|
|
36817
36931
|
}
|
|
36818
|
-
function chargeCall(path, a, tool, ref) {
|
|
36819
|
-
const cost = tokensFor(a, tool)
|
|
36932
|
+
function chargeCall(path, a, tool, ref, key) {
|
|
36933
|
+
const cost = tokensFor(a, tool);
|
|
36934
|
+
if (!verifyWallet(path).ok)
|
|
36935
|
+
return { ok: false, tokens: cost, balance: 0 };
|
|
36936
|
+
const bal = walletBalance(path, a.invoker.id);
|
|
36820
36937
|
if (bal < cost)
|
|
36821
36938
|
return { ok: false, tokens: cost, balance: bal };
|
|
36822
36939
|
const w = readWallet(path);
|
|
36823
|
-
w.entries.push({ at: nowIso(), from: a.invoker.id, to: a.provider.id, tokens: cost, ref });
|
|
36940
|
+
w.entries.push(sealEntry(w, { at: nowIso(), from: a.invoker.id, to: a.provider.id, tokens: cost, ref }, key));
|
|
36824
36941
|
writeWallet(path, w);
|
|
36825
36942
|
return { ok: true, tokens: cost, balance: bal - cost };
|
|
36826
36943
|
}
|
|
@@ -36952,6 +37069,25 @@ var init_crosswalk = __esm({
|
|
|
36952
37069
|
I("9.2", "Internal audit", "partial", "Independently verifiable ledger, receipts and passports for auditors", ["saktum ledger verify", "saktum receipts verify"]),
|
|
36953
37070
|
I("A.10", "Third-party and customer relationships", "covered", "Passports, manifests, signed agreements, Verifiable Credentials", ["saktum attest --vc", "saktum agreement verify"])
|
|
36954
37071
|
] },
|
|
37072
|
+
{ id: "iso-27001", name: "ISO/IEC 27001 (Annex A, 2022)", note: "Information security management; certification is by accredited bodies.", items: [
|
|
37073
|
+
I("A.5.15", "Access control", "covered", "Least-privilege mandates and task-scoped, short-lived agent credentials", ["saktum agent create --intent", "saktum identity issue --minutes --tools"]),
|
|
37074
|
+
I("A.5.19\u2013A.5.22", "Information security in supplier relationships", "covered", "Passports, attestations, monitoring and signed agreements for third-party MCP servers", ["saktum passport", "saktum watch", "saktum agreement verify"]),
|
|
37075
|
+
I("A.8.2", "Privileged access rights", "partial", "Approvals for risky actions, autonomy levels and revocation (agents; not human administrators)", ["saktum agent approve", "saktum agent revoke"]),
|
|
37076
|
+
I("A.8.15", "Logging", "covered", "Signed, chained receipts with input and output digests; checkpoints detect deletion", ["saktum receipts verify", "saktum receipts checkpoint"]),
|
|
37077
|
+
I("A.8.16", "Monitoring activities", "covered", "Daily monitoring of approved servers, result flags, OpenTelemetry export", ["saktum watch", "saktum receipts export --otel"]),
|
|
37078
|
+
I("A.8.24", "Use of cryptography", "partial", "Ed25519 signatures, keys in OS keychains or external key services (confidentiality at rest is the customer's storage)", ["saktum self-verify"])
|
|
37079
|
+
] },
|
|
37080
|
+
{ id: "osfi-e23", name: "OSFI E-23 (Canada)", note: "Model risk management for federally regulated financial institutions, including AI; applicability and dates per OSFI.", items: [
|
|
37081
|
+
I("Inventory", "Model inventory", "covered", "Agent and MCP server inventories across the organisation", ["saktum agents scan", "saktum fleet"]),
|
|
37082
|
+
I("Risk rating", "Risk-based model classification", "covered", "Risk tiers R0\u2013R4 for servers and agents; policy ceilings", ["saktum check", "saktum fleet --policy"]),
|
|
37083
|
+
I("Governance", "Accountability and roles", "covered", "Identity chains to accountable people and organisations; operator countersignatures", ["saktum identity verify", "saktum agent cosign"]),
|
|
37084
|
+
I("Monitoring", "Ongoing monitoring across the lifecycle", "covered", "Track records, maturity levels, daily monitoring, receipts", ["saktum passport --agent", "saktum watch"]),
|
|
37085
|
+
I("Explainability", "Explainability and transparency", "partial", "Every decision carries a reason and rationale (actions, not model internals)", ["saktum receipts summary"]),
|
|
37086
|
+
I("Third parties", "Third-party and vendor models", "partial", "Passports and attestations for third-party tools (the models themselves are out of scope)", ["saktum passport", "saktum attest --vc"])
|
|
37087
|
+
] },
|
|
37088
|
+
{ id: "ca-sb53", name: "California SB 53", note: "Applies to frontier AI model developers, not to organisations running agents; listed so readers see it was considered.", items: [
|
|
37089
|
+
I("Scope", "Frontier developer transparency and safety frameworks", "gap", "Not applicable to Saktum's users (agents and tools, not frontier model training)", [])
|
|
37090
|
+
] },
|
|
36955
37091
|
{ id: "owasp-llm", name: "OWASP Top 10 for LLM Applications (2025)", note: "Mapped for agents' tool use; model-level risks are out of scope.", items: [
|
|
36956
37092
|
I("LLM01", "Prompt injection", "partial", "Hidden-instruction checks on tools; mandates contain a manipulated agent (detection inside models is out of scope)", ["saktum check", "saktum demo"]),
|
|
36957
37093
|
I("LLM02", "Sensitive information disclosure", "partial", "Personal and classified data enforced per recipient; secrets never printed; argument digests only", ["saktum proxy --enforce"]),
|
|
@@ -37039,6 +37175,234 @@ var init_agents = __esm({
|
|
|
37039
37175
|
}
|
|
37040
37176
|
});
|
|
37041
37177
|
|
|
37178
|
+
// packages/testkit-core/dist/trust.js
|
|
37179
|
+
import { createHmac } from "node:crypto";
|
|
37180
|
+
function signRevocation(m, key, reason) {
|
|
37181
|
+
return signDocument({ revocationFormat: "0.1", mandate: mandateDigest(m), agent: m.agent.id, at: (/* @__PURE__ */ new Date()).toISOString(), ...reason ? { reason } : {} }, key);
|
|
37182
|
+
}
|
|
37183
|
+
function validRevocation(r, m) {
|
|
37184
|
+
const x = r;
|
|
37185
|
+
if (!x || x.mandate !== mandateDigest(m))
|
|
37186
|
+
return false;
|
|
37187
|
+
if (!x.signature)
|
|
37188
|
+
return true;
|
|
37189
|
+
const v = verifyDocument(x);
|
|
37190
|
+
const op = m.operatorCountersign?.signature?.kid;
|
|
37191
|
+
return v.valid && (v.kid === m.owner.id || Boolean(op) && v.kid === op);
|
|
37192
|
+
}
|
|
37193
|
+
function makeCheckpoint(entries, key, log = "receipts") {
|
|
37194
|
+
const last = entries[entries.length - 1];
|
|
37195
|
+
return signDocument({ checkpointFormat: "0.1", log, seq: last?.seq ?? 0, head: last?.entryHash ?? "sha256:genesis", at: (/* @__PURE__ */ new Date()).toISOString() }, key);
|
|
37196
|
+
}
|
|
37197
|
+
function verifyAgainstCheckpoint(entries, cp, trustedSigners) {
|
|
37198
|
+
const v = verifyDocument(cpCore(cp));
|
|
37199
|
+
if (!v.valid)
|
|
37200
|
+
return { ok: false, reason: "checkpoint signature not valid" };
|
|
37201
|
+
if (trustedSigners?.length && !trustedSigners.includes(v.kid))
|
|
37202
|
+
return { ok: false, reason: "checkpoint signed by an untrusted key" };
|
|
37203
|
+
if (entries.length < cp.seq)
|
|
37204
|
+
return { ok: false, reason: `the log has ${entries.length} entries but the checkpoint covers ${cp.seq}: entries were deleted` };
|
|
37205
|
+
const head = cp.seq === 0 ? "sha256:genesis" : entries[cp.seq - 1]?.entryHash;
|
|
37206
|
+
if (head !== cp.head)
|
|
37207
|
+
return { ok: false, reason: `entry ${cp.seq} differs from the checkpoint: the log was rewritten` };
|
|
37208
|
+
return { ok: true };
|
|
37209
|
+
}
|
|
37210
|
+
function witnessCheckpoint(cp, entries, key) {
|
|
37211
|
+
const ok = verifyAgainstCheckpoint(entries, cp);
|
|
37212
|
+
if (!ok.ok)
|
|
37213
|
+
throw new Error(`Not witnessing: ${ok.reason}`);
|
|
37214
|
+
return { ...cp, witnesses: [...cp.witnesses ?? [], signDocument({ witnessFormat: "0.1", checkpoint: sha256Tag(canonicalize(cpCore(cp))), at: (/* @__PURE__ */ new Date()).toISOString() }, key)] };
|
|
37215
|
+
}
|
|
37216
|
+
function validWitnesses(cp) {
|
|
37217
|
+
const d = sha256Tag(canonicalize(cpCore(cp)));
|
|
37218
|
+
return (cp.witnesses ?? []).flatMap((w) => {
|
|
37219
|
+
const x = w;
|
|
37220
|
+
const v = verifyDocument(w);
|
|
37221
|
+
return v.valid && x.checkpoint === d ? [v.kid] : [];
|
|
37222
|
+
});
|
|
37223
|
+
}
|
|
37224
|
+
async function verifyDomain(domain, did, o = {}) {
|
|
37225
|
+
if (!/^[a-z0-9.-]{3,253}$/i.test(domain))
|
|
37226
|
+
return { verified: false };
|
|
37227
|
+
try {
|
|
37228
|
+
const rt = o.resolveTxt ?? (await import("node:dns/promises")).resolveTxt;
|
|
37229
|
+
const recs = await rt(`_saktum.${domain}`);
|
|
37230
|
+
if (recs.flat().some((t) => t.trim() === `saktum-did=${did}`))
|
|
37231
|
+
return { verified: true, method: "dns" };
|
|
37232
|
+
} catch {
|
|
37233
|
+
}
|
|
37234
|
+
try {
|
|
37235
|
+
const r = await (o.fetchImpl ?? fetch)(`https://${domain}/.well-known/saktum.json`);
|
|
37236
|
+
if (r.ok) {
|
|
37237
|
+
const j = await r.json();
|
|
37238
|
+
if (j.did === did || j.dids?.includes(did))
|
|
37239
|
+
return { verified: true, method: "well-known" };
|
|
37240
|
+
}
|
|
37241
|
+
} catch {
|
|
37242
|
+
}
|
|
37243
|
+
return { verified: false };
|
|
37244
|
+
}
|
|
37245
|
+
var keyedDigest, revokedInChain, approvalUsedInChain, cpCore;
|
|
37246
|
+
var init_trust = __esm({
|
|
37247
|
+
"packages/testkit-core/dist/trust.js"() {
|
|
37248
|
+
"use strict";
|
|
37249
|
+
init_dist();
|
|
37250
|
+
init_agentid();
|
|
37251
|
+
keyedDigest = (args, key) => "hmac-sha256:" + createHmac("sha256", key).update(canonicalize(JSON.parse(JSON.stringify(args ?? {})))).digest("hex");
|
|
37252
|
+
revokedInChain = (entries) => entries.some((e) => e.result.code === "revoked");
|
|
37253
|
+
approvalUsedInChain = (entries, rid) => entries.some((e) => /approved by/.test(String(e.receipt.reason ?? "")) && String(e.receipt.reason ?? "").includes(`(${rid})`));
|
|
37254
|
+
cpCore = (cp) => {
|
|
37255
|
+
const { witnesses: _w, ...rest } = cp;
|
|
37256
|
+
return rest;
|
|
37257
|
+
};
|
|
37258
|
+
}
|
|
37259
|
+
});
|
|
37260
|
+
|
|
37261
|
+
// packages/testkit-core/dist/webauthn.js
|
|
37262
|
+
import { createHash as createHash3, createPublicKey as createPublicKey2, verify as verify2 } from "node:crypto";
|
|
37263
|
+
function decodeCbor(buf) {
|
|
37264
|
+
let i = 0;
|
|
37265
|
+
const read = () => {
|
|
37266
|
+
const ib = buf[i++], mt = ib >> 5, ai = ib & 31;
|
|
37267
|
+
let len = ai;
|
|
37268
|
+
if (ai === 24)
|
|
37269
|
+
len = buf[i++];
|
|
37270
|
+
else if (ai === 25) {
|
|
37271
|
+
len = buf[i] << 8 | buf[i + 1];
|
|
37272
|
+
i += 2;
|
|
37273
|
+
} else if (ai === 26) {
|
|
37274
|
+
len = (buf[i] << 24 >>> 0) + (buf[i + 1] << 16) + (buf[i + 2] << 8) + buf[i + 3];
|
|
37275
|
+
i += 4;
|
|
37276
|
+
} else if (ai > 26)
|
|
37277
|
+
throw new Error("unsupported CBOR length");
|
|
37278
|
+
switch (mt) {
|
|
37279
|
+
case 0:
|
|
37280
|
+
return len;
|
|
37281
|
+
case 1:
|
|
37282
|
+
return -1 - len;
|
|
37283
|
+
case 2: {
|
|
37284
|
+
const v = buf.slice(i, i + len);
|
|
37285
|
+
i += len;
|
|
37286
|
+
return v;
|
|
37287
|
+
}
|
|
37288
|
+
case 3: {
|
|
37289
|
+
const v = new TextDecoder().decode(buf.slice(i, i + len));
|
|
37290
|
+
i += len;
|
|
37291
|
+
return v;
|
|
37292
|
+
}
|
|
37293
|
+
case 4: {
|
|
37294
|
+
const a = [];
|
|
37295
|
+
for (let k = 0; k < len; k++)
|
|
37296
|
+
a.push(read());
|
|
37297
|
+
return a;
|
|
37298
|
+
}
|
|
37299
|
+
case 5: {
|
|
37300
|
+
const m = /* @__PURE__ */ new Map();
|
|
37301
|
+
for (let k = 0; k < len; k++) {
|
|
37302
|
+
const key = read();
|
|
37303
|
+
m.set(key, read());
|
|
37304
|
+
}
|
|
37305
|
+
return m;
|
|
37306
|
+
}
|
|
37307
|
+
case 7:
|
|
37308
|
+
return ai === 20 ? false : ai === 21 ? true : null;
|
|
37309
|
+
default:
|
|
37310
|
+
throw new Error("unsupported CBOR type");
|
|
37311
|
+
}
|
|
37312
|
+
};
|
|
37313
|
+
const value = read();
|
|
37314
|
+
return { value, length: i };
|
|
37315
|
+
}
|
|
37316
|
+
function coseToJwk(m) {
|
|
37317
|
+
const kty = m.get(1), alg = m.get(3);
|
|
37318
|
+
if (kty === 2 && alg === -7)
|
|
37319
|
+
return { kty: "EC", crv: "P-256", x: b64u3(m.get(-2)), y: b64u3(m.get(-3)) };
|
|
37320
|
+
if (kty === 1 && alg === -8)
|
|
37321
|
+
return { kty: "OKP", crv: "Ed25519", x: b64u3(m.get(-2)) };
|
|
37322
|
+
throw new Error("unsupported passkey algorithm (ES256 and EdDSA are supported)");
|
|
37323
|
+
}
|
|
37324
|
+
function checkClientData(clientDataJSON, type, challenge, origin) {
|
|
37325
|
+
const c = JSON.parse(Buffer.from(clientDataJSON, "base64url").toString("utf8"));
|
|
37326
|
+
if (c.type !== type)
|
|
37327
|
+
throw new Error("wrong client data type");
|
|
37328
|
+
if (c.challenge !== b64u3(Buffer.from(challenge)))
|
|
37329
|
+
throw new Error("challenge does not match");
|
|
37330
|
+
if (c.origin !== origin)
|
|
37331
|
+
throw new Error("origin does not match");
|
|
37332
|
+
}
|
|
37333
|
+
function verifyPasskeyRegistration(r, expected) {
|
|
37334
|
+
checkClientData(r.clientDataJSON, "webauthn.create", expected.challenge, expected.origin);
|
|
37335
|
+
const att = decodeCbor(Buffer.from(r.attestationObject, "base64url")).value;
|
|
37336
|
+
const ad = att.get("authData");
|
|
37337
|
+
if (!Buffer.from(ad.slice(0, 32)).equals(sha256(expected.rpId)))
|
|
37338
|
+
throw new Error("relying party does not match");
|
|
37339
|
+
const flags = ad[32];
|
|
37340
|
+
if (!(flags & 1))
|
|
37341
|
+
throw new Error("user presence not confirmed");
|
|
37342
|
+
if (!(flags & 64))
|
|
37343
|
+
throw new Error("no credential data");
|
|
37344
|
+
const idLen = ad[53] << 8 | ad[54];
|
|
37345
|
+
const credentialId = b64u3(ad.slice(55, 55 + idLen));
|
|
37346
|
+
const jwk = coseToJwk(decodeCbor(ad.slice(55 + idLen)).value);
|
|
37347
|
+
return { credentialId, jwk };
|
|
37348
|
+
}
|
|
37349
|
+
function verifyPasskeyAssertion(a, jwk, expected) {
|
|
37350
|
+
checkClientData(a.clientDataJSON, "webauthn.get", expected.challenge, expected.origin);
|
|
37351
|
+
const ad = Buffer.from(a.authenticatorData, "base64url");
|
|
37352
|
+
if (!ad.slice(0, 32).equals(sha256(expected.rpId)))
|
|
37353
|
+
throw new Error("relying party does not match");
|
|
37354
|
+
if (!(ad[32] & 1))
|
|
37355
|
+
throw new Error("user presence not confirmed");
|
|
37356
|
+
const data = Buffer.concat([ad, sha256(Buffer.from(a.clientDataJSON, "base64url"))]);
|
|
37357
|
+
const key = createPublicKey2({ key: jwk, format: "jwk" });
|
|
37358
|
+
return jwk.kty === "OKP" ? verify2(null, data, key, Buffer.from(a.signature, "base64url")) : verify2("sha256", data, key, Buffer.from(a.signature, "base64url"));
|
|
37359
|
+
}
|
|
37360
|
+
var sha256, b64u3;
|
|
37361
|
+
var init_webauthn = __esm({
|
|
37362
|
+
"packages/testkit-core/dist/webauthn.js"() {
|
|
37363
|
+
"use strict";
|
|
37364
|
+
sha256 = (b) => createHash3("sha256").update(b).digest();
|
|
37365
|
+
b64u3 = (b) => Buffer.from(b).toString("base64url");
|
|
37366
|
+
}
|
|
37367
|
+
});
|
|
37368
|
+
|
|
37369
|
+
// packages/testkit-core/dist/guards.js
|
|
37370
|
+
function findSecret(text2) {
|
|
37371
|
+
for (const p of SECRET_PATTERNS) {
|
|
37372
|
+
const re = new RegExp(p.re.source, p.re.flags.replace("g", ""));
|
|
37373
|
+
const m = text2.match(re);
|
|
37374
|
+
if (m && (!p.valid || p.valid(m)))
|
|
37375
|
+
return p.name;
|
|
37376
|
+
}
|
|
37377
|
+
return void 0;
|
|
37378
|
+
}
|
|
37379
|
+
function findHiddenInstruction(text2, o = {}) {
|
|
37380
|
+
for (const re of o.broad ? [...HIDDEN_INSTRUCTION, ...RESULT_INJECTION] : HIDDEN_INSTRUCTION) {
|
|
37381
|
+
const m = text2.match(re);
|
|
37382
|
+
if (m)
|
|
37383
|
+
return m[0].slice(0, 80);
|
|
37384
|
+
}
|
|
37385
|
+
return void 0;
|
|
37386
|
+
}
|
|
37387
|
+
function resultText(result) {
|
|
37388
|
+
const r = result ?? {};
|
|
37389
|
+
return [...(r.content ?? []).map((c) => typeof c.text === "string" ? c.text : ""), r.structuredContent ? JSON.stringify(r.structuredContent) : ""].join("\n");
|
|
37390
|
+
}
|
|
37391
|
+
var RESULT_INJECTION;
|
|
37392
|
+
var init_guards = __esm({
|
|
37393
|
+
"packages/testkit-core/dist/guards.js"() {
|
|
37394
|
+
"use strict";
|
|
37395
|
+
init_analysers();
|
|
37396
|
+
init_leakage();
|
|
37397
|
+
RESULT_INJECTION = [
|
|
37398
|
+
/\bignore (the |your )?(user|previous|prior|above|earlier|original)\b/i,
|
|
37399
|
+
/\b(send|upload|post|forward|email|exfiltrate) (the |all |any |your |their )?(conversation|chat|credentials|api keys?|secrets?|tokens?|passwords?|private data)\b[^.\n]{0,40}\bto\b/i,
|
|
37400
|
+
/\byou are now\b|\bnew instructions?:/i,
|
|
37401
|
+
/\b(do not|don['’]t|never) (tell|inform|alert|notify) the user\b/i
|
|
37402
|
+
];
|
|
37403
|
+
}
|
|
37404
|
+
});
|
|
37405
|
+
|
|
37042
37406
|
// packages/testkit-core/dist/index.js
|
|
37043
37407
|
var dist_exports = {};
|
|
37044
37408
|
__export(dist_exports, {
|
|
@@ -37057,6 +37421,7 @@ __export(dist_exports, {
|
|
|
37057
37421
|
FRAMEWORKS: () => FRAMEWORKS,
|
|
37058
37422
|
FUNCTIONAL_LIMITS: () => FUNCTIONAL_LIMITS,
|
|
37059
37423
|
GENESIS: () => GENESIS,
|
|
37424
|
+
HIDDEN_INSTRUCTION: () => HIDDEN_INSTRUCTION,
|
|
37060
37425
|
INVISIBLE: () => INVISIBLE,
|
|
37061
37426
|
KNOWN_FIELDS: () => KNOWN_FIELDS,
|
|
37062
37427
|
LEAKAGE_NEEDS: () => LEAKAGE_NEEDS,
|
|
@@ -37085,9 +37450,11 @@ __export(dist_exports, {
|
|
|
37085
37450
|
allowlistFromLedger: () => allowlistFromLedger,
|
|
37086
37451
|
analyseSetup: () => analyseSetup,
|
|
37087
37452
|
analysers: () => analysers,
|
|
37453
|
+
appendStatement: () => appendStatement,
|
|
37088
37454
|
appendTestCase: () => appendTestCase,
|
|
37089
37455
|
appendToLedger: () => appendToLedger,
|
|
37090
37456
|
approvalRequestId: () => approvalRequestId,
|
|
37457
|
+
approvalUsedInChain: () => approvalUsedInChain,
|
|
37091
37458
|
approveAction: () => approveAction,
|
|
37092
37459
|
argumentsHash: () => argumentsHash,
|
|
37093
37460
|
attestationToCredential: () => attestationToCredential,
|
|
@@ -37104,6 +37471,7 @@ __export(dist_exports, {
|
|
|
37104
37471
|
checkMandate: () => checkMandate,
|
|
37105
37472
|
checkNeedsSession: () => checkNeedsSession,
|
|
37106
37473
|
checkOperator: () => checkOperator,
|
|
37474
|
+
checkStatement: () => checkStatement,
|
|
37107
37475
|
clientCompatibility: () => clientCompatibility,
|
|
37108
37476
|
compileContract: () => compileContract,
|
|
37109
37477
|
compileUntrustedSchema: () => compileUntrustedSchema,
|
|
@@ -37127,16 +37495,20 @@ __export(dist_exports, {
|
|
|
37127
37495
|
evaluatePolicy: () => evaluatePolicy,
|
|
37128
37496
|
exampleFor: () => exampleFor,
|
|
37129
37497
|
extractJson: () => extractJson,
|
|
37498
|
+
findHiddenInstruction: () => findHiddenInstruction,
|
|
37130
37499
|
findInLedger: () => findInLedger,
|
|
37131
37500
|
findOrphans: () => findOrphans,
|
|
37501
|
+
findSecret: () => findSecret,
|
|
37132
37502
|
fleetHtml: () => fleetHtml,
|
|
37133
37503
|
gradeFor: () => gradeFor,
|
|
37134
37504
|
hasIntent: () => hasIntent,
|
|
37135
37505
|
invalidArgProblems: () => invalidArgProblems,
|
|
37136
37506
|
invalidArgsFor: () => invalidArgsFor,
|
|
37137
37507
|
issueCredential: () => issueCredential,
|
|
37508
|
+
keyedDigest: () => keyedDigest,
|
|
37138
37509
|
kpis: () => kpis,
|
|
37139
37510
|
leakageAnalysers: () => leakageAnalysers,
|
|
37511
|
+
ledgerStatus: () => ledgerStatus,
|
|
37140
37512
|
lintPaths: () => lintPaths,
|
|
37141
37513
|
lintSarif: () => lintSarif,
|
|
37142
37514
|
lintSource: () => lintSource,
|
|
@@ -37145,6 +37517,7 @@ __export(dist_exports, {
|
|
|
37145
37517
|
loadPack: () => loadPack,
|
|
37146
37518
|
loadPackDir: () => loadPackDir,
|
|
37147
37519
|
loadPackText: () => loadPackText,
|
|
37520
|
+
makeCheckpoint: () => makeCheckpoint,
|
|
37148
37521
|
mandateDecision: () => mandateDecision,
|
|
37149
37522
|
mandateDigest: () => mandateDigest,
|
|
37150
37523
|
maxDepth: () => maxDepth,
|
|
@@ -37170,8 +37543,10 @@ __export(dist_exports, {
|
|
|
37170
37543
|
renderSetup: () => renderSetup,
|
|
37171
37544
|
renderVerdict: () => renderVerdict,
|
|
37172
37545
|
resultProblems: () => resultProblems,
|
|
37546
|
+
resultText: () => resultText,
|
|
37173
37547
|
revocationOf: () => revocationOf,
|
|
37174
37548
|
revokeMandate: () => revokeMandate,
|
|
37549
|
+
revokedInChain: () => revokedInChain,
|
|
37175
37550
|
riskTier: () => riskTier,
|
|
37176
37551
|
roiEstimate: () => roiEstimate,
|
|
37177
37552
|
runCheck: () => runCheck,
|
|
@@ -37186,6 +37561,7 @@ __export(dist_exports, {
|
|
|
37186
37561
|
semanticValues: () => semanticValues,
|
|
37187
37562
|
signCredentialJwt: () => signCredentialJwt,
|
|
37188
37563
|
signReceipt: () => signReceipt,
|
|
37564
|
+
signRevocation: () => signRevocation,
|
|
37189
37565
|
sourceFiles: () => sourceFiles,
|
|
37190
37566
|
splitCommand: () => splitCommand,
|
|
37191
37567
|
subjectFromResult: () => subjectFromResult,
|
|
@@ -37199,15 +37575,23 @@ __export(dist_exports, {
|
|
|
37199
37575
|
topUp: () => topUp,
|
|
37200
37576
|
trustStatement: () => trustStatement,
|
|
37201
37577
|
usageStatement: () => usageStatement,
|
|
37578
|
+
validRevocation: () => validRevocation,
|
|
37579
|
+
validWitnesses: () => validWitnesses,
|
|
37580
|
+
verifyAgainstCheckpoint: () => verifyAgainstCheckpoint,
|
|
37202
37581
|
verifyAgreement: () => verifyAgreement,
|
|
37203
37582
|
verifyChain: () => verifyChain,
|
|
37204
37583
|
verifyCredentialJwt: () => verifyCredentialJwt,
|
|
37584
|
+
verifyDomain: () => verifyDomain,
|
|
37205
37585
|
verifyLedger: () => verifyLedger,
|
|
37586
|
+
verifyPasskeyAssertion: () => verifyPasskeyAssertion,
|
|
37587
|
+
verifyPasskeyRegistration: () => verifyPasskeyRegistration,
|
|
37206
37588
|
verifyReceipt: () => verifyReceipt,
|
|
37207
37589
|
verifyReceiptLog: () => verifyReceiptLog,
|
|
37590
|
+
verifyWallet: () => verifyWallet,
|
|
37208
37591
|
walletBalance: () => walletBalance,
|
|
37209
37592
|
watchAllowlist: () => watchAllowlist,
|
|
37210
|
-
wellKnownUrls: () => wellKnownUrls
|
|
37593
|
+
wellKnownUrls: () => wellKnownUrls,
|
|
37594
|
+
witnessCheckpoint: () => witnessCheckpoint
|
|
37211
37595
|
});
|
|
37212
37596
|
var init_dist4 = __esm({
|
|
37213
37597
|
"packages/testkit-core/dist/index.js"() {
|
|
@@ -37244,6 +37628,9 @@ var init_dist4 = __esm({
|
|
|
37244
37628
|
init_market();
|
|
37245
37629
|
init_crosswalk();
|
|
37246
37630
|
init_agents();
|
|
37631
|
+
init_trust();
|
|
37632
|
+
init_webauthn();
|
|
37633
|
+
init_guards();
|
|
37247
37634
|
}
|
|
37248
37635
|
});
|
|
37249
37636
|
|
|
@@ -37899,6 +38286,7 @@ var proxy_exports = {};
|
|
|
37899
38286
|
__export(proxy_exports, {
|
|
37900
38287
|
runProxy: () => runProxy
|
|
37901
38288
|
});
|
|
38289
|
+
import { createHmac as createHmac2 } from "node:crypto";
|
|
37902
38290
|
import { spawn as spawn3 } from "node:child_process";
|
|
37903
38291
|
import { appendFileSync, existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync7 } from "node:fs";
|
|
37904
38292
|
import { dirname as dirname3 } from "node:path";
|
|
@@ -37923,6 +38311,25 @@ async function runProxy(o) {
|
|
|
37923
38311
|
const bare = !/[\\/]/.test(o.command);
|
|
37924
38312
|
const child = spawn3(o.command, o.args, { stdio: ["pipe", "pipe", "inherit"], shell: process.platform === "win32" && (bare || /\.(cmd|bat)$/i.test(o.command)) });
|
|
37925
38313
|
let service = o.command.split(/[\\/]/).pop() ?? o.command, version2;
|
|
38314
|
+
let remoteRevoked = false, toolsChanged = false;
|
|
38315
|
+
const pollRevocations = async () => {
|
|
38316
|
+
if (!o.revocationsUrl || !o.mandate)
|
|
38317
|
+
return;
|
|
38318
|
+
try {
|
|
38319
|
+
const r = await fetch(o.revocationsUrl);
|
|
38320
|
+
if (r.ok) {
|
|
38321
|
+
const j = await r.json();
|
|
38322
|
+
const list = Array.isArray(j) ? j : j.revoked ?? [];
|
|
38323
|
+
if (list.some((e) => validRevocation(e, o.mandate)))
|
|
38324
|
+
remoteRevoked = true;
|
|
38325
|
+
}
|
|
38326
|
+
} catch {
|
|
38327
|
+
}
|
|
38328
|
+
};
|
|
38329
|
+
await pollRevocations();
|
|
38330
|
+
if (o.revocationsUrl)
|
|
38331
|
+
setInterval(pollRevocations, 5 * 6e4).unref();
|
|
38332
|
+
const digest = (args) => o.digestKey ? keyedDigest(args, o.digestKey) : argumentsHash(args);
|
|
37926
38333
|
const annotations = /* @__PURE__ */ new Map();
|
|
37927
38334
|
const toolDefs = /* @__PURE__ */ new Map();
|
|
37928
38335
|
const pendingKinds = /* @__PURE__ */ new Map();
|
|
@@ -37954,6 +38361,12 @@ async function runProxy(o) {
|
|
|
37954
38361
|
appendFileSync(o.receiptsPath, JSON.stringify(entry) + "\n");
|
|
37955
38362
|
last = entry;
|
|
37956
38363
|
history.push(entry);
|
|
38364
|
+
if (o.checkpointEvery && o.checkpointFile && entry.seq % o.checkpointEvery === 0) {
|
|
38365
|
+
try {
|
|
38366
|
+
appendFileSync(o.checkpointFile, JSON.stringify(makeCheckpoint(history, o.agentKey)) + "\n");
|
|
38367
|
+
} catch {
|
|
38368
|
+
}
|
|
38369
|
+
}
|
|
37957
38370
|
};
|
|
37958
38371
|
createInterface({ input: process.stdin }).on("line", (line) => {
|
|
37959
38372
|
let msg;
|
|
@@ -37968,71 +38381,79 @@ async function runProxy(o) {
|
|
|
37968
38381
|
if (msg.method === "tools/call" && msg.id !== void 0) {
|
|
37969
38382
|
const tool = String(msg.params?.name ?? "");
|
|
37970
38383
|
const args = msg.params?.arguments ?? {};
|
|
37971
|
-
const argsHash =
|
|
38384
|
+
const argsHash = digest(args);
|
|
37972
38385
|
const ann = annotations.get(tool);
|
|
37973
38386
|
const def = toolDefs.get(tool);
|
|
37974
38387
|
const isMoney = def ? capabilityProfile([def]).capabilities.some((c) => c.capability === "money") : false;
|
|
37975
38388
|
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
|
-
|
|
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" };
|
|
38389
|
+
let d;
|
|
37978
38390
|
let rationale;
|
|
37979
|
-
|
|
37980
|
-
|
|
37981
|
-
|
|
37982
|
-
|
|
37983
|
-
|
|
37984
|
-
|
|
37985
|
-
|
|
37986
|
-
|
|
37987
|
-
|
|
37988
|
-
|
|
37989
|
-
|
|
37990
|
-
|
|
37991
|
-
|
|
37992
|
-
|
|
37993
|
-
|
|
37994
|
-
|
|
37995
|
-
|
|
37996
|
-
|
|
37997
|
-
|
|
37998
|
-
|
|
37999
|
-
|
|
38000
|
-
|
|
38001
|
-
|
|
38002
|
-
|
|
38003
|
-
|
|
38004
|
-
|
|
38391
|
+
let metering;
|
|
38392
|
+
try {
|
|
38393
|
+
const rev = o.mandate ? revocationOf(o.mandate, o.revocationsPath) : void 0;
|
|
38394
|
+
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)" } : findSecret(JSON.stringify(args ?? {})) ? { allow: false, code: "secret-in-arguments", reason: `the arguments contain what looks like a secret (${findSecret(JSON.stringify(args ?? {}))}); it was not sent and is not recorded` } : 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" };
|
|
38395
|
+
if (d.allow && o.mandate && hasIntent(o.mandate)) {
|
|
38396
|
+
const di = decideIntent(o.mandate, def ?? { name: tool }, args, { server: service });
|
|
38397
|
+
rationale = di.rationale;
|
|
38398
|
+
for (const [k, val] of Object.entries(di.values))
|
|
38399
|
+
if (typeof val === "number" || typeof val === "string" || typeof val === "boolean")
|
|
38400
|
+
values[k] = val;
|
|
38401
|
+
if (!di.allow)
|
|
38402
|
+
d = { allow: false, code: di.code, reason: di.reason };
|
|
38403
|
+
else if (di.reason !== "within the mandate")
|
|
38404
|
+
d = { allow: true, code: "ok", reason: di.reason };
|
|
38405
|
+
}
|
|
38406
|
+
if (!d.allow && d.code === "approval-needed" && o.mandate) {
|
|
38407
|
+
const rid = approvalRequestId(o.mandate, tool, args);
|
|
38408
|
+
const ap = approvalUsedInChain(history, rid) ? { ok: false } : consumeApproval(o.mandate, rid, o.approvalsPath);
|
|
38409
|
+
if (ap.ok)
|
|
38410
|
+
d = { allow: true, code: "ok", reason: `approved by ${ap.by} (${rid}), after: ${d.reason}` };
|
|
38411
|
+
else {
|
|
38412
|
+
d = { ...d, reason: `${d.reason} [approval request ${rid}]` };
|
|
38413
|
+
try {
|
|
38414
|
+
recordPending(o.approvalsPath ?? DEFAULT_APPROVALS(), { id: rid, tool, reason: d.reason, agent: o.mandate.agent.name });
|
|
38415
|
+
} catch {
|
|
38416
|
+
}
|
|
38417
|
+
if (o.approvalWebhook) {
|
|
38418
|
+
const t = o.approvalSecret ? createHmac2("sha256", o.approvalSecret).update(rid).digest("hex").slice(0, 32) : "";
|
|
38419
|
+
const link = o.approvalUrl ? `${o.approvalUrl}${o.approvalUrl.includes("?") ? "&" : "?"}id=${rid}${t ? `&t=${t}` : ""}` : "";
|
|
38420
|
+
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>`}`;
|
|
38421
|
+
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);
|
|
38422
|
+
}
|
|
38005
38423
|
}
|
|
38006
38424
|
}
|
|
38425
|
+
if (d.allow && o.credential) {
|
|
38426
|
+
const vc = verifyChain(o.credential, { revoked: o.revokedCredentials });
|
|
38427
|
+
const root = [...o.credential.chain ?? [], o.credential][0].subject.id;
|
|
38428
|
+
if (!vc.valid)
|
|
38429
|
+
d = { allow: false, code: "identity-chain", reason: `the agent's accountability chain is broken: ${vc.reason}` };
|
|
38430
|
+
else if (vc.tools && !vc.tools.includes(tool))
|
|
38431
|
+
d = { allow: false, code: "outside-credential-scope", reason: `the agent's credential covers only ${vc.tools.join(", ")}` };
|
|
38432
|
+
else if (o.agreement && root !== o.agreement.invoker.id)
|
|
38433
|
+
d = { allow: false, code: "identity-chain", reason: "the agent's organisation is not the party to the agreement" };
|
|
38434
|
+
}
|
|
38435
|
+
if (d.allow && o.agreement) {
|
|
38436
|
+
const va = verifyAgreement(o.agreement);
|
|
38437
|
+
if (!va.valid)
|
|
38438
|
+
d = { allow: false, code: "no-valid-agreement", reason: `no valid agreement with the provider: ${va.reason}` };
|
|
38439
|
+
else if (o.agreement.scope.tools && !o.agreement.scope.tools.includes(tool))
|
|
38440
|
+
d = { allow: false, code: "outside-agreement", reason: `${tool} is outside the agreement ${o.agreement.id}` };
|
|
38441
|
+
else if (o.walletPath) {
|
|
38442
|
+
const ch = chargeCall(o.walletPath, o.agreement, tool, `${o.agreement.id}:${tool}`, o.agentKey);
|
|
38443
|
+
if (!ch.ok)
|
|
38444
|
+
d = { allow: false, code: "insufficient-credit", reason: `${tool} costs ${ch.tokens} tokens; the prepaid balance is ${ch.balance}` };
|
|
38445
|
+
else
|
|
38446
|
+
metering = { agreement: o.agreement.id, tokens: ch.tokens, balance: ch.balance };
|
|
38447
|
+
} else
|
|
38448
|
+
metering = { agreement: o.agreement.id, tokens: o.agreement.rates.perTool?.[tool] ?? o.agreement.rates.perCall, balance: -1 };
|
|
38449
|
+
}
|
|
38450
|
+
} catch (err) {
|
|
38451
|
+
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
38452
|
}
|
|
38008
|
-
if (d.allow && o.
|
|
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) {
|
|
38453
|
+
if (!d.allow && (o.enforce || d.code === "error-fail-closed")) {
|
|
38033
38454
|
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
38455
|
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
|
-
record2(tool, argsHash, "deny", d.reason, { status: "blocked", destructive: isDestructive(ann), code: d.code, values, ...rationale ? { rationale } : {} });
|
|
38456
|
+
record2(tool, argsHash, "deny", d.reason, { status: "blocked", destructive: isDestructive(ann), code: d.code, values: d.code === "secret-in-arguments" ? void 0 : values, ...rationale ? { rationale } : {} });
|
|
38036
38457
|
o.log?.(`denied ${tool} (${d.code}): ${d.reason}`);
|
|
38037
38458
|
return;
|
|
38038
38459
|
}
|
|
@@ -38075,13 +38496,28 @@ async function runProxy(o) {
|
|
|
38075
38496
|
annotations.set(t.name, t.annotations);
|
|
38076
38497
|
toolDefs.set(t.name, def);
|
|
38077
38498
|
}
|
|
38499
|
+
if (o.pin) {
|
|
38500
|
+
const fp = sha256Tag(canonicalize([...msg.result.tools].sort((a, b) => String(a.name).localeCompare(String(b.name)))));
|
|
38501
|
+
toolsChanged = fp !== o.pin;
|
|
38502
|
+
if (toolsChanged)
|
|
38503
|
+
o.log?.(`tools changed: ${fp} differs from the pinned ${o.pin}`);
|
|
38504
|
+
}
|
|
38078
38505
|
pendingKinds.delete(k);
|
|
38079
38506
|
}
|
|
38080
38507
|
const c = calls.get(k);
|
|
38081
38508
|
if (c) {
|
|
38082
38509
|
calls.delete(k);
|
|
38083
38510
|
const status = msg.error ? "protocol-error" : msg.result?.isError ? "tool-error" : "ok";
|
|
38084
|
-
|
|
38511
|
+
const text2 = msg.result ? resultText(msg.result) : "";
|
|
38512
|
+
const hidden = text2 ? findHiddenInstruction(text2, { broad: true }) : void 0, secret = text2 ? findSecret(text2) : void 0;
|
|
38513
|
+
const flags = [...hidden ? ["hidden-instruction-in-result"] : [], ...secret ? [`secret-in-result:${secret}`] : []];
|
|
38514
|
+
if (flags.length)
|
|
38515
|
+
o.log?.(`${c.tool}: result flagged (${flags.join(", ")})`);
|
|
38516
|
+
if (flags.length && o.quarantineResults) {
|
|
38517
|
+
msg.result = { content: [{ type: "text", text: `Withheld by Saktum: this tool's result contained ${hidden ? "instructions aimed at the agent" : "what looks like a secret"}. Ask the user before continuing.` }], isError: true };
|
|
38518
|
+
line = JSON.stringify(msg);
|
|
38519
|
+
}
|
|
38520
|
+
record2(c.tool, c.argsHash, msg.error ? "error" : "allow", c.reason + (flags.length ? ` [result ${o.quarantineResults ? "withheld" : "flagged"}: ${flags.join(", ")}]` : ""), { status, latencyMs: Date.now() - c.start, destructive: c.destructive, code: c.code, values: c.values, outputDigest: digest(msg.result ?? msg.error ?? null), ...flags.length ? { flags } : {}, ...c.rationale ? { rationale: c.rationale } : {}, ...c.metering ? { metering: c.metering } : {} });
|
|
38085
38521
|
}
|
|
38086
38522
|
process.stdout.write(line + "\n");
|
|
38087
38523
|
});
|
|
@@ -38094,6 +38530,7 @@ async function runProxy(o) {
|
|
|
38094
38530
|
var init_proxy = __esm({
|
|
38095
38531
|
"packages/cli/dist/proxy.js"() {
|
|
38096
38532
|
"use strict";
|
|
38533
|
+
init_dist();
|
|
38097
38534
|
init_dist4();
|
|
38098
38535
|
}
|
|
38099
38536
|
});
|
|
@@ -38854,7 +39291,7 @@ __export(demo_exports, {
|
|
|
38854
39291
|
import { mkdirSync as mkdirSync5, readFileSync as readFileSync8, writeFileSync as writeFileSync4, existsSync as existsSync6, rmSync } from "node:fs";
|
|
38855
39292
|
import { join as join6 } from "node:path";
|
|
38856
39293
|
async function startDemoServer(story = "autonomy") {
|
|
38857
|
-
const tools = story === "grocery" ? GROCERY_TOOLS : story === "travel" ? TRAVEL_TOOLS : story === "finance" ? FINANCE_TOOLS : story === "coding" ? CODING_TOOLS : DEMO_TOOLS;
|
|
39294
|
+
const tools = story === "grocery" ? GROCERY_TOOLS : story === "travel" ? TRAVEL_TOOLS : story === "finance" ? FINANCE_TOOLS : story === "coding" ? CODING_TOOLS : story === "support" ? SUPPORT_TOOLS : DEMO_TOOLS;
|
|
38858
39295
|
const server = new Server({ name: story === "travel" ? "demo-travel" : story === "finance" ? "demo-finance" : "demo-grocer", version: "1.0.0" }, { capabilities: { tools: {} } });
|
|
38859
39296
|
const cart = [];
|
|
38860
39297
|
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
|
|
@@ -38887,6 +39324,10 @@ async function startDemoServer(story = "autonomy") {
|
|
|
38887
39324
|
return text2(`Sent "${a.report}" to ${a.recipient}.`);
|
|
38888
39325
|
case "pay_invoice":
|
|
38889
39326
|
return text2(`Paid $${a.amount} to ${a.vendor}.`);
|
|
39327
|
+
case "lookup_customer":
|
|
39328
|
+
return text2(`${a.customer_id}: 3 orders; latest arrived damaged.`);
|
|
39329
|
+
case "issue_refund":
|
|
39330
|
+
return text2(`Refunded $${a.amount} to ${a.customer_id}.`);
|
|
38890
39331
|
case "run_tests":
|
|
38891
39332
|
return text2(`${a.repository}: 412 tests passed.`);
|
|
38892
39333
|
case "open_pull_request":
|
|
@@ -39118,7 +39559,7 @@ async function runDemo(dir, log, story = "all") {
|
|
|
39118
39559
|
const owner = loadOrCreateKey(join6(dir, "owner-key.json"));
|
|
39119
39560
|
log("Saktum demo: agents acting on real instructions (rules, preferences, substitutions, upsells), every decision explained and signed.\n");
|
|
39120
39561
|
const files = [];
|
|
39121
|
-
for (const st of story === "travel" ? [TRAVEL] : story === "grocery" ? [GROCERY] : story === "finance" ? [FINANCE] : story === "coding" ? [CODING] : [GROCERY, TRAVEL, FINANCE, CODING])
|
|
39562
|
+
for (const st of story === "travel" ? [TRAVEL] : story === "grocery" ? [GROCERY] : story === "finance" ? [FINANCE] : story === "coding" ? [CODING] : story === "support" ? [SUPPORT] : [GROCERY, TRAVEL, FINANCE, CODING, SUPPORT])
|
|
39122
39563
|
files.push(await runStory(dir, st, owner, log));
|
|
39123
39564
|
if (story === "all")
|
|
39124
39565
|
files.push(await runMarketplace(dir, log));
|
|
@@ -39195,7 +39636,7 @@ async function runAutonomyDemo(dir, log) {
|
|
|
39195
39636
|
log("What you just saw: the same agent and the same shop. Only the mandate changed what it was allowed to do, and every\ndecision, allowed or blocked, has a signed receipt. Open the passports to see each agent's permissions and path.");
|
|
39196
39637
|
return { files };
|
|
39197
39638
|
}
|
|
39198
|
-
var PRODUCTS, DEMO_TOOLS, B, GROCERY_TOOLS, TRAVEL_TOOLS, FINANCE_TOOLS, CODING_TOOLS, SCRIPT, EXTRA, GROCERY, TRAVEL, FINANCE, CODING;
|
|
39639
|
+
var PRODUCTS, DEMO_TOOLS, B, GROCERY_TOOLS, TRAVEL_TOOLS, FINANCE_TOOLS, CODING_TOOLS, SUPPORT_TOOLS, SCRIPT, EXTRA, GROCERY, TRAVEL, FINANCE, CODING, SUPPORT;
|
|
39199
39640
|
var init_demo = __esm({
|
|
39200
39641
|
"packages/cli/dist/demo.js"() {
|
|
39201
39642
|
"use strict";
|
|
@@ -39255,6 +39696,10 @@ var init_demo = __esm({
|
|
|
39255
39696
|
{ name: "deploy_to_staging", description: "Deploy a build to the staging environment.", inputSchema: { type: "object", properties: { repository: { type: "string" }, build: { type: "string" } }, required: ["repository", "build"] }, annotations: { readOnlyHint: false, destructiveHint: false }, _meta: B({ repository: "code.repository" }, "change") },
|
|
39256
39697
|
{ name: "deploy_to_production", description: "Release a build to production.", inputSchema: { type: "object", properties: { repository: { type: "string" }, build: { type: "string" } }, required: ["repository", "build"] }, annotations: { readOnlyHint: false, destructiveHint: true }, _meta: B({ repository: "code.repository" }, "deploy") }
|
|
39257
39698
|
];
|
|
39699
|
+
SUPPORT_TOOLS = [
|
|
39700
|
+
{ name: "lookup_customer", description: "Look up a customer's account and recent orders.", inputSchema: { type: "object", properties: { customer_id: { type: "string" } }, required: ["customer_id"] }, annotations: { readOnlyHint: true }, _meta: B({ customer_id: "support.customer_id" }, "search") },
|
|
39701
|
+
{ name: "issue_refund", description: "Refund an amount to the customer's original payment method.", inputSchema: { type: "object", properties: { customer_id: { type: "string" }, amount: { type: "number" } }, required: ["customer_id", "amount"] }, annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false }, _meta: B({ customer_id: "support.customer_id", amount: "support.amount" }, "pay") }
|
|
39702
|
+
];
|
|
39258
39703
|
SCRIPT = [
|
|
39259
39704
|
{ tool: "get_deals", args: {}, say: "checks this week's deals" },
|
|
39260
39705
|
{ tool: "search_products", args: { query: "coffee" }, say: "searches for coffee" },
|
|
@@ -39345,6 +39790,21 @@ var init_demo = __esm({
|
|
|
39345
39790
|
{ tool: "", args: {}, say: "in the morning, you approve exactly that release (saktum agent approve)", approveLast: true },
|
|
39346
39791
|
{ tool: "deploy_to_production", args: { repository: "payments-service", build: "build-2291" }, say: "retries the same release" }
|
|
39347
39792
|
] };
|
|
39793
|
+
SUPPORT = { id: "support", title: `Support agent: "resolve this customer's case; refunds over $100 need a person"`, server: "support", tools: SUPPORT_TOOLS.map((t) => t.name), m: {
|
|
39794
|
+
autonomy: "act",
|
|
39795
|
+
purpose: "Resolve support case 7731 for customer C-1042",
|
|
39796
|
+
actions: [{ cls: "search", autonomy: "act" }, { cls: "pay", autonomy: "act" }],
|
|
39797
|
+
rules: [{ field: "support.customer_id", op: "in", value: ["C-1042"], label: "only this case's customer" }],
|
|
39798
|
+
approveAbove: { arg: "amount", value: 100 },
|
|
39799
|
+
disclosures: { operator: "Acme support", incentives: "None", dataUse: "This case's customer only" }
|
|
39800
|
+
}, steps: [
|
|
39801
|
+
{ tool: "lookup_customer", args: { customer_id: "C-1042" }, say: "looks up the customer on the case" },
|
|
39802
|
+
{ tool: "issue_refund", args: { customer_id: "C-1042", amount: 40 }, say: "refunds $40 for the damaged item" },
|
|
39803
|
+
{ tool: "lookup_customer", args: { customer_id: "C-2077" }, say: "tries to look up a different customer" },
|
|
39804
|
+
{ tool: "issue_refund", args: { customer_id: "C-1042", amount: 250 }, say: "tries to refund $250 (goodwill)" },
|
|
39805
|
+
{ tool: "", args: {}, say: "a support lead approves exactly that refund (saktum agent approve)", approveLast: true },
|
|
39806
|
+
{ tool: "issue_refund", args: { customer_id: "C-1042", amount: 250 }, say: "retries the same refund" }
|
|
39807
|
+
] };
|
|
39348
39808
|
}
|
|
39349
39809
|
});
|
|
39350
39810
|
|
|
@@ -39738,6 +40198,15 @@ What would you like to do?
|
|
|
39738
40198
|
All commands: npx saktum --help \xB7 Guide: https://github.com/soodhere/saktum-check
|
|
39739
40199
|
`;
|
|
39740
40200
|
var bundledPacks = fileURLToPath2(new URL("../../../packs/", import.meta.url));
|
|
40201
|
+
var secretFrom = (spec) => {
|
|
40202
|
+
if (spec.startsWith("env:")) {
|
|
40203
|
+
const v = process.env[spec.slice(4)];
|
|
40204
|
+
if (!v)
|
|
40205
|
+
throw new Error(`Environment variable ${spec.slice(4)} is not set.`);
|
|
40206
|
+
return v;
|
|
40207
|
+
}
|
|
40208
|
+
return spec;
|
|
40209
|
+
};
|
|
39741
40210
|
var collect = (v, acc) => [...acc, v];
|
|
39742
40211
|
var parseHeaders = (hs) => Object.fromEntries(hs.map((h) => {
|
|
39743
40212
|
const i = h.indexOf(":");
|
|
@@ -40143,15 +40612,15 @@ ${r.errors.slice(0, 10).map((e) => ` ${sanitizeText(e, 200)}`).join("\n")}
|
|
|
40143
40612
|
const latest = /* @__PURE__ */ new Map();
|
|
40144
40613
|
for (const e of entries)
|
|
40145
40614
|
latest.set(e.subject.server, e);
|
|
40146
|
-
for (const e of latest.values())
|
|
40615
|
+
for (const e of [...latest.values()].filter((x) => x.attestation))
|
|
40147
40616
|
writeFileSync5(`${o.out}/${passportSlug(e.subject.server)}.html`, renderLedgerPassport(e));
|
|
40148
|
-
writeFileSync5(`${o.out}/index.html`, renderPassportGallery(entries));
|
|
40617
|
+
writeFileSync5(`${o.out}/index.html`, renderPassportGallery(entries.filter((x) => x.attestation)));
|
|
40149
40618
|
process.stdout.write(`Wrote ${latest.size} passport page(s) and the gallery to ${sanitizeText(o.out)}.
|
|
40150
40619
|
`);
|
|
40151
40620
|
});
|
|
40152
40621
|
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
40622
|
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) } : {} });
|
|
40623
|
+
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
40624
|
writeFileSync5(o.ledger, text2);
|
|
40156
40625
|
process.stdout.write(`Recorded entry #${entry.seq} for ${sanitizeText(entry.subject.server, 80)} (signed by ${entry.signer}); entry hash ${entry.entryHash}.
|
|
40157
40626
|
`);
|
|
@@ -40247,13 +40716,16 @@ Wrote ${sanitizeText(o.out)} and the agent key ${sanitizeText(o.agentKey)} (keep
|
|
|
40247
40716
|
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
40717
|
`);
|
|
40249
40718
|
});
|
|
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) => {
|
|
40719
|
+
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
40720
|
const m = JSON.parse(readFileSync10(f, "utf8"));
|
|
40252
|
-
const
|
|
40721
|
+
const key = o.key ? loadOrCreateKey(o.key) : void 0;
|
|
40722
|
+
const r = revokeMandate(m, o.reason, void 0, key);
|
|
40723
|
+
if (o.out && key)
|
|
40724
|
+
writeFileSync5(o.out, JSON.stringify(signRevocation(m, key, o.reason), null, 2) + "\n");
|
|
40253
40725
|
process.stdout.write(`Revoked the mandate for ${sanitizeText(m.agent.name, 80)} at ${r.at}. Its calls are now refused (code: revoked).
|
|
40254
40726
|
`);
|
|
40255
40727
|
});
|
|
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) => {
|
|
40728
|
+
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").option("--quarantine-results", "withhold tool results that contain instructions aimed at the agent or secrets (default: flag them in receipts)", false).action(async (parts, o) => {
|
|
40257
40729
|
const { homedir: homedir2 } = await import("node:os");
|
|
40258
40730
|
const { join: join7 } = await import("node:path");
|
|
40259
40731
|
let mandate;
|
|
@@ -40283,6 +40755,12 @@ Wrote ${sanitizeText(o.out)} and the agent key ${sanitizeText(o.agentKey)} (keep
|
|
|
40283
40755
|
...o.approvalWebhook ? { approvalWebhook: o.approvalWebhook } : {},
|
|
40284
40756
|
...o.approvalUrl ? { approvalUrl: o.approvalUrl } : {},
|
|
40285
40757
|
...o.bindings ? { bindingsOverride: JSON.parse(readFileSync10(o.bindings, "utf8")) } : {},
|
|
40758
|
+
...o.revocationsUrl ? { revocationsUrl: o.revocationsUrl } : {},
|
|
40759
|
+
...o.digestKey ? { digestKey: secretFrom(o.digestKey) } : {},
|
|
40760
|
+
...o.pin ? { pin: o.pin } : {},
|
|
40761
|
+
...o.checkpointEvery && o.checkpointFile ? { checkpointEvery: Number(o.checkpointEvery), checkpointFile: o.checkpointFile } : {},
|
|
40762
|
+
...o.approvalSecret ? { approvalSecret: secretFrom(o.approvalSecret) } : {},
|
|
40763
|
+
...o.quarantineResults ? { quarantineResults: true } : {},
|
|
40286
40764
|
log: (m) => process.stderr.write(`saktum: ${m}
|
|
40287
40765
|
`)
|
|
40288
40766
|
});
|
|
@@ -40326,6 +40804,14 @@ ${r.errors.slice(0, 10).map((e) => ` ${e}`).join("\n")}
|
|
|
40326
40804
|
`);
|
|
40327
40805
|
exitCode = logs.every((l) => l.verified) ? 0 : 1;
|
|
40328
40806
|
});
|
|
40807
|
+
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) => {
|
|
40808
|
+
const { homedir: homedir2 } = await import("node:os");
|
|
40809
|
+
const { join: join7 } = await import("node:path");
|
|
40810
|
+
const cp = makeCheckpoint(parseReceiptLog(readFileSync10(f ?? join7(homedir2(), ".saktum", "receipts.jsonl"), "utf8")), loadOrCreateKey(o.key));
|
|
40811
|
+
writeFileSync5(o.out, JSON.stringify(cp, null, 2) + "\n");
|
|
40812
|
+
process.stdout.write(`Checkpoint at receipt ${cp.seq} (${cp.head.slice(0, 20)}...) written to ${sanitizeText(o.out)}.
|
|
40813
|
+
`);
|
|
40814
|
+
});
|
|
40329
40815
|
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
40816
|
const { homedir: homedir2 } = await import("node:os");
|
|
40331
40817
|
const { join: join7 } = await import("node:path");
|
|
@@ -40484,11 +40970,13 @@ To declare them, add to each tool's definition (MCP tools accept _meta):
|
|
|
40484
40970
|
`);
|
|
40485
40971
|
});
|
|
40486
40972
|
const identity = program2.command("identity").description("Identity chains: organisation -> people -> agents");
|
|
40487
|
-
identity.command("issue").description("Issue a credential to a person or an agent, from your own credential").requiredOption("--from <credential>", "your credential (the organisation's, or one it issued to you)").requiredOption("--key <path>", "your signing key").requiredOption("--type <type>", "member or agent").requiredOption("--name <name>", "the subject's name").option("--subject-key <path>", "the subject's key file (its id is used)").option("--subject <did>", "the subject's did:key").option("--role <role>", "role, for a member").option("--expires <date>", "YYYY-MM-DD", new Date(Date.now() + 180 * 864e5).toISOString().slice(0, 10)).option("--out <file>", "credential file", "credential.json").action((o) => {
|
|
40973
|
+
identity.command("issue").description("Issue a credential to a person or an agent, from your own credential").requiredOption("--from <credential>", "your credential (the organisation's, or one it issued to you)").requiredOption("--key <path>", "your signing key").requiredOption("--type <type>", "member or agent").requiredOption("--name <name>", "the subject's name").option("--subject-key <path>", "the subject's key file (its id is used)").option("--subject <did>", "the subject's did:key").option("--role <role>", "role, for a member").option("--expires <date>", "YYYY-MM-DD", new Date(Date.now() + 180 * 864e5).toISOString().slice(0, 10)).option("--out <file>", "credential file", "credential.json").option("--minutes <n>", "short-lived: expire this many minutes from now (overrides --expires)").option("--tools <list>", "comma-separated tools this credential covers (can only narrow down the chain)").option("--max-depth <n>", "how many credentials may follow this one in a chain (0 = no further delegation)").action((o) => {
|
|
40974
|
+
if (o.minutes)
|
|
40975
|
+
o.expires = new Date(Date.now() + Number(o.minutes) * 6e4).toISOString();
|
|
40488
40976
|
const subject = o.subject ?? (o.subjectKey ? loadOrCreateKey(o.subjectKey).kid : void 0);
|
|
40489
40977
|
if (!subject)
|
|
40490
40978
|
throw new Error("Give --subject <did:key> or --subject-key <file>.");
|
|
40491
|
-
const c = issueCredential(JSON.parse(readFileSync10(o.from, "utf8")), loadOrCreateKey(o.key), { type: o.type, id: subject, name: o.name, role: o.role, expires: o.expires });
|
|
40979
|
+
const c = issueCredential(JSON.parse(readFileSync10(o.from, "utf8")), loadOrCreateKey(o.key), { type: o.type, id: subject, name: o.name, role: o.role, expires: o.expires, ...o.tools ? { tools: o.tools.split(",").map((t) => t.trim()).filter(Boolean) } : {}, ...o.maxDepth !== void 0 ? { maxDepth: Number(o.maxDepth) } : {} });
|
|
40492
40980
|
writeFileSync5(o.out, JSON.stringify(c, null, 2) + "\n");
|
|
40493
40981
|
process.stdout.write(`Issued ${c.id} to ${sanitizeText(o.name, 80)} (${o.type}). Chain: ${verifyChain(c).path.join(" -> ")}
|
|
40494
40982
|
`);
|
|
@@ -40641,11 +41129,19 @@ ${" ".repeat(36)}${i.evidence}${i.commands.length ? ` (${i.commands.join("; ")})
|
|
|
40641
41129
|
${DISCLAIMER}
|
|
40642
41130
|
`);
|
|
40643
41131
|
});
|
|
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
|
|
41132
|
+
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
41133
|
if (!/^https?:\/\//.test(url2))
|
|
40646
41134
|
throw new Error("Give the remote server's http(s) URL.");
|
|
41135
|
+
const h = parseHeaders(o.header);
|
|
41136
|
+
for (const x of o.headerEnv) {
|
|
41137
|
+
const i = x.indexOf("=");
|
|
41138
|
+
const v = process.env[x.slice(i + 1)];
|
|
41139
|
+
if (i < 1 || v === void 0)
|
|
41140
|
+
throw new Error(`--header-env ${x}: use Name=VAR with VAR set`);
|
|
41141
|
+
h[x.slice(0, i)] = v;
|
|
41142
|
+
}
|
|
40647
41143
|
const { runBridge: runBridge2 } = await Promise.resolve().then(() => (init_bridge(), bridge_exports));
|
|
40648
|
-
exitCode = await runBridge2(url2,
|
|
41144
|
+
exitCode = await runBridge2(url2, h);
|
|
40649
41145
|
});
|
|
40650
41146
|
const approvals = program2.command("approvals").description("Approvals by link (v0.10)");
|
|
40651
41147
|
approvals.command("list").option("--approvals <file>", "approvals file").action((o) => {
|
|
@@ -40656,50 +41152,112 @@ ${DISCLAIMER}
|
|
|
40656
41152
|
process.stdout.write(`${p.length} waiting.
|
|
40657
41153
|
`);
|
|
40658
41154
|
});
|
|
40659
|
-
approvals.command("serve").description("A local page where the mandate's owner approves exactly one pending action with
|
|
41155
|
+
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
41156
|
const http = await import("node:http");
|
|
40661
|
-
const { randomBytes } = await import("node:crypto");
|
|
41157
|
+
const { randomBytes, createHmac: createHmac3 } = await import("node:crypto");
|
|
40662
41158
|
const m = JSON.parse(readFileSync10(o.mandate, "utf8"));
|
|
40663
41159
|
const key = loadOrCreateKey(o.key);
|
|
40664
41160
|
const token = randomBytes(16).toString("hex");
|
|
40665
41161
|
if (key.kid !== m.owner.id)
|
|
40666
41162
|
throw new Error("This key is not the mandate owner's key.");
|
|
41163
|
+
const secret = o.secret ? secretFrom(o.secret) : "";
|
|
41164
|
+
const origin = `http://${o.host}:${o.port}`, rpId = o.host;
|
|
41165
|
+
const nonces = /* @__PURE__ */ new Map();
|
|
41166
|
+
const pks = () => existsSync7(o.passkeys) ? JSON.parse(readFileSync10(o.passkeys, "utf8")) : [];
|
|
40667
41167
|
const esc22 = (x) => String(x).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
|
|
40668
|
-
const
|
|
41168
|
+
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(/=+$/,'');`;
|
|
41169
|
+
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>`;
|
|
41170
|
+
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);
|
|
41171
|
+
const item = (x, q) => {
|
|
41172
|
+
const n = randomBytes(12).toString("hex");
|
|
41173
|
+
nonces.set(x.id, n);
|
|
41174
|
+
const ch = `${x.id}:${n}`;
|
|
41175
|
+
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>`;
|
|
41176
|
+
};
|
|
41177
|
+
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
41178
|
const server = http.createServer((req, res) => {
|
|
40670
|
-
const u = new URL(req.url ?? "/",
|
|
40671
|
-
|
|
40672
|
-
res.writeHead(
|
|
40673
|
-
res.end(
|
|
41179
|
+
const u = new URL(req.url ?? "/", origin);
|
|
41180
|
+
const send = (code, html) => {
|
|
41181
|
+
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'" });
|
|
41182
|
+
res.end(html);
|
|
41183
|
+
};
|
|
41184
|
+
if (u.pathname === "/passkey/register") {
|
|
41185
|
+
if (u.searchParams.get("token") !== token)
|
|
41186
|
+
return send(403, "Forbidden");
|
|
41187
|
+
if (req.method === "GET") {
|
|
41188
|
+
const ch = randomBytes(16).toString("hex");
|
|
41189
|
+
nonces.set("register", ch);
|
|
41190
|
+
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>`));
|
|
41191
|
+
}
|
|
41192
|
+
let b = "";
|
|
41193
|
+
req.on("data", (c) => {
|
|
41194
|
+
b += c;
|
|
41195
|
+
if (b.length > 2e4)
|
|
41196
|
+
req.destroy();
|
|
41197
|
+
});
|
|
41198
|
+
req.on("end", () => {
|
|
41199
|
+
try {
|
|
41200
|
+
const r = verifyPasskeyRegistration(JSON.parse(b), { challenge: nonces.get("register") ?? "", origin, rpId });
|
|
41201
|
+
writeFileSync5(o.passkeys, JSON.stringify([...pks(), { ...r, binding: signDocument({ credentialId: r.credentialId, owner: m.owner.id, at: (/* @__PURE__ */ new Date()).toISOString() }, key) }], null, 2));
|
|
41202
|
+
nonces.delete("register");
|
|
41203
|
+
res.writeHead(200);
|
|
41204
|
+
res.end("Passkey registered. Restart approvals serve to use it.");
|
|
41205
|
+
} catch (e) {
|
|
41206
|
+
res.writeHead(400);
|
|
41207
|
+
res.end(`Registration failed: ${e.message}`);
|
|
41208
|
+
}
|
|
41209
|
+
});
|
|
40674
41210
|
return;
|
|
40675
41211
|
}
|
|
40676
|
-
if (req.method === "POST") {
|
|
41212
|
+
if (req.method === "POST" && u.pathname === "/approve") {
|
|
40677
41213
|
let b = "";
|
|
40678
41214
|
req.on("data", (c) => {
|
|
40679
41215
|
b += c;
|
|
40680
|
-
if (b.length >
|
|
41216
|
+
if (b.length > 2e4)
|
|
40681
41217
|
req.destroy();
|
|
40682
41218
|
});
|
|
40683
41219
|
req.on("end", () => {
|
|
40684
|
-
|
|
40685
|
-
|
|
40686
|
-
|
|
40687
|
-
|
|
40688
|
-
|
|
41220
|
+
let id = "", assertion = {};
|
|
41221
|
+
try {
|
|
41222
|
+
if ((req.headers["content-type"] ?? "").includes("json")) {
|
|
41223
|
+
const j = JSON.parse(b);
|
|
41224
|
+
id = j.id;
|
|
41225
|
+
assertion = j;
|
|
41226
|
+
} else
|
|
41227
|
+
id = new URLSearchParams(b).get("id") ?? "";
|
|
41228
|
+
} catch {
|
|
41229
|
+
}
|
|
41230
|
+
if (!okToken(u, id))
|
|
41231
|
+
return send(403, "Forbidden");
|
|
41232
|
+
if (!listPending(o.approvals).some((p2) => p2.id === id))
|
|
41233
|
+
return send(400, `<p>No pending request ${esc22(id)}.</p>`);
|
|
41234
|
+
if (o.passkey) {
|
|
41235
|
+
const pk = pks().find((p2) => p2.credentialId === assertion.credentialId && verifyDocument(p2.binding).kid === m.owner.id);
|
|
41236
|
+
let ok = false;
|
|
41237
|
+
try {
|
|
41238
|
+
ok = Boolean(pk) && verifyPasskeyAssertion(assertion, pk.jwk, { challenge: `${id}:${nonces.get(id) ?? ""}`, origin, rpId });
|
|
41239
|
+
} catch {
|
|
41240
|
+
ok = false;
|
|
41241
|
+
}
|
|
41242
|
+
if (!ok)
|
|
41243
|
+
return send(403, "<p>\u2717 Passkey check failed. Nothing was approved.</p>");
|
|
41244
|
+
nonces.delete(id);
|
|
40689
41245
|
}
|
|
40690
41246
|
approveAction(m, id, key, Number(o.minutes), o.approvals);
|
|
40691
|
-
|
|
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>`));
|
|
41247
|
+
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
41248
|
});
|
|
40694
41249
|
return;
|
|
40695
41250
|
}
|
|
40696
|
-
const only = u.searchParams.get("id");
|
|
41251
|
+
const only = u.searchParams.get("id") ?? void 0;
|
|
41252
|
+
if (!okToken(u, only))
|
|
41253
|
+
return send(403, "Forbidden");
|
|
41254
|
+
const q = u.searchParams.get("token") ? `token=${token}` : `t=${u.searchParams.get("t")}`;
|
|
40697
41255
|
const p = listPending(o.approvals).filter((x) => !only || x.id === only);
|
|
40698
|
-
|
|
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>"));
|
|
41256
|
+
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
41257
|
});
|
|
40701
|
-
server.listen(Number(o.port), o.host, () => process.stdout.write(`Approvals page:
|
|
40702
|
-
|
|
41258
|
+
server.listen(Number(o.port), o.host, () => process.stdout.write(`Approvals page (owner): ${origin}/?token=${token}
|
|
41259
|
+
${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}
|
|
41260
|
+
` : ""}Ctrl+C to stop.
|
|
40703
41261
|
`));
|
|
40704
41262
|
await new Promise(() => void 0);
|
|
40705
41263
|
});
|
|
@@ -40715,11 +41273,87 @@ Give the proxy --approval-url "http://${o.host}:${o.port}/?token=${token}" so re
|
|
|
40715
41273
|
if (o.out)
|
|
40716
41274
|
writeFileSync5(o.out, JSON.stringify(a, null, 2) + "\n");
|
|
40717
41275
|
});
|
|
40718
|
-
program2.
|
|
41276
|
+
const ledger2 = program2.commands.find((c) => c.name() === "ledger");
|
|
41277
|
+
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) => {
|
|
41278
|
+
const ok = loadOrCreateKey(o.oldKey), nk = loadOrCreateKey(o.newKey);
|
|
41279
|
+
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);
|
|
41280
|
+
writeFileSync5(o.out, JSON.stringify(st, null, 2) + "\n");
|
|
41281
|
+
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).
|
|
41282
|
+
`);
|
|
41283
|
+
});
|
|
41284
|
+
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) => {
|
|
41285
|
+
const k = loadOrCreateKey(o.key);
|
|
41286
|
+
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");
|
|
41287
|
+
process.stdout.write(`Revocation statement written to ${sanitizeText(o.out)}.
|
|
41288
|
+
`);
|
|
41289
|
+
});
|
|
41290
|
+
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) => {
|
|
41291
|
+
const e = parseLedger(await readLedgerText(src));
|
|
41292
|
+
const cp = makeCheckpoint(e, loadOrCreateKey(o.key), "saktum-ledger");
|
|
41293
|
+
writeFileSync5(o.out, JSON.stringify(cp, null, 2) + "\n");
|
|
41294
|
+
process.stdout.write(`Checkpoint at entry ${cp.seq} written to ${sanitizeText(o.out)}.
|
|
41295
|
+
`);
|
|
41296
|
+
});
|
|
41297
|
+
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) => {
|
|
41298
|
+
const cp = JSON.parse(readFileSync10(f, "utf8"));
|
|
41299
|
+
const e = parseLedger(await readLedgerText(o.ledger));
|
|
41300
|
+
if (!verifyLedger(e).ok)
|
|
41301
|
+
throw new Error("The ledger does not verify.");
|
|
41302
|
+
const w = witnessCheckpoint(cp, e, loadOrCreateKey(o.key));
|
|
41303
|
+
writeFileSync5(f, JSON.stringify(w, null, 2) + "\n");
|
|
41304
|
+
process.stdout.write(`Witnessed. Valid witnesses: ${validWitnesses(w).length}.
|
|
41305
|
+
`);
|
|
41306
|
+
});
|
|
41307
|
+
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) => {
|
|
41308
|
+
const cp = JSON.parse(readFileSync10(f, "utf8"));
|
|
41309
|
+
const e = o.receipts ? parseReceiptLog(readFileSync10(o.receipts, "utf8")) : parseLedger(await readLedgerText(o.ledger ?? DEFAULT_LEDGER_URL));
|
|
41310
|
+
const r = verifyAgainstCheckpoint(e, cp);
|
|
41311
|
+
process.stdout.write(r.ok ? `\u2713 Consistent with the checkpoint at ${cp.seq} (${validWitnesses(cp).length} witness signature(s)).
|
|
41312
|
+
` : `\u2717 ${r.reason}
|
|
41313
|
+
`);
|
|
41314
|
+
exitCode = r.ok ? 0 : 1;
|
|
41315
|
+
});
|
|
41316
|
+
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) => {
|
|
41317
|
+
const c = JSON.parse(readFileSync10(f, "utf8"));
|
|
41318
|
+
const d = c.issuer.domain;
|
|
41319
|
+
if (!d)
|
|
41320
|
+
throw new Error("This credential names no domain (org init --domain).");
|
|
41321
|
+
const r = await verifyDomain(d, c.subject.id);
|
|
41322
|
+
process.stdout.write(r.verified ? `\u2713 ${d} is verified for ${sanitizeText(c.subject.name, 80)} (${r.method}).
|
|
41323
|
+
` : `\u2717 Not verified. Add a DNS TXT record:
|
|
41324
|
+
_saktum.${d} "saktum-did=${c.subject.id}"
|
|
41325
|
+
or publish https://${d}/.well-known/saktum.json containing {"did":"${c.subject.id}"}.
|
|
41326
|
+
`);
|
|
41327
|
+
exitCode = r.verified ? 0 : 1;
|
|
41328
|
+
});
|
|
41329
|
+
wallet.command("verify").option("--wallet <file>", "wallet file", "saktum-wallet.json").action((o) => {
|
|
41330
|
+
const r = verifyWallet(o.wallet);
|
|
41331
|
+
process.stdout.write(r.ok ? "\u2713 Wallet entries intact (chained and, where signed, signatures valid).\n" : `\u2717 ${r.errors.join("; ")}
|
|
41332
|
+
`);
|
|
41333
|
+
exitCode = r.ok ? 0 : 1;
|
|
41334
|
+
});
|
|
41335
|
+
program2.command("self-verify").description("Check that the saktum you are running matches the published, signed release").action(async () => {
|
|
41336
|
+
const { createHash: createHash4 } = await import("node:crypto");
|
|
41337
|
+
const self = process.argv[1];
|
|
41338
|
+
const mine = createHash4("sha256").update(readFileSync10(self)).digest("hex");
|
|
41339
|
+
let published = "";
|
|
41340
|
+
try {
|
|
41341
|
+
const r = await fetch(`https://github.com/soodhere/saktum-check/releases/download/v${ENGINE_VERSION}/saktum.mjs.sha256`);
|
|
41342
|
+
if (r.ok)
|
|
41343
|
+
published = (await r.text()).trim().split(/\s+/)[0] ?? "";
|
|
41344
|
+
} catch {
|
|
41345
|
+
}
|
|
41346
|
+
process.stdout.write(`This copy (${sanitizeText(self, 120)}): sha256 ${mine}
|
|
41347
|
+
Published v${ENGINE_VERSION}: ${published || "(not reachable)"}
|
|
41348
|
+
${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
|
|
41349
|
+
npm provenance: npm audit signatures
|
|
41350
|
+
`);
|
|
41351
|
+
});
|
|
41352
|
+
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, support, marketplace, autonomy, or all (grocery, travel, finance, coding, support and marketplace)", "all").action(async (o) => {
|
|
40719
41353
|
const { runDemo: runDemo2 } = await Promise.resolve().then(() => (init_demo(), demo_exports));
|
|
40720
41354
|
await runDemo2(o.out, (l) => process.stdout.write(l + "\n"), o.story);
|
|
40721
41355
|
});
|
|
40722
|
-
program2.command("demo-server", { hidden: true }).description("The demo MCP servers (used by saktum demo)").option("--story <name>", "grocery, travel, finance, coding or autonomy", "autonomy").action(async (o) => {
|
|
41356
|
+
program2.command("demo-server", { hidden: true }).description("The demo MCP servers (used by saktum demo)").option("--story <name>", "grocery, travel, finance, coding, support or autonomy", "autonomy").action(async (o) => {
|
|
40723
41357
|
const { startDemoServer: startDemoServer2 } = await Promise.resolve().then(() => (init_demo(), demo_exports));
|
|
40724
41358
|
await startDemoServer2(o.story);
|
|
40725
41359
|
});
|