@agent-custody/receipts 0.12.0 → 0.14.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 +20 -12
- package/dist/claude-init.d.ts +46 -0
- package/dist/claude-init.js +208 -0
- package/dist/cli.js +115 -0
- package/dist/completeness.d.ts +106 -0
- package/dist/completeness.js +240 -0
- package/dist/deny-report.d.ts +30 -0
- package/dist/deny-report.js +106 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +3 -0
- package/dist/log-admin.js +3 -3
- package/dist/log.d.ts +13 -2
- package/dist/log.js +97 -17
- package/dist/policy.d.ts +6 -0
- package/dist/policy.js +17 -0
- package/dist/sdk/claude.js +18 -2
- package/dist/sdk/index.d.ts +2 -0
- package/dist/sdk/index.js +3 -1
- package/dist/witness.js +3 -3
- package/docs/completeness.md +59 -0
- package/docs/compliance.md +117 -7
- package/docs/policies.md +12 -0
- package/docs/sdk.md +83 -1
- package/docs/threat-model.md +1 -0
- package/docs/tutorials.md +4 -0
- package/docs/usage.md +1 -1
- package/package.json +3 -2
- package/templates/claude-code.cedar +96 -0
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { type VerifyOptions } from "./verify.ts";
|
|
2
|
+
/** One provider object, reduced to what the comparison reads. */
|
|
3
|
+
export interface ProviderObject {
|
|
4
|
+
id: string;
|
|
5
|
+
/** when the provider created it, as epoch milliseconds */
|
|
6
|
+
createdMs: number;
|
|
7
|
+
amount?: number;
|
|
8
|
+
currency?: string;
|
|
9
|
+
/** the provider's own object, for beneficiary fields */
|
|
10
|
+
raw: Record<string, unknown>;
|
|
11
|
+
}
|
|
12
|
+
export interface ProviderSource {
|
|
13
|
+
/** for reports, e.g. "stripe refunds" */
|
|
14
|
+
name: string;
|
|
15
|
+
list(sinceMs: number, untilMs: number): AsyncIterable<ProviderObject>;
|
|
16
|
+
}
|
|
17
|
+
export type StripeObject = "refunds" | "payouts" | "transfers";
|
|
18
|
+
export interface StripeSourceOptions {
|
|
19
|
+
/** a read-only (restricted) key; from the environment, never a flag */
|
|
20
|
+
secretKey: string;
|
|
21
|
+
object: StripeObject;
|
|
22
|
+
baseUrl?: string;
|
|
23
|
+
fetch?: typeof fetch;
|
|
24
|
+
}
|
|
25
|
+
/** Lists Stripe objects created in the window, every page, with `created[gte]` and `created[lt]`. */
|
|
26
|
+
export declare function stripeSource(o: StripeSourceOptions): ProviderSource;
|
|
27
|
+
export interface CompletenessOptions {
|
|
28
|
+
/** the auditor's copy of the receipts directory */
|
|
29
|
+
receiptsDir: string;
|
|
30
|
+
/** how each receipt is verified; only receipts that verify are matched */
|
|
31
|
+
verify: VerifyOptions;
|
|
32
|
+
source: ProviderSource;
|
|
33
|
+
/** the tools whose executed calls create provider objects, e.g. ["stripe.refund"] */
|
|
34
|
+
tools: string[];
|
|
35
|
+
sinceMs: number;
|
|
36
|
+
untilMs: number;
|
|
37
|
+
/** where the provider's object id sits in the JSON of the result's first text item; default "id" */
|
|
38
|
+
idPath?: string;
|
|
39
|
+
/** the call argument that holds the amount in minor units; default "amount" */
|
|
40
|
+
amountField?: string;
|
|
41
|
+
/** the call argument that holds the currency; default "currency", compared case-insensitively when both sides have one */
|
|
42
|
+
currencyField?: string;
|
|
43
|
+
/** call argument → provider field pairs that must be equal, e.g. { charge: "charge" } */
|
|
44
|
+
beneficiary?: Record<string, string>;
|
|
45
|
+
/**
|
|
46
|
+
* provider objects are listed this far either side of the window, so a receipt signed just inside the window still
|
|
47
|
+
* finds an object the provider created just outside it; default fifteen minutes
|
|
48
|
+
*/
|
|
49
|
+
marginMs?: number;
|
|
50
|
+
}
|
|
51
|
+
export interface CompletenessReport {
|
|
52
|
+
provider: string;
|
|
53
|
+
tools: string[];
|
|
54
|
+
window: {
|
|
55
|
+
since: string;
|
|
56
|
+
until: string;
|
|
57
|
+
};
|
|
58
|
+
receiptsRead: number;
|
|
59
|
+
matched: {
|
|
60
|
+
receiptId: string;
|
|
61
|
+
providerId: string;
|
|
62
|
+
}[];
|
|
63
|
+
/** provider objects in the window with no verified receipt: actions taken outside the gateway */
|
|
64
|
+
providerOnly: {
|
|
65
|
+
providerId: string;
|
|
66
|
+
created: string;
|
|
67
|
+
amount?: number;
|
|
68
|
+
currency?: string;
|
|
69
|
+
}[];
|
|
70
|
+
/** executed receipts in the window whose provider object the provider does not have */
|
|
71
|
+
receiptOnly: {
|
|
72
|
+
receiptId: string;
|
|
73
|
+
providerId: string;
|
|
74
|
+
timestamp: string;
|
|
75
|
+
}[];
|
|
76
|
+
mismatches: {
|
|
77
|
+
receiptId: string;
|
|
78
|
+
providerId: string;
|
|
79
|
+
field: string;
|
|
80
|
+
receipt: unknown;
|
|
81
|
+
provider: unknown;
|
|
82
|
+
}[];
|
|
83
|
+
/** provider objects that more than one verified receipt names: one action recorded twice, or receipts that disagree */
|
|
84
|
+
duplicates: {
|
|
85
|
+
providerId: string;
|
|
86
|
+
receiptIds: string[];
|
|
87
|
+
}[];
|
|
88
|
+
/** receipt files that did not verify, and so were not matched */
|
|
89
|
+
unverified: {
|
|
90
|
+
file: string;
|
|
91
|
+
failing: string[];
|
|
92
|
+
}[];
|
|
93
|
+
/** verified, executed receipts whose provider id cannot be read */
|
|
94
|
+
unmatchable: {
|
|
95
|
+
receiptId: string;
|
|
96
|
+
reason: string;
|
|
97
|
+
}[];
|
|
98
|
+
/** calls committed before they were forwarded whose outcome receipt is missing: each may be a provider object above */
|
|
99
|
+
forwardedWithoutOutcome: {
|
|
100
|
+
receiptId: string;
|
|
101
|
+
tool: string;
|
|
102
|
+
}[];
|
|
103
|
+
complete: boolean;
|
|
104
|
+
}
|
|
105
|
+
export declare function checkCompleteness(o: CompletenessOptions): Promise<CompletenessReport>;
|
|
106
|
+
export declare function formatCompleteness(r: CompletenessReport): string;
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
// Completeness from the provider's side. Receipts prove what went through the gateway; nothing on the gateway's side
|
|
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
|
+
// window and matches each one to a verified receipt by the provider's object id, which the receipt's result carries.
|
|
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. Nothing here writes, retries, or calls the provider for anything but a list.
|
|
6
|
+
import { readdirSync, readFileSync } from "node:fs";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { isCommitment, REST } from "./capture.js";
|
|
9
|
+
import { verifyOrphanAuthorization } from "./simulate.js";
|
|
10
|
+
import { verifyBundle } from "./verify.js";
|
|
11
|
+
/** Lists Stripe objects created in the window, every page, with `created[gte]` and `created[lt]`. */
|
|
12
|
+
export function stripeSource(o) {
|
|
13
|
+
const f = o.fetch ?? fetch;
|
|
14
|
+
const base = o.baseUrl ?? "https://api.stripe.com/";
|
|
15
|
+
return {
|
|
16
|
+
name: `stripe ${o.object}`,
|
|
17
|
+
async *list(sinceMs, untilMs) {
|
|
18
|
+
let after;
|
|
19
|
+
for (;;) {
|
|
20
|
+
const url = new URL(`v1/${o.object}`, base);
|
|
21
|
+
url.searchParams.set("limit", "100");
|
|
22
|
+
url.searchParams.set("created[gte]", String(Math.floor(sinceMs / 1000)));
|
|
23
|
+
url.searchParams.set("created[lt]", String(Math.ceil(untilMs / 1000)));
|
|
24
|
+
if (after)
|
|
25
|
+
url.searchParams.set("starting_after", after);
|
|
26
|
+
const res = await f(url, { headers: { authorization: `Bearer ${o.secretKey}` }, signal: AbortSignal.timeout(15_000) });
|
|
27
|
+
if (!res.ok)
|
|
28
|
+
throw new Error(`stripe ${o.object}: HTTP ${res.status}`);
|
|
29
|
+
const page = (await res.json());
|
|
30
|
+
const data = Array.isArray(page.data) ? page.data : [];
|
|
31
|
+
for (const obj of data) {
|
|
32
|
+
if (typeof obj.id !== "string" || typeof obj.created !== "number")
|
|
33
|
+
throw new Error(`stripe ${o.object}: an object without an id or a created time`);
|
|
34
|
+
yield {
|
|
35
|
+
id: obj.id,
|
|
36
|
+
createdMs: obj.created * 1000,
|
|
37
|
+
...(typeof obj.amount === "number" ? { amount: obj.amount } : {}),
|
|
38
|
+
...(typeof obj.currency === "string" ? { currency: obj.currency } : {}),
|
|
39
|
+
raw: obj,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
if (!page.has_more || data.length === 0)
|
|
43
|
+
return;
|
|
44
|
+
after = data[data.length - 1].id;
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
const AUTHORIZATION = ".authorization.json";
|
|
50
|
+
const iso = (ms) => new Date(ms).toISOString();
|
|
51
|
+
function at(value, path) {
|
|
52
|
+
let v = value;
|
|
53
|
+
for (const part of path.split(".")) {
|
|
54
|
+
if (!v || typeof v !== "object" || !Object.hasOwn(v, part))
|
|
55
|
+
return undefined;
|
|
56
|
+
v = v[part];
|
|
57
|
+
}
|
|
58
|
+
return v;
|
|
59
|
+
}
|
|
60
|
+
/** The provider object id that an executed call's result carries, or why it cannot be read. */
|
|
61
|
+
function providerIdOf(p, idPath) {
|
|
62
|
+
const result = p.execution.result;
|
|
63
|
+
if (isCommitment(result))
|
|
64
|
+
return { reason: "the result is withheld under a capture rule; the provider's object id cannot be read from the receipt" };
|
|
65
|
+
const r = result;
|
|
66
|
+
// a `$rest` commitment may hold only unrelated fields: the content is withheld only when it is not kept in clear
|
|
67
|
+
if (r && !Object.hasOwn(r, "content") && isCommitment(r[REST]))
|
|
68
|
+
return { reason: "the result content is withheld under a capture rule; the provider's object id cannot be read from the receipt" };
|
|
69
|
+
const content = r?.content;
|
|
70
|
+
const first = Array.isArray(content) ? content[0] : undefined;
|
|
71
|
+
if (isCommitment(content) || isCommitment(first))
|
|
72
|
+
return { reason: "the result content is withheld under a capture rule; the provider's object id cannot be read from the receipt" };
|
|
73
|
+
const text = first?.text;
|
|
74
|
+
if (isCommitment(text))
|
|
75
|
+
return { reason: "the result content is withheld under a capture rule; the provider's object id cannot be read from the receipt" };
|
|
76
|
+
if (typeof text !== "string")
|
|
77
|
+
return { reason: "the result carries no text to read the provider's object id from" };
|
|
78
|
+
let parsed;
|
|
79
|
+
try {
|
|
80
|
+
parsed = JSON.parse(text);
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
return { reason: "the result's text is not JSON" };
|
|
84
|
+
}
|
|
85
|
+
const id = at(parsed, idPath);
|
|
86
|
+
return typeof id === "string" && id.length ? { id } : { reason: `the result has no string at "${idPath}"` };
|
|
87
|
+
}
|
|
88
|
+
/** A call argument, or that a capture rule withholds it: listed fields stay in clear beside one `$rest` commitment. */
|
|
89
|
+
function argOf(args, field) {
|
|
90
|
+
if (Object.hasOwn(args, field))
|
|
91
|
+
return isCommitment(args[field]) ? { withheld: true } : { value: args[field] };
|
|
92
|
+
return isCommitment(args[REST]) ? { withheld: true } : { value: undefined };
|
|
93
|
+
}
|
|
94
|
+
export async function checkCompleteness(o) {
|
|
95
|
+
const idPath = o.idPath ?? "id";
|
|
96
|
+
const amountField = o.amountField ?? "amount";
|
|
97
|
+
const currencyField = o.currencyField ?? "currency";
|
|
98
|
+
const margin = o.marginMs ?? 15 * 60_000;
|
|
99
|
+
const tools = new Set(o.tools);
|
|
100
|
+
const inWindow = (ms) => ms >= o.sinceMs && ms < o.untilMs;
|
|
101
|
+
const report = {
|
|
102
|
+
provider: o.source.name,
|
|
103
|
+
tools: [...o.tools],
|
|
104
|
+
window: { since: iso(o.sinceMs), until: iso(o.untilMs) },
|
|
105
|
+
receiptsRead: 0,
|
|
106
|
+
matched: [],
|
|
107
|
+
providerOnly: [],
|
|
108
|
+
receiptOnly: [],
|
|
109
|
+
mismatches: [],
|
|
110
|
+
duplicates: [],
|
|
111
|
+
unverified: [],
|
|
112
|
+
unmatchable: [],
|
|
113
|
+
forwardedWithoutOutcome: [],
|
|
114
|
+
complete: false,
|
|
115
|
+
};
|
|
116
|
+
const names = readdirSync(o.receiptsDir, { withFileTypes: true }).filter((e) => (e.isFile() || e.isSymbolicLink()) && e.name.endsWith(".json")).map((e) => e.name).sort();
|
|
117
|
+
const outcomes = new Set();
|
|
118
|
+
const byProviderId = new Map();
|
|
119
|
+
for (const name of names) {
|
|
120
|
+
if (name.endsWith(AUTHORIZATION))
|
|
121
|
+
continue;
|
|
122
|
+
report.receiptsRead++;
|
|
123
|
+
let result;
|
|
124
|
+
try {
|
|
125
|
+
result = verifyBundle(JSON.parse(readFileSync(join(o.receiptsDir, name), "utf8")), o.verify);
|
|
126
|
+
}
|
|
127
|
+
catch (e) {
|
|
128
|
+
report.unverified.push({ file: name, failing: [e instanceof Error ? e.message : String(e)] });
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
if (!result.ok || !result.statement) {
|
|
132
|
+
report.unverified.push({ file: name, failing: result.checks.filter((c) => !c.ok).map((c) => c.name) });
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
const p = result.statement.predicate;
|
|
136
|
+
// the gateway names each file by its receipt id: a valid receipt under another name could stand in for a missing outcome
|
|
137
|
+
if (name !== `${p.receiptId}.json`) {
|
|
138
|
+
report.unverified.push({ file: name, failing: [`the file name does not match the signed receipt id ${p.receiptId}`] });
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
outcomes.add(p.receiptId);
|
|
142
|
+
if (!tools.has(p.tool.name) || p.reconciliation || p.execution.status !== "executed")
|
|
143
|
+
continue;
|
|
144
|
+
const id = providerIdOf(p, idPath);
|
|
145
|
+
if ("reason" in id) {
|
|
146
|
+
if (inWindow(Date.parse(p.timestamp)))
|
|
147
|
+
report.unmatchable.push({ receiptId: p.receiptId, reason: id.reason });
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
byProviderId.set(id.id, [...(byProviderId.get(id.id) ?? []), p]);
|
|
151
|
+
}
|
|
152
|
+
for (const name of names) {
|
|
153
|
+
if (!name.endsWith(AUTHORIZATION))
|
|
154
|
+
continue;
|
|
155
|
+
// committed and forwarded, then nothing: the provider may hold an object this report cannot tie to a receipt
|
|
156
|
+
let auth;
|
|
157
|
+
try {
|
|
158
|
+
auth = verifyOrphanAuthorization(JSON.parse(readFileSync(join(o.receiptsDir, name), "utf8")), o.verify.issuerKeys, o.verify.logKeys ?? []);
|
|
159
|
+
}
|
|
160
|
+
catch (e) {
|
|
161
|
+
report.unverified.push({ file: name, failing: [e instanceof Error ? e.message : String(e)] });
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
if (name !== `${auth.receiptId}${AUTHORIZATION}`)
|
|
165
|
+
report.unverified.push({ file: name, failing: [`the file name does not match the signed receipt id ${auth.receiptId}`] });
|
|
166
|
+
if (outcomes.has(auth.receiptId) || !tools.has(auth.tool.name) || !inWindow(Date.parse(auth.timestamp)))
|
|
167
|
+
continue;
|
|
168
|
+
report.forwardedWithoutOutcome.push({ receiptId: auth.receiptId, tool: auth.tool.name });
|
|
169
|
+
}
|
|
170
|
+
const seen = new Set();
|
|
171
|
+
for await (const obj of o.source.list(o.sinceMs - margin, o.untilMs + margin)) {
|
|
172
|
+
seen.add(obj.id);
|
|
173
|
+
const receipts = byProviderId.get(obj.id) ?? [];
|
|
174
|
+
// the margin finds a receipt across the window's edge; it does not widen the period reported on
|
|
175
|
+
const inScope = inWindow(obj.createdMs) || receipts.some((p) => inWindow(Date.parse(p.timestamp)));
|
|
176
|
+
if (!inScope)
|
|
177
|
+
continue;
|
|
178
|
+
if (!receipts.length) {
|
|
179
|
+
report.providerOnly.push({ providerId: obj.id, created: iso(obj.createdMs), ...(obj.amount !== undefined ? { amount: obj.amount } : {}), ...(obj.currency !== undefined ? { currency: obj.currency } : {}) });
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
if (receipts.length > 1)
|
|
183
|
+
report.duplicates.push({ providerId: obj.id, receiptIds: receipts.map((p) => p.receiptId) });
|
|
184
|
+
for (const p of receipts) {
|
|
185
|
+
report.matched.push({ receiptId: p.receiptId, providerId: obj.id });
|
|
186
|
+
const args = p.request.args;
|
|
187
|
+
const withheld = (arg) => report.unmatchable.push({ receiptId: p.receiptId, reason: `the argument "${arg}" is withheld under a capture rule, so it cannot be compared` });
|
|
188
|
+
const amount = argOf(args, amountField);
|
|
189
|
+
if ("withheld" in amount) {
|
|
190
|
+
if (obj.amount !== undefined)
|
|
191
|
+
withheld(amountField);
|
|
192
|
+
}
|
|
193
|
+
else if (obj.amount !== undefined && amount.value !== obj.amount)
|
|
194
|
+
report.mismatches.push({ receiptId: p.receiptId, providerId: obj.id, field: "amount", receipt: amount.value, provider: obj.amount });
|
|
195
|
+
const currency = argOf(args, currencyField);
|
|
196
|
+
if ("withheld" in currency) {
|
|
197
|
+
if (obj.currency !== undefined)
|
|
198
|
+
withheld(currencyField);
|
|
199
|
+
}
|
|
200
|
+
else if (typeof currency.value === "string" && obj.currency !== undefined && currency.value.toLowerCase() !== obj.currency.toLowerCase())
|
|
201
|
+
report.mismatches.push({ receiptId: p.receiptId, providerId: obj.id, field: "currency", receipt: currency.value, provider: obj.currency });
|
|
202
|
+
for (const [arg, field] of Object.entries(o.beneficiary ?? {})) {
|
|
203
|
+
const value = argOf(args, arg);
|
|
204
|
+
if ("withheld" in value || value.value === undefined) {
|
|
205
|
+
report.unmatchable.push({ receiptId: p.receiptId, reason: `the beneficiary argument "${arg}" is missing or withheld, so it cannot be compared` });
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
const provider = at(obj.raw, field);
|
|
209
|
+
if (String(value.value) !== String(provider))
|
|
210
|
+
report.mismatches.push({ receiptId: p.receiptId, providerId: obj.id, field: arg, receipt: value.value, provider });
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
for (const [providerId, receipts] of byProviderId) {
|
|
215
|
+
if (seen.has(providerId))
|
|
216
|
+
continue;
|
|
217
|
+
for (const p of receipts)
|
|
218
|
+
if (inWindow(Date.parse(p.timestamp)))
|
|
219
|
+
report.receiptOnly.push({ receiptId: p.receiptId, providerId, timestamp: p.timestamp });
|
|
220
|
+
}
|
|
221
|
+
report.matched.sort((a, b) => a.receiptId.localeCompare(b.receiptId));
|
|
222
|
+
report.complete = [report.providerOnly, report.receiptOnly, report.mismatches, report.duplicates, report.unverified, report.unmatchable, report.forwardedWithoutOutcome].every((l) => l.length === 0);
|
|
223
|
+
return report;
|
|
224
|
+
}
|
|
225
|
+
export function formatCompleteness(r) {
|
|
226
|
+
const lines = [`${r.provider} for ${r.tools.join(", ")}, ${r.window.since} to ${r.window.until}: ${r.receiptsRead} receipt(s) read, ${r.matched.length} matched`];
|
|
227
|
+
const section = (title, rows) => {
|
|
228
|
+
if (rows.length)
|
|
229
|
+
lines.push("", `${title} (${rows.length})`, ...rows.map((row) => ` ${row}`));
|
|
230
|
+
};
|
|
231
|
+
section("PROVIDER ACTIONS WITH NO RECEIPT", r.providerOnly.map((x) => `${x.providerId} created ${x.created}${x.amount !== undefined ? ` amount ${x.amount}${x.currency ? ` ${x.currency}` : ""}` : ""}`));
|
|
232
|
+
section("RECEIPTS THE PROVIDER DOES NOT HAVE", r.receiptOnly.map((x) => `${x.receiptId} names ${x.providerId}, signed ${x.timestamp}`));
|
|
233
|
+
section("MISMATCHES", r.mismatches.map((x) => `${x.receiptId} / ${x.providerId}: ${x.field} is ${JSON.stringify(x.receipt)} in the receipt, ${JSON.stringify(x.provider)} at the provider`));
|
|
234
|
+
section("ONE PROVIDER OBJECT, SEVERAL RECEIPTS", r.duplicates.map((x) => `${x.providerId} is named by ${x.receiptIds.join(", ")}`));
|
|
235
|
+
section("FORWARDED WITHOUT AN OUTCOME RECEIPT", r.forwardedWithoutOutcome.map((x) => `${x.receiptId} (${x.tool}): committed and forwarded, no receipt of the outcome`));
|
|
236
|
+
section("UNMATCHABLE", r.unmatchable.map((x) => `${x.receiptId}: ${x.reason}`));
|
|
237
|
+
section("NOT VERIFIED, NOT MATCHED", r.unverified.map((x) => `${x.file}: ${x.failing.join("; ")}`));
|
|
238
|
+
lines.push("", r.complete ? "RESULT: COMPLETE" : "RESULT: INCOMPLETE");
|
|
239
|
+
return lines.join("\n");
|
|
240
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export interface DeniedCall {
|
|
2
|
+
receiptId: string;
|
|
3
|
+
timestamp: string;
|
|
4
|
+
tool: string;
|
|
5
|
+
/** The command, the file path, or the URL of the call. */
|
|
6
|
+
target: string;
|
|
7
|
+
/** The Cedar policy ids that decided, such as `policy3`. */
|
|
8
|
+
policyIds: string[];
|
|
9
|
+
/** The `@reason` of each rule that has one. */
|
|
10
|
+
reasons: string[];
|
|
11
|
+
/** The text of each rule, when the policy file still has the digest that the receipt names. */
|
|
12
|
+
rules: string[];
|
|
13
|
+
}
|
|
14
|
+
export interface DenyReport {
|
|
15
|
+
configFile: string;
|
|
16
|
+
receiptsDir: string;
|
|
17
|
+
observe: boolean;
|
|
18
|
+
/** Receipts that verified. */
|
|
19
|
+
verified: number;
|
|
20
|
+
/** Denials recorded with `enforced: false`: the call ran. */
|
|
21
|
+
wouldDeny: DeniedCall[];
|
|
22
|
+
/** Denials that the policy enforced: the call was blocked. */
|
|
23
|
+
denied: DeniedCall[];
|
|
24
|
+
unverified: {
|
|
25
|
+
file: string;
|
|
26
|
+
reason: string;
|
|
27
|
+
}[];
|
|
28
|
+
}
|
|
29
|
+
export declare function denyReport(configFile: string): DenyReport;
|
|
30
|
+
export declare function formatDenyReport(r: DenyReport): string;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// `agent-custody report`: the calls that the policy would have denied, read from the receipts of an SDK config.
|
|
2
|
+
// Each receipt is verified with the agent's key first. A receipt that does not verify is counted apart and never listed as a denial.
|
|
3
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { loadSdkConfig } from "./config.js";
|
|
6
|
+
import { loadPrivateKey, loadPublicKey } from "./crypto.js";
|
|
7
|
+
import { policyDigest, policyReasons, policyRules } from "./policy.js";
|
|
8
|
+
import { verifyBundle } from "./verify.js";
|
|
9
|
+
const ANNOTATIONS = /^(?:\s*@\w+\s*\("(?:[^"\\]|\\.)*"\))+\s*/;
|
|
10
|
+
const TARGET_ARGS = ["command", "file_path", "notebook_path", "path", "url"];
|
|
11
|
+
function targetOf(args) {
|
|
12
|
+
if (!args || typeof args !== "object")
|
|
13
|
+
return "(withheld)";
|
|
14
|
+
const a = args;
|
|
15
|
+
const name = TARGET_ARGS.find((k) => typeof a[k] === "string");
|
|
16
|
+
const text = name ? a[name] : JSON.stringify(a);
|
|
17
|
+
return text.replace(/\s+/g, " ").trim();
|
|
18
|
+
}
|
|
19
|
+
export function denyReport(configFile) {
|
|
20
|
+
const cfg = loadSdkConfig(configFile);
|
|
21
|
+
const issuer = loadPrivateKey(cfg.identity.keyFile);
|
|
22
|
+
const opts = {
|
|
23
|
+
issuerKeys: [{ publicKey: issuer.publicKey, keyid: issuer.keyid }],
|
|
24
|
+
principalKeys: [],
|
|
25
|
+
logKeys: (cfg.log?.keys ?? []).map(loadPublicKey),
|
|
26
|
+
...(cfg.logFile ? { logFile: cfg.logFile } : {}),
|
|
27
|
+
...(cfg.log?.logId ? { logId: cfg.log.logId } : {}),
|
|
28
|
+
};
|
|
29
|
+
const policyText = cfg.policyFile && existsSync(cfg.policyFile) ? readFileSync(cfg.policyFile, "utf8") : null;
|
|
30
|
+
const rules = policyText === null ? [] : policyRules(policyText);
|
|
31
|
+
const reasons = policyText === null ? [] : policyReasons(policyText);
|
|
32
|
+
const currentDigest = policyText === null ? null : policyDigest(policyText);
|
|
33
|
+
const report = { configFile, receiptsDir: cfg.receiptsDir, observe: cfg.mode === "observe", verified: 0, wouldDeny: [], denied: [], unverified: [] };
|
|
34
|
+
const files = existsSync(cfg.receiptsDir)
|
|
35
|
+
? readdirSync(cfg.receiptsDir, { withFileTypes: true }).filter((e) => (e.isFile() || e.isSymbolicLink()) && e.name.endsWith(".json") && !e.name.endsWith(".authorization.json")).map((e) => e.name).sort()
|
|
36
|
+
: [];
|
|
37
|
+
for (const file of files) {
|
|
38
|
+
try {
|
|
39
|
+
const result = verifyBundle(JSON.parse(readFileSync(join(cfg.receiptsDir, file), "utf8")), opts);
|
|
40
|
+
if (!result.ok || !result.statement) {
|
|
41
|
+
const failed = result.checks.filter((c) => !c.ok).map((c) => c.name);
|
|
42
|
+
throw new Error(`failed: ${failed.join("; ")}`);
|
|
43
|
+
}
|
|
44
|
+
const p = result.statement.predicate;
|
|
45
|
+
if (`${p.receiptId}.json` !== file)
|
|
46
|
+
throw new Error("the file name does not match the receipt id");
|
|
47
|
+
report.verified++;
|
|
48
|
+
if (p.policy?.decision !== "deny")
|
|
49
|
+
continue;
|
|
50
|
+
const policyIds = p.policy.reasons;
|
|
51
|
+
const known = p.policy.policyDigest === currentDigest;
|
|
52
|
+
const call = {
|
|
53
|
+
receiptId: p.receiptId,
|
|
54
|
+
timestamp: p.timestamp,
|
|
55
|
+
tool: p.tool.name,
|
|
56
|
+
target: targetOf(p.request.args),
|
|
57
|
+
policyIds,
|
|
58
|
+
reasons: known ? policyIds.map((id) => reasons[Number(id.replace(/^policy/, ""))]).filter((r) => typeof r === "string") : [],
|
|
59
|
+
rules: known ? policyIds.map((id) => rules[Number(id.replace(/^policy/, ""))]).filter((r) => typeof r === "string").map((r) => r.replace(/\s+/g, " ").replace(/;$/, "").replace(ANNOTATIONS, "").trim()) : [],
|
|
60
|
+
};
|
|
61
|
+
(p.policy.enforced === false ? report.wouldDeny : report.denied).push(call);
|
|
62
|
+
}
|
|
63
|
+
catch (e) {
|
|
64
|
+
report.unverified.push({ file, reason: e instanceof Error ? e.message : String(e) });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
const byTime = (a, b) => (a.timestamp < b.timestamp ? -1 : a.timestamp > b.timestamp ? 1 : 0);
|
|
68
|
+
report.wouldDeny.sort(byTime);
|
|
69
|
+
report.denied.sort(byTime);
|
|
70
|
+
return report;
|
|
71
|
+
}
|
|
72
|
+
const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
73
|
+
const clip = (s) => (s.length > 160 ? `${s.slice(0, 157)}...` : s);
|
|
74
|
+
export function formatDenyReport(r) {
|
|
75
|
+
const lines = [];
|
|
76
|
+
const list = (calls) => {
|
|
77
|
+
for (const c of calls) {
|
|
78
|
+
lines.push("", ` ${c.tool}: ${clip(c.target)}`);
|
|
79
|
+
if (c.reasons.length)
|
|
80
|
+
lines.push(` reason: ${c.reasons.join("; ")}`);
|
|
81
|
+
lines.push(` rule: ${c.rules.length ? c.rules.join(" | ") : c.policyIds.join(", ") || "(none)"}${c.rules.length ? ` [${c.policyIds.join(", ")}]` : ""}`);
|
|
82
|
+
lines.push(` receipt: ${c.receiptId} (${c.timestamp})`);
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
if (!r.verified && !r.unverified.length) {
|
|
86
|
+
lines.push(`No receipts in ${r.receiptsDir} yet.`, "Start a Claude Code session with the hooks registered, then run this report again.");
|
|
87
|
+
return lines.join("\n");
|
|
88
|
+
}
|
|
89
|
+
lines.push(`would have denied ${plural(r.wouldDeny.length, "call")}${r.wouldDeny.length ? " (the policy recorded each one and blocked nothing)" : ""}`);
|
|
90
|
+
list(r.wouldDeny);
|
|
91
|
+
lines.push("", `Checked ${plural(r.verified + r.unverified.length, "receipt")}: ${r.verified} verified, ${r.unverified.length} did not verify.`);
|
|
92
|
+
if (r.denied.length) {
|
|
93
|
+
lines.push("", `denied ${plural(r.denied.length, "call")} (the policy enforced these, and the call did not run)`);
|
|
94
|
+
list(r.denied);
|
|
95
|
+
}
|
|
96
|
+
if (r.unverified.length) {
|
|
97
|
+
lines.push("", `${plural(r.unverified.length, "receipt")} did not verify. The report does not count them.`);
|
|
98
|
+
for (const u of r.unverified)
|
|
99
|
+
lines.push(` ${u.file}: ${u.reason}`);
|
|
100
|
+
}
|
|
101
|
+
lines.push("");
|
|
102
|
+
lines.push(r.observe
|
|
103
|
+
? `To enforce this policy, remove the "mode": "observe" line from ${r.configFile}. A denied call is then blocked before it runs.`
|
|
104
|
+
: `The config ${r.configFile} has no "mode": "observe" line, so the policy already blocks a denied call.`);
|
|
105
|
+
return lines.join("\n");
|
|
106
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -26,6 +26,8 @@ export { bothCheckpoints, dirCheckpoints, postgresCheckpoints } from "./checkpoi
|
|
|
26
26
|
export { adminRoutes, welcomeSheet } from "./log-admin.ts";
|
|
27
27
|
export { fetchWitnessKeys, Witness } from "./witness.ts";
|
|
28
28
|
export { Anchor, ANCHOR_CHAINS, anchorCalldata, anchorLeaf, checkAnchorRecord, resolveAnchorChain } from "./anchor.ts";
|
|
29
|
+
export { checkCompleteness, formatCompleteness, stripeSource } from "./completeness.ts";
|
|
30
|
+
export type { CompletenessOptions, CompletenessReport, ProviderObject, ProviderSource, StripeObject, StripeSourceOptions } from "./completeness.ts";
|
|
29
31
|
export type { AnchorChain, AnchorCheck, AnchorCheckOptions, AnchorOptions, AnchorRecord, AnchorRun, AnchorTenantOutcome, AnchorTxOutcome } from "./anchor.ts";
|
|
30
32
|
export { evmChain } from "./anchor-evm.ts";
|
|
31
33
|
export type { EvmChainOptions } from "./anchor-evm.ts";
|
|
@@ -57,3 +59,5 @@ export * from "./sidecar.ts";
|
|
|
57
59
|
export * from "./upstream.ts";
|
|
58
60
|
export * from "./retention.ts";
|
|
59
61
|
export * from "./simulate.ts";
|
|
62
|
+
export * from "./claude-init.ts";
|
|
63
|
+
export * from "./deny-report.ts";
|
package/dist/index.js
CHANGED
|
@@ -18,6 +18,7 @@ export { bothCheckpoints, dirCheckpoints, postgresCheckpoints } from "./checkpoi
|
|
|
18
18
|
export { adminRoutes, welcomeSheet } from "./log-admin.js";
|
|
19
19
|
export { fetchWitnessKeys, Witness } from "./witness.js";
|
|
20
20
|
export { Anchor, ANCHOR_CHAINS, anchorCalldata, anchorLeaf, checkAnchorRecord, resolveAnchorChain } from "./anchor.js";
|
|
21
|
+
export { checkCompleteness, formatCompleteness, stripeSource } from "./completeness.js";
|
|
21
22
|
export { evmChain } from "./anchor-evm.js";
|
|
22
23
|
export { checkLog, formatLogCheck } from "./log-check.js";
|
|
23
24
|
export * from "./config.js";
|
|
@@ -37,3 +38,5 @@ export * from "./sidecar.js";
|
|
|
37
38
|
export * from "./upstream.js";
|
|
38
39
|
export * from "./retention.js";
|
|
39
40
|
export * from "./simulate.js";
|
|
41
|
+
export * from "./claude-init.js";
|
|
42
|
+
export * from "./deny-report.js";
|
package/dist/log-admin.js
CHANGED
|
@@ -31,12 +31,12 @@ export function welcomeSheet(o) {
|
|
|
31
31
|
"hashOnly means this log never receives your receipts, only their hashes.",
|
|
32
32
|
"",
|
|
33
33
|
"For whoever verifies your receipts:",
|
|
34
|
-
` npx agent-custody verify receipts/<id>.json --issuer-key <your gateway.pub> --principal-key <your principal.pub> --log-url ${url} --log-id ${o.logId}`,
|
|
35
|
-
` npx agent-custody audit --older receipts/<earlier>.json --newer receipts/<later>.json --log-url ${url} --log-id ${o.logId}`,
|
|
34
|
+
` npx @agent-custody/receipts verify receipts/<id>.json --issuer-key <your gateway.pub> --principal-key <your principal.pub> --log-url ${url} --log-id ${o.logId}`,
|
|
35
|
+
` npx @agent-custody/receipts audit --older receipts/<earlier>.json --newer receipts/<later>.json --log-url ${url} --log-id ${o.logId}`,
|
|
36
36
|
"--log-url fetches this log's published keys and pins them; --log-id makes sure the tree heads are this log's.",
|
|
37
37
|
"",
|
|
38
38
|
"Your log is yours to take, any time, with your token:",
|
|
39
|
-
` npx agent-custody log-export --log-url ${url} --tenant ${o.tenant} --token-env AGENT_CUSTODY_LOG_TOKEN --out custody-export/`,
|
|
39
|
+
` npx @agent-custody/receipts log-export --log-url ${url} --tenant ${o.tenant} --token-env AGENT_CUSTODY_LOG_TOKEN --out custody-export/`,
|
|
40
40
|
"It fetches every leaf hash, the signed head, the keys, the checkpoints, and your usage, checks they add up, and writes",
|
|
41
41
|
"a log copy that verify --log and audit --log read with no server.",
|
|
42
42
|
"",
|
package/dist/log.d.ts
CHANGED
|
@@ -26,10 +26,21 @@ export declare function inclusionProof(leafHashes: Buffer[], leafIndex: number,
|
|
|
26
26
|
/** RFC 9162 section 2.1.3.2 verification. Pure function: needs only the leaf hash, proof and claimed root. */
|
|
27
27
|
export declare function verifyInclusion(leaf: Buffer, proof: InclusionProof, rootHex: string): boolean;
|
|
28
28
|
export declare class MerkleLog {
|
|
29
|
-
private hashes;
|
|
30
|
-
private
|
|
29
|
+
private readonly hashes;
|
|
30
|
+
private tree;
|
|
31
31
|
private readonly file;
|
|
32
|
+
private bytes;
|
|
33
|
+
private inode;
|
|
32
34
|
constructor(file: string);
|
|
35
|
+
/** Reads the leaves that another handle or process appended since the last read. A file that was replaced or cut short is read again from the start. */
|
|
36
|
+
private catchUp;
|
|
37
|
+
/**
|
|
38
|
+
* Runs `fn` while this process holds `<file>.lock`, made with O_EXCL. Each hook of a coding agent is its own
|
|
39
|
+
* process, so appends overlap. A lock older than ten seconds belongs to a process that died: the next writer removes it.
|
|
40
|
+
*/
|
|
41
|
+
private locked;
|
|
42
|
+
/** Under the lock: reads what other writers appended, then writes this line, so each leaf gets the next index. */
|
|
43
|
+
private appendLine;
|
|
33
44
|
get size(): number;
|
|
34
45
|
/** Leaf hashes `from` (inclusive) to `to` (exclusive), as hex: what an export carries and what a copy is rebuilt from. */
|
|
35
46
|
leafHashes(from: number, to?: number): string[];
|