@agent-custody/receipts 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +29 -13
  2. package/dist/approval.d.ts +74 -0
  3. package/dist/approval.js +196 -0
  4. package/dist/capture.js +49 -1
  5. package/dist/check.d.ts +19 -0
  6. package/dist/check.js +288 -0
  7. package/dist/cli.js +238 -11
  8. package/dist/config.d.ts +85 -0
  9. package/dist/config.js +72 -2
  10. package/dist/console-page.d.ts +4 -0
  11. package/dist/console-page.js +342 -0
  12. package/dist/console.d.ts +20 -0
  13. package/dist/console.js +521 -0
  14. package/dist/gateway.d.ts +9 -0
  15. package/dist/gateway.js +335 -45
  16. package/dist/index.d.ts +9 -2
  17. package/dist/index.js +7 -1
  18. package/dist/issue.d.ts +8 -3
  19. package/dist/issue.js +13 -4
  20. package/dist/log-store.d.ts +3 -2
  21. package/dist/log-store.js +2 -0
  22. package/dist/operations.d.ts +101 -0
  23. package/dist/operations.js +239 -0
  24. package/dist/otel.js +12 -5
  25. package/dist/policy.d.ts +2 -0
  26. package/dist/policy.js +10 -0
  27. package/dist/portal.d.ts +78 -4
  28. package/dist/portal.js +516 -26
  29. package/dist/receipt.d.ts +36 -1
  30. package/dist/rest.js +14 -1
  31. package/dist/simulate.d.ts +58 -0
  32. package/dist/simulate.js +204 -0
  33. package/dist/splunk.js +11 -4
  34. package/dist/sso.d.ts +47 -0
  35. package/dist/sso.js +161 -0
  36. package/dist/verify.d.ts +2 -0
  37. package/dist/verify.js +241 -7
  38. package/docs/approvals.md +107 -0
  39. package/docs/codex-recovery.md +132 -0
  40. package/docs/configuration.md +224 -0
  41. package/docs/console.md +79 -0
  42. package/docs/financial-operations.md +99 -0
  43. package/docs/policies.md +23 -0
  44. package/docs/threat-model.md +13 -0
  45. package/docs/tutorials.md +9 -0
  46. package/docs/usage.md +49 -4
  47. package/docs/verification.md +26 -8
  48. package/package.json +8 -2
  49. package/vectors/audit.json +27 -27
  50. package/vectors/canonical.json +5 -5
  51. package/vectors/receipts.json +2866 -464
package/dist/receipt.d.ts CHANGED
@@ -3,6 +3,8 @@ import type { CaptureNote, Commitment } from "./capture.ts";
3
3
  import type { InclusionProof } from "./log.ts";
4
4
  import type { PolicyDecision } from "./policy.ts";
5
5
  import type { UpstreamEvidence } from "./upstream.ts";
6
+ import type { ApprovalRecord } from "./approval.ts";
7
+ export type { ApprovalRecord } from "./approval.ts";
6
8
  export declare const RECEIPT_TYPE = "application/vnd.in-toto+json";
7
9
  export declare const RECEIPT_PREDICATE_TYPE = "https://agent-custody.dev/receipt/v0.2";
8
10
  /** The statement a gateway commits to the log before forwarding a consequential call; the receipt for that call embeds it. */
@@ -30,6 +32,34 @@ export interface FactRecord {
30
32
  resultDigest: string | Commitment;
31
33
  provenance: "observed";
32
34
  }
35
+ /** A gateway's durable financial operation identity; execution still describes only the tool/API call. */
36
+ export interface OperationEvidence {
37
+ id: string;
38
+ idempotencyKey: string;
39
+ /** Commits the configured provider read and status mapping before the financial call is forwarded. */
40
+ lookupDigest: string;
41
+ status: "submitted" | "pending" | "confirmed" | "failed" | "unknown";
42
+ /** Amounts stay in the original request, under its capture rule, rather than being copied into public metadata. */
43
+ budget: {
44
+ id: string;
45
+ currency: string;
46
+ period: string;
47
+ };
48
+ originalReceiptId: string;
49
+ provenance: "observed";
50
+ }
51
+ /** A later provider read, observed by the gateway, linked to the original signed, logged operation. */
52
+ export interface ReconciliationEvidence {
53
+ original: ReceiptBundle | AuthorizationBundle;
54
+ lookup: {
55
+ tool: string;
56
+ args: Record<string, unknown>;
57
+ statusPath: string;
58
+ identityPath: string;
59
+ confirmed: string[];
60
+ failed: string[];
61
+ };
62
+ }
33
63
  export interface ReceiptPredicate {
34
64
  receiptId: string;
35
65
  timestamp: string;
@@ -56,6 +86,8 @@ export interface ReceiptPredicate {
56
86
  envelope: Envelope;
57
87
  provenance: "attested";
58
88
  };
89
+ /** The gateway's payload-bound human approval check, when this tool requires approval. */
90
+ approval?: ApprovalRecord;
59
91
  /** Correlation ids from the host, when it supplied any. Never checked, always claimed. */
60
92
  session: {
61
93
  id: string | null;
@@ -100,6 +132,9 @@ export interface ReceiptPredicate {
100
132
  * side effect exists only after the side effect.
101
133
  */
102
134
  authorization?: AuthorizationBundle;
135
+ operation?: OperationEvidence;
136
+ /** The provider read's full result is execution.result and follows the ordinary result capture rule. */
137
+ reconciliation?: ReconciliationEvidence;
103
138
  execution: {
104
139
  status: "executed" | "failed";
105
140
  /** the result as the receipt carries it; `resultDigest` is over the whole result, salted from the field salts when any are withheld */
@@ -130,7 +165,7 @@ export interface ReceiptPredicate {
130
165
  capture?: CaptureNote;
131
166
  }
132
167
  /** What the gateway commits before a consequential call goes out: everything the receipt will say, except the outcome. */
133
- export type AuthorizationPredicate = Pick<ReceiptPredicate, "receiptId" | "timestamp" | "issuer" | "principal" | "agent" | "delegation" | "tool" | "request" | "facts" | "consumed" | "policy" | "capture">;
168
+ export type AuthorizationPredicate = Pick<ReceiptPredicate, "receiptId" | "timestamp" | "issuer" | "principal" | "agent" | "delegation" | "approval" | "tool" | "request" | "facts" | "consumed" | "policy" | "capture" | "operation">;
134
169
  export interface AuthorizationStatement {
135
170
  _type: "https://in-toto.io/Statement/v1";
136
171
  subject: {
package/dist/rest.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { OPERATION_META_KEY } from "./operations.js";
1
2
  const encode = (v) => encodeURIComponent(typeof v === "string" ? v : JSON.stringify(v));
2
3
  /** Builds the request for one tool call: path parameters substituted, the rest of the arguments as query or body. */
3
4
  export function buildRequest(base, tool, args) {
@@ -42,7 +43,19 @@ export function restUpstream(name, cfg, opts = {}) {
42
43
  if (!tool)
43
44
  throw new Error(`upstream ${name} has no tool "${params.name}"`);
44
45
  const { url, method, body } = buildRequest(cfg.baseUrl, tool, params.arguments ?? {});
45
- const res = await f(url, { method, headers: { accept: "application/json", ...(body !== null ? { "content-type": "application/json" } : {}), ...headers }, ...(body !== null ? { body } : {}), signal: AbortSignal.timeout(cfg.timeoutMs) });
46
+ const requestHeaders = new Headers({ accept: "application/json", ...(body !== null ? { "content-type": "application/json" } : {}), ...headers });
47
+ if (tool.idempotencyHeader) {
48
+ const operation = params._meta?.[OPERATION_META_KEY];
49
+ if (!operation || typeof operation !== "object" || !Object.hasOwn(operation, "id") || !Object.hasOwn(operation, "idempotencyKey"))
50
+ throw new Error(`tool ${tool.name}: durable operation metadata is required`);
51
+ const { id, idempotencyKey } = operation;
52
+ if (typeof id !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id) || typeof idempotencyKey !== "string" || !/^[0-9a-f]{64}$/.test(idempotencyKey))
53
+ throw new Error(`tool ${tool.name}: malformed durable operation metadata`);
54
+ // Set after static/environment headers, case-insensitively, so a configured header cannot replace
55
+ // the durable key. The metadata itself never enters the provider's body or query arguments.
56
+ requestHeaders.set(tool.idempotencyHeader, idempotencyKey);
57
+ }
58
+ const res = await f(url, { method, headers: requestHeaders, ...(body !== null ? { body } : {}), signal: AbortSignal.timeout(cfg.timeoutMs) });
46
59
  const text = await res.text();
47
60
  // The result is what the API returned, as text. JSON stays JSON so policy facts and consumers can read it.
48
61
  return { content: [{ type: "text", text: text.length ? text : JSON.stringify({ status: res.status }) }], ...(res.ok ? {} : { isError: true }) };
@@ -0,0 +1,58 @@
1
+ import { type PublicKeyRef } from "./crypto.ts";
2
+ import { type PolicyDecision } from "./policy.ts";
3
+ import { type AuthorizationBundle, type AuthorizationStatement, type ReceiptPredicate } from "./receipt.ts";
4
+ export interface SimulationChange {
5
+ receiptId: string;
6
+ tool: string;
7
+ /** The recorded Cedar decision, including observe-mode and provenance information. */
8
+ previous: NonNullable<ReceiptPredicate["policy"]>;
9
+ proposed: PolicyDecision;
10
+ }
11
+ export interface SimulationSkip {
12
+ receiptId: string;
13
+ tool: string;
14
+ reason: string;
15
+ }
16
+ export interface SimulationGroup {
17
+ tool: string;
18
+ /** The proposed policy's determining policy ids and evaluation errors. */
19
+ reason: string;
20
+ receiptIds: string[];
21
+ }
22
+ export interface SimulationReport {
23
+ runId: string;
24
+ timestamp: string;
25
+ policyDigest: string;
26
+ previousPolicyDigests: string[];
27
+ total: number;
28
+ evaluated: number;
29
+ unchanged: number;
30
+ complete: boolean;
31
+ changes: SimulationChange[];
32
+ skipped: SimulationSkip[];
33
+ /** Changed decisions, grouped by tool and the proposed reason. */
34
+ groups: SimulationGroup[];
35
+ }
36
+ export interface SimulationOptions {
37
+ /** The customer's capture key. It decrypts the withheld values that were encrypted under it. */
38
+ captureKey?: Buffer;
39
+ /** Disclosure files by receipt id, as `agent-custody reveal` writes them. A disclosure applies only to its own receipt. */
40
+ disclosures?: ReadonlyMap<string, unknown>;
41
+ /** Calls that have no receipt to replay. Each counts in `total` and is reported as skipped. */
42
+ unreplayable?: SimulationSkip[];
43
+ }
44
+ /**
45
+ * Check an authorization bundle that has no receipt, as the verifier does for an embedded one: the issuer signed it, it
46
+ * is an authorization statement, and its leaf is in the log under a signed tree head. Throws when a check fails.
47
+ * Returns the statement's predicate.
48
+ */
49
+ export declare function verifyOrphanAuthorization(bundle: AuthorizationBundle, issuerKeys: PublicKeyRef[], logKeys: PublicKeyRef[]): AuthorizationStatement["predicate"];
50
+ /**
51
+ * Compare a proposed Cedar policy with recorded policy decisions, using each receipt's original arguments, fact
52
+ * values, agent, and (for gateways) grant context. Observe-mode decisions are the baseline even when the call ran.
53
+ * Receipts are not signature-verified here; verify their bundles separately when their authenticity matters.
54
+ * Missing inputs and non-Cedar gate failures are reported as skipped, never guessed or fetched again.
55
+ * The receipts are read once, one at a time, so a caller can verify and parse a large history lazily.
56
+ */
57
+ export declare function simulatePolicy(policyText: string, receipts: Iterable<ReceiptPredicate>, options?: SimulationOptions): SimulationReport;
58
+ export declare function formatSimulation(report: SimulationReport): string;
@@ -0,0 +1,204 @@
1
+ // Offline policy replay. The recorded inputs stay fixed; no tool or fact provider is called.
2
+ import { randomUUID } from "node:crypto";
3
+ import * as cedar from "@cedar-policy/cedar-wasm/nodejs";
4
+ import { isCommitment, pathText, restorePaths, under } from "./capture.js";
5
+ import { canonicalize, dsseVerify } from "./crypto.js";
6
+ import { decodeDelegation, DELEGATION_TYPE, delegationValidAt } from "./delegation.js";
7
+ import { leafHash, verifyInclusion } from "./log.js";
8
+ import { evaluate, policyDigest } from "./policy.js";
9
+ import { AUTHORIZATION_PREDICATE_TYPE, RECEIPT_TYPE, TREEHEAD_TYPE } from "./receipt.js";
10
+ import { structuralProblem } from "./verify.js";
11
+ const strings = (v) => Array.isArray(v) && v.every((x) => typeof x === "string");
12
+ const order = (a, b) => a < b ? -1 : a > b ? 1 : 0;
13
+ /** A gateway can deny before Cedar runs. Such a denial cannot be changed by replacing Cedar text. */
14
+ function gateProblem(p) {
15
+ if (p.issuer.kind !== "gateway")
16
+ return null;
17
+ // The approval gate runs before Cedar and records its refusal as a deny. The approval record, which stays in clear
18
+ // under a private rule, says so. A later approval refusal beside an allow, or beside an unenforced deny, means that
19
+ // Cedar did run.
20
+ if (p.policy?.decision === "deny" && p.policy.enforced !== false && p.approval?.status === "denied")
21
+ return "non-policy gate: the approval was refused before Cedar ran";
22
+ // A failed gatherFacts never assigns its partial result to the receipt. With private errors, no facts, and no
23
+ // determining policy ids, an evaluation error and missing lookup inputs are indistinguishable. Observe mode may
24
+ // even have executed this call, so execution status cannot establish whether Cedar ran.
25
+ if (p.policy?.decision === "deny" && isCommitment(p.policy.errors) && Object.keys(p.facts).length === 0 && p.policy.reasons.length === 0) {
26
+ return "original failure details are withheld; cannot establish complete Cedar inputs";
27
+ }
28
+ // The decision is the baseline. A grant revoked after Cedar ran can withhold execution, but does not invalidate
29
+ // the recorded policy inputs or turn that allow into an early gate denial.
30
+ const messages = Array.isArray(p.policy?.errors) ? p.policy.errors : [];
31
+ const gate = messages.find((s) => /^delegation grant /s.test(s)
32
+ || /^tool ".*" is not in the delegation scopes$/s.test(s)
33
+ || /^fact argument ".*" needs call argument ".*", which is missing$/s.test(s)
34
+ || /^fact ".*" lookup via .* failed:/s.test(s));
35
+ return gate ? `non-policy gate: ${gate}` : null;
36
+ }
37
+ /**
38
+ * Check an authorization bundle that has no receipt, as the verifier does for an embedded one: the issuer signed it, it
39
+ * is an authorization statement, and its leaf is in the log under a signed tree head. Throws when a check fails.
40
+ * Returns the statement's predicate.
41
+ */
42
+ export function verifyOrphanAuthorization(bundle, issuerKeys, logKeys) {
43
+ const signed = dsseVerify(bundle.envelope, issuerKeys);
44
+ if (!signed.ok)
45
+ throw new Error(`authorization signature (issuer key) (${signed.error})`);
46
+ const statement = signed.payload;
47
+ if (bundle.envelope.payloadType !== RECEIPT_TYPE || statement.predicateType !== AUTHORIZATION_PREDICATE_TYPE)
48
+ throw new Error("authorization payload type");
49
+ const head = dsseVerify(bundle.treeHead, [...logKeys, ...issuerKeys]);
50
+ if (!head.ok || bundle.treeHead.payloadType !== TREEHEAD_TYPE)
51
+ throw new Error(`authorization tree head signature${head.ok ? "" : ` (${head.error})`}`);
52
+ const tree = head.payload;
53
+ if (tree.treeSize !== bundle.inclusion.treeSize || !verifyInclusion(leafHash(canonicalize(bundle.envelope)), bundle.inclusion, tree.rootHash))
54
+ throw new Error("authorization log inclusion proof");
55
+ return statement.predicate;
56
+ }
57
+ /**
58
+ * Compare a proposed Cedar policy with recorded policy decisions, using each receipt's original arguments, fact
59
+ * values, agent, and (for gateways) grant context. Observe-mode decisions are the baseline even when the call ran.
60
+ * Receipts are not signature-verified here; verify their bundles separately when their authenticity matters.
61
+ * Missing inputs and non-Cedar gate failures are reported as skipped, never guessed or fetched again.
62
+ * The receipts are read once, one at a time, so a caller can verify and parse a large history lazily.
63
+ */
64
+ export function simulatePolicy(policyText, receipts, options = {}) {
65
+ const parsed = cedar.checkParsePolicySet({ staticPolicies: policyText });
66
+ if (parsed.type === "failure")
67
+ throw new Error(`invalid Cedar policy: ${parsed.errors.map((e) => e.message).join("; ")}`);
68
+ const unreplayable = options.unreplayable ?? [];
69
+ const report = {
70
+ runId: randomUUID(),
71
+ timestamp: new Date().toISOString(),
72
+ policyDigest: policyDigest(policyText),
73
+ previousPolicyDigests: [],
74
+ total: unreplayable.length,
75
+ evaluated: 0,
76
+ unchanged: 0,
77
+ complete: true,
78
+ changes: [],
79
+ skipped: [...unreplayable],
80
+ groups: [],
81
+ };
82
+ const digests = new Set();
83
+ for (const original of receipts) {
84
+ report.total++;
85
+ const receiptId = typeof original?.receiptId === "string" ? original.receiptId : "(unknown receipt)";
86
+ const tool = typeof original?.tool?.name === "string" ? original.tool.name : "(unknown tool)";
87
+ const skip = (reason) => { report.skipped.push({ receiptId, tool, reason }); };
88
+ const broken = structuralProblem(original);
89
+ if (broken) {
90
+ skip(`malformed receipt: ${broken}`);
91
+ continue;
92
+ }
93
+ if (original.policy === null) {
94
+ skip("no recorded policy decision (record-only receipt)");
95
+ continue;
96
+ }
97
+ const previous = original.policy;
98
+ if (typeof previous.policyDigest !== "string" || !previous.policyDigest || !strings(previous.reasons)
99
+ || (!strings(previous.errors) && !(isCommitment(previous.errors) && original.capture?.withheld.some((p) => p.length === 2 && p[0] === "policy" && p[1] === "errors")))
100
+ || (previous.enforced !== undefined && typeof previous.enforced !== "boolean")) {
101
+ skip("malformed receipt: recorded policy metadata is invalid");
102
+ continue;
103
+ }
104
+ digests.add(previous.policyDigest);
105
+ if (!receiptId || !tool || typeof original.agent.id !== "string" || !original.agent.id
106
+ || !Number.isFinite(Date.parse(original.timestamp)) || !["sdk", "gateway"].includes(original.issuer.kind)) {
107
+ skip("malformed receipt: receipt id, tool, agent, timestamp, or issuer is invalid");
108
+ continue;
109
+ }
110
+ const restored = restorePaths(original, original.capture, options.disclosures?.get(receiptId), options.captureKey);
111
+ if (restored.problems.length) {
112
+ skip(`malformed capture: ${restored.problems.map((p) => p.error).join("; ")}`);
113
+ continue;
114
+ }
115
+ const missing = restored.missing.filter((p) => under(p, ["request", "args"]) || (p[0] === "facts" && p[2] === "value"));
116
+ if (missing.length) {
117
+ skip(`required policy inputs are withheld: ${missing.map(pathText).join(", ")}`);
118
+ continue;
119
+ }
120
+ const p = restored.predicate;
121
+ if (tool === "(unknown tool)" && p.issuer.kind === "gateway" && p.capture) {
122
+ skip("the original tool name is unavailable under the capture rule");
123
+ continue;
124
+ }
125
+ if (Object.values(p.facts).some((f) => !Object.hasOwn(f, "value") || f.value === undefined)) {
126
+ skip("malformed receipt: a recorded fact has no value");
127
+ continue;
128
+ }
129
+ const gate = gateProblem(p);
130
+ if (gate) {
131
+ skip(gate);
132
+ continue;
133
+ }
134
+ const context = {
135
+ args: p.request.args,
136
+ facts: Object.fromEntries(Object.entries(p.facts).map(([name, fact]) => [name, fact.value])),
137
+ };
138
+ if (p.issuer.kind === "gateway") {
139
+ const envelope = p.delegation?.envelope;
140
+ const grant = envelope?.payloadType === DELEGATION_TYPE ? decodeDelegation(envelope) : null;
141
+ if (!grant || grant.agent !== p.agent.id || grant.principal !== p.principal.id) {
142
+ skip("the recorded delegation context is missing, malformed, or does not name this agent and principal");
143
+ continue;
144
+ }
145
+ if (!grant.scopes.includes(tool)) {
146
+ skip("the tool is outside the recorded delegation scopes");
147
+ continue;
148
+ }
149
+ if (!delegationValidAt(grant, p.timestamp)) {
150
+ skip("the recorded delegation was outside its validity window at receipt time");
151
+ continue;
152
+ }
153
+ context.grant = { principal: grant.principal, scopes: grant.scopes };
154
+ }
155
+ let proposed;
156
+ try {
157
+ proposed = evaluate(policyText, { agentId: p.agent.id, tool, context });
158
+ }
159
+ catch (e) {
160
+ // An evaluator exception is a deny, just as at the gateway; it must never become an allow in a replay.
161
+ proposed = { decision: "deny", reasons: [], errors: [e instanceof Error ? e.message : String(e)], policyDigest: report.policyDigest };
162
+ }
163
+ report.evaluated++;
164
+ if (proposed.decision === previous.decision)
165
+ report.unchanged++;
166
+ else
167
+ report.changes.push({ receiptId, tool, previous, proposed });
168
+ }
169
+ report.previousPolicyDigests = [...digests].sort(order);
170
+ report.complete = report.skipped.length === 0;
171
+ const groups = new Map();
172
+ for (const change of report.changes) {
173
+ const reason = [...new Set([...change.proposed.reasons, ...change.proposed.errors])].sort(order).join("; ") || "no permit policy matched";
174
+ const key = JSON.stringify([change.tool, reason]);
175
+ const group = groups.get(key) ?? { tool: change.tool, reason, receiptIds: [] };
176
+ group.receiptIds.push(change.receiptId);
177
+ groups.set(key, group);
178
+ }
179
+ report.groups = [...groups.values()].sort((a, b) => order(a.tool, b.tool) || order(a.reason, b.reason));
180
+ for (const group of report.groups)
181
+ group.receiptIds.sort(order);
182
+ return report;
183
+ }
184
+ export function formatSimulation(report) {
185
+ const changes = new Map(report.changes.map((c) => [JSON.stringify([c.tool, c.receiptId]), c]));
186
+ const lines = [
187
+ `Policy simulation ${report.runId}`,
188
+ `Timestamp: ${report.timestamp}`,
189
+ `Proposed policy: ${report.policyDigest}`,
190
+ `Previous policies: ${report.previousPolicyDigests.join(", ") || "none"}`,
191
+ `Receipts: ${report.total}; evaluated: ${report.evaluated}; unchanged: ${report.unchanged}; changed: ${report.changes.length}; skipped: ${report.skipped.length}`,
192
+ ];
193
+ for (const group of report.groups) {
194
+ lines.push("", `${group.tool}: ${group.reason}`);
195
+ for (const receiptId of group.receiptIds) {
196
+ const change = changes.get(JSON.stringify([group.tool, receiptId]));
197
+ lines.push(` ${receiptId}: ${change.previous.decision} -> ${change.proposed.decision}`);
198
+ }
199
+ }
200
+ for (const skipped of report.skipped)
201
+ lines.push(`SKIPPED ${skipped.receiptId} (${skipped.tool}): ${skipped.reason}`);
202
+ lines.push("", report.complete ? "RESULT: COMPLETE" : "RESULT: INCOMPLETE");
203
+ return lines.join("\n");
204
+ }
package/dist/splunk.js CHANGED
@@ -4,6 +4,9 @@ export function hecEvent(p, bundle, cfg) {
4
4
  const exec = p.execution;
5
5
  // under a capture rule a message is a commitment; the event says so rather than carrying it
6
6
  const text = (v) => (typeof v === "string" ? v : v && typeof v === "object" ? "(withheld under the capture rule)" : undefined);
7
+ // A reconciliation receipt records a provider read. No policy ran and the payment tool did not run again, so the
8
+ // event carries no decision and its status is "reconciled", never "executed" with "allow".
9
+ const reconciliation = p.reconciliation !== undefined;
7
10
  return {
8
11
  time: Date.parse(p.timestamp) / 1000,
9
12
  source: cfg.source ?? "agent-custody",
@@ -19,11 +22,15 @@ export function hecEvent(p, bundle, cfg) {
19
22
  agent: p.agent.id,
20
23
  agent_provenance: p.agent.provenance,
21
24
  principal: p.principal.id,
22
- status: exec.status,
25
+ status: reconciliation ? "reconciled" : exec.status,
23
26
  reason: text(exec.reason) ?? text(exec.error) ?? null,
24
- policy_decision: p.policy?.decision ?? null,
25
- policy_digest: p.policy?.policyDigest ?? null,
26
- policy_reasons: p.policy?.reasons ?? [],
27
+ policy_decision: reconciliation ? null : p.policy?.decision ?? null,
28
+ policy_digest: reconciliation ? null : p.policy?.policyDigest ?? null,
29
+ policy_reasons: reconciliation ? [] : p.policy?.reasons ?? [],
30
+ reconciliation,
31
+ reconciliation_lookup_tool: reconciliation ? p.reconciliation.lookup?.tool ?? null : null,
32
+ operation_status: p.operation?.status ?? null,
33
+ operation_original_receipt_id: p.operation?.originalReceiptId ?? null,
27
34
  args_digest: p.request.argsDigest,
28
35
  log_leaf_index: bundle.inclusion.leafIndex,
29
36
  log_tree_size: bundle.inclusion.treeSize,
package/dist/sso.d.ts ADDED
@@ -0,0 +1,47 @@
1
+ export interface OidcConfig {
2
+ issuer: string;
3
+ clientId: string;
4
+ clientSecret: string;
5
+ }
6
+ export interface SamlConfig {
7
+ entryPoint: string;
8
+ idpCert: string;
9
+ idpIssuer?: string;
10
+ }
11
+ export interface SsoIdentity {
12
+ subject: string;
13
+ email: string;
14
+ }
15
+ export declare function pkce(): {
16
+ verifier: string;
17
+ challenge: string;
18
+ };
19
+ export declare function oidcAuthorizeUrl(c: OidcConfig, o: {
20
+ redirectUri: string;
21
+ state: string;
22
+ nonce: string;
23
+ codeChallenge: string;
24
+ fetch?: typeof fetch;
25
+ }): Promise<string>;
26
+ export declare function oidcExchange(c: OidcConfig, o: {
27
+ code: string;
28
+ redirectUri: string;
29
+ codeVerifier: string;
30
+ nonce: string;
31
+ fetch?: typeof fetch;
32
+ now?: number;
33
+ }): Promise<SsoIdentity>;
34
+ export declare function samlAuthorizeUrl(c: SamlConfig, o: {
35
+ spEntityId: string;
36
+ acsUrl: string;
37
+ relayState?: string;
38
+ }): Promise<{
39
+ url: string;
40
+ requestId: string;
41
+ }>;
42
+ export declare function samlValidate(c: SamlConfig, o: {
43
+ spEntityId: string;
44
+ acsUrl: string;
45
+ samlResponse: string;
46
+ requestId: string;
47
+ }): Promise<SsoIdentity>;
package/dist/sso.js ADDED
@@ -0,0 +1,161 @@
1
+ // Enterprise sign-in for the portal: OIDC (code + PKCE) and SAML 2.0. The caller checks the email domain.
2
+ import { createHash, createPublicKey, randomBytes, verify as cryptoVerify } from "node:crypto";
3
+ import { createRequire } from "node:module";
4
+ const SKEW_SECONDS = 60;
5
+ const CACHE_MS = 3_600_000;
6
+ const b64url = (b) => b.toString("base64url");
7
+ export function pkce() {
8
+ const verifier = b64url(randomBytes(32));
9
+ return { verifier, challenge: b64url(createHash("sha256").update(verifier).digest()) };
10
+ }
11
+ const discoveries = new Map();
12
+ const keySets = new Map();
13
+ const getJson = async (f, url, what) => {
14
+ const r = await f(url, { headers: { accept: "application/json" }, redirect: "error", signal: AbortSignal.timeout(10_000) });
15
+ if (!r.ok)
16
+ throw new Error(`${what} answered HTTP ${r.status}`);
17
+ return r.json();
18
+ };
19
+ const httpsUrl = (u, what) => {
20
+ if (typeof u !== "string" || !URL.canParse(u) || new URL(u).protocol !== "https:")
21
+ throw new Error(`${what} must be an https URL`);
22
+ return u;
23
+ };
24
+ async function discover(c, f) {
25
+ httpsUrl(c.issuer, "the OIDC issuer");
26
+ const hit = discoveries.get(c.issuer);
27
+ if (hit && Date.now() - hit.at < CACHE_MS)
28
+ return hit.doc;
29
+ const doc = (await getJson(f, `${c.issuer.replace(/\/$/, "")}/.well-known/openid-configuration`, "OIDC discovery"));
30
+ if (doc.issuer !== c.issuer)
31
+ throw new Error("the OIDC discovery document names a different issuer");
32
+ for (const k of ["authorization_endpoint", "token_endpoint", "jwks_uri"])
33
+ httpsUrl(doc[k], `the OIDC ${k}`);
34
+ discoveries.set(c.issuer, { at: Date.now(), doc });
35
+ return doc;
36
+ }
37
+ async function jwks(c, d, f, fresh) {
38
+ const hit = keySets.get(c.issuer);
39
+ if (hit && !fresh && Date.now() - hit.at < CACHE_MS)
40
+ return hit.keys;
41
+ const keys = (await getJson(f, d.jwks_uri, "OIDC key set")).keys;
42
+ if (!Array.isArray(keys))
43
+ throw new Error("the OIDC key set has no keys");
44
+ keySets.set(c.issuer, { at: Date.now(), keys });
45
+ return keys;
46
+ }
47
+ export async function oidcAuthorizeUrl(c, o) {
48
+ const d = await discover(c, o.fetch ?? fetch);
49
+ const u = new URL(d.authorization_endpoint);
50
+ const q = { response_type: "code", client_id: c.clientId, redirect_uri: o.redirectUri, scope: "openid email profile", state: o.state, nonce: o.nonce, code_challenge: o.codeChallenge, code_challenge_method: "S256" };
51
+ for (const [k, v] of Object.entries(q))
52
+ u.searchParams.set(k, v);
53
+ return u.toString();
54
+ }
55
+ async function verifySignature(c, d, f, token) {
56
+ const parts = token.split(".");
57
+ const [h, p, s] = parts;
58
+ if (parts.length !== 3 || !h || !p || !s)
59
+ throw new Error("the id_token is not a JWS");
60
+ const header = JSON.parse(Buffer.from(h, "base64url").toString());
61
+ const kty = { RS256: "RSA", ES256: "EC" }[header.alg];
62
+ if (!kty)
63
+ throw new Error(`the id_token algorithm ${String(header.alg)} is not accepted; use RS256 or ES256`);
64
+ const candidates = (keys) => keys.filter((k) => k.kty === kty && (!k.use || k.use === "sig") && (!header.kid || k.kid === header.kid));
65
+ let found = candidates(await jwks(c, d, f, false));
66
+ if (!found.length)
67
+ found = candidates(await jwks(c, d, f, true)); // rotated keys
68
+ if (!found.length)
69
+ throw new Error("no key in the OIDC key set matches the id_token");
70
+ const ok = found.some((k) => {
71
+ if (header.alg === "ES256" && k.crv !== "P-256")
72
+ return false;
73
+ const key = createPublicKey({ key: k, format: "jwk" });
74
+ return cryptoVerify("sha256", Buffer.from(`${h}.${p}`), header.alg === "ES256" ? { key, dsaEncoding: "ieee-p1363" } : key, Buffer.from(s, "base64url"));
75
+ });
76
+ if (!ok)
77
+ throw new Error("the id_token signature is not valid");
78
+ return JSON.parse(Buffer.from(p, "base64url").toString());
79
+ }
80
+ export async function oidcExchange(c, o) {
81
+ const f = o.fetch ?? fetch;
82
+ const d = await discover(c, f);
83
+ const r = await f(d.token_endpoint, {
84
+ method: "POST",
85
+ headers: { accept: "application/json", "content-type": "application/x-www-form-urlencoded" },
86
+ body: new URLSearchParams({ grant_type: "authorization_code", code: o.code, redirect_uri: o.redirectUri, client_id: c.clientId, client_secret: c.clientSecret, code_verifier: o.codeVerifier }),
87
+ redirect: "error",
88
+ signal: AbortSignal.timeout(10_000),
89
+ });
90
+ const tok = (await r.json().catch(() => ({})));
91
+ if (!r.ok || !tok.id_token)
92
+ throw new Error(`the OIDC token endpoint refused the code (HTTP ${r.status}${tok.error ? `, ${tok.error}` : ""})`);
93
+ const claims = await verifySignature(c, d, f, tok.id_token);
94
+ const now = (o.now ?? Date.now()) / 1000;
95
+ const aud = [claims.aud].flat();
96
+ if (claims.iss !== c.issuer)
97
+ throw new Error("the id_token issuer is not the configured issuer");
98
+ if (!aud.includes(c.clientId))
99
+ throw new Error("the id_token audience does not include this client");
100
+ if (aud.length > 1 && claims.azp !== c.clientId)
101
+ throw new Error("the id_token has several audiences and its azp is not this client");
102
+ if (typeof claims.exp !== "number" || claims.exp + SKEW_SECONDS <= now)
103
+ throw new Error("the id_token has expired");
104
+ if (typeof claims.iat === "number" && claims.iat - SKEW_SECONDS > now)
105
+ throw new Error("the id_token is issued in the future");
106
+ if (claims.nonce !== o.nonce)
107
+ throw new Error("the id_token nonce does not match this sign-in");
108
+ if (typeof claims.sub !== "string" || !claims.sub)
109
+ throw new Error("the id_token has no sub claim");
110
+ if (typeof claims.email !== "string" || !claims.email.includes("@"))
111
+ throw new Error("the id_token has no email claim");
112
+ // Many enterprise IdPs omit email_verified.
113
+ if (claims.email_verified === false)
114
+ throw new Error("the provider says the email address is not verified");
115
+ return { subject: claims.sub, email: claims.email.toLowerCase() };
116
+ }
117
+ // Never verify XML signatures by hand: node-saml does it.
118
+ const EMAIL_CLAIM = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress";
119
+ const EMAIL_FORMAT = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress";
120
+ function samlClient(c, sp, requestId) {
121
+ let lib;
122
+ try {
123
+ lib = createRequire(import.meta.url)("@node-saml/node-saml");
124
+ }
125
+ catch (cause) {
126
+ if (cause.code !== "MODULE_NOT_FOUND")
127
+ throw cause;
128
+ throw new Error("SAML sign-in needs the optional package @node-saml/node-saml; install it beside @agent-custody/receipts", { cause });
129
+ }
130
+ return new lib.SAML({
131
+ entryPoint: c.entryPoint, idpCert: c.idpCert, issuer: sp.spEntityId, callbackUrl: sp.acsUrl, audience: sp.spEntityId,
132
+ wantAssertionsSigned: true, wantAuthnResponseSigned: false,
133
+ acceptedClockSkewMs: SKEW_SECONDS * 1000, signatureAlgorithm: "sha256", generateUniqueId: () => requestId,
134
+ });
135
+ }
136
+ export async function samlAuthorizeUrl(c, o) {
137
+ const requestId = `_${randomBytes(20).toString("hex")}`;
138
+ return { url: await samlClient(c, o, requestId).getAuthorizeUrlAsync(o.relayState ?? "", undefined, {}), requestId };
139
+ }
140
+ export async function samlValidate(c, o) {
141
+ const { profile } = await samlClient(c, o, o.requestId).validatePostResponseAsync({ SAMLResponse: o.samlResponse });
142
+ if (!profile?.nameID)
143
+ throw new Error("the SAML response has no NameID");
144
+ // Only the assertion is signed: the Response's InResponseTo proves nothing.
145
+ const assertion = profile.getAssertion().Assertion;
146
+ if (c.idpIssuer && profile.issuer !== c.idpIssuer)
147
+ throw new Error("the SAML assertion issuer is not the configured IdP");
148
+ const bearer = (assertion.Subject?.[0]?.SubjectConfirmation ?? [])
149
+ .filter((s) => s.$?.Method === "urn:oasis:names:tc:SAML:2.0:cm:bearer")
150
+ .flatMap((s) => s.SubjectConfirmationData ?? []);
151
+ const bound = bearer.some((d) => d.$?.InResponseTo === o.requestId && d.$?.Recipient === o.acsUrl && Date.parse(d.$?.NotOnOrAfter) + SKEW_SECONDS * 1000 > Date.now());
152
+ if (!bound)
153
+ throw new Error("the SAML assertion is not an answer to this sign-in request");
154
+ if (!assertion.Conditions?.[0]?.$?.NotOnOrAfter)
155
+ throw new Error("the SAML assertion has no validity period");
156
+ const attr = (name) => [profile.attributes?.[name]].flat()[0];
157
+ const email = [attr("email"), attr(EMAIL_CLAIM), profile.nameIDFormat === EMAIL_FORMAT ? profile.nameID : undefined].find((e) => typeof e === "string" && e.includes("@"));
158
+ if (!email)
159
+ throw new Error("the SAML assertion has no email address");
160
+ return { subject: profile.nameID, email: email.toLowerCase() };
161
+ }
package/dist/verify.d.ts CHANGED
@@ -10,6 +10,8 @@ export interface VerifyOptions {
10
10
  /** keys trusted to have issued receipts: gateway keys, SDK application keys */
11
11
  issuerKeys: PublicKeyRef[];
12
12
  principalKeys: PublicKeyRef[];
13
+ /** Human approval keys, trusted independently of receipt issuers and delegation principals. Required for an approved action. */
14
+ approvalKeys?: PublicKeyRef[];
13
15
  /** keys of logs run by someone other than the issuer; tree heads are checked against these and the issuer keys */
14
16
  logKeys?: PublicKeyRef[];
15
17
  /** keys of upstreams that sign their results; with one given, an execution carrying an upstream signature is checked and becomes attested */