passcontrol 1.3.0 → 1.5.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/LICENSE +3 -1
- package/README.md +10 -1
- package/bin/passcontrol.mjs +455 -10
- package/cli/budget-format.mjs +113 -0
- package/cli/claude-code.mjs +80 -16
- package/cli/config.mjs +36 -2
- package/cli/declared-session.mjs +61 -0
- package/cli/delegation.d.mts +60 -0
- package/cli/delegation.mjs +192 -0
- package/cli/journal.mjs +84 -0
- package/cli/mcp/README.md +4 -1
- package/cli/mcp/gateway.mjs +13 -0
- package/cli/mcp/server.mjs +27 -0
- package/cli/menu.mjs +7 -0
- package/cli/profiles.mjs +92 -0
- package/cli/protocols.d.mts +2 -0
- package/cli/protocols.mjs +17 -1
- package/cli/sidecar.mjs +194 -20
- package/cli/statusline.mjs +213 -0
- package/cli/verify.mjs +215 -5
- package/cli/visa-client.mjs +5 -1
- package/cli/watch-feed.mjs +275 -0
- package/cli/watch.mjs +601 -0
- package/package.json +1 -1
- package/sdk/index.d.ts +2 -1
- package/sdk/index.js +3 -0
- package/sdk/passcontrol.d.ts +46 -0
- package/sdk/passcontrol.js +47 -2
- package/sdk/verify.d.ts +115 -0
- package/sdk/verify.js +219 -1
package/sdk/passcontrol.d.ts
CHANGED
|
@@ -16,6 +16,35 @@ export interface PassControlOptions {
|
|
|
16
16
|
/** Override the transport (tests / custom fetch). Defaults to global fetch. */
|
|
17
17
|
fetch?: typeof fetch;
|
|
18
18
|
}
|
|
19
|
+
/** A worker's side of a signed delegation (Bet D). */
|
|
20
|
+
export interface PassControlDelegationOptions {
|
|
21
|
+
gateway: string;
|
|
22
|
+
/** The chain the worker was handed, root first. */
|
|
23
|
+
chain: string[];
|
|
24
|
+
/** The worker's own private key. Its public half is the chain's last `sub`. */
|
|
25
|
+
workerPrivateKey: string;
|
|
26
|
+
refreshSkewSeconds?: number;
|
|
27
|
+
fetch?: typeof fetch;
|
|
28
|
+
}
|
|
29
|
+
export interface DelegateOptions {
|
|
30
|
+
/** The worker's public key. The worker keeps its private key; the parent never holds it. */
|
|
31
|
+
workerPublicKey: string;
|
|
32
|
+
scope: {
|
|
33
|
+
provider: ProviderId | string;
|
|
34
|
+
models: string[];
|
|
35
|
+
}[];
|
|
36
|
+
/** The most this delegation and everything under it may spend, in micro-cents. */
|
|
37
|
+
capMicrocents: number;
|
|
38
|
+
/** At most 24 hours, and never past the signer's own delegation. */
|
|
39
|
+
ttlSeconds: number;
|
|
40
|
+
/** false: the worker may not delegate on. */
|
|
41
|
+
allowFurtherDelegation?: boolean;
|
|
42
|
+
/**
|
|
43
|
+
* The gateway's issuer (receipts' `iss`). Defaults to the gateway origin, which is
|
|
44
|
+
* the issuer unless the gateway is reached through another address.
|
|
45
|
+
*/
|
|
46
|
+
audience?: string;
|
|
47
|
+
}
|
|
19
48
|
export declare class PassControl {
|
|
20
49
|
private readonly gateway;
|
|
21
50
|
private readonly gatewayOrigin;
|
|
@@ -23,6 +52,8 @@ export declare class PassControl {
|
|
|
23
52
|
private readonly secret;
|
|
24
53
|
private readonly skewMs;
|
|
25
54
|
private readonly transport;
|
|
55
|
+
/** Set only on a worker's client: its chain, sent to /api/auth/delegated. */
|
|
56
|
+
private delegationChain;
|
|
26
57
|
private cached;
|
|
27
58
|
private inflight;
|
|
28
59
|
constructor(opts: PassControlOptions);
|
|
@@ -33,6 +64,21 @@ export declare class PassControl {
|
|
|
33
64
|
getVisa(): Promise<string>;
|
|
34
65
|
/** Drop the cached visa so the next getVisa() re-mints. */
|
|
35
66
|
invalidate(): void;
|
|
67
|
+
/**
|
|
68
|
+
* A client for a WORKER holding a delegation (Bet D). Its calls are refused past the
|
|
69
|
+
* delegation's scope, cap or expiry, and the agent's kill switch and suspension stop
|
|
70
|
+
* it too. Its receipts name the worker, never the agent's passport.
|
|
71
|
+
*/
|
|
72
|
+
static fromDelegation(opts: PassControlDelegationOptions): PassControl;
|
|
73
|
+
/**
|
|
74
|
+
* Hand a worker a narrower slice of this client's authority: signed here, offline,
|
|
75
|
+
* by this client's key (the agent's passport, or a worker's own key one level down).
|
|
76
|
+
* Returns the chain to give the worker, root first.
|
|
77
|
+
*/
|
|
78
|
+
delegate(opts: DelegateOptions): {
|
|
79
|
+
token: string;
|
|
80
|
+
chain: string[];
|
|
81
|
+
};
|
|
36
82
|
/** A `fetch` that injects the visa and refreshes it transparently. Pass this as
|
|
37
83
|
* the `fetch` option to the OpenAI/Anthropic SDK. Retries once on a 401 (the
|
|
38
84
|
* visa was rejected/expired) after forcing a re-mint. */
|
package/sdk/passcontrol.js
CHANGED
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
// an end-user browser bundle even though the underlying Web APIs are portable.
|
|
16
16
|
import { ed25519 } from "@noble/curves/ed25519";
|
|
17
17
|
import { requireGatewayOrigin } from "./gateway.js";
|
|
18
|
+
import { createDelegationLink } from "../cli/delegation.mjs";
|
|
18
19
|
// --- base64url over raw bytes (no Buffer dependency; works everywhere) -------
|
|
19
20
|
function bytesToB64url(bytes) {
|
|
20
21
|
let bin = "";
|
|
@@ -73,6 +74,8 @@ export class PassControl {
|
|
|
73
74
|
secret;
|
|
74
75
|
skewMs;
|
|
75
76
|
transport;
|
|
77
|
+
/** Set only on a worker's client: its chain, sent to /api/auth/delegated. */
|
|
78
|
+
delegationChain = null;
|
|
76
79
|
cached = null;
|
|
77
80
|
inflight = null;
|
|
78
81
|
constructor(opts) {
|
|
@@ -103,10 +106,12 @@ export class PassControl {
|
|
|
103
106
|
const payloadBytes = new TextEncoder().encode(JSON.stringify(payloadObj));
|
|
104
107
|
const payload = bytesToB64url(payloadBytes);
|
|
105
108
|
const signature = bytesToB64url(ed25519.sign(payloadBytes, this.secret));
|
|
106
|
-
|
|
109
|
+
// A worker exchanges its chain, signing the challenge with its OWN key: the
|
|
110
|
+
// delegation token alone does nothing at the gateway.
|
|
111
|
+
const res = await this.transport(`${this.gateway}/api/auth/${this.delegationChain ? "delegated" : "challenge"}`, {
|
|
107
112
|
method: "POST",
|
|
108
113
|
headers: { "content-type": "application/json" },
|
|
109
|
-
body: JSON.stringify({ payload, signature }),
|
|
114
|
+
body: JSON.stringify(this.delegationChain ? { payload, signature, chain: this.delegationChain } : { payload, signature }),
|
|
110
115
|
});
|
|
111
116
|
if (!res.ok) {
|
|
112
117
|
const detail = await res.text().catch(() => "");
|
|
@@ -139,6 +144,46 @@ export class PassControl {
|
|
|
139
144
|
invalidate() {
|
|
140
145
|
this.cached = null;
|
|
141
146
|
}
|
|
147
|
+
/**
|
|
148
|
+
* A client for a WORKER holding a delegation (Bet D). Its calls are refused past the
|
|
149
|
+
* delegation's scope, cap or expiry, and the agent's kill switch and suspension stop
|
|
150
|
+
* it too. Its receipts name the worker, never the agent's passport.
|
|
151
|
+
*/
|
|
152
|
+
static fromDelegation(opts) {
|
|
153
|
+
if (!Array.isArray(opts.chain) || opts.chain.length < 1) {
|
|
154
|
+
throw new Error("PassControl: fromDelegation needs the chain the worker was handed.");
|
|
155
|
+
}
|
|
156
|
+
const priv = b64urlToBytes(opts.workerPrivateKey);
|
|
157
|
+
if (priv.length !== 32)
|
|
158
|
+
throw new Error("PassControl: workerPrivateKey must encode 32 bytes.");
|
|
159
|
+
const client = new PassControl({
|
|
160
|
+
gateway: opts.gateway,
|
|
161
|
+
passportId: bytesToB64url(ed25519.getPublicKey(priv)),
|
|
162
|
+
passportSecret: opts.workerPrivateKey,
|
|
163
|
+
...(opts.refreshSkewSeconds !== undefined ? { refreshSkewSeconds: opts.refreshSkewSeconds } : {}),
|
|
164
|
+
...(opts.fetch ? { fetch: opts.fetch } : {}),
|
|
165
|
+
});
|
|
166
|
+
client.delegationChain = [...opts.chain];
|
|
167
|
+
return client;
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Hand a worker a narrower slice of this client's authority: signed here, offline,
|
|
171
|
+
* by this client's key (the agent's passport, or a worker's own key one level down).
|
|
172
|
+
* Returns the chain to give the worker, root first.
|
|
173
|
+
*/
|
|
174
|
+
delegate(opts) {
|
|
175
|
+
const token = createDelegationLink({
|
|
176
|
+
signerPrivateKey: bytesToB64url(this.secret),
|
|
177
|
+
audience: opts.audience ?? this.gatewayOrigin,
|
|
178
|
+
workerPublicKey: opts.workerPublicKey,
|
|
179
|
+
scope: opts.scope,
|
|
180
|
+
capMicrocents: opts.capMicrocents,
|
|
181
|
+
ttlSeconds: opts.ttlSeconds,
|
|
182
|
+
...(opts.allowFurtherDelegation !== undefined ? { allowFurtherDelegation: opts.allowFurtherDelegation } : {}),
|
|
183
|
+
...(this.delegationChain ? { parentChain: this.delegationChain } : {}),
|
|
184
|
+
});
|
|
185
|
+
return { token, chain: [...(this.delegationChain ?? []), token] };
|
|
186
|
+
}
|
|
142
187
|
/** A `fetch` that injects the visa and refreshes it transparently. Pass this as
|
|
143
188
|
* the `fetch` option to the OpenAI/Anthropic SDK. Retries once on a 401 (the
|
|
144
189
|
* visa was rejected/expired) after forcing a re-mint. */
|
package/sdk/verify.d.ts
CHANGED
|
@@ -36,6 +36,13 @@ export interface ReceiptClaims {
|
|
|
36
36
|
use: string;
|
|
37
37
|
} | {
|
|
38
38
|
kind: "passport_proof_per_request";
|
|
39
|
+
} | {
|
|
40
|
+
kind: "delegated";
|
|
41
|
+
act: string;
|
|
42
|
+
dlg: string;
|
|
43
|
+
dep: number;
|
|
44
|
+
ch: string;
|
|
45
|
+
prf?: true;
|
|
39
46
|
};
|
|
40
47
|
prov: string;
|
|
41
48
|
mdl: string | null;
|
|
@@ -257,6 +264,114 @@ export declare function verifyStatement(jws: string, options: VerifyOptions): Pr
|
|
|
257
264
|
* and the statement's `root`.
|
|
258
265
|
*/
|
|
259
266
|
export declare function verifyInclusion(receiptJws: string, proof: readonly InclusionProofStep[], root: Uint8Array | string): boolean;
|
|
267
|
+
export declare const SESSION_TYP = "passcontrol-session+jws";
|
|
268
|
+
/** The newest session-seal version this verifier understands. See SESSION_PROTOCOL. */
|
|
269
|
+
export declare const SESSION_SUPPORTED_VER: number;
|
|
270
|
+
/** One node of a session's agent tree. `agt: null` is the main agent; `par: null` is "spawned by the main agent". */
|
|
271
|
+
export interface SessionTreeNode {
|
|
272
|
+
agt: string | null;
|
|
273
|
+
par: string | null;
|
|
274
|
+
n: number;
|
|
275
|
+
cost: number;
|
|
276
|
+
/** Calls the gateway refused (`res.status` starting `blocked_`). */
|
|
277
|
+
refused: number;
|
|
278
|
+
}
|
|
279
|
+
export interface SessionClaims {
|
|
280
|
+
iss: string;
|
|
281
|
+
/** The agent id. */
|
|
282
|
+
sub: string;
|
|
283
|
+
jti: string;
|
|
284
|
+
iat: number;
|
|
285
|
+
fmt: string;
|
|
286
|
+
v: number;
|
|
287
|
+
/** The session id and who declared it (`claude-code`, `codex`, `sidecar`). Declared by the client, never authenticated. */
|
|
288
|
+
ses: {
|
|
289
|
+
id: string;
|
|
290
|
+
src: string;
|
|
291
|
+
};
|
|
292
|
+
/** Half-open window `[from, to)`, epoch seconds. */
|
|
293
|
+
per: {
|
|
294
|
+
from: number;
|
|
295
|
+
to: number;
|
|
296
|
+
};
|
|
297
|
+
n: number;
|
|
298
|
+
nr: number;
|
|
299
|
+
cost: number;
|
|
300
|
+
unp: number;
|
|
301
|
+
unk: number;
|
|
302
|
+
root: string | null;
|
|
303
|
+
tree: SessionTreeNode[];
|
|
304
|
+
mdl: {
|
|
305
|
+
mdl: string | null;
|
|
306
|
+
n: number;
|
|
307
|
+
cost: number;
|
|
308
|
+
}[];
|
|
309
|
+
}
|
|
310
|
+
/** Why one receipt in a bundle was not accepted as part of the session. */
|
|
311
|
+
export type SessionReceiptRejection = VerifyFailure | "duplicate" | "other_session" | "other_agent" | "outside_period";
|
|
312
|
+
export interface SessionVerifyResult {
|
|
313
|
+
/** All of: signature, bundle and receipts pass, and the journal check did not fail. */
|
|
314
|
+
ok: boolean;
|
|
315
|
+
/** Set when the seal itself failed, or when the bundle or journal could not be read. */
|
|
316
|
+
reason?: VerifyFailure | "malformed_bundle" | "malformed_journal";
|
|
317
|
+
claims?: SessionClaims;
|
|
318
|
+
/** null = not run. `journal` is null when no journal was given: the seal is then no stronger than a statement. */
|
|
319
|
+
checks: {
|
|
320
|
+
signature: boolean;
|
|
321
|
+
bundle: boolean | null;
|
|
322
|
+
receipts: boolean | null;
|
|
323
|
+
journal: boolean | null;
|
|
324
|
+
};
|
|
325
|
+
/** Seal claims that do not match what the bundle adds up to: root, n, cost, unp, tree, mdl. */
|
|
326
|
+
mismatched: string[];
|
|
327
|
+
rejected: {
|
|
328
|
+
index: number;
|
|
329
|
+
id: string | null;
|
|
330
|
+
reason: SessionReceiptRejection;
|
|
331
|
+
}[];
|
|
332
|
+
/** Journaled receipt ids the bundle does not contain. MISSING, not proof of tampering: see verifySession. */
|
|
333
|
+
missing: string[];
|
|
334
|
+
/** Bundle receipts the journal never saw. Reported, never a failure. */
|
|
335
|
+
unjournaled: {
|
|
336
|
+
id: string;
|
|
337
|
+
why: "failover_predecessor" | "not_in_journal";
|
|
338
|
+
}[];
|
|
339
|
+
/**
|
|
340
|
+
* Journal lines that name ANOTHER session (`ses`), left out of check 4: one sidecar
|
|
341
|
+
* run serves many sessions. A line that names none is checked as before.
|
|
342
|
+
*/
|
|
343
|
+
otherSessions: number;
|
|
344
|
+
}
|
|
345
|
+
export interface SessionBundle {
|
|
346
|
+
seal: string;
|
|
347
|
+
/** Every receipt the seal covers, as compact JWS, in seal order. */
|
|
348
|
+
bundle: string[];
|
|
349
|
+
/** The user's sidecar journal: receipt ids, or `{ id, ... }` entries. */
|
|
350
|
+
journal?: unknown;
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Verify a session seal against its bundle and, when given, the user's journal.
|
|
354
|
+
*
|
|
355
|
+
* Four checks: (1) the seal's signature; (2) its root and totals recompute from
|
|
356
|
+
* the bundle; (3) every receipt in the bundle verifies and belongs to this
|
|
357
|
+
* session, agent and window; (4) every receipt id the user's sidecar journaled is
|
|
358
|
+
* in the bundle, directly or through a receipt's `prev` link.
|
|
359
|
+
*
|
|
360
|
+
* WHAT CHECK 4 ADDS. A statement can only show the issuer committed to a set. The
|
|
361
|
+
* journal is the user's own independent list of their calls, so a call left out
|
|
362
|
+
* of the seal is caught. Without a journal a seal is no stronger than a statement,
|
|
363
|
+
* and `checks.journal` is null to say so.
|
|
364
|
+
*
|
|
365
|
+
* WHAT `missing` MEANS. A journaled id that is absent is MISSING, never proof of
|
|
366
|
+
* tampering: the gateway's log write is best-effort, so a lost row and an
|
|
367
|
+
* omission look the same from here. Receipts in the bundle but not the journal
|
|
368
|
+
* (failover predecessors, direct calls, another machine) are reported in
|
|
369
|
+
* `unjournaled` and never fail the session.
|
|
370
|
+
*
|
|
371
|
+
* The session id inside each receipt is DECLARED by the client. Check 3 shows the
|
|
372
|
+
* issuer grouped what the client declared; it does not show who made the call.
|
|
373
|
+
*/
|
|
374
|
+
export declare function verifySession(input: SessionBundle, options: VerifyOptions): Promise<SessionVerifyResult>;
|
|
260
375
|
export interface VerifyAgentTokenOptions extends VerifyOptions {
|
|
261
376
|
/** The audience YOU are. Required: a token minted for someone else is not for you. */
|
|
262
377
|
audience: string;
|
package/sdk/verify.js
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
// edge runtimes, and the browser.
|
|
10
10
|
import { ed25519 } from "@noble/curves/ed25519";
|
|
11
11
|
import { sha256 } from "@noble/hashes/sha256";
|
|
12
|
-
import { RECEIPT_PROTOCOL, STATEMENT_PROTOCOL } from "../cli/protocols.mjs";
|
|
12
|
+
import { RECEIPT_PROTOCOL, SESSION_PROTOCOL, STATEMENT_PROTOCOL } from "../cli/protocols.mjs";
|
|
13
13
|
export const RECEIPT_TYP = "passcontrol-receipt+jwt";
|
|
14
14
|
export const AGENT_TOKEN_TYP = "passcontrol-agent+jwt";
|
|
15
15
|
/** The newest artifact version this verifier understands. */
|
|
@@ -264,6 +264,224 @@ export function verifyInclusion(receiptJws, proof, root) {
|
|
|
264
264
|
return false;
|
|
265
265
|
}
|
|
266
266
|
}
|
|
267
|
+
// ── Session seals ────────────────────────────────────────────────────────────
|
|
268
|
+
export const SESSION_TYP = "passcontrol-session+jws";
|
|
269
|
+
/** The newest session-seal version this verifier understands. See SESSION_PROTOCOL. */
|
|
270
|
+
export const SESSION_SUPPORTED_VER = SESSION_PROTOCOL.maximum;
|
|
271
|
+
// The same hashing as verifyInclusion, restated for the same reason: this file
|
|
272
|
+
// is vendored alone. Leaves in bundle order; an odd node is promoted unchanged.
|
|
273
|
+
function sessionHash(prefix, ...parts) {
|
|
274
|
+
const total = parts.reduce((sum, p) => sum + p.length, 1);
|
|
275
|
+
const buf = new Uint8Array(total);
|
|
276
|
+
buf[0] = prefix;
|
|
277
|
+
let at = 1;
|
|
278
|
+
for (const p of parts) {
|
|
279
|
+
buf.set(p, at);
|
|
280
|
+
at += p.length;
|
|
281
|
+
}
|
|
282
|
+
return sha256(buf);
|
|
283
|
+
}
|
|
284
|
+
/** Platform-neutral (no Buffer): this file also runs in the browser. */
|
|
285
|
+
function bytesToB64url(bytes) {
|
|
286
|
+
let bin = "";
|
|
287
|
+
for (const b of bytes)
|
|
288
|
+
bin += String.fromCharCode(b);
|
|
289
|
+
return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
290
|
+
}
|
|
291
|
+
function sessionRoot(bundle) {
|
|
292
|
+
if (bundle.length === 0)
|
|
293
|
+
return null;
|
|
294
|
+
let level = bundle.map((jws) => sessionHash(0x00, utf8(jws)));
|
|
295
|
+
while (level.length > 1) {
|
|
296
|
+
const next = [];
|
|
297
|
+
for (let i = 0; i < level.length; i += 2) {
|
|
298
|
+
const right = level[i + 1];
|
|
299
|
+
next.push(right ? sessionHash(0x01, level[i], right) : level[i]);
|
|
300
|
+
}
|
|
301
|
+
level = next;
|
|
302
|
+
}
|
|
303
|
+
return bytesToB64url(level[0]);
|
|
304
|
+
}
|
|
305
|
+
function decodePayload(jws) {
|
|
306
|
+
try {
|
|
307
|
+
const claims = JSON.parse(new TextDecoder().decode(b64urlToBytes(jws.split(".")[1] ?? "")));
|
|
308
|
+
return claims && typeof claims === "object" && !Array.isArray(claims) ? claims : null;
|
|
309
|
+
}
|
|
310
|
+
catch {
|
|
311
|
+
return null;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : 0);
|
|
315
|
+
const orNull = (v) => (typeof v === "string" ? v : null);
|
|
316
|
+
const TREE_KEYS = [{ name: "agt", text: true }, { name: "par", text: true }, { name: "n" }, { name: "cost" }, { name: "refused" }];
|
|
317
|
+
const MODEL_KEYS = [{ name: "mdl", text: true }, { name: "n" }, { name: "cost" }];
|
|
318
|
+
/** Tree and model lists, compared as sets: one canonical string each. */
|
|
319
|
+
function canonical(entries, keys) {
|
|
320
|
+
if (!Array.isArray(entries))
|
|
321
|
+
return null;
|
|
322
|
+
const rows = entries.map((e) => keys.map((k) => (k.text ? orNull(e?.[k.name]) : num(e?.[k.name]))));
|
|
323
|
+
const cmp = (a, b) => (JSON.stringify(a) < JSON.stringify(b) ? -1 : JSON.stringify(a) > JSON.stringify(b) ? 1 : 0);
|
|
324
|
+
return JSON.stringify(rows.sort(cmp));
|
|
325
|
+
}
|
|
326
|
+
function bundleTotals(decoded) {
|
|
327
|
+
const tree = new Map();
|
|
328
|
+
const models = new Map();
|
|
329
|
+
let cost = 0;
|
|
330
|
+
let unp = 0;
|
|
331
|
+
for (const c of decoded) {
|
|
332
|
+
if (!c)
|
|
333
|
+
continue;
|
|
334
|
+
const ctx = c.ctx && typeof c.ctx === "object" ? c.ctx : {};
|
|
335
|
+
const agt = orNull(ctx.agt);
|
|
336
|
+
const par = orNull(ctx.par);
|
|
337
|
+
const refused = typeof c.res?.status === "string" && c.res.status.startsWith("blocked_") ? 1 : 0;
|
|
338
|
+
const key = JSON.stringify([agt, par]);
|
|
339
|
+
const node = tree.get(key) ?? { agt, par, n: 0, cost: 0, refused: 0 };
|
|
340
|
+
node.n += 1;
|
|
341
|
+
node.cost += num(c.cost);
|
|
342
|
+
node.refused += refused;
|
|
343
|
+
tree.set(key, node);
|
|
344
|
+
const mdl = orNull(c.mdl);
|
|
345
|
+
const m = models.get(JSON.stringify(mdl)) ?? { mdl, n: 0, cost: 0 };
|
|
346
|
+
m.n += 1;
|
|
347
|
+
m.cost += num(c.cost);
|
|
348
|
+
models.set(JSON.stringify(mdl), m);
|
|
349
|
+
cost += num(c.cost);
|
|
350
|
+
if (c.unp === true)
|
|
351
|
+
unp += 1;
|
|
352
|
+
}
|
|
353
|
+
return { cost, unp, tree: [...tree.values()], mdl: [...models.values()] };
|
|
354
|
+
}
|
|
355
|
+
/** This session's journaled ids (and lines naming no session), and how many named another. */
|
|
356
|
+
function journalIds(journal, session) {
|
|
357
|
+
if (!Array.isArray(journal))
|
|
358
|
+
return null;
|
|
359
|
+
const ids = [];
|
|
360
|
+
let other = 0;
|
|
361
|
+
for (const entry of journal) {
|
|
362
|
+
const id = typeof entry === "string" ? entry : entry && typeof entry === "object" ? entry.id : undefined;
|
|
363
|
+
if (typeof id !== "string" || id.length === 0)
|
|
364
|
+
return null;
|
|
365
|
+
const ses = entry && typeof entry === "object" ? entry.ses : undefined;
|
|
366
|
+
if (typeof ses === "string" && ses !== session) {
|
|
367
|
+
other += 1;
|
|
368
|
+
continue;
|
|
369
|
+
}
|
|
370
|
+
ids.push(id);
|
|
371
|
+
}
|
|
372
|
+
return { ids, other };
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* Verify a session seal against its bundle and, when given, the user's journal.
|
|
376
|
+
*
|
|
377
|
+
* Four checks: (1) the seal's signature; (2) its root and totals recompute from
|
|
378
|
+
* the bundle; (3) every receipt in the bundle verifies and belongs to this
|
|
379
|
+
* session, agent and window; (4) every receipt id the user's sidecar journaled is
|
|
380
|
+
* in the bundle, directly or through a receipt's `prev` link.
|
|
381
|
+
*
|
|
382
|
+
* WHAT CHECK 4 ADDS. A statement can only show the issuer committed to a set. The
|
|
383
|
+
* journal is the user's own independent list of their calls, so a call left out
|
|
384
|
+
* of the seal is caught. Without a journal a seal is no stronger than a statement,
|
|
385
|
+
* and `checks.journal` is null to say so.
|
|
386
|
+
*
|
|
387
|
+
* WHAT `missing` MEANS. A journaled id that is absent is MISSING, never proof of
|
|
388
|
+
* tampering: the gateway's log write is best-effort, so a lost row and an
|
|
389
|
+
* omission look the same from here. Receipts in the bundle but not the journal
|
|
390
|
+
* (failover predecessors, direct calls, another machine) are reported in
|
|
391
|
+
* `unjournaled` and never fail the session.
|
|
392
|
+
*
|
|
393
|
+
* The session id inside each receipt is DECLARED by the client. Check 3 shows the
|
|
394
|
+
* issuer grouped what the client declared; it does not show who made the call.
|
|
395
|
+
*/
|
|
396
|
+
export async function verifySession(input, options) {
|
|
397
|
+
const jwksCache = options.jwksCache ?? new Map();
|
|
398
|
+
const result = {
|
|
399
|
+
ok: false,
|
|
400
|
+
checks: { signature: false, bundle: null, receipts: null, journal: null },
|
|
401
|
+
mismatched: [],
|
|
402
|
+
rejected: [],
|
|
403
|
+
missing: [],
|
|
404
|
+
unjournaled: [],
|
|
405
|
+
otherSessions: 0,
|
|
406
|
+
};
|
|
407
|
+
const sealed = await verifySigned(String(input?.seal ?? ""), SESSION_TYP, { ...options, jwksCache }, {
|
|
408
|
+
claim: "v",
|
|
409
|
+
max: SESSION_SUPPORTED_VER,
|
|
410
|
+
});
|
|
411
|
+
if (!sealed.ok)
|
|
412
|
+
return { ...result, reason: sealed.reason };
|
|
413
|
+
const claims = sealed.claims;
|
|
414
|
+
result.claims = claims;
|
|
415
|
+
result.checks.signature = true;
|
|
416
|
+
const bundle = Array.isArray(input?.bundle) && input.bundle.every((j) => typeof j === "string") ? input.bundle : null;
|
|
417
|
+
if (!bundle)
|
|
418
|
+
return { ...result, reason: "malformed_bundle", checks: { ...result.checks, bundle: false } };
|
|
419
|
+
// 2. The root and every total, recomputed from the bundle.
|
|
420
|
+
const decoded = bundle.map(decodePayload);
|
|
421
|
+
const totals = bundleTotals(decoded);
|
|
422
|
+
if (sessionRoot(bundle) !== (claims.root ?? null))
|
|
423
|
+
result.mismatched.push("root");
|
|
424
|
+
if (claims.n !== bundle.length)
|
|
425
|
+
result.mismatched.push("n");
|
|
426
|
+
if (claims.cost !== totals.cost)
|
|
427
|
+
result.mismatched.push("cost");
|
|
428
|
+
if (claims.unp !== totals.unp)
|
|
429
|
+
result.mismatched.push("unp");
|
|
430
|
+
if (canonical(claims.tree, TREE_KEYS) !== canonical(totals.tree, TREE_KEYS))
|
|
431
|
+
result.mismatched.push("tree");
|
|
432
|
+
if (canonical(claims.mdl, MODEL_KEYS) !== canonical(totals.mdl, MODEL_KEYS))
|
|
433
|
+
result.mismatched.push("mdl");
|
|
434
|
+
result.checks.bundle = result.mismatched.length === 0;
|
|
435
|
+
// 3. Every receipt verifies, and belongs to this session, agent and window.
|
|
436
|
+
// Traced steps describe the seal only; the receipts are checked untraced.
|
|
437
|
+
const receiptOptions = { ...options, jwksCache, onStep: undefined };
|
|
438
|
+
const seen = new Set();
|
|
439
|
+
for (let index = 0; index < bundle.length; index++) {
|
|
440
|
+
const id = orNull(decoded[index]?.jti);
|
|
441
|
+
const verified = await verifyReceipt(bundle[index], receiptOptions);
|
|
442
|
+
let reason = verified.ok ? null : verified.reason;
|
|
443
|
+
if (verified.ok) {
|
|
444
|
+
const c = verified.claims;
|
|
445
|
+
const t = Math.floor(num(c.t0) / 1000);
|
|
446
|
+
if (seen.has(c.jti))
|
|
447
|
+
reason = "duplicate";
|
|
448
|
+
else if (c.ctx?.ses !== claims.ses?.id)
|
|
449
|
+
reason = "other_session";
|
|
450
|
+
else if (c.agid !== claims.sub)
|
|
451
|
+
reason = "other_agent";
|
|
452
|
+
else if (!(t >= num(claims.per?.from) && t < num(claims.per?.to)))
|
|
453
|
+
reason = "outside_period";
|
|
454
|
+
seen.add(c.jti);
|
|
455
|
+
}
|
|
456
|
+
if (reason)
|
|
457
|
+
result.rejected.push({ index, id, reason });
|
|
458
|
+
}
|
|
459
|
+
result.checks.receipts = result.rejected.length === 0;
|
|
460
|
+
// 4. The user's own record.
|
|
461
|
+
if (input.journal !== undefined) {
|
|
462
|
+
const journaled = journalIds(input.journal, claims.ses?.id);
|
|
463
|
+
if (!journaled) {
|
|
464
|
+
result.reason = "malformed_journal";
|
|
465
|
+
result.checks.journal = false;
|
|
466
|
+
}
|
|
467
|
+
else {
|
|
468
|
+
const inBundle = new Set(decoded.map((c) => orNull(c?.jti)).filter((v) => v !== null));
|
|
469
|
+
const predecessors = new Set(decoded.map((c) => orNull(c?.prev)).filter((v) => v !== null));
|
|
470
|
+
result.otherSessions = journaled.other;
|
|
471
|
+
const ids = new Set(journaled.ids);
|
|
472
|
+
result.missing = [...ids].filter((id) => !inBundle.has(id) && !predecessors.has(id));
|
|
473
|
+
for (const id of inBundle) {
|
|
474
|
+
if (!ids.has(id)) {
|
|
475
|
+
result.unjournaled.push({ id, why: predecessors.has(id) ? "failover_predecessor" : "not_in_journal" });
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
result.checks.journal = result.missing.length === 0;
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
const { signature, bundle: b, receipts, journal } = result.checks;
|
|
482
|
+
result.ok = signature && b === true && receipts === true && journal !== false;
|
|
483
|
+
return result;
|
|
484
|
+
}
|
|
267
485
|
/**
|
|
268
486
|
* Verify an agent-to-agent token.
|
|
269
487
|
*
|