@agent-custody/receipts 0.8.0 → 0.10.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 +19 -7
- package/dist/check.d.ts +19 -0
- package/dist/check.js +288 -0
- package/dist/cli.js +119 -11
- package/dist/config.d.ts +1 -0
- package/dist/config.js +3 -0
- package/dist/console-page.d.ts +4 -0
- package/dist/console-page.js +342 -0
- package/dist/console.d.ts +20 -0
- package/dist/console.js +522 -0
- package/dist/gateway-http.js +1 -1
- package/dist/gateway.d.ts +18 -0
- package/dist/gateway.js +196 -48
- package/dist/index.d.ts +6 -2
- package/dist/index.js +4 -1
- package/dist/issue.d.ts +31 -1
- package/dist/issue.js +261 -10
- package/dist/log-store.d.ts +3 -2
- package/dist/log-store.js +2 -0
- package/dist/policy.d.ts +4 -0
- package/dist/policy.js +15 -0
- package/dist/portal.d.ts +78 -4
- package/dist/portal.js +517 -26
- package/dist/simulate.d.ts +7 -1
- package/dist/simulate.js +27 -2
- package/dist/sso.d.ts +47 -0
- package/dist/sso.js +161 -0
- package/dist/verify.js +8 -4
- package/docs/codex-recovery.md +132 -0
- package/docs/configuration.md +226 -0
- package/docs/console.md +78 -0
- package/docs/policies.md +4 -1
- package/docs/threat-model.md +13 -0
- package/docs/tutorials.md +4 -0
- package/docs/usage.md +38 -4
- package/package.json +8 -2
- package/vectors/audit.json +27 -27
- package/vectors/receipts.json +1135 -929
package/dist/simulate.d.ts
CHANGED
|
@@ -27,6 +27,8 @@ export interface SimulationReport {
|
|
|
27
27
|
total: number;
|
|
28
28
|
evaluated: number;
|
|
29
29
|
unchanged: number;
|
|
30
|
+
/** Reconciliation receipts. Each is a provider read with no policy decision, so a replay counts it here and not in `evaluated` or `skipped`. */
|
|
31
|
+
reconciliations: number;
|
|
30
32
|
complete: boolean;
|
|
31
33
|
changes: SimulationChange[];
|
|
32
34
|
skipped: SimulationSkip[];
|
|
@@ -50,7 +52,11 @@ export declare function verifyOrphanAuthorization(bundle: AuthorizationBundle, i
|
|
|
50
52
|
/**
|
|
51
53
|
* Compare a proposed Cedar policy with recorded policy decisions, using each receipt's original arguments, fact
|
|
52
54
|
* 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.
|
|
55
|
+
* Receipts are not signature-verified here; verify their bundles separately when their authenticity matters. A
|
|
56
|
+
* reconciliation receipt is trusted as a provider read only after `verifyBundle` accepts it: the library checks no more
|
|
57
|
+
* than its shape and its link to an original receipt id.
|
|
58
|
+
* A reconciliation whose original receipt is not among the supplied receipts or `unreplayable` is reported as skipped,
|
|
59
|
+
* because the call it settles cannot be replayed.
|
|
54
60
|
* Missing inputs and non-Cedar gate failures are reported as skipped, never guessed or fetched again.
|
|
55
61
|
* The receipts are read once, one at a time, so a caller can verify and parse a large history lazily.
|
|
56
62
|
*/
|
package/dist/simulate.js
CHANGED
|
@@ -57,7 +57,11 @@ export function verifyOrphanAuthorization(bundle, issuerKeys, logKeys) {
|
|
|
57
57
|
/**
|
|
58
58
|
* Compare a proposed Cedar policy with recorded policy decisions, using each receipt's original arguments, fact
|
|
59
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.
|
|
60
|
+
* Receipts are not signature-verified here; verify their bundles separately when their authenticity matters. A
|
|
61
|
+
* reconciliation receipt is trusted as a provider read only after `verifyBundle` accepts it: the library checks no more
|
|
62
|
+
* than its shape and its link to an original receipt id.
|
|
63
|
+
* A reconciliation whose original receipt is not among the supplied receipts or `unreplayable` is reported as skipped,
|
|
64
|
+
* because the call it settles cannot be replayed.
|
|
61
65
|
* Missing inputs and non-Cedar gate failures are reported as skipped, never guessed or fetched again.
|
|
62
66
|
* The receipts are read once, one at a time, so a caller can verify and parse a large history lazily.
|
|
63
67
|
*/
|
|
@@ -74,22 +78,37 @@ export function simulatePolicy(policyText, receipts, options = {}) {
|
|
|
74
78
|
total: unreplayable.length,
|
|
75
79
|
evaluated: 0,
|
|
76
80
|
unchanged: 0,
|
|
81
|
+
reconciliations: 0,
|
|
77
82
|
complete: true,
|
|
78
83
|
changes: [],
|
|
79
84
|
skipped: [...unreplayable],
|
|
80
85
|
groups: [],
|
|
81
86
|
};
|
|
82
87
|
const digests = new Set();
|
|
88
|
+
const seen = new Set(unreplayable.map((u) => u.receiptId));
|
|
89
|
+
const reconciled = [];
|
|
83
90
|
for (const original of receipts) {
|
|
84
91
|
report.total++;
|
|
85
92
|
const receiptId = typeof original?.receiptId === "string" ? original.receiptId : "(unknown receipt)";
|
|
86
93
|
const tool = typeof original?.tool?.name === "string" ? original.tool.name : "(unknown tool)";
|
|
87
94
|
const skip = (reason) => { report.skipped.push({ receiptId, tool, reason }); };
|
|
95
|
+
if (original?.reconciliation === undefined)
|
|
96
|
+
seen.add(receiptId);
|
|
88
97
|
const broken = structuralProblem(original);
|
|
89
98
|
if (broken) {
|
|
90
99
|
skip(`malformed receipt: ${broken}`);
|
|
91
100
|
continue;
|
|
92
101
|
}
|
|
102
|
+
if (original.reconciliation !== undefined) {
|
|
103
|
+
const link = original.operation?.originalReceiptId;
|
|
104
|
+
if (original.issuer.kind !== "gateway" || typeof link !== "string" || link === receiptId) {
|
|
105
|
+
skip("malformed receipt: a reconciliation needs a gateway issuer and an operation that names another receipt");
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
report.reconciliations++;
|
|
109
|
+
reconciled.push({ receiptId: link, tool, reason: `only the reconciliation ${receiptId} survives; the original receipt is missing, so the call cannot be replayed` });
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
93
112
|
if (original.policy === null) {
|
|
94
113
|
skip("no recorded policy decision (record-only receipt)");
|
|
95
114
|
continue;
|
|
@@ -166,6 +185,12 @@ export function simulatePolicy(policyText, receipts, options = {}) {
|
|
|
166
185
|
else
|
|
167
186
|
report.changes.push({ receiptId, tool, previous, proposed });
|
|
168
187
|
}
|
|
188
|
+
for (const lost of reconciled) {
|
|
189
|
+
if (seen.has(lost.receiptId))
|
|
190
|
+
continue;
|
|
191
|
+
report.reconciliations--;
|
|
192
|
+
report.skipped.push(lost);
|
|
193
|
+
}
|
|
169
194
|
report.previousPolicyDigests = [...digests].sort(order);
|
|
170
195
|
report.complete = report.skipped.length === 0;
|
|
171
196
|
const groups = new Map();
|
|
@@ -188,7 +213,7 @@ export function formatSimulation(report) {
|
|
|
188
213
|
`Timestamp: ${report.timestamp}`,
|
|
189
214
|
`Proposed policy: ${report.policyDigest}`,
|
|
190
215
|
`Previous policies: ${report.previousPolicyDigests.join(", ") || "none"}`,
|
|
191
|
-
`Receipts: ${report.total}; evaluated: ${report.evaluated}; unchanged: ${report.unchanged}; changed: ${report.changes.length}; skipped: ${report.skipped.length}`,
|
|
216
|
+
`Receipts: ${report.total}; evaluated: ${report.evaluated}; unchanged: ${report.unchanged}; reconciliations: ${report.reconciliations}; changed: ${report.changes.length}; skipped: ${report.skipped.length}`,
|
|
192
217
|
];
|
|
193
218
|
for (const group of report.groups) {
|
|
194
219
|
lines.push("", `${group.tool}: ${group.reason}`);
|
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.js
CHANGED
|
@@ -118,13 +118,15 @@ export function structuralProblem(p) {
|
|
|
118
118
|
return "receiptId or timestamp is not a string";
|
|
119
119
|
if (!isObject(p.issuer) || !isObject(p.principal) || !isObject(p.agent) || !isObject(p.session) || !isObject(p.model))
|
|
120
120
|
return "issuer, principal, agent, session, or model is not an object";
|
|
121
|
+
if (p.principal.provenance === "attested" && typeof p.principal.keyid !== "string")
|
|
122
|
+
return "an attested principal has no keyid";
|
|
121
123
|
if (!isObject(p.tool) || typeof p.tool.name !== "string")
|
|
122
124
|
return "tool.name is not a string";
|
|
123
125
|
if (!isObject(p.request) || typeof p.request.argsDigest !== "string" || !isObject(p.request.args))
|
|
124
126
|
return "request.args or request.argsDigest is not what it should be";
|
|
125
127
|
if (!isObject(p.execution) || typeof p.execution.status !== "string" || !["executed", "failed", "denied", "error", "withheld"].includes(p.execution.status))
|
|
126
128
|
return "execution.status is not a status";
|
|
127
|
-
if (p.policy !== null && (!isObject(p.policy) || (p.policy.decision !== "allow" && p.policy.decision !== "deny") || !Array.isArray(p.policy.reasons)))
|
|
129
|
+
if (p.policy !== null && (!isObject(p.policy) || (p.policy.decision !== "allow" && p.policy.decision !== "deny") || !Array.isArray(p.policy.reasons) || typeof p.policy.policyDigest !== "string"))
|
|
128
130
|
return "policy is neither null nor a decision";
|
|
129
131
|
if (!isObject(p.facts) || Object.values(p.facts).some((f) => !isObject(f) || typeof f.tool !== "string"))
|
|
130
132
|
return "facts is not a map of facts";
|
|
@@ -132,7 +134,7 @@ export function structuralProblem(p) {
|
|
|
132
134
|
return "consumed is not an object";
|
|
133
135
|
if (p.delegation !== undefined && (!isObject(p.delegation) || !isObject(p.delegation.envelope)))
|
|
134
136
|
return "delegation is not a signed envelope";
|
|
135
|
-
if (p.authorization !== undefined && (!isObject(p.authorization) || !isObject(p.authorization.envelope)))
|
|
137
|
+
if (p.authorization !== undefined && (!isObject(p.authorization) || !isObject(p.authorization.envelope) || !isObject(p.authorization.treeHead) || !isObject(p.authorization.inclusion)))
|
|
136
138
|
return "authorization is not a bundle";
|
|
137
139
|
if (p.approval !== undefined) {
|
|
138
140
|
const a = p.approval;
|
|
@@ -559,7 +561,9 @@ export function formatReport(r) {
|
|
|
559
561
|
row("args", p.request.provenance, p.request.args);
|
|
560
562
|
for (const [k, f] of Object.entries(p.facts))
|
|
561
563
|
row(`fact.${k}`, f.provenance, f.value);
|
|
562
|
-
if (p.
|
|
564
|
+
if (p.reconciliation)
|
|
565
|
+
row("policy", "-", "(none evaluated: a provider read, not a call)");
|
|
566
|
+
else if (p.policy)
|
|
563
567
|
row("policy", p.policy.provenance, `${p.policy.decision}${p.policy.enforced === false ? " (observe mode, not enforced)" : ""} [${p.policy.reasons.join(",")}] policy ${short(p.policy.policyDigest)}`);
|
|
564
568
|
else
|
|
565
569
|
row("policy", "-", "(none evaluated)");
|
|
@@ -581,6 +585,6 @@ export function formatReport(r) {
|
|
|
581
585
|
// a refusal says why, as the receipt records it; under a capture rule the reason is a commitment, and the report says so rather than printing it
|
|
582
586
|
const reason = "reason" in p.execution ? p.execution.reason : undefined;
|
|
583
587
|
const why = reason === undefined ? "" : typeof reason === "string" ? `: ${reason}` : ": (reason withheld under the capture rule)";
|
|
584
|
-
row("execution", attestedAs, `${p.execution.status}${why}${note}`);
|
|
588
|
+
row("execution", attestedAs, `${p.reconciliation ? "provider read, " : ""}${p.execution.status}${why}${note}`);
|
|
585
589
|
return lines.join("\n");
|
|
586
590
|
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
# A real Codex agent, a wrong plan, and recovery
|
|
2
|
+
|
|
3
|
+
The model handles a support request using MCP tools behind the custody gateway. The CRM import deliberately says `enterprise` when the account is actually on `free`. Codex decides whether to record benefits and issue a simulated service credit. An operator then introduces the correction, traces potentially affected actions and beliefs, reviews a recovery plan, and explicitly approves compensation.
|
|
4
|
+
|
|
5
|
+
The support calls come from `codex exec`, not a handwritten tool sequence. The correction and recovery are operator commands. Billing is a persistent local stand-in, not Stripe; a reversal compensates a simulated credit and preserves the original record. No real money moves.
|
|
6
|
+
|
|
7
|
+
See the [recorded live run](../../state/examples/codex-recovery/SAMPLE-RUN.md) for an actual result, including the final verification of 13 receipts.
|
|
8
|
+
|
|
9
|
+
## Before running
|
|
10
|
+
|
|
11
|
+
Use Node 22 with native TypeScript support (or later), Bun, and a Codex CLI that supports `exec`, MCP, `--ignore-user-config`, and `--ephemeral`. Tested with Node 24 and codex-cli 0.163.0. Codex needs working authentication and model access; use `codex login` if needed. An existing ChatGPT login works; an API key is not required when that login is available. Live runs consume the account's normal model usage and require network access to the model.
|
|
12
|
+
|
|
13
|
+
From the repository root:
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
bun install --frozen-lockfile
|
|
17
|
+
bun run build
|
|
18
|
+
codex login status
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Run the support task
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
cd packages/state
|
|
25
|
+
node examples/codex-recovery/run.ts run
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Optionally select a model your Codex account supports:
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
node examples/codex-recovery/run.ts run --model <model>
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
The runner creates a fresh `examples-out/codex-recovery-*/case/` directory and prints its path. It imports the wrong plan, launches Codex with a task and business policy, waits up to three minutes, then simulates the operator learning about the CRM bug. The operator revokes the support grant, retracts the wrong plan, and writes `plan = free`. The runner verifies the receipts and prints a proposed recovery plan. It stops before applying that plan.
|
|
35
|
+
|
|
36
|
+
The expected story is:
|
|
37
|
+
|
|
38
|
+
```text
|
|
39
|
+
CRM import: enterprise
|
|
40
|
+
→ Codex reads the account memory
|
|
41
|
+
→ Codex may record discount 20 / priority support and issue a 2500-pence credit
|
|
42
|
+
→ Operator corrects the plan to free and retires the support grant
|
|
43
|
+
→ Review possible dependencies and proposed recovery
|
|
44
|
+
→ Explicit approval: correct stale benefits and reverse the simulated credit
|
|
45
|
+
→ Check current state and all signed receipts
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
The agent can decline, perform fewer actions, or encounter an error. Read `agent-answer.txt` and `codex-events.jsonl` to see what actually happened. The runner does not retry until the desired mistake appears or replace a failed model run with scripted calls. The plan reports `agentCalls` and `exposed`; zero gateway activity is explicitly labelled as not demonstrating an agent workflow. A credit without an observed dependency on the plan requires manual review rather than automatic recovery.
|
|
49
|
+
|
|
50
|
+
## Review and recover
|
|
51
|
+
|
|
52
|
+
Read `recovery-plan.json`. It names the exact beliefs to retract, corrected values to write, and simulated credits to reverse. The plan digest binds approval to those actions and the observed state. Changes after review invalidate it.
|
|
53
|
+
|
|
54
|
+
Copy the `recover` command printed by the runner, or use:
|
|
55
|
+
|
|
56
|
+
```sh
|
|
57
|
+
node examples/codex-recovery/run.ts recover \
|
|
58
|
+
--dir /absolute/path/to/case \
|
|
59
|
+
--approve <printed-plan-digest>
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
For the typical enterprise-to-free run, expect:
|
|
63
|
+
|
|
64
|
+
- Current plan: `free`; discount: `0`; support tier: `standard`.
|
|
65
|
+
- Original simulated credit: preserved, with status `reversed` and its reversal receipt ID.
|
|
66
|
+
- Original beliefs: retained in history, with receipted retractions.
|
|
67
|
+
- `receiptsVerified` includes the original calls, correction, and recovery.
|
|
68
|
+
- The command ends with `OK: recovery complete; evidence verified.`
|
|
69
|
+
|
|
70
|
+
Repeat verification without issuing tool calls:
|
|
71
|
+
|
|
72
|
+
```sh
|
|
73
|
+
node examples/codex-recovery/run.ts verify --dir /absolute/path/to/case
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
To refresh a plan after intervening activity or a partially completed recovery:
|
|
77
|
+
|
|
78
|
+
```sh
|
|
79
|
+
node examples/codex-recovery/run.ts inspect --dir /absolute/path/to/case
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
If Codex fails, its artifacts remain. Check `codex-stderr.log` and `codex-events.jsonl`. To continue an operator investigation of that failed run, use `correct --dir /absolute/path/to/case`, then inspect its actual evidence. A new `run` always creates a separate case. Demo grants last 24 hours; after expiration, inspect/verify still work, but recovery needs newly issued operator authority.
|
|
83
|
+
|
|
84
|
+
## Demo commands and flags
|
|
85
|
+
|
|
86
|
+
These commands belong to the example runner, not the published `agent-custody` or `agent-custody-memory` CLI. Run them from `packages/state` as `node examples/codex-recovery/run.ts <command>`.
|
|
87
|
+
|
|
88
|
+
| Command | Flags | Behavior |
|
|
89
|
+
| --- | --- | --- |
|
|
90
|
+
| `run` | optional `--model <model>` | Creates a fresh case, runs Codex, introduces the operator correction, and saves a recovery plan; stops before recovery |
|
|
91
|
+
| `correct` | required `--dir <case>` | Revokes support authority, retracts the wrong plan, records the corrected plan, and saves a recovery plan; useful after a failed agent run |
|
|
92
|
+
| `inspect` | required `--dir <case>` | Verifies existing evidence and saves a fresh plan and approval digest without issuing tool calls |
|
|
93
|
+
| `recover` | required `--dir <case>` and `--approve <digest>` | Rejects a changed plan or state; applies the reviewed recovery, saves the verification report, and prints `OK` on success |
|
|
94
|
+
| `verify` | required `--dir <case>` | Checks evidence and current recovery state without issuing tool calls; prints the report and exits nonzero if recovery is incomplete |
|
|
95
|
+
| `help` | none | Lists the example runner's commands |
|
|
96
|
+
|
|
97
|
+
Here `--approve` is an explicit confirmation by the local operator running the command. The digest covers the reviewed plan and snapshot; it is not a separate cryptographically signed human-approval artifact. The gateway's [payload-bound human approvals](approvals.md) are a different feature. Recovery calls still use the operator's signed delegation grant and receive signed gateway receipts; the recovery-plan digest is included in retraction and credit-reversal reasons.
|
|
98
|
+
|
|
99
|
+
## What to inspect
|
|
100
|
+
|
|
101
|
+
| Artifact | What it tells you |
|
|
102
|
+
| --- | --- |
|
|
103
|
+
| `prompt.txt`, `codex-command.json` | The actual task and Codex invocation |
|
|
104
|
+
| `codex-events.jsonl`, `agent-answer.txt`, `agent-run.json` | Model events, final answer, and whether the live process completed |
|
|
105
|
+
| `ledger.jsonl` | Original beliefs, corrections, and retractions |
|
|
106
|
+
| `receipts/`, `log.jsonl`, `keys/*.pub` | Signed calls, precommitted billing authorizations, and verification material |
|
|
107
|
+
| `billing.json` | Simulated credits and compensation, linked to receipt IDs |
|
|
108
|
+
| `recovery-plan.json`, `approval.json`, `verification.json` | Reviewed actions, explicit approval, and final verification result |
|
|
109
|
+
|
|
110
|
+
The verifier checks receipt signatures, delegation, inclusion in the local log, signed upstream results, and consistency of the demo stores with those receipts. All demo keys and the log live on the same machine: this is a workflow demonstration, not evidence against a malicious operator controlling that machine.
|
|
111
|
+
|
|
112
|
+
## Boundaries
|
|
113
|
+
|
|
114
|
+
- Blast radius records prior exposure in a gateway session. It does not prove that the model reasoned from a fact or that the fact caused an action.
|
|
115
|
+
- A verified receipt authenticates recorded evidence, not the truth of the customer's plan or correctness of a business decision.
|
|
116
|
+
- The gateway caps credits and confines writes to this account's benefits. Entitlement is intentionally left to the agent in this incident; a production policy could independently check it and prevent the credit.
|
|
117
|
+
- Codex runs with read-only shell sandbox settings, shell tools disabled, web search disabled, and user-configured apps/plugins disabled. Its MCP server is required and configured for this invocation only. Calls to this local demo server are preapproved in Codex; the gateway still enforces the grant and Cedar policy. The gateway owns the signing keys and the billing service; the model is not given them as tool data. These settings demonstrate controlled tool access, not adversarial OS isolation of an untrusted process.
|
|
118
|
+
- Recovery is deliberately limited to the two benefit predicates and simulated service credits in this case. Real refunds, customer communications, downstream caches, and model context need their own recovery decisions.
|
|
119
|
+
- Run operator commands sequentially for one case. The plan freshness check is not a transactional lock against concurrent operators.
|
|
120
|
+
|
|
121
|
+
## Offline regression coverage
|
|
122
|
+
|
|
123
|
+
The regular suite never calls Codex or the network. It drives the same MCP servers and recovery functions with scripted calls, clearly labelled as scripted:
|
|
124
|
+
|
|
125
|
+
```sh
|
|
126
|
+
node examples/10-support-recovery.ts
|
|
127
|
+
bun run test test/codex-recovery.test.ts test/examples.test.ts
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
The checks cover approval, stale plans, revoked support authority, duplicate-credit prevention, receipt tampering, store/evidence consistency, missing observed dependencies (a credit or a benefit that no memory read supports), the refresh after a partial recovery, and runs without agent activity.
|
|
131
|
+
|
|
132
|
+
Codex integration references: [non-interactive mode](https://learn.chatgpt.com/docs/non-interactive-mode), [MCP configuration](https://learn.chatgpt.com/docs/extend/mcp?surface=cli).
|