@agent-custody/receipts 0.13.0 → 0.15.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 +46 -28
- package/dist/check.d.ts +10 -0
- package/dist/check.js +179 -3
- package/dist/claude-init.d.ts +46 -0
- package/dist/claude-init.js +208 -0
- package/dist/cli.js +126 -11
- package/dist/config.d.ts +128 -1
- package/dist/config.js +92 -3
- package/dist/console.js +16 -7
- package/dist/deny-report.d.ts +30 -0
- package/dist/deny-report.js +106 -0
- package/dist/door.d.ts +203 -0
- package/dist/door.js +712 -0
- package/dist/export.d.ts +39 -0
- package/dist/export.js +95 -0
- package/dist/gateway.js +53 -21
- package/dist/index.d.ts +8 -0
- package/dist/index.js +7 -0
- package/dist/issue.js +5 -65
- package/dist/lock.d.ts +12 -0
- package/dist/lock.js +124 -0
- package/dist/log-admin.js +3 -3
- package/dist/log.d.ts +20 -3
- package/dist/log.js +117 -24
- package/dist/opa-server.d.ts +34 -0
- package/dist/opa-server.js +93 -0
- package/dist/policy-rego.d.ts +30 -0
- package/dist/policy-rego.js +114 -0
- package/dist/policy.d.ts +6 -0
- package/dist/policy.js +17 -0
- package/dist/pr-summary.d.ts +25 -0
- package/dist/pr-summary.js +87 -0
- package/dist/receipt.d.ts +3 -1
- package/dist/retention.d.ts +1 -1
- package/dist/retention.js +14 -4
- package/dist/sdk/claude.js +18 -2
- package/dist/sdk/index.d.ts +2 -0
- package/dist/sdk/index.js +11 -2
- package/dist/simulate.d.ts +3 -1
- package/dist/simulate.js +15 -7
- package/dist/verify.js +6 -3
- package/dist/witness.js +3 -3
- package/docs/compliance.md +117 -7
- package/docs/configuration.md +3 -3
- package/docs/door-signals.md +66 -0
- package/docs/door.md +168 -0
- package/docs/github-action.md +164 -0
- package/docs/policies.md +124 -1
- package/docs/sdk.md +99 -1
- package/docs/tutorials.md +5 -0
- package/docs/usage.md +3 -3
- package/docs/verification.md +9 -2
- package/package.json +16 -14
- package/templates/claude-code.cedar +373 -0
- package/vectors/audit.json +27 -27
- package/vectors/canonical.json +5 -5
- package/vectors/merkle.json +123 -0
- package/vectors/receipts.json +1258 -1005
package/dist/config.js
CHANGED
|
@@ -149,7 +149,17 @@ export const GatewayConfigSchema = z.object({
|
|
|
149
149
|
/** the one grant a stdio gateway serves; over HTTP each connection presents its own, and this is not needed */
|
|
150
150
|
grantFile: z.string().optional(),
|
|
151
151
|
trustedPrincipalKeys: z.array(z.string()).min(1),
|
|
152
|
-
|
|
152
|
+
/** the policy file: Cedar, or Rego when it ends in .rego (compiled with the opa binary on PATH when it loads) */
|
|
153
|
+
policyFile: z.string().optional(),
|
|
154
|
+
/** an OPA server that decides each call instead of a local file; its package defines allow and deny, as a .rego file does */
|
|
155
|
+
opa: z.object({
|
|
156
|
+
url: z.string().url(),
|
|
157
|
+
/** the package path under /v1/data whose allow and deny rules decide; default agentcustody */
|
|
158
|
+
decision: z.string().min(1).regex(/^[A-Za-z_][A-Za-z0-9_]*([./][A-Za-z_][A-Za-z0-9_]*)*$/, "a package path such as agentcustody or authz/agents").optional(),
|
|
159
|
+
tokenEnv: z.string().min(1).optional(),
|
|
160
|
+
/** milliseconds one decision may take before the call is denied; default 2000 */
|
|
161
|
+
timeoutMs: z.number().int().positive().optional(),
|
|
162
|
+
}).optional(),
|
|
153
163
|
facts: z.array(FactSchema).default([]),
|
|
154
164
|
/**
|
|
155
165
|
* Consequential tools, by name or "*" for all: before forwarding one of these, the gateway commits a signed
|
|
@@ -187,6 +197,7 @@ export const GatewayConfigSchema = z.object({
|
|
|
187
197
|
otel: OtelSchema.optional(),
|
|
188
198
|
splunk: SplunkSchema.optional(),
|
|
189
199
|
}).refine(hasOneLog, oneLog).refine((c) => (c.upstream ? 1 : 0) + (c.upstreams ? 1 : 0) === 1, { message: "exactly one of upstream or upstreams is required" })
|
|
200
|
+
.refine((c) => (c.policyFile ? 1 : 0) + (c.opa ? 1 : 0) === 1, { message: "exactly one of policyFile or opa is required" })
|
|
190
201
|
// a key fetched from the log itself proves nothing about a log that is dishonest from the start, so a remote log that
|
|
191
202
|
// gates consequential calls must have its keys pinned in the config (issue #99)
|
|
192
203
|
.refine((c) => !c.log || (!c.precommit.length && !c.operations) || !!c.log.keys?.length, { message: "precommit with a remote log needs log.keys: the log's public key files, pinned, to check its answer before a consequential call is forwarded" })
|
|
@@ -205,7 +216,7 @@ export function loadConfig(path) {
|
|
|
205
216
|
identity: { keyFile: r(cfg.identity.keyFile) },
|
|
206
217
|
...(cfg.grantFile ? { grantFile: r(cfg.grantFile) } : {}),
|
|
207
218
|
trustedPrincipalKeys: cfg.trustedPrincipalKeys.map(r),
|
|
208
|
-
policyFile: r(cfg.policyFile),
|
|
219
|
+
...(cfg.policyFile ? { policyFile: r(cfg.policyFile) } : {}),
|
|
209
220
|
receiptsDir: r(cfg.receiptsDir),
|
|
210
221
|
...(cfg.logFile ? { logFile: r(cfg.logFile) } : {}),
|
|
211
222
|
...(cfg.log?.keys ? { log: { ...cfg.log, keys: cfg.log.keys.map(r) } } : {}),
|
|
@@ -214,12 +225,90 @@ export function loadConfig(path) {
|
|
|
214
225
|
...(cfg.operations ? { operations: { ...cfg.operations, database: r(cfg.operations.database) } } : {}),
|
|
215
226
|
};
|
|
216
227
|
}
|
|
228
|
+
/** One route of the door: a name the policy sees as the action, and what arrives there. `path` is exact, a prefix when it ends in `/*`, or `*` for anything. The first route that matches wins. */
|
|
229
|
+
const DoorRouteSchema = z.object({
|
|
230
|
+
name: z.string().min(1),
|
|
231
|
+
/** methods this route covers; default every method */
|
|
232
|
+
methods: z.array(z.enum(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"])).min(1).optional(),
|
|
233
|
+
path: z.string().min(1).regex(/^(\*|\/[^*]*(\/\*)?)$/, "a path is exact (/refunds), a prefix (/api/*), or *"),
|
|
234
|
+
});
|
|
235
|
+
/**
|
|
236
|
+
* The door: a reverse proxy in front of a business's own website, API, or forms. Every arrival is classified (verified,
|
|
237
|
+
* claimed, or unknown), decided by the Cedar policy per route, forwarded to the origin or refused, and receipted either
|
|
238
|
+
* way. The origin's credentials, if any, come from the environment through headerEnv, never from the file or the caller.
|
|
239
|
+
*/
|
|
240
|
+
export const DoorConfigSchema = z.object({
|
|
241
|
+
identity: z.object({ keyFile: z.string() }),
|
|
242
|
+
/** where allowed requests go: the site or API the door stands in front of */
|
|
243
|
+
origin: z.object({
|
|
244
|
+
url: z.string().url(),
|
|
245
|
+
headers: z.record(z.string(), z.string()).optional(),
|
|
246
|
+
headerEnv: z.record(z.string(), z.string().min(1)).optional(),
|
|
247
|
+
timeoutMs: z.number().int().positive().default(30_000),
|
|
248
|
+
}),
|
|
249
|
+
routes: z.array(DoorRouteSchema).default([]),
|
|
250
|
+
/** the action name for an arrival no route matches; default "other" */
|
|
251
|
+
unmatchedRoute: z.string().min(1).default("other"),
|
|
252
|
+
/** principal keys whose grants the door accepts as a passport: an arrival carrying one of their grants, in scope for its route, is `verified` */
|
|
253
|
+
trustedPrincipalKeys: z.array(z.string()).default([]),
|
|
254
|
+
policyFile: z.string(),
|
|
255
|
+
/** "enforce" (default) refuses what the policy denies; "observe" forwards everything and records the decision with `enforced: false` */
|
|
256
|
+
mode: z.enum(["enforce", "observe"]).optional(),
|
|
257
|
+
/** behind a reverse proxy you run: the arrival's address is the last in X-Forwarded-For, the one that proxy appended, and the client-address headers are relayed as it sent them */
|
|
258
|
+
trustProxy: z.boolean().optional(),
|
|
259
|
+
/** the largest request body the door relays; a larger one is refused with 413 and receipted. Default 1 MiB */
|
|
260
|
+
maxBodyBytes: z.number().int().positive().default(1024 * 1024),
|
|
261
|
+
/** the largest origin response the door relays; a larger one is recorded by size and the client gets 502. Default 32 MiB */
|
|
262
|
+
maxResponseBytes: z.number().int().positive().default(32 * 1024 * 1024),
|
|
263
|
+
/** arrivals handled at once; past this the next is answered 503 before its body is read, and not receipted. Default 256 */
|
|
264
|
+
maxInFlight: z.number().int().positive().default(256),
|
|
265
|
+
/** routes whose arrivals are committed to the log before they are relayed whatever the method, or ["*"]; every arrival whose method is not GET, HEAD, or OPTIONS is committed regardless */
|
|
266
|
+
precommit: z.array(z.string().min(1)).default([]),
|
|
267
|
+
/** the human branch: a Turnstile or hCaptcha token an arrival sends in `header` is verified with the provider, and the outcome is the arrival's `challenge` signal */
|
|
268
|
+
challenge: z.object({
|
|
269
|
+
provider: z.enum(["turnstile", "hcaptcha"]),
|
|
270
|
+
/** the public site key, given back to a refused arrival so a page can render the widget */
|
|
271
|
+
siteKey: z.string().min(1),
|
|
272
|
+
/** the environment variable holding the provider's secret key */
|
|
273
|
+
secretEnv: z.string().min(1),
|
|
274
|
+
header: z.string().min(1).default("x-agent-custody-challenge"),
|
|
275
|
+
timeoutMs: z.number().int().positive().default(5_000),
|
|
276
|
+
/** the hostnames of the pages that render the widget; a token the provider issued on any other host fails */
|
|
277
|
+
hostnames: z.array(z.string().min(1).transform((h) => h.toLowerCase())).min(1),
|
|
278
|
+
/** the widget's action (Turnstile only); when set, a token issued for another action fails */
|
|
279
|
+
action: z.string().min(1).optional(),
|
|
280
|
+
/** checks with the provider at once; an arrival past this is `unavailable`, never relayed on a pass it did not get. Default 64 */
|
|
281
|
+
maxInFlight: z.number().int().positive().default(64),
|
|
282
|
+
}).refine((c) => !c.action || c.provider === "turnstile", { message: "challenge.action is a Turnstile field; hCaptcha does not report an action" }).optional(),
|
|
283
|
+
receiptsDir: z.string(),
|
|
284
|
+
logFile: z.string().optional(),
|
|
285
|
+
log: LogSchema.optional(),
|
|
286
|
+
otel: OtelSchema.optional(),
|
|
287
|
+
splunk: SplunkSchema.optional(),
|
|
288
|
+
capture: CaptureSchema.optional(),
|
|
289
|
+
captureKeyEnv: z.string().min(1).optional(),
|
|
290
|
+
}).refine(hasOneLog, oneLog).refine((c) => new Set(c.routes.map((r) => r.name)).size === c.routes.length, { message: "route names must be unique" })
|
|
291
|
+
.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" });
|
|
292
|
+
export function loadDoorConfig(path) {
|
|
293
|
+
const cfg = DoorConfigSchema.parse(JSON.parse(readFileSync(path, "utf8")));
|
|
294
|
+
const base = dirname(resolve(path));
|
|
295
|
+
const r = (p) => resolve(base, p);
|
|
296
|
+
return {
|
|
297
|
+
...cfg,
|
|
298
|
+
identity: { keyFile: r(cfg.identity.keyFile) },
|
|
299
|
+
trustedPrincipalKeys: cfg.trustedPrincipalKeys.map(r),
|
|
300
|
+
policyFile: r(cfg.policyFile),
|
|
301
|
+
receiptsDir: r(cfg.receiptsDir),
|
|
302
|
+
...(cfg.logFile ? { logFile: r(cfg.logFile) } : {}),
|
|
303
|
+
...(cfg.log?.keys ? { log: { ...cfg.log, keys: cfg.log.keys.map(r) } } : {}),
|
|
304
|
+
};
|
|
305
|
+
}
|
|
217
306
|
export const SdkConfigSchema = z.object({
|
|
218
307
|
/** identity the receipts will name; nothing checks it, so it is recorded as claimed */
|
|
219
308
|
agentId: z.string().min(1),
|
|
220
309
|
principalId: z.string().min(1).optional(),
|
|
221
310
|
identity: z.object({ keyFile: z.string() }),
|
|
222
|
-
/** optional Cedar
|
|
311
|
+
/** optional policy, Cedar or Rego (.rego); when present, wrapped tools and PreToolUse hooks can deny */
|
|
223
312
|
policyFile: z.string().optional(),
|
|
224
313
|
/** "observe" records the policy's decision with `enforced: false` and never blocks; "enforce" (default) blocks a deny */
|
|
225
314
|
mode: z.enum(["enforce", "observe"]).optional(),
|
package/dist/console.js
CHANGED
|
@@ -15,6 +15,7 @@ import { decodeDelegation, delegationValidAt, grantDigest, verifyDelegation } fr
|
|
|
15
15
|
import { writeRevokedGrants } from "./gateway.js";
|
|
16
16
|
import { CONSOLE_CSP, CONSOLE_HTML } from "./console-page.js";
|
|
17
17
|
import { hasPermitRule, policyDigest } from "./policy.js";
|
|
18
|
+
import { isRegoFile } from "./policy-rego.js";
|
|
18
19
|
import { simulatePolicy } from "./simulate.js";
|
|
19
20
|
import { verifyBundle } from "./verify.js";
|
|
20
21
|
const MAX_BODY = 1_000_000;
|
|
@@ -26,6 +27,14 @@ class HttpError extends Error {
|
|
|
26
27
|
this.status = status;
|
|
27
28
|
}
|
|
28
29
|
}
|
|
30
|
+
/** The console edits Cedar files. A Rego file is edited where it lives, and an OPA server's policy in its bundles. */
|
|
31
|
+
function cedarPolicyFile(cfg) {
|
|
32
|
+
if (!cfg.policyFile)
|
|
33
|
+
throw new HttpError(409, `this gateway asks the OPA server at ${cfg.opa?.url} for its decisions; edit the policy in the server's bundles`);
|
|
34
|
+
if (isRegoFile(cfg.policyFile))
|
|
35
|
+
throw new HttpError(409, `${basename(cfg.policyFile)} is a Rego policy; the console edits Cedar policies only, so edit it in place and the gateway compiles it on its next call`);
|
|
36
|
+
return cfg.policyFile;
|
|
37
|
+
}
|
|
29
38
|
const sha = (s) => createHash("sha256").update(s).digest();
|
|
30
39
|
function atomicWrite(path, text) {
|
|
31
40
|
const tmp = `${path}.${process.pid}.tmp`;
|
|
@@ -280,9 +289,9 @@ export async function serveConsole(options) {
|
|
|
280
289
|
}
|
|
281
290
|
},
|
|
282
291
|
"GET /api/policy": async () => {
|
|
283
|
-
const
|
|
284
|
-
const text = readFileSync(
|
|
285
|
-
return { path:
|
|
292
|
+
const policyFile = cedarPolicyFile(loadConfig(options.configFile));
|
|
293
|
+
const text = readFileSync(policyFile, "utf8");
|
|
294
|
+
return { path: policyFile, text, digest: policyDigest(text), history: readdirSync(join(state, "policy-history")).sort().reverse().slice(0, 20) };
|
|
286
295
|
},
|
|
287
296
|
"POST /api/policy/validate": async (req) => {
|
|
288
297
|
const text = String(object(await readBody(req)).text ?? "");
|
|
@@ -346,18 +355,18 @@ export async function serveConsole(options) {
|
|
|
346
355
|
// from reading the digest to the rename, nothing else may save: two tabs that loaded the same digest would otherwise both pass the
|
|
347
356
|
// check, the later rename would win, and the history of the lost edit would not even be the version it replaced
|
|
348
357
|
return withPolicyLock(() => {
|
|
349
|
-
const
|
|
350
|
-
const current = readFileSync(
|
|
358
|
+
const policyFile = cedarPolicyFile(loadConfig(options.configFile));
|
|
359
|
+
const current = readFileSync(policyFile, "utf8");
|
|
351
360
|
if (body.expectDigest !== policyDigest(current))
|
|
352
361
|
throw new HttpError(409, "the policy file changed since you loaded it; reload and try again");
|
|
353
362
|
writeFileSync(join(state, "policy-history", `${new Date().toISOString().replace(/[:.]/g, "-")}-${policyDigest(current).slice(0, 12)}.cedar`), current);
|
|
354
363
|
try {
|
|
355
|
-
atomicWrite(
|
|
364
|
+
atomicWrite(policyFile, text);
|
|
356
365
|
}
|
|
357
366
|
catch (e) {
|
|
358
367
|
throw new HttpError(500, `the policy file cannot be written (${e instanceof Error ? e.message : String(e)}); mount the config directory read-write for the console`);
|
|
359
368
|
}
|
|
360
|
-
audit("policy.save", { file:
|
|
369
|
+
audit("policy.save", { file: policyFile, from: policyDigest(current), to: policyDigest(text), bytes: text.length, confirmed: issues }, by);
|
|
361
370
|
return { digest: policyDigest(text), note: "saved; a running gateway applies it from its next call" };
|
|
362
371
|
});
|
|
363
372
|
},
|
|
@@ -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 ? clip(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/door.d.ts
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { type IncomingMessage, type ServerResponse } from "node:http";
|
|
2
|
+
import type { DoorConfig, DoorRouteConfig } from "./config.ts";
|
|
3
|
+
import { type Envelope, type PublicKeyRef } from "./crypto.ts";
|
|
4
|
+
import { type Delegation } from "./delegation.ts";
|
|
5
|
+
import { type FlushResult } from "./issue.ts";
|
|
6
|
+
import { type LogSink } from "./log-sink.ts";
|
|
7
|
+
import { type ReceiptExporter } from "./otel.ts";
|
|
8
|
+
export declare const DOOR_VERSION = "0.1.0";
|
|
9
|
+
/** on every answer the door gives: the receipt that records the decision */
|
|
10
|
+
export declare const RECEIPT_HEADER = "x-agent-custody-receipt";
|
|
11
|
+
/** on every answer: `verified`, `claimed`, or `unknown`, what the door made of the arrival */
|
|
12
|
+
export declare const CLASS_HEADER = "x-agent-custody-class";
|
|
13
|
+
/** the fact the door records for every arrival, and the policy reads as `context.facts.arrival` */
|
|
14
|
+
export declare const ARRIVAL_FACT = "arrival";
|
|
15
|
+
/** the header an agent may use to name itself without a grant; recorded as claimed, never checked */
|
|
16
|
+
export declare const AGENT_HEADER = "x-agent-custody-agent";
|
|
17
|
+
export type ArrivalClass = "verified" | "claimed" | "unknown";
|
|
18
|
+
/** What the door observed about one arrival. Every field is the door's own observation; none is the caller's claim about itself except `declared`, which says so. */
|
|
19
|
+
export interface Arrival {
|
|
20
|
+
class: ArrivalClass;
|
|
21
|
+
/** the agent named in a verified grant, else the name the caller declared, else "unknown" */
|
|
22
|
+
subject: string;
|
|
23
|
+
/** what became of the grant header: a trusted grant in scope for this route, one out of scope, one that did not verify, or none */
|
|
24
|
+
grant: "verified" | "out-of-scope" | "invalid" | "absent";
|
|
25
|
+
grantError?: string;
|
|
26
|
+
/** an RFC 9421 `Signature-Input` header was present; the door does not check it yet */
|
|
27
|
+
signature: boolean;
|
|
28
|
+
/** the agent name from the `x-agent-custody-agent` header, when sent; a claim */
|
|
29
|
+
declared?: string;
|
|
30
|
+
remote: string;
|
|
31
|
+
method: string;
|
|
32
|
+
path: string;
|
|
33
|
+
route: string;
|
|
34
|
+
/** how often this source has arrived lately, counted by this door process; set by the door, absent from `classifyArrival` alone */
|
|
35
|
+
rate?: ArrivalRate;
|
|
36
|
+
/** what became of the challenge token, when the door is configured to challenge; absent otherwise, and from `classifyArrival` alone */
|
|
37
|
+
challenge?: ArrivalChallenge;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The outcome of a human challenge. `passed`: the provider confirmed the token, so the provider judged a person present
|
|
41
|
+
* at the time it was solved. `failed`: the provider refused it, with its error codes. `unavailable`: the provider did
|
|
42
|
+
* not answer in time. `absent`: no token was sent. A passed challenge does not change `class`: it says nothing about who
|
|
43
|
+
* the arrival is, only that a provider's test was passed in front of it.
|
|
44
|
+
*/
|
|
45
|
+
export interface ArrivalChallenge {
|
|
46
|
+
provider: "turnstile" | "hcaptcha";
|
|
47
|
+
outcome: "passed" | "failed" | "unavailable" | "absent";
|
|
48
|
+
error?: string;
|
|
49
|
+
}
|
|
50
|
+
/** a provider token is about 2 KB; a longer value is refused as failed without calling the provider */
|
|
51
|
+
export declare const MAX_CHALLENGE_TOKEN = 4096;
|
|
52
|
+
export interface ChallengeCheck {
|
|
53
|
+
provider: "turnstile" | "hcaptcha";
|
|
54
|
+
secret: string;
|
|
55
|
+
token: string;
|
|
56
|
+
/** the client's address, sent as `remoteip` only when the door knows it is the client's and not a proxy's */
|
|
57
|
+
remoteIp?: string;
|
|
58
|
+
/** the hostnames of the pages that render the widget, lowercase */
|
|
59
|
+
hostnames: string[];
|
|
60
|
+
/** the widget's action, when one is required (Turnstile) */
|
|
61
|
+
action?: string;
|
|
62
|
+
/** the public site key; sent to hCaptcha, whose secret belongs to the account, so a token from another of its site keys is refused */
|
|
63
|
+
siteKey?: string;
|
|
64
|
+
timeoutMs: number;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Asks the provider whether the token is good. The token and the secret go to the provider only; neither is recorded,
|
|
68
|
+
* and a redirect is never followed, since it would resend both to the Location's host. `success` is not enough: the
|
|
69
|
+
* token must have been issued on one of the site's own hostnames, and for the configured action, or a token solved on
|
|
70
|
+
* another site with this site key, or for another widget, would pass.
|
|
71
|
+
*/
|
|
72
|
+
export declare function verifyChallengeToken(check: ChallengeCheck, f: typeof fetch): Promise<ArrivalChallenge>;
|
|
73
|
+
/**
|
|
74
|
+
* Arrivals from one source in the last 10 seconds (`burst`) and 60 seconds (`minute`), this one included, whatever the
|
|
75
|
+
* policy decided about them. The source is the agent a verified grant names, else the arrival's address. One process's
|
|
76
|
+
* memory: the count starts at one when the door starts, and two doors do not share it.
|
|
77
|
+
*/
|
|
78
|
+
export interface ArrivalRate {
|
|
79
|
+
by: "agent" | "remote";
|
|
80
|
+
burst: number;
|
|
81
|
+
minute: number;
|
|
82
|
+
}
|
|
83
|
+
export declare const RATE_BURST_MS = 10000;
|
|
84
|
+
export declare const RATE_MINUTE_MS = 60000;
|
|
85
|
+
export interface RateTrackerLimits {
|
|
86
|
+
/** sources kept at once; past this the least recently seen is forgotten. Default 10000 */
|
|
87
|
+
maxSources?: number;
|
|
88
|
+
/** a source key longer than this is kept as its sha256. Default 256 */
|
|
89
|
+
maxKeyLength?: number;
|
|
90
|
+
}
|
|
91
|
+
export interface RateTracker {
|
|
92
|
+
hit(source: string): {
|
|
93
|
+
burst: number;
|
|
94
|
+
minute: number;
|
|
95
|
+
};
|
|
96
|
+
/** sources kept now */
|
|
97
|
+
size(): number;
|
|
98
|
+
/** stops the sweep */
|
|
99
|
+
close(): void;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Counts arrivals per source over the two windows. Each source keeps its arrival times in order with two heads that only
|
|
103
|
+
* move forward, so one arrival costs the same however many came before it in the window; the array is compacted once
|
|
104
|
+
* half of it is behind the minute head. The source key comes from the arrival, and with `trustProxy` the client may
|
|
105
|
+
* choose it, so the map bounds itself: at most `maxSources` keys, none longer than `maxKeyLength`, and a source with no
|
|
106
|
+
* arrival in the last minute is dropped every minute whether or not traffic goes on. A source forgotten early counts
|
|
107
|
+
* again from 1, which only lowers what a pace rule sees for a client that floods the map. The clock is monotonic
|
|
108
|
+
* (`performance.now`), so a step of the wall clock (an NTP correction, a VM resume) neither keeps old arrivals inside
|
|
109
|
+
* the windows nor drops new ones; an injected clock that goes back is held at the last time seen. `now` is for tests.
|
|
110
|
+
*/
|
|
111
|
+
export declare function createRateTracker(now?: () => number, limits?: RateTrackerLimits): RateTracker;
|
|
112
|
+
export interface Classified {
|
|
113
|
+
arrival: Arrival;
|
|
114
|
+
/** set when the arrival is verified: the grant, as presented */
|
|
115
|
+
delegation?: {
|
|
116
|
+
envelope: Envelope;
|
|
117
|
+
grant: Delegation;
|
|
118
|
+
principalKeyid: string;
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* The record of the call keeps what arrived; the policy reads a copy Cedar accepts. Cedar has no `null` and no
|
|
123
|
+
* non-integer number, and refuses the whole request on either, so a body with `"coupon": null` or `"price": 9.99` would
|
|
124
|
+
* be denied whatever the policy says. In the copy a `null` is dropped and a number that is not a safe integer becomes its
|
|
125
|
+
* string; a rule that compares `price` as a number then errors, and the call is denied by that rule rather than by Cedar.
|
|
126
|
+
*/
|
|
127
|
+
export declare function cedarArgs(value: unknown): unknown;
|
|
128
|
+
/**
|
|
129
|
+
* What a receipt records of an arrival when the config gives its route no capture rule: the method, the path, the
|
|
130
|
+
* recorded headers, and the body's size in clear; the query and the body withheld, each a salted commitment. A query can
|
|
131
|
+
* carry an API key and a form body a password. Set a rule for the route (or `"*"`) to record more in clear.
|
|
132
|
+
*/
|
|
133
|
+
export declare const DOOR_DEFAULT_CAPTURE: {
|
|
134
|
+
args: {
|
|
135
|
+
mode: "digest";
|
|
136
|
+
clear: string[];
|
|
137
|
+
};
|
|
138
|
+
result: {
|
|
139
|
+
mode: "clear";
|
|
140
|
+
};
|
|
141
|
+
facts: {
|
|
142
|
+
mode: "clear";
|
|
143
|
+
};
|
|
144
|
+
};
|
|
145
|
+
/**
|
|
146
|
+
* The path as the origin will read it: each segment percent-decoded once, so that `/%61dmin` falls under `/admin/*`, and
|
|
147
|
+
* empty segments merged, so that `//admin/users` and `/admin//users` fall under it too (nginx, Apache, and many
|
|
148
|
+
* frameworks merge them, and the origin would serve the admin page to an arrival the door matched as something else).
|
|
149
|
+
* A trailing slash is kept. Refused when a segment does not decode, or decodes to a slash, a backslash, or a dot
|
|
150
|
+
* segment: the origin would then read a path the door did not match. `relay` is the merged, decoded path encoded once
|
|
151
|
+
* more, the form the origin is sent, so the door and the origin read one path.
|
|
152
|
+
*/
|
|
153
|
+
export declare function normalizePath(pathname: string): {
|
|
154
|
+
path: string;
|
|
155
|
+
relay: string;
|
|
156
|
+
} | {
|
|
157
|
+
problem: string;
|
|
158
|
+
};
|
|
159
|
+
/** The route an arrival falls under: the first configured route whose methods and decoded path match, else the unmatched name. A trailing slash matches as no trailing slash. */
|
|
160
|
+
export declare function matchRoute(routes: DoorRouteConfig[], unmatched: string, method: string, pathname: string): string;
|
|
161
|
+
/**
|
|
162
|
+
* The arrival's address: the socket's, or with trustProxy the last address in `X-Forwarded-For`, the one the proxy in
|
|
163
|
+
* front of the door appended. Everything before it was sent by the client, which may write what it likes there.
|
|
164
|
+
*/
|
|
165
|
+
export declare function remoteOf(req: IncomingMessage, trustProxy: boolean): string;
|
|
166
|
+
/**
|
|
167
|
+
* What the arrival presented, checked where it can be. A grant signed by a trusted principal, in its window, naming this
|
|
168
|
+
* route among its scopes, makes the arrival `verified` and its principal attested. A grant that is out of scope, expired,
|
|
169
|
+
* or signed by a stranger leaves the arrival `claimed`: it asserted an identity the door could not accept for this route.
|
|
170
|
+
* An `x-agent-custody-agent` header or an HTTP signature header alone is `claimed`. Nothing at all is `unknown`.
|
|
171
|
+
*/
|
|
172
|
+
export declare function classifyArrival(req: IncomingMessage, trusted: PublicKeyRef[], route: string, trustProxy: boolean, at: string): Classified;
|
|
173
|
+
export interface DoorOptions {
|
|
174
|
+
/** the log to append to, in place of the one the config names; for embedding and tests */
|
|
175
|
+
log?: LogSink;
|
|
176
|
+
exporter?: ReceiptExporter;
|
|
177
|
+
fetch?: typeof fetch;
|
|
178
|
+
/** appends the outbox at start and every 30 seconds; only a serving door sets it */
|
|
179
|
+
autoFlush?: boolean;
|
|
180
|
+
}
|
|
181
|
+
export interface DoorHost {
|
|
182
|
+
keyid: string;
|
|
183
|
+
policyDigest(): string;
|
|
184
|
+
/** decides, forwards or refuses, and receipts one arrival; answers the response */
|
|
185
|
+
handle(req: IncomingMessage, res: ServerResponse): Promise<void>;
|
|
186
|
+
flushOutbox(): Promise<FlushResult>;
|
|
187
|
+
pendingReceipts(): number;
|
|
188
|
+
close(): Promise<void>;
|
|
189
|
+
}
|
|
190
|
+
/** The query as own properties: a parameter named `constructor` or `__proto__` is a parameter, never an inherited member or the prototype. */
|
|
191
|
+
export declare function queryOf(url: URL): Record<string, string | string[]>;
|
|
192
|
+
export declare function createDoorHost(cfg: DoorConfig, options?: DoorOptions): Promise<DoorHost>;
|
|
193
|
+
export interface DoorServerOptions {
|
|
194
|
+
port: number;
|
|
195
|
+
host?: string;
|
|
196
|
+
log?: (message: string) => void;
|
|
197
|
+
}
|
|
198
|
+
export interface RunningDoor {
|
|
199
|
+
url: string;
|
|
200
|
+
close(): Promise<void>;
|
|
201
|
+
}
|
|
202
|
+
/** Serves a door host over plain HTTP. Bind to loopback or put TLS in front. `GET /.well-known/agent-custody-door` answers the key id and the policy digest. */
|
|
203
|
+
export declare function serveDoor(host: DoorHost, opts: DoorServerOptions): Promise<RunningDoor>;
|