@agent-custody/receipts 0.16.10 → 0.16.12
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 +32 -12
- package/dist/approval-requests.d.ts +114 -0
- package/dist/approval-requests.js +198 -0
- package/dist/approval.d.ts +8 -0
- package/dist/approval.js +10 -3
- package/dist/check.js +14 -0
- package/dist/cli.js +184 -5
- package/dist/completeness.d.ts +11 -2
- package/dist/completeness.js +45 -9
- package/dist/config.d.ts +6 -0
- package/dist/config.js +19 -1
- package/dist/console-page.js +87 -2
- package/dist/console.js +72 -0
- package/dist/crypto.d.ts +2 -0
- package/dist/crypto.js +2 -1
- package/dist/delegation.d.ts +1 -1
- package/dist/delegation.js +19 -2
- package/dist/did-key.d.ts +2 -0
- package/dist/did-key.js +21 -1
- package/dist/door-app.js +1 -1
- package/dist/door-core.d.ts +385 -0
- package/dist/door-core.js +757 -0
- package/dist/door-error-rates.d.ts +102 -0
- package/dist/door-error-rates.js +178 -0
- package/dist/door-form.d.ts +7 -2
- package/dist/door-form.js +52 -4
- package/dist/door-measure.d.ts +153 -0
- package/dist/door-measure.js +325 -0
- package/dist/door-signals.d.ts +414 -0
- package/dist/door-signals.js +555 -0
- package/dist/door-test-set.d.ts +43 -0
- package/dist/door-test-set.js +117 -0
- package/dist/door-worker.d.ts +148 -0
- package/dist/door-worker.js +283 -0
- package/dist/door.d.ts +11 -293
- package/dist/door.js +45 -755
- package/dist/gateway-http.d.ts +1 -6
- package/dist/gateway-http.js +2 -19
- package/dist/gateway.js +24 -3
- package/dist/grant-header.d.ts +8 -0
- package/dist/grant-header.js +19 -0
- package/dist/index.d.ts +11 -2
- package/dist/index.js +6 -1
- package/dist/issue.d.ts +2 -16
- package/dist/issue.js +2 -12
- package/dist/lock.d.ts +5 -0
- package/dist/lock.js +1 -1
- package/dist/log-http.d.ts +37 -0
- package/dist/log-http.js +74 -0
- package/dist/log-sink.d.ts +3 -37
- package/dist/log-sink.js +5 -71
- package/dist/log.d.ts +2 -27
- package/dist/log.js +2 -173
- package/dist/merkle.d.ts +27 -0
- package/dist/merkle.js +175 -0
- package/dist/object-issuer.d.ts +29 -0
- package/dist/object-issuer.js +172 -0
- package/dist/receipt-pending.d.ts +16 -0
- package/dist/receipt-pending.js +14 -0
- package/dist/web-bot-auth.d.ts +26 -6
- package/dist/web-bot-auth.js +116 -56
- package/docs/approvals.md +33 -0
- package/docs/completeness.md +44 -5
- package/docs/console.md +11 -4
- package/docs/door-error-rates.md +490 -0
- package/docs/door-languages.md +3 -1
- package/docs/door-middleware.md +6 -1
- package/docs/door-quickstart.md +53 -17
- package/docs/door-signals.md +117 -7
- package/docs/door-worker.md +94 -0
- package/docs/door.md +41 -12
- package/docs/github-action.md +2 -2
- package/docs/tutorials.md +6 -0
- package/docs/verification.md +1 -1
- package/package.json +4 -1
- package/vectors/audit.json +27 -27
- package/vectors/canonical.json +5 -5
- package/vectors/receipts.json +1645 -1549
package/dist/cli.js
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { hostname, userInfo } from "node:os";
|
|
2
|
+
import { hostname, tmpdir, userInfo } from "node:os";
|
|
3
3
|
import { captureKeyFrom, getAt, pathText, restorePaths, setAt } from "./capture.js";
|
|
4
4
|
import { saltsFileFor } from "./retention.js";
|
|
5
5
|
import { parseArgs } from "node:util";
|
|
6
|
-
import { closeSync, constants as fsConstants, existsSync, fchmodSync, openSync, readFileSync, readdirSync, writeFileSync, writeSync } from "node:fs";
|
|
6
|
+
import { closeSync, constants as fsConstants, createReadStream, existsSync, fchmodSync, mkdtempSync, openSync, readFileSync, readdirSync, rmSync, writeFileSync, writeSync } from "node:fs";
|
|
7
|
+
import { createInterface } from "node:readline";
|
|
7
8
|
import { dirname, join, resolve } from "node:path";
|
|
8
9
|
import { loadAcsGuardianConfig, loadConfig, loadDoorConfig, loadEgressConfig, loadSdkConfig } from "./config.js";
|
|
9
10
|
import { dsseVerify, generateKeyPair, loadPrivateKey, loadPublicKey, writeKeyPair } from "./crypto.js";
|
|
11
|
+
import { DEFAULT_APPROVAL_LIFETIME_SECONDS } from "./approval.js";
|
|
12
|
+
import { approvalRequestExpiresAt, approveApprovalRequest, denyApprovalRequest, listApprovalRequests, readApprovalRequest } from "./approval-requests.js";
|
|
10
13
|
import { createDelegation, decodeDelegation, delegateFrom, grantDigest } from "./delegation.js";
|
|
11
14
|
import { didKeyOf } from "./did-key.js";
|
|
12
15
|
import { createGateway, createGatewayHost, serveStdio, writeRevokedGrants } from "./gateway.js";
|
|
@@ -21,6 +24,9 @@ import { checkCompleteness, formatCompleteness, githubSource, stripeSource } fro
|
|
|
21
24
|
import { evmChain } from "./anchor-evm.js";
|
|
22
25
|
import { serveHttp } from "./gateway-http.js";
|
|
23
26
|
import { createDoorHost, serveDoor } from "./door.js";
|
|
27
|
+
import { challengeLabels, doorErrorRates, formatErrorRates, parseLabels, readDoorArrivals } from "./door-error-rates.js";
|
|
28
|
+
import { buildDoorTestSet } from "./door-test-set.js";
|
|
29
|
+
import { createMeasure, formatMeasure, labelsFromReceipts, parseLabelledRecord } from "./door-measure.js";
|
|
24
30
|
import { createEgressHost, serveEgress } from "./egress.js";
|
|
25
31
|
import { draftEgressPolicy } from "./egress-draft.js";
|
|
26
32
|
import { createAcsGuardian } from "./acs.js";
|
|
@@ -63,7 +69,48 @@ function untilStopped() {
|
|
|
63
69
|
}
|
|
64
70
|
const SERVICES = new Set(["serve", "witness", "signer", "portal", "log", "console", "door", "egress"]);
|
|
65
71
|
/** a command that waits for untilStopped(); a stdio gateway runs until its input closes and keeps the default signal behaviour */
|
|
66
|
-
const runsUntilStopped = (cmd, args) => !!cmd && ((SERVICES.has(cmd) && !(cmd === "egress" && args[0] === "draft-policy")) || (cmd === "gateway" && (args.includes("--http") || args.includes("--a2a"))));
|
|
72
|
+
const runsUntilStopped = (cmd, args) => !!cmd && ((SERVICES.has(cmd) && !(cmd === "egress" && args[0] === "draft-policy") && !(cmd === "door" && ["error-rates", "measure", "labels"].includes(args[0] ?? ""))) || (cmd === "gateway" && (args.includes("--http") || args.includes("--a2a"))));
|
|
73
|
+
async function doorErrorRatesCommand(args) {
|
|
74
|
+
const { values } = parseArgs({ args, options: { receipts: { type: "string" }, labels: { type: "string" }, "issuer-key": { type: "string", multiple: true }, "principal-key": { type: "string", multiple: true }, log: { type: "string" }, "log-key": { type: "string", multiple: true }, "challenge-labels": { type: "boolean", default: false }, "test-set": { type: "boolean", default: false }, "per-kind": { type: "string", default: "200" }, json: { type: "boolean", default: false } } });
|
|
75
|
+
let read;
|
|
76
|
+
let labels;
|
|
77
|
+
if (values["test-set"]) {
|
|
78
|
+
const perKind = Number(values["per-kind"]);
|
|
79
|
+
if (!Number.isInteger(perKind) || perKind < 1 || perKind > 10_000)
|
|
80
|
+
throw new Error("--per-kind takes a whole number from 1 to 10000");
|
|
81
|
+
const dir = mkdtempSync(join(tmpdir(), "agent-custody-door-test-set-"));
|
|
82
|
+
try {
|
|
83
|
+
const set = await buildDoorTestSet(dir, { perKind });
|
|
84
|
+
read = readDoorArrivals(set.receiptsDir, { issuerKeys: [set.doorKey], principalKeys: [set.principalKey] });
|
|
85
|
+
labels = set.labels;
|
|
86
|
+
}
|
|
87
|
+
finally {
|
|
88
|
+
rmSync(dir, { recursive: true, force: true });
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
if (!values.receipts || !values.labels || !values["issuer-key"]?.length)
|
|
93
|
+
throw new Error("door error-rates needs --receipts <dir> --labels <labels.jsonl> --issuer-key <door.pub>, or --test-set");
|
|
94
|
+
read = readDoorArrivals(values.receipts, { issuerKeys: values["issuer-key"].map(loadPublicKey), principalKeys: (values["principal-key"] ?? []).map(loadPublicKey), logKeys: (values["log-key"] ?? []).map(loadPublicKey), ...(values.log ? { logFile: values.log } : {}) });
|
|
95
|
+
labels = parseLabels(readFileSync(values.labels, "utf8"));
|
|
96
|
+
if (values["challenge-labels"])
|
|
97
|
+
labels = [...labels, ...challengeLabels(read.arrivals, labels.map((l) => l.receiptId))];
|
|
98
|
+
}
|
|
99
|
+
const { rows, unmatched } = doorErrorRates(read.arrivals, labels);
|
|
100
|
+
for (const s of read.skipped)
|
|
101
|
+
console.error(`skipped ${s.file}: ${s.reason}`);
|
|
102
|
+
if (unmatched.length)
|
|
103
|
+
console.error(`${unmatched.length} label(s) name a receipt that was not read or did not verify, and are not scored`);
|
|
104
|
+
process.stdout.write(values.json ? JSON.stringify({ rows, skipped: read.skipped, unmatched }, null, 2) + "\n" : formatErrorRates(rows));
|
|
105
|
+
return 0;
|
|
106
|
+
}
|
|
107
|
+
/** `90s`, `10m`, or `1h`, in seconds. */
|
|
108
|
+
function durationSeconds(text) {
|
|
109
|
+
const m = /^(\d+)([smh])$/.exec(text.trim());
|
|
110
|
+
if (!m || Number(m[1]) <= 0)
|
|
111
|
+
throw new Error(`--expires takes 90s, 10m, or 1h; got "${text}"`);
|
|
112
|
+
return Number(m[1]) * { s: 1, m: 60, h: 3600 }[m[2]];
|
|
113
|
+
}
|
|
67
114
|
/** A secret kept in a file that only this process can read, such as a container secret mounted at /run/secrets. The file's path is not a secret; its contents are. */
|
|
68
115
|
function tokenFromFile(path) {
|
|
69
116
|
const v = readFileSync(path, "utf8").trim();
|
|
@@ -88,6 +135,10 @@ const USAGE = `agent-custody <command>
|
|
|
88
135
|
a narrower grant for a sub-agent, signed by the agent the parent names; the parent travels inside
|
|
89
136
|
reveal <bundle> --capture-key-env NAME --issuer-key <pub> [--out <file>] [--include-salts] the values a receipt withheld (capture mode encrypted), as a disclosure file
|
|
90
137
|
for verify --disclose; needs the customer's capture key
|
|
138
|
+
approvals list|show <id>|approve <id> --key <file> [--expires 10m]|deny <id> [--reason <text>] --config <gateway.json>
|
|
139
|
+
human in the loop: the approval requests a gateway with approvals.requests left for
|
|
140
|
+
calls that came without an approval; approve signs the exact call with your key, and
|
|
141
|
+
the same call sent again is forwarded once
|
|
91
142
|
revoke --config <gateway.json|door.json> --grant <grant.json>
|
|
92
143
|
revokes a grant: its digest goes into the config's revokedGrants file. At a gateway, every
|
|
93
144
|
session under it or under a grant delegated from it refuses its next call, and no new session opens for them;
|
|
@@ -110,6 +161,27 @@ const USAGE = `agent-custody <command>
|
|
|
110
161
|
origin or refused with 403, and receipted either way; GET /.well-known/agent-custody-door.
|
|
111
162
|
With "authz": true in the config it relays nothing and answers nginx auth_request and
|
|
112
163
|
Envoy ext_authz checks instead: 200 with the receipt headers, or 403
|
|
164
|
+
door error-rates --receipts <dir> --labels <labels.jsonl> --issuer-key <door.pub>... [--principal-key <pub>]...
|
|
165
|
+
[--log <log.jsonl>] [--log-key <pub>]... [--challenge-labels] [--json]
|
|
166
|
+
door error-rates --test-set [--per-kind 200] [--json]
|
|
167
|
+
the credential signals: how often the door's class is wrong for each kind of arrival, from
|
|
168
|
+
labelled receipts, with a 95% interval; never pooled across kinds. --test-set builds the published
|
|
169
|
+
labelled set in memory and scores it. Receipts that do not verify are skipped (door-error-rates.md).
|
|
170
|
+
Use it when you have receipts and know what each arrival was
|
|
171
|
+
door measure <labelled.jsonl>... [--json]
|
|
172
|
+
the behaviour and fingerprint flags: how often each flag is wrong on labelled arrivals. For each set
|
|
173
|
+
and flag, the false-positive rate on humans and the detection rate on automated clients, per session
|
|
174
|
+
and per arrival, each with a 95% Wilson interval. Replays each recorded session through the door's
|
|
175
|
+
own functions. Use it when you have a labelled set: a recording, a public dataset, or the output of
|
|
176
|
+
door labels
|
|
177
|
+
door labels --receipts <dir> --issuer-key <door.pub>... [--principal-key <pub>]... [--log-key <pub>]... [--log <log.jsonl>] [--set own-door]
|
|
178
|
+
[--receipt-ids] [--out <file>]
|
|
179
|
+
a labelled set from your own door's verified receipts, for door measure: an arrival that passed the
|
|
180
|
+
challenge is human, a verified agent's arrival is automated, the rest are left out. Each line holds
|
|
181
|
+
the label and the flags only: no path, address, agent name, header, or time. It uploads nothing. A
|
|
182
|
+
verified agent's receipt verifies only with the key of the principal that signed its grant.
|
|
183
|
+
--receipt-ids adds each receipt's id, and the file is then also a labels file for door error-rates.
|
|
184
|
+
Use it when you have receipts and no labels of your own
|
|
113
185
|
egress --config <egress.json> [--port 8791] [--host 127.0.0.1]
|
|
114
186
|
the egress witness: a forward proxy (CONNECT and plain HTTP, no TLS interception) for a
|
|
115
187
|
locked-down agent's calls that do not go to the gateway. Each agent proves itself with its own
|
|
@@ -148,9 +220,10 @@ const USAGE = `agent-custody <command>
|
|
|
148
220
|
completeness --receipts <dir> --issuer-key <pub>... [--principal-key <pub>]... [--log-key <pub>]... [--log <log.jsonl>] [--log-id <id>]
|
|
149
221
|
--provider stripe --object refunds|payouts|transfers --key-env NAME --tool <name>... --since <ISO> --until <ISO>
|
|
150
222
|
(or --provider github --repo <owner>/<name> --object pushes|merges|releases)
|
|
151
|
-
[--id-path id] [--amount-field amount] [--currency-field currency] [--beneficiary <arg>=<field>]... [--json]
|
|
223
|
+
[--id-path id] [--receipt-id-path metadata.agent_custody_receipt] [--amount-field amount] [--currency-field currency] [--beneficiary <arg>=<field>]... [--json]
|
|
152
224
|
for an auditor: lists the provider's objects in the window with a read-only key, and
|
|
153
|
-
matches each to a verified receipt by the provider's object id
|
|
225
|
+
matches each to a verified receipt: a gateway receipt by the provider's object id, a door
|
|
226
|
+
receipt by the receipt id the object carries; reports actions with no
|
|
154
227
|
receipt, receipts the provider does not have, and mismatched amounts; exits 1 unless complete
|
|
155
228
|
replay verified local receipts against a proposed policy using their recorded inputs;
|
|
156
229
|
--out saves the full JSON report. Exits 1 when any call could not be evaluated.
|
|
@@ -334,6 +407,56 @@ async function main(argv) {
|
|
|
334
407
|
console.log(values.json ? JSON.stringify(findings, null, 2) : formatFindings(findings));
|
|
335
408
|
return findings.some((f) => f.level === "error") ? 1 : 0;
|
|
336
409
|
}
|
|
410
|
+
case "approvals": {
|
|
411
|
+
const sub = rest[0];
|
|
412
|
+
const listing = sub === "list";
|
|
413
|
+
const id = listing ? undefined : rest[1];
|
|
414
|
+
const { values } = parseArgs({ args: rest.slice(listing ? 1 : 2), options: { config: { type: "string" }, key: { type: "string" }, expires: { type: "string", default: "10m" }, reason: { type: "string" }, all: { type: "boolean", default: false }, json: { type: "boolean", default: false } } });
|
|
415
|
+
if (!values.config)
|
|
416
|
+
throw new Error("approvals needs --config: the gateway config whose approvals.requests.dir holds the requests");
|
|
417
|
+
const cfg = loadConfig(values.config);
|
|
418
|
+
const dir = cfg.approvals?.requests?.dir;
|
|
419
|
+
if (!dir)
|
|
420
|
+
throw new Error(`approvals needs approvals.requests.dir in ${values.config}`);
|
|
421
|
+
if (listing) {
|
|
422
|
+
const all = listApprovalRequests(dir).filter((r) => values.all || r.status === "pending");
|
|
423
|
+
if (values.json)
|
|
424
|
+
console.log(JSON.stringify(all, null, 2));
|
|
425
|
+
else if (!all.length)
|
|
426
|
+
console.log("no approval requests waiting");
|
|
427
|
+
else
|
|
428
|
+
for (const r of all)
|
|
429
|
+
console.log(`${r.requestId} ${r.status.padEnd(8)} ${r.createdAt} ${r.binding.agent} → ${r.binding.tool} for ${r.binding.principal}${r.requiredApprovers === 2 ? ` (two approvers, ${new Set(r.envelope?.signatures.map((x) => x.keyid) ?? []).size} signed)` : ""}`);
|
|
430
|
+
return 0;
|
|
431
|
+
}
|
|
432
|
+
if (!id)
|
|
433
|
+
throw new Error(`approvals ${sub ?? ""} needs a request id`);
|
|
434
|
+
if (sub === "show") {
|
|
435
|
+
const r = readApprovalRequest(dir, id);
|
|
436
|
+
if (!r)
|
|
437
|
+
throw new Error(`no approval request ${id} in ${dir}`);
|
|
438
|
+
console.log(JSON.stringify(values.json ? r : { requestId: r.requestId, status: r.status, createdAt: r.createdAt, principal: r.binding.principal, agent: r.binding.agent, tool: r.binding.tool, arguments: r.binding.args, ...(r.binding.fields ? { fields: r.binding.fields } : {}), requiredApprovers: r.requiredApprovers, signedBy: r.envelope?.signatures.map((x) => x.keyid) ?? [], ...(r.reason ? { reason: r.reason } : {}) }, null, 2));
|
|
439
|
+
return 0;
|
|
440
|
+
}
|
|
441
|
+
if (sub === "approve") {
|
|
442
|
+
if (!values.key)
|
|
443
|
+
throw new Error("approvals approve needs --key: the approver's private key");
|
|
444
|
+
const max = cfg.approvals?.maxLifetimeSeconds ?? DEFAULT_APPROVAL_LIFETIME_SECONDS;
|
|
445
|
+
const seconds = durationSeconds(values.expires);
|
|
446
|
+
if (seconds > max)
|
|
447
|
+
throw new Error(`--expires ${values.expires} is longer than the gateway accepts (approvals.maxLifetimeSeconds ${max})`);
|
|
448
|
+
const r = approveApprovalRequest(dir, id, loadPrivateKey(values.key), { expiresAt: new Date(Date.now() + seconds * 1000).toISOString(), trusted: cfg.approvals.trustedKeys.map(loadPublicKey), maxLifetimeSeconds: max });
|
|
449
|
+
const until = approvalRequestExpiresAt(r);
|
|
450
|
+
console.log(r.status === "approved" ? `approved ${id}: ${r.binding.agent} may send ${r.binding.tool} with exactly these arguments, once, until ${until}` : `signed ${id}, valid until ${until}: it needs a second approver with a different key`);
|
|
451
|
+
return 0;
|
|
452
|
+
}
|
|
453
|
+
if (sub === "deny") {
|
|
454
|
+
denyApprovalRequest(dir, id, values.reason ? { reason: values.reason } : {});
|
|
455
|
+
console.log(`denied ${id}: the gateway refuses that exact call, and says so, until the request is deleted`);
|
|
456
|
+
return 0;
|
|
457
|
+
}
|
|
458
|
+
throw new Error("approvals takes list, show <id>, approve <id> --key <file>, or deny <id> [--reason <text>]");
|
|
459
|
+
}
|
|
337
460
|
case "revoke": {
|
|
338
461
|
const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, grant: { type: "string" } } });
|
|
339
462
|
if (!values.config || !values.grant)
|
|
@@ -390,6 +513,60 @@ async function main(argv) {
|
|
|
390
513
|
return 0;
|
|
391
514
|
}
|
|
392
515
|
case "door": {
|
|
516
|
+
if (rest[0] === "error-rates")
|
|
517
|
+
return doorErrorRatesCommand(rest.slice(1));
|
|
518
|
+
if (rest[0] === "measure") {
|
|
519
|
+
const { values, positionals } = parseArgs({ args: rest.slice(1), allowPositionals: true, options: { json: { type: "boolean", default: false } } });
|
|
520
|
+
if (!positionals.length)
|
|
521
|
+
throw new Error("door measure needs at least one labelled set: door measure <labelled.jsonl>... [--json]");
|
|
522
|
+
const m = createMeasure();
|
|
523
|
+
for (const file of positionals) {
|
|
524
|
+
let line = 0;
|
|
525
|
+
for await (const text of createInterface({ input: createReadStream(file), crlfDelay: Infinity })) {
|
|
526
|
+
line++;
|
|
527
|
+
if (!text.trim())
|
|
528
|
+
continue;
|
|
529
|
+
try {
|
|
530
|
+
m.add(parseLabelledRecord(text));
|
|
531
|
+
}
|
|
532
|
+
catch (e) {
|
|
533
|
+
throw new Error(`${file}:${line}: ${e instanceof Error ? e.message : String(e)}`);
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
const result = m.result();
|
|
538
|
+
console.log(values.json ? JSON.stringify(result, null, 2) : formatMeasure(result));
|
|
539
|
+
return result.sets.length ? 0 : 1;
|
|
540
|
+
}
|
|
541
|
+
if (rest[0] === "labels") {
|
|
542
|
+
const { values } = parseArgs({ args: rest.slice(1), options: { receipts: { type: "string" }, "issuer-key": { type: "string", multiple: true }, "principal-key": { type: "string", multiple: true }, "log-key": { type: "string", multiple: true }, log: { type: "string" }, set: { type: "string", default: "own-door" }, "receipt-ids": { type: "boolean", default: false }, out: { type: "string" } } });
|
|
543
|
+
if (!values.receipts || !values["issuer-key"]?.length)
|
|
544
|
+
throw new Error("door labels needs --receipts <dir> --issuer-key <door.pub>");
|
|
545
|
+
const keys = { issuerKeys: values["issuer-key"].map(loadPublicKey), principalKeys: (values["principal-key"] ?? []).map(loadPublicKey), logKeys: (values["log-key"] ?? []).map(loadPublicKey), ...(values.log ? { logFile: values.log } : {}) };
|
|
546
|
+
const predicates = [];
|
|
547
|
+
let unverified = 0;
|
|
548
|
+
for (const file of receiptFiles(values.receipts)) {
|
|
549
|
+
try {
|
|
550
|
+
const checked = verifyBundle(JSON.parse(readFileSync(file, "utf8")), keys);
|
|
551
|
+
if (checked.ok && checked.statement)
|
|
552
|
+
predicates.push(checked.statement.predicate);
|
|
553
|
+
else
|
|
554
|
+
unverified++;
|
|
555
|
+
}
|
|
556
|
+
catch {
|
|
557
|
+
unverified++;
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
const labels = labelsFromReceipts(predicates, values.set, { receiptIds: values["receipt-ids"] });
|
|
561
|
+
const text = labels.records.map((r) => JSON.stringify(r)).join("\n") + (labels.records.length ? "\n" : "");
|
|
562
|
+
if (values.out)
|
|
563
|
+
writeFileSync(values.out, text);
|
|
564
|
+
else
|
|
565
|
+
process.stdout.write(text);
|
|
566
|
+
const count = (label) => labels.records.filter((r) => r.label === label).length;
|
|
567
|
+
console.error(`door labels: ${labels.read} door receipt(s) read, ${unverified} file(s) skipped (not a receipt that verifies with these keys${unverified && !values["principal-key"]?.length ? "; a verified agent's receipt needs --principal-key" : ""}); ${count("human")} human (challenge passed), ${count("automated")} automated (verified agent), ${labels.unlabelled} without a label, ${labels.noSignals} without signals (the door had no "behaviour" config). Nothing was uploaded: the output is yours to inspect and to send or not`);
|
|
568
|
+
return labels.records.length ? 0 : 1;
|
|
569
|
+
}
|
|
393
570
|
const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, port: { type: "string", default: "8780" }, host: { type: "string", default: "127.0.0.1" } } });
|
|
394
571
|
if (!values.config)
|
|
395
572
|
throw new Error("door needs --config");
|
|
@@ -1035,6 +1212,7 @@ async function main(argv) {
|
|
|
1035
1212
|
since: { type: "string" },
|
|
1036
1213
|
until: { type: "string" },
|
|
1037
1214
|
"id-path": { type: "string" },
|
|
1215
|
+
"receipt-id-path": { type: "string" },
|
|
1038
1216
|
"amount-field": { type: "string" },
|
|
1039
1217
|
"currency-field": { type: "string" },
|
|
1040
1218
|
beneficiary: { type: "string", multiple: true },
|
|
@@ -1080,6 +1258,7 @@ async function main(argv) {
|
|
|
1080
1258
|
sinceMs,
|
|
1081
1259
|
untilMs,
|
|
1082
1260
|
...(values["id-path"] ? { idPath: values["id-path"] } : {}),
|
|
1261
|
+
...(values["receipt-id-path"] ? { receiptIdPath: values["receipt-id-path"] } : {}),
|
|
1083
1262
|
...(values["amount-field"] ? { amountField: values["amount-field"] } : {}),
|
|
1084
1263
|
...(values["currency-field"] ? { currencyField: values["currency-field"] } : {}),
|
|
1085
1264
|
...(Object.keys(beneficiary).length ? { beneficiary } : {}),
|
package/dist/completeness.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { IssuerKind } from "./receipt.ts";
|
|
1
2
|
import { type VerifyOptions } from "./verify.ts";
|
|
2
3
|
/** One provider object, reduced to what the comparison reads. */
|
|
3
4
|
export interface ProviderObject {
|
|
@@ -52,7 +53,13 @@ export interface CompletenessOptions {
|
|
|
52
53
|
untilMs: number;
|
|
53
54
|
/** where the provider's object id sits in the JSON of the result's first text item; default "id" */
|
|
54
55
|
idPath?: string;
|
|
55
|
-
/**
|
|
56
|
+
/**
|
|
57
|
+
* where a provider object carries the id of the door receipt that relayed its request; default
|
|
58
|
+
* "metadata.agent_custody_receipt". A door receipt matches only by this field, only when the origin answered 2xx,
|
|
59
|
+
* and only an object created within `marginMs` of the receipt.
|
|
60
|
+
*/
|
|
61
|
+
receiptIdPath?: string;
|
|
62
|
+
/** the call argument that holds the amount in minor units; default "amount". For a door receipt, a field of the JSON body */
|
|
56
63
|
amountField?: string;
|
|
57
64
|
/** the call argument that holds the currency; default "currency", compared case-insensitively when both sides have one */
|
|
58
65
|
currencyField?: string;
|
|
@@ -72,9 +79,11 @@ export interface CompletenessReport {
|
|
|
72
79
|
until: string;
|
|
73
80
|
};
|
|
74
81
|
receiptsRead: number;
|
|
82
|
+
/** `kind` is the issuer kind of the receipt: `gateway` matched by the provider id, `door` by the receipt id the object carries */
|
|
75
83
|
matched: {
|
|
76
84
|
receiptId: string;
|
|
77
85
|
providerId: string;
|
|
86
|
+
kind: IssuerKind;
|
|
78
87
|
}[];
|
|
79
88
|
/** provider objects in the window with no verified receipt: actions taken outside the gateway */
|
|
80
89
|
providerOnly: {
|
|
@@ -84,7 +93,7 @@ export interface CompletenessReport {
|
|
|
84
93
|
currency?: string;
|
|
85
94
|
repeated?: true;
|
|
86
95
|
}[];
|
|
87
|
-
/** executed receipts in the window whose provider object the provider does not have */
|
|
96
|
+
/** executed receipts in the window whose provider object the provider does not have; never a door receipt, which names no provider object */
|
|
88
97
|
receiptOnly: {
|
|
89
98
|
receiptId: string;
|
|
90
99
|
providerId: string;
|
package/dist/completeness.js
CHANGED
|
@@ -2,7 +2,9 @@
|
|
|
2
2
|
// can see an action that never did. An auditor with a read-only key of their own lists the provider's objects over a
|
|
3
3
|
// window and matches each one to a verified receipt by the provider's object id, which the receipt's result carries.
|
|
4
4
|
// A provider object with no receipt is an action taken outside the gateway; a receipt with no provider object is an
|
|
5
|
-
// action the provider does not have.
|
|
5
|
+
// action the provider does not have. A door receipt records the origin's answer by digest only, so it carries no
|
|
6
|
+
// provider id: it is matched by its own receipt id, which the origin copies from the door's receipt header into the
|
|
7
|
+
// provider object. Nothing here writes, retries, or calls the provider for anything but a list.
|
|
6
8
|
import { readdirSync, readFileSync } from "node:fs";
|
|
7
9
|
import { join } from "node:path";
|
|
8
10
|
import { isCommitment, REST } from "./capture.js";
|
|
@@ -146,8 +148,18 @@ function argOf(args, field) {
|
|
|
146
148
|
return isCommitment(args[field]) ? { withheld: true } : { value: args[field] };
|
|
147
149
|
return isCommitment(args[REST]) ? { withheld: true } : { value: undefined };
|
|
148
150
|
}
|
|
151
|
+
/** A door receipt's arguments are the HTTP request: the call's own arguments are the JSON body, or withheld with it. */
|
|
152
|
+
function doorArgs(args) {
|
|
153
|
+
if (!Object.hasOwn(args, "body"))
|
|
154
|
+
return isCommitment(args[REST]) ? { [REST]: args[REST] } : {};
|
|
155
|
+
const body = args.body;
|
|
156
|
+
if (isCommitment(body))
|
|
157
|
+
return { [REST]: body };
|
|
158
|
+
return body && typeof body === "object" && !Array.isArray(body) ? body : {};
|
|
159
|
+
}
|
|
149
160
|
export async function checkCompleteness(o) {
|
|
150
161
|
const idPath = o.idPath ?? "id";
|
|
162
|
+
const receiptIdPath = o.receiptIdPath ?? "metadata.agent_custody_receipt";
|
|
151
163
|
const amountField = o.amountField ?? "amount";
|
|
152
164
|
const currencyField = o.currencyField ?? "currency";
|
|
153
165
|
const margin = o.marginMs ?? 15 * 60_000;
|
|
@@ -171,6 +183,7 @@ export async function checkCompleteness(o) {
|
|
|
171
183
|
const names = readdirSync(o.receiptsDir, { withFileTypes: true }).filter((e) => (e.isFile() || e.isSymbolicLink()) && e.name.endsWith(".json")).map((e) => e.name).sort();
|
|
172
184
|
const outcomes = new Set();
|
|
173
185
|
const byProviderId = new Map();
|
|
186
|
+
const doorReceipts = new Map();
|
|
174
187
|
for (const name of names) {
|
|
175
188
|
if (name.endsWith(AUTHORIZATION))
|
|
176
189
|
continue;
|
|
@@ -196,6 +209,13 @@ export async function checkCompleteness(o) {
|
|
|
196
209
|
outcomes.add(p.receiptId);
|
|
197
210
|
if (!tools.has(p.tool.name) || p.reconciliation || p.execution.status !== "executed")
|
|
198
211
|
continue;
|
|
212
|
+
if (p.issuer.kind === "door") {
|
|
213
|
+
// the door records any origin answer below 500 as executed; only a 2xx can have made the object
|
|
214
|
+
const status = p.execution.result?.status;
|
|
215
|
+
if (typeof status === "number" && status >= 200 && status < 300)
|
|
216
|
+
doorReceipts.set(p.receiptId, p);
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
199
219
|
const id = providerIdOf(p, idPath);
|
|
200
220
|
if ("reason" in id) {
|
|
201
221
|
if (inWindow(Date.parse(p.timestamp)))
|
|
@@ -223,24 +243,34 @@ export async function checkCompleteness(o) {
|
|
|
223
243
|
report.forwardedWithoutOutcome.push({ receiptId: auth.receiptId, tool: auth.tool.name });
|
|
224
244
|
}
|
|
225
245
|
const seen = new Set();
|
|
246
|
+
const claimed = new Set();
|
|
226
247
|
for await (const obj of o.source.list(o.sinceMs - margin, o.untilMs + margin)) {
|
|
227
|
-
// a second object with an id already listed
|
|
248
|
+
// a second object with an id already listed, or naming a door receipt already claimed, is another action: the
|
|
249
|
+
// receipt accounts for the first one
|
|
228
250
|
const repeated = seen.has(obj.id);
|
|
229
251
|
seen.add(obj.id);
|
|
230
|
-
const
|
|
252
|
+
const tag = at(obj.raw, receiptIdPath);
|
|
253
|
+
const tagged = typeof tag === "string" ? doorReceipts.get(tag) : undefined;
|
|
254
|
+
// the object is made while the door relays: a receipt from another time cannot account for it
|
|
255
|
+
const door = tagged && Math.abs(obj.createdMs - Date.parse(tagged.timestamp)) <= margin ? tagged : undefined;
|
|
256
|
+
const doorRepeated = !!door && claimed.has(door.receiptId);
|
|
257
|
+
if (door)
|
|
258
|
+
claimed.add(door.receiptId);
|
|
259
|
+
const named = [...(byProviderId.get(obj.id) ?? []), ...(door ? [door] : [])];
|
|
260
|
+
const receipts = [...(repeated ? [] : byProviderId.get(obj.id) ?? []), ...(door && !doorRepeated ? [door] : [])];
|
|
231
261
|
// the margin finds a receipt across the window's edge; it does not widen the period reported on
|
|
232
|
-
const inScope = inWindow(obj.createdMs) ||
|
|
262
|
+
const inScope = inWindow(obj.createdMs) || named.some((p) => inWindow(Date.parse(p.timestamp)));
|
|
233
263
|
if (!inScope)
|
|
234
264
|
continue;
|
|
235
|
-
if (!receipts.length
|
|
236
|
-
report.providerOnly.push({ providerId: obj.id, created: iso(obj.createdMs), ...(obj.amount !== undefined ? { amount: obj.amount } : {}), ...(obj.currency !== undefined ? { currency: obj.currency } : {}), ...(
|
|
265
|
+
if (!receipts.length) {
|
|
266
|
+
report.providerOnly.push({ providerId: obj.id, created: iso(obj.createdMs), ...(obj.amount !== undefined ? { amount: obj.amount } : {}), ...(obj.currency !== undefined ? { currency: obj.currency } : {}), ...(named.length ? { repeated: true } : {}) });
|
|
237
267
|
continue;
|
|
238
268
|
}
|
|
239
269
|
if (receipts.length > 1)
|
|
240
270
|
report.duplicates.push({ providerId: obj.id, receiptIds: receipts.map((p) => p.receiptId) });
|
|
241
271
|
for (const p of receipts) {
|
|
242
|
-
report.matched.push({ receiptId: p.receiptId, providerId: obj.id });
|
|
243
|
-
const args = p.request.args;
|
|
272
|
+
report.matched.push({ receiptId: p.receiptId, providerId: obj.id, kind: p.issuer.kind });
|
|
273
|
+
const args = p.issuer.kind === "door" ? doorArgs(p.request.args) : p.request.args;
|
|
244
274
|
const withheld = (arg) => report.unmatchable.push({ receiptId: p.receiptId, reason: `the argument "${arg}" is withheld under a capture rule, so it cannot be compared` });
|
|
245
275
|
const amount = argOf(args, amountField);
|
|
246
276
|
if ("withheld" in amount) {
|
|
@@ -279,8 +309,14 @@ export async function checkCompleteness(o) {
|
|
|
279
309
|
report.complete = [report.providerOnly, report.receiptOnly, report.mismatches, report.duplicates, report.unverified, report.unmatchable, report.forwardedWithoutOutcome].every((l) => l.length === 0);
|
|
280
310
|
return report;
|
|
281
311
|
}
|
|
312
|
+
function matchedByKind(r) {
|
|
313
|
+
const counts = new Map();
|
|
314
|
+
for (const m of r.matched)
|
|
315
|
+
counts.set(m.kind, (counts.get(m.kind) ?? 0) + 1);
|
|
316
|
+
return counts.size ? ` (${[...counts].map(([k, n]) => `${n} ${k}`).join(", ")})` : "";
|
|
317
|
+
}
|
|
282
318
|
export function formatCompleteness(r) {
|
|
283
|
-
const lines = [`${r.provider} for ${r.tools.join(", ")}, ${r.window.since} to ${r.window.until}: ${r.receiptsRead} receipt(s) read, ${r.matched.length} matched`];
|
|
319
|
+
const lines = [`${r.provider} for ${r.tools.join(", ")}, ${r.window.since} to ${r.window.until}: ${r.receiptsRead} receipt(s) read, ${r.matched.length} matched${matchedByKind(r)}`];
|
|
284
320
|
const section = (title, rows) => {
|
|
285
321
|
if (rows.length)
|
|
286
322
|
lines.push("", `${title} (${rows.length})`, ...rows.map((row) => ` ${row}`));
|
package/dist/config.d.ts
CHANGED
|
@@ -275,6 +275,9 @@ export declare const GatewayConfigSchema: z.ZodObject<{
|
|
|
275
275
|
trustedKeys: z.ZodArray<z.ZodString>;
|
|
276
276
|
usedDir: z.ZodString;
|
|
277
277
|
maxLifetimeSeconds: z.ZodOptional<z.ZodNumber>;
|
|
278
|
+
requests: z.ZodOptional<z.ZodObject<{
|
|
279
|
+
dir: z.ZodString;
|
|
280
|
+
}, z.core.$strip>>;
|
|
278
281
|
tools: z.ZodArray<z.ZodObject<{
|
|
279
282
|
tool: z.ZodString;
|
|
280
283
|
minApprovers: z.ZodDefault<z.ZodUnion<readonly [z.ZodLiteral<1>, z.ZodLiteral<2>]>>;
|
|
@@ -463,6 +466,9 @@ export declare const DoorConfigSchema: z.ZodObject<{
|
|
|
463
466
|
maxInFlight: z.ZodDefault<z.ZodNumber>;
|
|
464
467
|
maxResponseBytes: z.ZodDefault<z.ZodNumber>;
|
|
465
468
|
}, z.core.$strip>>;
|
|
469
|
+
behaviour: z.ZodOptional<z.ZodObject<{
|
|
470
|
+
tlsHeader: z.ZodOptional<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>;
|
|
471
|
+
}, z.core.$strict>>;
|
|
466
472
|
receiptsDir: z.ZodString;
|
|
467
473
|
logFile: z.ZodOptional<z.ZodString>;
|
|
468
474
|
log: z.ZodOptional<z.ZodObject<{
|
package/dist/config.js
CHANGED
|
@@ -74,6 +74,11 @@ const ApprovalsSchema = z.object({
|
|
|
74
74
|
usedDir: z.string().min(1),
|
|
75
75
|
/** The longest lifetime (expiresAt minus issuedAt) that the gateway accepts. The signer chooses the expiry, and this caps it. Default: 3600. */
|
|
76
76
|
maxLifetimeSeconds: z.number().int().positive().optional(),
|
|
77
|
+
/**
|
|
78
|
+
* Human in the loop: a protected call that arrives without an approval also leaves a request in `dir`, which an approver
|
|
79
|
+
* signs with `agent-custody approvals approve`; the same call sent again then takes the signed envelope from it.
|
|
80
|
+
*/
|
|
81
|
+
requests: z.object({ dir: z.string().min(1) }).optional(),
|
|
77
82
|
tools: z.array(z.object({
|
|
78
83
|
tool: z.string().min(1),
|
|
79
84
|
minApprovers: z.union([z.literal(1), z.literal(2)]).default(1),
|
|
@@ -223,7 +228,7 @@ export function loadConfig(path) {
|
|
|
223
228
|
...(cfg.logFile ? { logFile: r(cfg.logFile) } : {}),
|
|
224
229
|
...(cfg.log?.keys ? { log: { ...cfg.log, keys: cfg.log.keys.map(r) } } : {}),
|
|
225
230
|
...(cfg.revokedGrants ? { revokedGrants: r(cfg.revokedGrants) } : {}),
|
|
226
|
-
...(cfg.approvals ? { approvals: { ...cfg.approvals, trustedKeys: cfg.approvals.trustedKeys.map(r), usedDir: r(cfg.approvals.usedDir) } } : {}),
|
|
231
|
+
...(cfg.approvals ? { approvals: { ...cfg.approvals, trustedKeys: cfg.approvals.trustedKeys.map(r), usedDir: r(cfg.approvals.usedDir), ...(cfg.approvals.requests ? { requests: { dir: r(cfg.approvals.requests.dir) } } : {}) } } : {}),
|
|
227
232
|
...(cfg.operations ? { operations: { ...cfg.operations, database: r(cfg.operations.database) } } : {}),
|
|
228
233
|
};
|
|
229
234
|
}
|
|
@@ -344,6 +349,18 @@ export const DoorConfigSchema = z.object({
|
|
|
344
349
|
/** the largest answer the door reads. Default 16 KiB */
|
|
345
350
|
maxResponseBytes: z.number().int().positive().default(16 * 1024),
|
|
346
351
|
}).optional(),
|
|
352
|
+
/**
|
|
353
|
+
* The door's own behavioural and fingerprint signals (door-signals.ts): the header fingerprint, the TLS fingerprint,
|
|
354
|
+
* the pace, the navigation, and the form report. Present, even empty, it adds `fingerprint` and `behaviour` to the
|
|
355
|
+
* arrival fact. They are signals for the policy to read; the door refuses nothing because of them.
|
|
356
|
+
*/
|
|
357
|
+
behaviour: z.strictObject({
|
|
358
|
+
/**
|
|
359
|
+
* The request header in which your proxy puts the client's JA4 TLS fingerprint. The proxy must overwrite the
|
|
360
|
+
* header on every request, or a client can send its own. Needs `trustProxy`
|
|
361
|
+
*/
|
|
362
|
+
tlsHeader: z.string().regex(/^[A-Za-z0-9-]{1,64}$/, "a header name has letters, digits, and hyphens").transform((h) => h.toLowerCase()).optional(),
|
|
363
|
+
}).optional(),
|
|
347
364
|
receiptsDir: z.string(),
|
|
348
365
|
logFile: z.string().optional(),
|
|
349
366
|
log: LogSchema.optional(),
|
|
@@ -352,6 +369,7 @@ export const DoorConfigSchema = z.object({
|
|
|
352
369
|
capture: CaptureSchema.optional(),
|
|
353
370
|
captureKeyEnv: z.string().min(1).optional(),
|
|
354
371
|
}).refine(hasOneLog, oneLog).refine((c) => new Set(c.routes.map((r) => r.name)).size === c.routes.length, { message: "route names must be unique" })
|
|
372
|
+
.refine((c) => !c.behaviour?.tlsHeader || c.trustProxy, { path: ["behaviour", "tlsHeader"], message: "behaviour.tlsHeader needs trustProxy: true, since only a proxy in front of the door sees the TLS handshake; without one the header is the client's" })
|
|
355
373
|
.refine((c) => !c.partner || c.partner.routes.every((r) => r === "*" || r === c.unmatchedRoute || c.routes.some((x) => x.name === r)), { message: "partner.routes names a route the door does not have" })
|
|
356
374
|
.refine((c) => !c.authz || c.trustProxy, { message: "authz needs trustProxy: true, since every check comes from the proxy and the arrival's address is the last in its X-Forwarded-For" })
|
|
357
375
|
.refine((c) => !c.log || !!c.log.keys?.length, { message: "a remote log needs log.keys: the log's public key files, pinned, to check its answer before a request is relayed" });
|
package/dist/console-page.js
CHANGED
|
@@ -34,6 +34,7 @@ textarea { width: 100%; min-height: 280px; background: var(--code); color: var(-
|
|
|
34
34
|
[hidden] { display: none !important; }
|
|
35
35
|
.mt { margin-top: 16px; }
|
|
36
36
|
textarea.short { min-height: 140px; }
|
|
37
|
+
pre.args { white-space: pre-wrap; overflow-wrap: anywhere; max-height: 360px; overflow: auto; }
|
|
37
38
|
dialog { background: var(--panel); color: var(--ink); border: 1px solid var(--line); border-radius: 8px; padding: 16px; max-width: min(480px, calc(100vw - 32px)); }
|
|
38
39
|
dialog::backdrop { background: rgba(0, 0, 0, .5); }
|
|
39
40
|
dialog h3 { margin: 0 0 8px; }
|
|
@@ -56,7 +57,7 @@ const SCRIPT = String.raw `
|
|
|
56
57
|
var token = '';
|
|
57
58
|
try { token = sessionStorage.getItem(KEY) || ''; } catch (e) {}
|
|
58
59
|
var view = document.getElementById('view');
|
|
59
|
-
var tabs = ['Overview', 'Check', 'Policy', 'Grants', 'Receipts', 'Audit'];
|
|
60
|
+
var tabs = ['Overview', 'Check', 'Policy', 'Grants', 'Approvals', 'Receipts', 'Audit'];
|
|
60
61
|
var current = 'Overview';
|
|
61
62
|
var policyDigest = '';
|
|
62
63
|
var dirty = false;
|
|
@@ -95,6 +96,29 @@ const SCRIPT = String.raw `
|
|
|
95
96
|
});
|
|
96
97
|
}
|
|
97
98
|
function fail(e) { say(e.message || String(e), true); }
|
|
99
|
+
function b64bytes(s) { var bin = atob(s); var u = new Uint8Array(bin.length); for (var i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i); return u; }
|
|
100
|
+
function bytes64(buf) { var u = new Uint8Array(buf); var s = ''; for (var i = 0; i < u.length; i++) s += String.fromCharCode(u[i]); return btoa(s); }
|
|
101
|
+
function hexOf(buf) { return Array.prototype.map.call(new Uint8Array(buf), function (b) { return ('0' + b.toString(16)).slice(-2); }).join(''); }
|
|
102
|
+
// Sign the DSSE bytes with an Ed25519 PKCS8 key from a file the approver picks. The key stays in this page; the keyid is
|
|
103
|
+
// the gateway's own: sha256 of the public key's SPKI DER.
|
|
104
|
+
function signWith(file, paeB64) {
|
|
105
|
+
var key;
|
|
106
|
+
return file.text().then(function (pem) {
|
|
107
|
+
var m = /-----BEGIN PRIVATE KEY-----([\s\S]+?)-----END PRIVATE KEY-----/.exec(pem);
|
|
108
|
+
if (!m) throw new Error('That is not a private key. Choose the .key file agent-custody keygen wrote for you.');
|
|
109
|
+
return crypto.subtle.importKey('pkcs8', b64bytes(m[1].replace(/\s+/g, '')), { name: 'Ed25519' }, true, ['sign']);
|
|
110
|
+
}).then(function (k) {
|
|
111
|
+
key = k;
|
|
112
|
+
return crypto.subtle.exportKey('jwk', k);
|
|
113
|
+
}).then(function (jwk) {
|
|
114
|
+
var x = jwk.x.replace(/-/g, '+').replace(/_/g, '/');
|
|
115
|
+
while (x.length % 4) x += '=';
|
|
116
|
+
var spki = new Uint8Array(44);
|
|
117
|
+
spki.set([0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00]);
|
|
118
|
+
spki.set(b64bytes(x), 12);
|
|
119
|
+
return Promise.all([crypto.subtle.digest('SHA-256', spki), crypto.subtle.sign({ name: 'Ed25519' }, key, b64bytes(paeB64))]);
|
|
120
|
+
}).then(function (r) { return { keyid: hexOf(r[0]), sig: bytes64(r[1]) }; });
|
|
121
|
+
}
|
|
98
122
|
function signOut() {
|
|
99
123
|
token = '';
|
|
100
124
|
try { sessionStorage.removeItem(KEY); } catch (e) {}
|
|
@@ -154,7 +178,7 @@ const SCRIPT = String.raw `
|
|
|
154
178
|
});
|
|
155
179
|
}
|
|
156
180
|
|
|
157
|
-
var ACTIONS = { 'policy.save': 'Policy saved', 'grant.revoke': 'Grant revoked' };
|
|
181
|
+
var ACTIONS = { 'policy.save': 'Policy saved', 'grant.revoke': 'Grant revoked', 'approval.sign': 'Approval signed', 'approval.deny': 'Approval denied' };
|
|
158
182
|
function historyTable(files) {
|
|
159
183
|
var t = h('table', null, h('tr', null, h('th', { text: 'saved' }), h('th', { text: 'digest' })));
|
|
160
184
|
files.forEach(function (f) {
|
|
@@ -350,6 +374,67 @@ const SCRIPT = String.raw `
|
|
|
350
374
|
});
|
|
351
375
|
},
|
|
352
376
|
|
|
377
|
+
Approvals: function () {
|
|
378
|
+
return api('GET', '/api/approvals').then(function (a) {
|
|
379
|
+
var title = h('h2', { text: 'Approvals' });
|
|
380
|
+
if (!a.configured) return h('div', null, title, h('p', { class: 'muted', text: 'Approval requests are off. With approvals.requests.dir in the gateway config, a protected call that arrives with no approval leaves a request here for a person to read and sign.' }));
|
|
381
|
+
var detail = h('div');
|
|
382
|
+
var pending = a.requests.filter(function (r) { return r.status === 'pending'; });
|
|
383
|
+
var t = h('table', null, h('tr', null, h('th', { text: 'asked' }), h('th', { text: 'agent' }), h('th', { text: 'tool' }), h('th', { text: 'for' }), h('th', { text: 'status' }), h('th', { text: '' })));
|
|
384
|
+
a.requests.forEach(function (r) {
|
|
385
|
+
var st = r.status === 'pending' && r.requiredApprovers === 2 ? 'pending, ' + r.signedBy.length + ' of 2 signed' : r.status;
|
|
386
|
+
t.appendChild(h('tr', null, h('td', null, when(r.createdAt)), h('td', { text: r.agent }), h('td', null, h('code', { text: r.tool })), h('td', { text: r.principal }),
|
|
387
|
+
h('td', null, h('span', { class: 'pill', text: st })), h('td', null, h('button', { type: 'button', class: 'link', onclick: function () { open(r); } }, r.status === 'pending' ? 'Review' : 'View'))));
|
|
388
|
+
});
|
|
389
|
+
function open(r) {
|
|
390
|
+
var head = h('h3', { tabindex: '-1', text: (r.status === 'pending' ? 'Review ' : 'Request ') + r.requestId });
|
|
391
|
+
var rows = [['agent', r.agent], ['tool', h('code', { text: r.tool })], ['principal', r.principal], ['asked', when(r.createdAt)], ['refused call', h('code', { text: r.receiptId })],
|
|
392
|
+
['approvers needed', String(r.requiredApprovers)], ['signed by', r.signedBy.length ? r.signedBy.map(short).join(', ') : 'nobody yet'], ['status', r.status + (r.reason ? ': ' + r.reason : '')]];
|
|
393
|
+
var card = h('div', { class: 'card detail' }, head, kv(rows), h('p', { text: 'The exact arguments. An approval covers these and nothing else: a changed value is a new request.' }),
|
|
394
|
+
h('pre', { class: 'args', text: JSON.stringify(r.arguments, null, 2) }));
|
|
395
|
+
if (r.status === 'pending') {
|
|
396
|
+
var choices = [[300, '5 minutes'], [600, '10 minutes'], [900, '15 minutes'], [1800, '30 minutes'], [3600, '1 hour']].filter(function (c) { return c[0] <= a.maxLifetimeSeconds; });
|
|
397
|
+
if (!choices.length) choices = [[a.maxLifetimeSeconds, a.maxLifetimeSeconds + ' seconds']];
|
|
398
|
+
var expires = h('select', { 'aria-label': 'Valid for' });
|
|
399
|
+
choices.forEach(function (c, i) { expires.appendChild(h('option', { value: String(c[0]), selected: i === Math.min(1, choices.length - 1) }, c[1])); });
|
|
400
|
+
var file = h('input', { type: 'file', accept: '.key,.pem', 'aria-label': 'Approver key file' });
|
|
401
|
+
var reason = h('input', { type: 'text', 'aria-label': 'Reason for denying', placeholder: 'Reason (optional)', maxlength: '1000' });
|
|
402
|
+
var status = h('span', { role: 'status', class: 'inline' });
|
|
403
|
+
var note = function (text, bad) { status.textContent = text; status.className = bad ? 'bad inline' : 'inline'; };
|
|
404
|
+
var approve = function () {
|
|
405
|
+
var f = file.files && file.files[0];
|
|
406
|
+
if (!f) return note('Choose your approver key file first. It is read in this browser to sign, and never sent.', true);
|
|
407
|
+
if (!window.crypto || !crypto.subtle) return note('This page cannot sign: the browser only offers signing on https or on localhost.', true);
|
|
408
|
+
note('Signing…');
|
|
409
|
+
var prepared;
|
|
410
|
+
api('POST', '/api/approvals/prepare', { requestId: r.requestId, expiresInSeconds: Number(expires.value) })
|
|
411
|
+
.then(function (p) { prepared = p; return signWith(f, p.pae); })
|
|
412
|
+
.then(function (s) { return api('POST', '/api/approvals/sign', { requestId: r.requestId, payload: prepared.payload, keyid: s.keyid, sig: s.sig }); })
|
|
413
|
+
.then(function (res) { file.value = ''; show('Approvals'); say(res.note); })
|
|
414
|
+
.catch(function (e) { note(e.message || String(e), true); });
|
|
415
|
+
};
|
|
416
|
+
var deny = function () {
|
|
417
|
+
ask('Deny this request?', ['The gateway will keep refusing this exact call, and tell the agent so, until the request is deleted.'], 'Deny', true).then(function (yes) {
|
|
418
|
+
if (!yes) return;
|
|
419
|
+
api('POST', '/api/approvals/deny', { requestId: r.requestId, reason: reason.value }).then(function (res) { show('Approvals'); say(res.note); }).catch(fail);
|
|
420
|
+
});
|
|
421
|
+
};
|
|
422
|
+
card.appendChild(h('div', { class: 'card' }, h('h3', { text: r.signedBy.length ? 'Countersign' : 'Approve' }),
|
|
423
|
+
h('p', { class: 'muted', text: 'Your key is read by this browser to sign the call, and only the signature is sent. The key must be one of the gateway\'s trusted approver keys' + (r.signedBy.length ? ', and not the one that already signed.' : '.') }),
|
|
424
|
+
h('div', { class: 'row' }, h('label', null, 'Key file ', file), h('label', null, 'Valid for ', expires),
|
|
425
|
+
h('button', { type: 'button', class: 'primary', onclick: approve }, r.signedBy.length ? 'Countersign' : 'Sign and approve'), status),
|
|
426
|
+
h('div', { class: 'row mt' }, reason, h('button', { type: 'button', class: 'secondary', onclick: deny }, 'Deny'))));
|
|
427
|
+
}
|
|
428
|
+
card.appendChild(h('div', { class: 'row' }, h('button', { type: 'button', class: 'secondary', onclick: function () { clear(detail); } }, 'Close')));
|
|
429
|
+
clear(detail).appendChild(card);
|
|
430
|
+
head.focus();
|
|
431
|
+
}
|
|
432
|
+
return h('div', null, title,
|
|
433
|
+
h('p', { class: 'muted', text: pending.length + ' waiting for a person. A protected call that came with no approval waits here; once it is approved, the agent sends the same call again and it goes through once.' }),
|
|
434
|
+
h('div', { class: 'card scroll' }, a.requests.length ? t : h('p', { class: 'muted', text: 'No requests yet.' })), detail);
|
|
435
|
+
});
|
|
436
|
+
},
|
|
437
|
+
|
|
353
438
|
Audit: function () {
|
|
354
439
|
return api('GET', '/api/audit').then(function (a) {
|
|
355
440
|
var t = h('table', null, h('tr', null, h('th', { text: 'when' }), h('th', { text: 'by' }), h('th', { text: 'action' }), h('th', { text: 'detail' })));
|