passcontrol 0.5.2 → 0.6.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.
@@ -0,0 +1,47 @@
1
+ export type ProviderId = "openai" | "anthropic" | "groq" | "mistral" | "together" | "deepseek";
2
+ export interface PassControlOptions {
3
+ /**
4
+ * Gateway origin, e.g. https://passcontrol.example.com — scheme, host and
5
+ * optional port only. Validated at construction against the same bare-origin
6
+ * rule as `ControlClient`; plain HTTP is accepted only on loopback. See
7
+ * ./gateway.
8
+ */
9
+ gateway: string;
10
+ /** base64url Ed25519 public key (the passport id). */
11
+ passportId: string;
12
+ /** base64url Ed25519 private key (32-byte seed). Stays on the agent; only signs. */
13
+ passportSecret: string;
14
+ /** Re-mint when fewer than this many seconds remain on the visa. Default 30. */
15
+ refreshSkewSeconds?: number;
16
+ /** Override the transport (tests / custom fetch). Defaults to global fetch. */
17
+ fetch?: typeof fetch;
18
+ }
19
+ export declare class PassControl {
20
+ private readonly gateway;
21
+ private readonly gatewayOrigin;
22
+ private readonly passportId;
23
+ private readonly secret;
24
+ private readonly skewMs;
25
+ private readonly transport;
26
+ private cached;
27
+ private inflight;
28
+ constructor(opts: PassControlOptions);
29
+ /** Sign a fresh challenge and exchange it for a visa. */
30
+ private mint;
31
+ /** Return a valid visa, minting or refreshing as needed. Concurrent callers
32
+ * share a single in-flight mint (no thundering herd of challenges). */
33
+ getVisa(): Promise<string>;
34
+ /** Drop the cached visa so the next getVisa() re-mints. */
35
+ invalidate(): void;
36
+ /** A `fetch` that injects the visa and refreshes it transparently. Pass this as
37
+ * the `fetch` option to the OpenAI/Anthropic SDK. Retries once on a 401 (the
38
+ * visa was rejected/expired) after forcing a re-mint. */
39
+ fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
40
+ /** Options to spread into an OpenAI/Anthropic SDK constructor. The fetch wrapper
41
+ * owns auth, so `apiKey` is a non-secret placeholder (the SDK requires one). */
42
+ clientOptions(provider: ProviderId): {
43
+ baseURL: string;
44
+ apiKey: string;
45
+ fetch: typeof fetch;
46
+ };
47
+ }
@@ -0,0 +1,197 @@
1
+ // PassControl client SDK — the thin layer that hides visa minting.
2
+ //
3
+ // A PassControl-issued passport holds an Ed25519 private key. To call a provider
4
+ // the agent must sign a challenge, mint a short-lived (5 min) work-visa, and send
5
+ // it instead of the real provider key. This SDK does that — and refreshes the visa
6
+ // transparently — so integration is *re-pointing* an existing OpenAI/Anthropic SDK,
7
+ // not rewriting the agent:
8
+ //
9
+ // Construct PassControl with gateway, passportId and passportSecret, then pass
10
+ // pc.clientOptions("openai") to the existing OpenAI client constructor.
11
+ // // …use `openai` normally. Visas mint/refresh under the hood.
12
+ //
13
+ // Dependencies: only @noble/curves (Ed25519) + the platform `fetch`/`crypto`.
14
+ // Runs on Node 18+ and edge/server runtimes. Do not place a passport secret in
15
+ // an end-user browser bundle even though the underlying Web APIs are portable.
16
+ import { ed25519 } from "@noble/curves/ed25519";
17
+ import { requireGatewayOrigin } from "./gateway.js";
18
+ // --- base64url over raw bytes (no Buffer dependency; works everywhere) -------
19
+ function bytesToB64url(bytes) {
20
+ let bin = "";
21
+ for (const b of bytes)
22
+ bin += String.fromCharCode(b);
23
+ const b64 = typeof btoa !== "undefined" ? btoa(bin) : Buffer.from(bin, "binary").toString("base64");
24
+ return b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
25
+ }
26
+ function b64urlToBytes(s) {
27
+ const b64 = s.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(s.length / 4) * 4, "=");
28
+ const bin = typeof atob !== "undefined" ? atob(b64) : Buffer.from(b64, "base64").toString("binary");
29
+ return Uint8Array.from(bin, (c) => c.charCodeAt(0));
30
+ }
31
+ /**
32
+ * Can this `init.body` be sent a second time?
33
+ *
34
+ * Only matters for the one-time 401 retry, and it is the whole question — because
35
+ * `init.body`, when it is non-null, IS the body each attempt sends. `send()` passes
36
+ * `{ ...init, headers }` next to the cloned `Request` template, and per the fetch
37
+ * spec an init body overrides the input request's; the clone's teed copy is then
38
+ * never read. So a `Request` input does not make a retry safe on its own: what
39
+ * decides is the *effective* body, which is `init.body` whenever one is supplied.
40
+ *
41
+ * Every shape below is a re-readable value. Anything else (a ReadableStream, an
42
+ * async iterable, a Node stream) is consumed by the first attempt; replaying one
43
+ * either throws a platform TypeError or, worse, sends an empty body to the
44
+ * provider — so we don't.
45
+ *
46
+ * `null`/`undefined` answer true, and that is what makes the caller's single call
47
+ * to this function complete: with no init body the effective body is the template
48
+ * `Request`'s own, which `clone()` tees and can therefore be sent again — or there
49
+ * is no template and no body at all. (It also means the answer does not hinge on
50
+ * whether a given runtime treats an explicit `body: null` as an override: both
51
+ * readings leave a replay-safe body.)
52
+ *
53
+ * Deliberately an allow-list. A body shape this does not recognise is treated as
54
+ * single-use, which costs one avoidable retry and can never send a wrong body.
55
+ */
56
+ function isReplayableBody(body) {
57
+ if (body === null || body === undefined || typeof body === "string")
58
+ return true;
59
+ if (typeof ArrayBuffer !== "undefined" && (ArrayBuffer.isView(body) || body instanceof ArrayBuffer))
60
+ return true;
61
+ if (typeof Blob !== "undefined" && body instanceof Blob)
62
+ return true;
63
+ if (typeof FormData !== "undefined" && body instanceof FormData)
64
+ return true;
65
+ if (typeof URLSearchParams !== "undefined" && body instanceof URLSearchParams)
66
+ return true;
67
+ return false;
68
+ }
69
+ export class PassControl {
70
+ gateway;
71
+ gatewayOrigin;
72
+ passportId;
73
+ secret;
74
+ skewMs;
75
+ transport;
76
+ cached = null;
77
+ inflight = null;
78
+ constructor(opts) {
79
+ if (!opts.gateway || !opts.passportId || !opts.passportSecret) {
80
+ throw new Error("PassControl: gateway, passportId, and passportSecret are required.");
81
+ }
82
+ // Same rule, same code as ControlClient's `pc_` key — see ./gateway. Both
83
+ // clients hand a bearer credential to whatever this option names, so the two
84
+ // must not be allowed to drift apart.
85
+ const origin = requireGatewayOrigin("PassControl", opts.gateway);
86
+ this.gateway = origin;
87
+ this.gatewayOrigin = origin;
88
+ this.passportId = opts.passportId;
89
+ this.secret = b64urlToBytes(opts.passportSecret);
90
+ if (b64urlToBytes(opts.passportId).length !== 32 || this.secret.length !== 32) {
91
+ throw new Error("PassControl: passportId and passportSecret must each encode 32 bytes.");
92
+ }
93
+ this.skewMs = Math.max(0, (opts.refreshSkewSeconds ?? 30) * 1000);
94
+ // Bind so the global fetch keeps its expected `this`.
95
+ const f = opts.fetch ?? globalThis.fetch;
96
+ if (!f)
97
+ throw new Error("PassControl: no fetch available; pass options.fetch.");
98
+ this.transport = (...args) => f(...args);
99
+ }
100
+ /** Sign a fresh challenge and exchange it for a visa. */
101
+ async mint() {
102
+ const payloadObj = { passport_id: this.passportId, ts: Date.now(), nonce: crypto.randomUUID() };
103
+ const payloadBytes = new TextEncoder().encode(JSON.stringify(payloadObj));
104
+ const payload = bytesToB64url(payloadBytes);
105
+ const signature = bytesToB64url(ed25519.sign(payloadBytes, this.secret));
106
+ const res = await this.transport(`${this.gateway}/api/auth/challenge`, {
107
+ method: "POST",
108
+ headers: { "content-type": "application/json" },
109
+ body: JSON.stringify({ payload, signature }),
110
+ });
111
+ if (!res.ok) {
112
+ const detail = await res.text().catch(() => "");
113
+ throw new Error(`PassControl: challenge failed (${res.status}) ${detail}`.trim());
114
+ }
115
+ const data = (await res.json());
116
+ if (!data.visa)
117
+ throw new Error("PassControl: challenge returned no visa.");
118
+ return { token: data.visa, expiresAt: Date.now() + (data.expires_in ?? 300) * 1000 };
119
+ }
120
+ /** Return a valid visa, minting or refreshing as needed. Concurrent callers
121
+ * share a single in-flight mint (no thundering herd of challenges). */
122
+ async getVisa() {
123
+ if (this.cached && Date.now() < this.cached.expiresAt - this.skewMs) {
124
+ return this.cached.token;
125
+ }
126
+ if (this.inflight)
127
+ return this.inflight;
128
+ this.inflight = this.mint()
129
+ .then((v) => {
130
+ this.cached = v;
131
+ return v.token;
132
+ })
133
+ .finally(() => {
134
+ this.inflight = null;
135
+ });
136
+ return this.inflight;
137
+ }
138
+ /** Drop the cached visa so the next getVisa() re-mints. */
139
+ invalidate() {
140
+ this.cached = null;
141
+ }
142
+ /** A `fetch` that injects the visa and refreshes it transparently. Pass this as
143
+ * the `fetch` option to the OpenAI/Anthropic SDK. Retries once on a 401 (the
144
+ * visa was rejected/expired) after forcing a re-mint. */
145
+ fetch = async (input, init = {}) => {
146
+ const inputRequest = typeof Request !== "undefined" && input instanceof Request ? input : null;
147
+ const rawUrl = inputRequest ? inputRequest.url : String(input);
148
+ const target = new URL(rawUrl, `${this.gateway}/`);
149
+ // `URL.origin` discards userinfo, so `https://a:b@gateway/...` compares equal to
150
+ // the gateway and would otherwise pass. Reject it here for the same reason the
151
+ // constructor does, instead of relying on the platform's Request to throw.
152
+ if (target.origin !== this.gatewayOrigin ||
153
+ target.username ||
154
+ target.password ||
155
+ !target.pathname.startsWith("/api/v1/")) {
156
+ throw new Error("PassControl: refusing to send a visa outside the configured gateway provider path.");
157
+ }
158
+ // Keep a pristine template so a Request input retains its method and body and
159
+ // each send gets an unread clone — clone() tees the body, streams included.
160
+ // That tee only covers the template's OWN body: a non-null `init.body` travels
161
+ // beside the clone and overrides it, so the effective body of every attempt is
162
+ // `init.body` when there is one. isReplayableBody decides on that basis alone.
163
+ const requestTemplate = inputRequest?.clone() ?? null;
164
+ const canReplay = isReplayableBody(init.body);
165
+ const send = async (visa) => {
166
+ const requestHeaders = inputRequest?.headers;
167
+ const headers = new Headers(init.headers ?? requestHeaders);
168
+ // The visa is the credential. Set it as Authorization (the gateway prefers
169
+ // Bearer) and strip any x-api-key the SDK added so only the visa travels.
170
+ headers.set("authorization", `Bearer ${visa}`);
171
+ headers.delete("x-api-key");
172
+ return this.transport(requestTemplate?.clone() ?? target.toString(), { ...init, headers });
173
+ };
174
+ let res = await send(await this.getVisa());
175
+ if (res.status === 401) {
176
+ // The gateway rejected this visa, so stop serving it either way — a caller
177
+ // we cannot retry for still deserves a fresh visa on its next call.
178
+ this.invalidate();
179
+ if (canReplay) {
180
+ // Release the rejected response's body before replacing it; an unread
181
+ // body holds its connection open until the runtime collects it.
182
+ void res.body?.cancel().catch(() => { });
183
+ res = await send(await this.getVisa());
184
+ }
185
+ }
186
+ return res;
187
+ };
188
+ /** Options to spread into an OpenAI/Anthropic SDK constructor. The fetch wrapper
189
+ * owns auth, so `apiKey` is a non-secret placeholder (the SDK requires one). */
190
+ clientOptions(provider) {
191
+ return {
192
+ baseURL: `${this.gateway}/api/v1/${provider}`,
193
+ apiKey: "passcontrol-visa",
194
+ fetch: this.fetch,
195
+ };
196
+ }
197
+ }
@@ -0,0 +1,182 @@
1
+ export declare const RECEIPT_TYP = "passcontrol-receipt+jwt";
2
+ export declare const AGENT_TOKEN_TYP = "passcontrol-agent+jwt";
3
+ /** The newest artifact version this verifier understands. */
4
+ export declare const SUPPORTED_VER = 2;
5
+ export type VerifyFailure = "malformed" | "untrusted_issuer" | "unknown_key" | "bad_signature" | "wrong_type" | "unsupported_version" | "jwks_unreachable" | "expired" | "wrong_audience" | "revoked" | "status_unavailable";
6
+ export type VerifyResult<T> = {
7
+ ok: true;
8
+ claims: T;
9
+ } | {
10
+ ok: false;
11
+ reason: VerifyFailure;
12
+ };
13
+ /**
14
+ * The checks this verifier runs, in the order it runs them. Exposed so a UI can
15
+ * show what it actually did rather than a spinner — see `onStep`.
16
+ */
17
+ export type VerifyStepName = "parse" | "algorithm" | "type" | "issuer" | "version" | "jwks" | "key" | "signature";
18
+ export interface VerifyStep {
19
+ step: VerifyStepName;
20
+ ok: boolean;
21
+ /** Present only on the failing step; equals the reason the caller receives. */
22
+ reason?: VerifyFailure;
23
+ /** Real elapsed milliseconds for this step. Not a target, not a minimum. */
24
+ ms: number;
25
+ }
26
+ export interface ReceiptClaims {
27
+ iss: string;
28
+ sub: string;
29
+ jti: string;
30
+ iat: number;
31
+ agid: string;
32
+ vjti?: string;
33
+ auth?: {
34
+ kind: "direct_key";
35
+ kid: string;
36
+ use: string;
37
+ };
38
+ prov: string;
39
+ mdl: string | null;
40
+ mth: string;
41
+ path: string;
42
+ req?: {
43
+ alg: string;
44
+ dig: string;
45
+ len: number;
46
+ };
47
+ use: {
48
+ in: number;
49
+ out: number;
50
+ };
51
+ cost: number;
52
+ res: {
53
+ status: string;
54
+ http: number;
55
+ };
56
+ t0: number;
57
+ lat: number;
58
+ own?: {
59
+ kind: string;
60
+ sub: string;
61
+ tier: string;
62
+ vat: string | null;
63
+ };
64
+ /**
65
+ * Present only on an attempt that followed a failed one: the `jti` of the
66
+ * receipt for the attempt this one replaced. Walk it backwards to read the
67
+ * whole chain — a receipt binds ONE call to ONE provider decision, so a
68
+ * failover is two receipts linked, never one compound artifact.
69
+ *
70
+ * Both attempts carry the same `req` digest, because that digest covers the
71
+ * bytes the CLIENT sent and those do not change between attempts. Matching
72
+ * two receipts by a shared digest is therefore a guess; this claim is the
73
+ * link.
74
+ *
75
+ * Optional, and `ver` stays 1: a verifier that predates these claims ignores
76
+ * what it does not recognise, and must not be invalidated for a feature it
77
+ * does not need to understand.
78
+ */
79
+ prev?: string;
80
+ /**
81
+ * Why the gateway moved on. An allowlisted enum at the issuing end, but treat
82
+ * it as an arbitrary string here — a receipt you verify may come from a
83
+ * different deployment or a newer version. Do not switch on it exhaustively.
84
+ *
85
+ * `upstream_5xx` and `unreachable` are the values where the attempt this
86
+ * receipt replaced MAY ALREADY HAVE BEEN BILLED by the other provider: it may
87
+ * have run the call before failing, and no one can tell. The other values mean
88
+ * the earlier provider refused before doing any work.
89
+ */
90
+ why?: string;
91
+ ver: number;
92
+ [claim: string]: unknown;
93
+ }
94
+ export interface AgentTokenClaims {
95
+ iss: string;
96
+ sub: string;
97
+ aud: string;
98
+ jti: string;
99
+ iat: number;
100
+ exp: number;
101
+ agid: string;
102
+ own?: {
103
+ kind: string;
104
+ sub: string;
105
+ tier: string;
106
+ vat: string | null;
107
+ } | null;
108
+ ver: number;
109
+ [claim: string]: unknown;
110
+ }
111
+ export interface VerifyOptions {
112
+ /**
113
+ * Origins whose signatures this verifier accepts. REQUIRED, with no default,
114
+ * ever — a verifier that trusts whatever issuer the token names is not
115
+ * verifying anything. Compared by exact string match (see matchesIssuer).
116
+ */
117
+ trustedIssuers: string[];
118
+ fetch?: typeof fetch;
119
+ /** Cache of issuer origin -> JWK Set, reused across calls. */
120
+ jwksCache?: Map<string, PublicJwk[]>;
121
+ /**
122
+ * Called as each check resolves, in order, stopping at the first failure.
123
+ *
124
+ * Purely observational: supplying it cannot change the outcome, and a callback
125
+ * that throws is swallowed rather than turned into a verification failure — a
126
+ * presentation bug must never be able to answer a security question.
127
+ *
128
+ * Note the trace covers the SIGNATURE checks only. verifyAgentToken's audience
129
+ * and expiry checks run after these and are not reported here.
130
+ */
131
+ onStep?: (step: VerifyStep) => void;
132
+ }
133
+ export interface PublicJwk {
134
+ kty: string;
135
+ crv: string;
136
+ x: string;
137
+ alg?: string;
138
+ use?: string;
139
+ kid?: string;
140
+ }
141
+ /**
142
+ * Exact string match, deliberately. Prefix or substring matching here is the
143
+ * classic issuer-confusion bug: `https://good.com.evil.com` starts with nothing
144
+ * useful but ends the way a naive `endsWith` would like, and
145
+ * `https://evil.com/?x=https://good.com` contains a trusted origin outright.
146
+ * A trailing slash is the one normalisation worth allowing.
147
+ */
148
+ export declare function matchesIssuer(iss: string, trusted: string[]): boolean;
149
+ /**
150
+ * Verify a signed call receipt.
151
+ *
152
+ * What a valid receipt proves: this issuer attests that the named passport or
153
+ * Direct Agent Key authenticated this call, with this verdict and this cost.
154
+ * A direct receipt proves bearer possession, not a passport signature. It does
155
+ * NOT prove:
156
+ * anything about the response, and nothing at all by its absence — see
157
+ * lib/receipt.ts for the limits, which are deliberate and documented.
158
+ */
159
+ export declare function verifyReceipt(jws: string, options: VerifyOptions): Promise<VerifyResult<ReceiptClaims>>;
160
+ export interface VerifyAgentTokenOptions extends VerifyOptions {
161
+ /** The audience YOU are. Required: a token minted for someone else is not for you. */
162
+ audience: string;
163
+ /**
164
+ * Additionally ask the issuer whether the passport is still active. Off by
165
+ * default — the whole point of this design is that verification needs no
166
+ * callback — but a long-lived decision may want live revocation state.
167
+ */
168
+ requireOnline?: boolean;
169
+ now?: () => number;
170
+ }
171
+ /**
172
+ * Verify an agent-to-agent token.
173
+ *
174
+ * ── Replay is YOUR problem, deliberately ────────────────────────────────────
175
+ *
176
+ * There is no server-side jti denylist, because there is no server in this
177
+ * path: verification is offline by design. A token is a bearer credential for
178
+ * its (short) lifetime, so if replay matters to you, dedupe on `claims.jti` —
179
+ * which is why it is returned. The short TTL bounds the window; it does not
180
+ * close it.
181
+ */
182
+ export declare function verifyAgentToken(token: string, options: VerifyAgentTokenOptions): Promise<VerifyResult<AgentTokenClaims>>;
package/sdk/verify.js ADDED
@@ -0,0 +1,238 @@
1
+ // Verifying what PassControl signs — from outside PassControl.
2
+ //
3
+ // This is the half of the system that runs on someone ELSE'S machine. A party
4
+ // handed a signed call receipt fetches the issuer's JWK Set once and verifies
5
+ // offline: no account here, no callback, and it keeps working after the issuing
6
+ // deployment is gone.
7
+ //
8
+ // Dependencies: only @noble/curves + the platform `fetch`. Runs on Node 18+,
9
+ // edge runtimes, and the browser.
10
+ import { ed25519 } from "@noble/curves/ed25519";
11
+ export const RECEIPT_TYP = "passcontrol-receipt+jwt";
12
+ export const AGENT_TOKEN_TYP = "passcontrol-agent+jwt";
13
+ /** The newest artifact version this verifier understands. */
14
+ export const SUPPORTED_VER = 2;
15
+ const b64urlToBytes = (value) => {
16
+ const b64 = value.replace(/-/g, "+").replace(/_/g, "/");
17
+ const pad = b64.length % 4 === 0 ? "" : "=".repeat(4 - (b64.length % 4));
18
+ const bin = atob(b64 + pad);
19
+ const out = new Uint8Array(bin.length);
20
+ for (let i = 0; i < bin.length; i++)
21
+ out[i] = bin.charCodeAt(i);
22
+ return out;
23
+ };
24
+ const utf8 = (s) => new TextEncoder().encode(s);
25
+ /**
26
+ * Exact string match, deliberately. Prefix or substring matching here is the
27
+ * classic issuer-confusion bug: `https://good.com.evil.com` starts with nothing
28
+ * useful but ends the way a naive `endsWith` would like, and
29
+ * `https://evil.com/?x=https://good.com` contains a trusted origin outright.
30
+ * A trailing slash is the one normalisation worth allowing.
31
+ */
32
+ export function matchesIssuer(iss, trusted) {
33
+ const strip = (v) => v.replace(/\/+$/, "");
34
+ return trusted.some((candidate) => strip(candidate) === strip(iss));
35
+ }
36
+ async function loadJwks(issuer, options, revalidate = false) {
37
+ if (!revalidate) {
38
+ const cached = options.jwksCache?.get(issuer);
39
+ if (cached)
40
+ return cached;
41
+ }
42
+ const fetchImpl = options.fetch ?? fetch;
43
+ try {
44
+ // `no-cache` means "revalidate with the origin", not "do not cache" — an
45
+ // unchanged key set still answers 304, so the retry below is cheap.
46
+ const res = await fetchImpl(new URL("/.well-known/jwks.json", issuer).toString(), revalidate ? { cache: "no-cache" } : undefined);
47
+ if (!res.ok)
48
+ return null;
49
+ const body = (await res.json());
50
+ const keys = Array.isArray(body?.keys) ? body.keys : [];
51
+ options.jwksCache?.set(issuer, keys);
52
+ return keys;
53
+ }
54
+ catch {
55
+ return null;
56
+ }
57
+ }
58
+ const selectCandidates = (keys, kid) => keys.filter((key) => key?.kty === "OKP" &&
59
+ key?.crv === "Ed25519" &&
60
+ typeof key.x === "string" &&
61
+ (!kid || !key.kid || key.kid === kid));
62
+ /** Monotonic where available; wall clock is an acceptable fallback for a UI timer. */
63
+ const nowMs = () => typeof performance !== "undefined" && typeof performance.now === "function"
64
+ ? performance.now()
65
+ : Date.now();
66
+ /**
67
+ * Emits one VerifyStep per gate, timing each from the end of the previous one.
68
+ * Returns a no-op when no consumer asked for a trace, so the untraced path pays
69
+ * nothing — not even a clock read.
70
+ */
71
+ function tracer(onStep) {
72
+ if (!onStep)
73
+ return () => { };
74
+ let previous = nowMs();
75
+ return (step, ok, reason) => {
76
+ const at = nowMs();
77
+ const ms = at - previous;
78
+ previous = at;
79
+ try {
80
+ onStep(reason === undefined ? { step, ok, ms } : { step, ok, reason, ms });
81
+ }
82
+ catch {
83
+ // Deliberately swallowed. See onStep's contract.
84
+ }
85
+ };
86
+ }
87
+ async function verifySigned(token, typ, options) {
88
+ const trace = tracer(options.onStep);
89
+ // Each gate below reports through `fail`, so the emitted reason and the
90
+ // returned reason cannot drift apart.
91
+ const fail = (step, reason) => {
92
+ trace(step, false, reason);
93
+ return { ok: false, reason };
94
+ };
95
+ const parts = token.split(".");
96
+ if (parts.length !== 3)
97
+ return fail("parse", "malformed");
98
+ const [headerPart, payloadPart, signaturePart] = parts;
99
+ if (!headerPart || !payloadPart || !signaturePart)
100
+ return fail("parse", "malformed");
101
+ let header;
102
+ let claims;
103
+ try {
104
+ header = JSON.parse(new TextDecoder().decode(b64urlToBytes(headerPart)));
105
+ claims = JSON.parse(new TextDecoder().decode(b64urlToBytes(payloadPart)));
106
+ }
107
+ catch {
108
+ return fail("parse", "malformed");
109
+ }
110
+ trace("parse", true);
111
+ // EdDSA is pinned, never read from the token. A verifier that dispatches on
112
+ // the token's own `alg` accepts alg:"none", and accepts an HS256 MAC computed
113
+ // over the public key it just fetched from the JWKS — the key material is
114
+ // public, so the "secret" is known to the attacker. That single mistake turns
115
+ // this whole mechanism into decoration.
116
+ if (header.alg !== "EdDSA")
117
+ return fail("algorithm", "bad_signature");
118
+ trace("algorithm", true);
119
+ // RFC 8725 explicit typing: a historical receipt must never satisfy a live
120
+ // authentication decision, and both are signed by the same key.
121
+ if (header.typ !== typ)
122
+ return fail("type", "wrong_type");
123
+ trace("type", true);
124
+ const iss = typeof claims.iss === "string" ? claims.iss : "";
125
+ if (!iss || !matchesIssuer(iss, options.trustedIssuers)) {
126
+ return fail("issuer", "untrusted_issuer");
127
+ }
128
+ trace("issuer", true);
129
+ // Additive-only versioning: a NEWER artifact than we understand is refused
130
+ // (it may rely on a claim we would ignore), but unknown claims within a
131
+ // supported version are fine — that is what lets the issuer add a field
132
+ // without invalidating verifiers already in the field.
133
+ const ver = typeof claims.ver === "number" ? claims.ver : 0;
134
+ if (ver > SUPPORTED_VER)
135
+ return fail("version", "unsupported_version");
136
+ trace("version", true);
137
+ const keys = await loadJwks(iss, options);
138
+ if (!keys)
139
+ return fail("jwks", "jwks_unreachable");
140
+ trace("jwks", true);
141
+ let candidates = selectCandidates(keys, header.kid);
142
+ if (candidates.length === 0) {
143
+ // Before saying an issuer does not publish this key — which is presented as
144
+ // a forgery — go back to the origin once, bypassing any HTTP cache. The
145
+ // JWKS ships `max-age=300, stale-while-revalidate=86400`, so a browser can
146
+ // hold a key list a day old; across a key rotation that list is missing the
147
+ // NEW key, and a genuine receipt signed minutes ago resolves to unknown_key.
148
+ // (INSTANCE_SIGNING_KEY_PREV keeps OLD keys published for the reverse case.)
149
+ // The retry is the price of an accusation, not of verification: it only runs
150
+ // on the path that was about to make one, and an unchanged key set answers
151
+ // 304. If it fails we keep `unknown_key` — we did reach the issuer and did
152
+ // read a key list, so "could not reach" would misdescribe what happened.
153
+ const fresh = await loadJwks(iss, options, true);
154
+ if (fresh)
155
+ candidates = selectCandidates(fresh, header.kid);
156
+ }
157
+ if (candidates.length === 0)
158
+ return fail("key", "unknown_key");
159
+ trace("key", true);
160
+ const signature = b64urlToBytes(signaturePart);
161
+ const signed = utf8(`${headerPart}.${payloadPart}`);
162
+ for (const key of candidates) {
163
+ try {
164
+ if (ed25519.verify(signature, signed, b64urlToBytes(key.x))) {
165
+ trace("signature", true);
166
+ return { ok: true, claims };
167
+ }
168
+ }
169
+ catch {
170
+ // Try the next key; a malformed JWK entry must not abort verification.
171
+ }
172
+ }
173
+ return fail("signature", "bad_signature");
174
+ }
175
+ /**
176
+ * Verify a signed call receipt.
177
+ *
178
+ * What a valid receipt proves: this issuer attests that the named passport or
179
+ * Direct Agent Key authenticated this call, with this verdict and this cost.
180
+ * A direct receipt proves bearer possession, not a passport signature. It does
181
+ * NOT prove:
182
+ * anything about the response, and nothing at all by its absence — see
183
+ * lib/receipt.ts for the limits, which are deliberate and documented.
184
+ */
185
+ export function verifyReceipt(jws, options) {
186
+ return verifySigned(jws, RECEIPT_TYP, options);
187
+ }
188
+ /**
189
+ * Verify an agent-to-agent token.
190
+ *
191
+ * ── Replay is YOUR problem, deliberately ────────────────────────────────────
192
+ *
193
+ * There is no server-side jti denylist, because there is no server in this
194
+ * path: verification is offline by design. A token is a bearer credential for
195
+ * its (short) lifetime, so if replay matters to you, dedupe on `claims.jti` —
196
+ * which is why it is returned. The short TTL bounds the window; it does not
197
+ * close it.
198
+ */
199
+ export async function verifyAgentToken(token, options) {
200
+ if (!options.audience)
201
+ return { ok: false, reason: "wrong_audience" };
202
+ const result = await verifySigned(token, AGENT_TOKEN_TYP, options);
203
+ if (!result.ok)
204
+ return result;
205
+ const claims = result.claims;
206
+ // Exact match. A token minted for `aud: "billing"` must not satisfy a
207
+ // verifier that is `payments`, however similar the names look.
208
+ if (claims.aud !== options.audience)
209
+ return { ok: false, reason: "wrong_audience" };
210
+ const now = Math.floor((options.now?.() ?? Date.now()) / 1000);
211
+ if (typeof claims.exp !== "number" || claims.exp <= now)
212
+ return { ok: false, reason: "expired" };
213
+ if (options.requireOnline) {
214
+ const live = await passportStatus(claims.iss, claims.sub, options);
215
+ // An unreachable issuer is NOT a revocation. Report it distinctly so the
216
+ // caller decides whether their situation tolerates an unknown, rather than
217
+ // having an outage silently read as "this agent was revoked".
218
+ if (live === null)
219
+ return { ok: false, reason: "status_unavailable" };
220
+ if (live !== "active")
221
+ return { ok: false, reason: "revoked" };
222
+ }
223
+ return { ok: true, claims };
224
+ }
225
+ async function passportStatus(issuer, passportId, options) {
226
+ const fetchImpl = options.fetch ?? fetch;
227
+ try {
228
+ const url = new URL(`/api/verify/${encodeURIComponent(passportId)}`, issuer).toString();
229
+ const res = await fetchImpl(url);
230
+ if (!res.ok)
231
+ return null;
232
+ const body = (await res.json());
233
+ return typeof body?.data?.status === "string" ? body.data.status : null;
234
+ }
235
+ catch {
236
+ return null;
237
+ }
238
+ }