passcontrol 0.8.0 → 0.9.1

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/cli/verify.mjs CHANGED
@@ -7,10 +7,14 @@
7
7
  // Nothing here needs a PassControl account, an API key, or a passport. You need
8
8
  // the artifact and the issuer's origin. That is the whole point.
9
9
  import { ed25519 } from "@noble/curves/ed25519";
10
- import { RECEIPT_PROTOCOL } from "./protocols.mjs";
10
+ import { sha256 } from "@noble/hashes/sha256";
11
+ import { RECEIPT_PROTOCOL, STATEMENT_PROTOCOL } from "./protocols.mjs";
11
12
 
12
13
  export const RECEIPT_TYP = "passcontrol-receipt+jwt";
13
14
  export const AGENT_TOKEN_TYP = "passcontrol-agent+jwt";
15
+ export const STATEMENT_TYP = "passcontrol-statement+jws";
16
+ // Its own version line, separate from the receipt's — see protocols.mjs.
17
+ export const STATEMENT_SUPPORTED_VER = STATEMENT_PROTOCOL.maximum;
14
18
  // Receipts v2 add Direct Agent identity claims. This is a maximum, not an
15
19
  // equality check: v1 receipts remain independently verifiable forever.
16
20
  export const SUPPORTED_VER = RECEIPT_PROTOCOL.maximum;
@@ -41,7 +45,23 @@ async function loadJwks(issuer, fetchImpl) {
41
45
  }
42
46
  }
43
47
 
44
- async function verifySigned(token, typ, { issuer, fetch: fetchImpl = fetch }) {
48
+ /**
49
+ * `version` names which claim carries the artifact's version and the newest
50
+ * value understood. Receipts version with `ver`; statements have their own line
51
+ * and use `v`. Without this a statement would flow through the receipt gate,
52
+ * find no `ver`, read as 0 and be accepted whatever it claimed — so a future
53
+ * statement v2 would pass this v1 verifier silently. The default reproduces the
54
+ * receipt behaviour exactly, so the verifyReceipt call site is unchanged.
55
+ *
56
+ * Kept deliberately identical in shape to sdk/verify.ts. These two are twins and
57
+ * the tests below pin them to agree.
58
+ */
59
+ async function verifySigned(
60
+ token,
61
+ typ,
62
+ { issuer, fetch: fetchImpl = fetch },
63
+ version = { claim: "ver", max: SUPPORTED_VER }
64
+ ) {
45
65
  const parts = String(token).split(".");
46
66
  if (parts.length !== 3 || !parts[0] || !parts[1] || !parts[2]) {
47
67
  return { ok: false, reason: "malformed" };
@@ -64,7 +84,9 @@ async function verifySigned(token, typ, { issuer, fetch: fetchImpl = fetch }) {
64
84
  if (!claims?.iss || !matchesIssuer(claims.iss, [issuer])) {
65
85
  return { ok: false, reason: "untrusted_issuer" };
66
86
  }
67
- if (Number(claims.ver ?? 0) > SUPPORTED_VER) return { ok: false, reason: "unsupported_version" };
87
+ if (Number(claims?.[version.claim] ?? 0) > version.max) {
88
+ return { ok: false, reason: "unsupported_version" };
89
+ }
68
90
 
69
91
  const keys = await loadJwks(claims.iss, fetchImpl);
70
92
  if (!keys) return { ok: false, reason: "jwks_unreachable" };
@@ -94,6 +116,59 @@ export function verifyReceipt(jws, options) {
94
116
  return verifySigned(jws, RECEIPT_TYP, options);
95
117
  }
96
118
 
119
+ /**
120
+ * Verify a signed spend statement.
121
+ *
122
+ * A valid statement proves the issuer committed to a fixed set of receipts for
123
+ * that window at signing time, and that it follows a specific earlier statement.
124
+ * It is NOT an independent audit of the totals: recomputing `root` needs every
125
+ * receipt in the window, which the holder of a statement does not have.
126
+ */
127
+ export function verifyStatement(jws, options) {
128
+ return verifySigned(jws, STATEMENT_TYP, options, {
129
+ claim: "v",
130
+ max: STATEMENT_SUPPORTED_VER,
131
+ });
132
+ }
133
+
134
+ /**
135
+ * Fold a receipt and an inclusion path back to a root.
136
+ *
137
+ * `false` means "not in THIS root" — not "not attested". Pairing a receipt with
138
+ * the wrong day's statement returns a truthful `false` that reads like an
139
+ * accusation, and nothing here can tell the difference.
140
+ */
141
+ export function verifyInclusion(receiptJws, proof, root) {
142
+ const bytes = (v) => (typeof v === "string" ? fromB64url(v) : v);
143
+ // Same domain separation as lib/merkle.ts: 0x00 for a leaf, 0x01 for a node,
144
+ // so a leaf can never be passed off as an internal node.
145
+ const hash = (prefix, ...parts) => {
146
+ const total = parts.reduce((sum, p) => sum + p.length, 1);
147
+ const buf = new Uint8Array(total);
148
+ buf[0] = prefix;
149
+ let at = 1;
150
+ for (const p of parts) {
151
+ buf.set(p, at);
152
+ at += p.length;
153
+ }
154
+ return sha256(buf);
155
+ };
156
+
157
+ try {
158
+ let node = hash(0x00, new TextEncoder().encode(String(receiptJws)));
159
+ for (const step of proof ?? []) {
160
+ const sibling = bytes(step.hash);
161
+ node = step.right ? hash(0x01, node, sibling) : hash(0x01, sibling, node);
162
+ }
163
+ const target = bytes(root);
164
+ if (node.length !== target.length) return false;
165
+ for (let i = 0; i < node.length; i++) if (node[i] !== target[i]) return false;
166
+ return true;
167
+ } catch {
168
+ return false;
169
+ }
170
+ }
171
+
97
172
  export async function verifyAgentToken(token, options) {
98
173
  const { audience, now = () => Date.now() } = options;
99
174
  if (!audience) return { ok: false, reason: "wrong_audience" };
@@ -1,4 +1,5 @@
1
1
  import { ed25519 } from "@noble/curves/ed25519";
2
+ import { sha256 } from "@noble/hashes/sha256";
2
3
  import { bareGatewayOrigin, formatChallengeError } from "./config.mjs";
3
4
 
4
5
  const b64url = (bytes) =>
@@ -10,6 +11,11 @@ export function createVisaClient({
10
11
  gateway,
11
12
  passportId,
12
13
  passportSecret,
14
+ // What this machine claims about where its passport key is kept, or null.
15
+ // Built by cli/passport-key-store.mjs from the resolution that produced the
16
+ // secret above; see lib/passport-key-storage.ts for why it travels inside the
17
+ // signed bytes rather than beside them.
18
+ keyStorage = null,
13
19
  fetch: fetchImpl = (...args) => globalThis.fetch(...args),
14
20
  now = () => Date.now(),
15
21
  randomUUID = () => globalThis.crypto.randomUUID(),
@@ -29,7 +35,15 @@ export function createVisaClient({
29
35
  let inflight = null;
30
36
 
31
37
  async function mint() {
32
- const payloadObject = { passport_id: passportId, ts: now(), nonce: randomUUID() };
38
+ const payloadObject = {
39
+ passport_id: passportId,
40
+ ts: now(),
41
+ nonce: randomUUID(),
42
+ // Omitted, never guessed at: every older client, the SDK and the examples
43
+ // mint without one, and an absent claim is a state the dashboard says out
44
+ // loud rather than a tier it assumes.
45
+ ...(keyStorage ? { key_storage: keyStorage } : {}),
46
+ };
33
47
  const payload = b64url(new TextEncoder().encode(JSON.stringify(payloadObject)));
34
48
  const signature = b64url(ed25519.sign(fromB64url(payload), fromB64url(passportSecret)));
35
49
  const response = await fetchImpl(`${origin}/api/auth/challenge`, {
@@ -69,6 +83,20 @@ export function createVisaClient({
69
83
  cached = null;
70
84
  }
71
85
 
86
+ function createProof(visa, method, url) {
87
+ const target = new URL(url);
88
+ const payloadBytes = new TextEncoder().encode(
89
+ JSON.stringify({
90
+ htm: String(method ?? "GET").toUpperCase(),
91
+ htu: `${target.origin}${target.pathname}`,
92
+ iat: Math.floor(now() / 1000),
93
+ jti: randomUUID(),
94
+ vh: b64url(sha256(new TextEncoder().encode(visa))),
95
+ })
96
+ );
97
+ return `${b64url(payloadBytes)}.${b64url(ed25519.sign(payloadBytes, fromB64url(passportSecret)))}`;
98
+ }
99
+
72
100
  async function fetchWithVisa(request) {
73
101
  let response = await request(await getVisa());
74
102
  if (response.status === 401) {
@@ -78,5 +106,5 @@ export function createVisaClient({
78
106
  return response;
79
107
  }
80
108
 
81
- return { getVisa, invalidate, fetchWithVisa };
109
+ return { getVisa, invalidate, fetchWithVisa, createProof };
82
110
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "passcontrol",
3
- "version": "0.8.0",
3
+ "version": "0.9.1",
4
4
  "description": "Identity, scope and budget controls for AI agents while provider keys stay server-side.",
5
5
  "license": "BUSL-1.1",
6
6
  "homepage": "https://passcontrol.vertias.eu",
package/sdk/README.md CHANGED
@@ -8,8 +8,8 @@ your existing OpenAI/Anthropic SDK, **not rewriting the agent**.
8
8
  Install it beside the provider SDK used by your agent:
9
9
 
10
10
  ```bash
11
- npm install passcontrol@^0.6.0 openai
12
- # or: npm install passcontrol@^0.6.0 @anthropic-ai/sdk
11
+ npm install passcontrol@0.9.1 openai
12
+ # or: npm install passcontrol@0.9.1 @anthropic-ai/sdk
13
13
  ```
14
14
 
15
15
  Dependencies: only [`@noble/curves`](https://github.com/paulmillr/noble-curves) and the
@@ -39,7 +39,7 @@ That rejects two self-host shapes worth knowing about up front:
39
39
  - **A gateway served under a sub-path** (`https://example.com/passcontrol`). Give it its own
40
40
  origin or subdomain.
41
41
 
42
- The rule exists because the visa is a bearer credential: the SDK pins it to exactly this origin
42
+ The rule limits the initial credential destination: the SDK pins it to exactly this origin
43
43
  and refuses to attach it anywhere else, so a gateway value that is loose about scheme or path
44
44
  would weaken the pin it is used to define.
45
45
 
@@ -118,6 +118,7 @@ const pc = new ControlClient({
118
118
  });
119
119
 
120
120
  const agents = await pc.agents.list({ status: "active" });
121
+ const account = await pc.account.get(); // { email, control_key_scope }
121
122
  const created = await pc.agents.create(
122
123
  { name: "billing-bot", passportPubkey, scopes: [{ provider: "anthropic", models: ["claude-*"] }] },
123
124
  { idempotencyKey: "create-billing-bot" } // safe retries
@@ -134,7 +135,7 @@ fleet, so it is only ever attached to `<origin>/api/control/v1` on the validated
134
135
  HTTP off loopback, a sub-path, or embedded userinfo throw at construction, before the transport
135
136
  — default or custom — is called. Keep the key server-side; it is never printed by the client.
136
137
 
137
- Resources: `agents.{list,get,create,update,suspend,resume,revoke}`, `logs.list`,
138
+ Resources: `account.get`, `agents.{list,get,create,update,suspend,resume,revoke}`, `logs.list`,
138
139
  `audit.list`, `spend.get`, `killSwitch.{get,set}`. Writes accept `{ idempotencyKey }`.
139
140
  The full reference lives in [the public OpenAPI document](https://github.com/Vertias3u/PassControl/blob/main/openapi.yaml).
140
141
 
@@ -144,9 +145,33 @@ The full reference lives in [the public OpenAPI document](https://github.com/Ver
144
145
  `refreshSkewSeconds` (default 30s) of expiry, then re-minted automatically.
145
146
  - **Single-flight.** Concurrent `getVisa()` calls share one challenge request.
146
147
  - **401 retry.** If a proxied call returns `401` (visa rejected/expired), the SDK
147
- invalidates the cache, re-mints once, and retries.
148
+ invalidates the cache, re-mints once, and retries if the effective request body is replayable. Single-use init streams are not retried.
148
149
  - **Origin pinning.** A visa is attached only to `/api/v1/*` on the configured gateway origin.
149
150
  Any other origin, scheme, port or path — including the challenge endpoint and the control
150
151
  plane — is refused before the request leaves the process.
151
152
  - **No secret on the wire.** The passport private key only signs the challenge locally;
152
153
  the gateway only ever sees the public key and the signature.
154
+
155
+
156
+ ## 0.9.0 compatibility and assurance
157
+
158
+ `clientOptions` accepts `openai`, `anthropic`, `groq`, `mistral`, `together`, `deepseek`,
159
+ and `gemini`. OpenAI POST Responses works through `pc.fetch`/the OpenAI SDK as well as
160
+ Chat Completions. Gemini uses Google's OpenAI-compatible endpoint; native
161
+ `generateContent` is not supported. See [accepted paths](https://github.com/Vertias3u/PassControl/blob/main/DOCUMENTATION.md#data-plane--proxy-a-model-call).
162
+
163
+ The TypeScript SDK **does not attach sender proofs in 0.9.0**. Its provider requests use
164
+ bearer visas: they work with sender-proof mode off/observe, but required mode refuses
165
+ them without an additional correct proof implementation. The current sidecar attaches
166
+ proofs. A valid mint signature is not a signature over each provider request.
167
+
168
+ The wrapper validates the initial gateway origin/path. It does not override fetch's
169
+ redirect policy, so it is not a complete redirect-chain credential boundary. Gateway
170
+ upstream forwarding separately refuses provider redirects. Keep custom transports and
171
+ the configured gateway trusted.
172
+
173
+ The SDK takes a raw secret supplied by your application; it does not automatically read
174
+ the CLI's OS credential store. The CLI's storage declarations are not storage attestation.
175
+ Signed receipts are issuer assertions and best-effort, not proof of complete logging or
176
+ provider billing. The SDK exports statement/inclusion verification; statement retrieval
177
+ methods target Cloud's service and do not add it to a self-hosted installation.
package/sdk/control.d.ts CHANGED
@@ -20,6 +20,10 @@ export interface WriteOpts {
20
20
  /** Idempotency-Key — a retry with the same key won't re-apply the mutation. */
21
21
  idempotencyKey?: string;
22
22
  }
23
+ export interface ControlAccount {
24
+ email: string | null;
25
+ control_key_scope: "read" | "write";
26
+ }
23
27
  export declare class ControlClient {
24
28
  #private;
25
29
  private readonly base;
@@ -41,9 +45,11 @@ export declare class ControlClient {
41
45
  }[];
42
46
  budget_tokens?: number | null;
43
47
  budget_cents?: number | null;
48
+ expiresAt?: string | null;
44
49
  }, opts?: WriteOpts) => Promise<{
45
50
  id: string;
46
51
  name: string;
52
+ expires_at: string | null;
47
53
  }>;
48
54
  update: (id: string, patch: {
49
55
  name?: string;
@@ -69,6 +75,9 @@ export declare class ControlClient {
69
75
  status: string;
70
76
  }>;
71
77
  };
78
+ readonly account: {
79
+ get: () => Promise<ControlAccount>;
80
+ };
72
81
  readonly logs: {
73
82
  /**
74
83
  * `class` selects a view, never a different record: omitted returns every
@@ -88,6 +97,35 @@ export declare class ControlClient {
88
97
  limit?: number;
89
98
  }) => Promise<any[]>;
90
99
  };
100
+ readonly statements: {
101
+ /**
102
+ * The chain of signed spend statements, newest first. Metadata only — fetch
103
+ * `get(seq)` for the signed artifact, which is ~600 bytes each.
104
+ *
105
+ * `row_count` may exceed `covered_count`, and `unpriced_count` /
106
+ * `unknown_pricing_count` are not decoration: they are the statement's own
107
+ * account of calls it could not cover or could not price. Rendering only
108
+ * `covered_count` and `cost_microcents` converts "we cannot say" into "zero".
109
+ */
110
+ list: (params?: {
111
+ limit?: number;
112
+ }) => Promise<any[]>;
113
+ get: (seq: number) => Promise<any>;
114
+ /**
115
+ * One statement plus proof that `receiptId` is among the receipts it
116
+ * committed to. Pass the returned `inclusion.proof` and `inclusion.root` to
117
+ * `verifyInclusion` from the verifier.
118
+ *
119
+ * Three outcomes worth handling separately, because they are not all errors:
120
+ * a 404 `receipt_not_in_statement` means that call is simply not in this
121
+ * window; a 200 carrying `drift: "statement_window_grew"` means rows arrived
122
+ * after the window was attested, which is benign and expected; and a **409**
123
+ * (`statement_receipts_missing` / `statement_receipts_altered`) means the
124
+ * record no longer matches what was signed. The last is the finding this
125
+ * whole mechanism exists to surface — do not swallow it as a generic error.
126
+ */
127
+ inclusion: (seq: number, receiptId: string) => Promise<any>;
128
+ };
91
129
  readonly spend: {
92
130
  get: () => Promise<{
93
131
  fleet: {
package/sdk/control.js CHANGED
@@ -86,6 +86,9 @@ export class ControlClient {
86
86
  resume: (id, opts) => this.req("POST", `/agents/${encodeURIComponent(id)}/resume`, { idempotencyKey: opts?.idempotencyKey }),
87
87
  revoke: (id, opts) => this.req("DELETE", `/agents/${encodeURIComponent(id)}`, { idempotencyKey: opts?.idempotencyKey }),
88
88
  };
89
+ account = {
90
+ get: () => this.req("GET", "/account"),
91
+ };
89
92
  logs = {
90
93
  /**
91
94
  * `class` selects a view, never a different record: omitted returns every
@@ -98,6 +101,35 @@ export class ControlClient {
98
101
  audit = {
99
102
  list: (params) => this.req("GET", "/audit", { query: params }),
100
103
  };
104
+ statements = {
105
+ /**
106
+ * The chain of signed spend statements, newest first. Metadata only — fetch
107
+ * `get(seq)` for the signed artifact, which is ~600 bytes each.
108
+ *
109
+ * `row_count` may exceed `covered_count`, and `unpriced_count` /
110
+ * `unknown_pricing_count` are not decoration: they are the statement's own
111
+ * account of calls it could not cover or could not price. Rendering only
112
+ * `covered_count` and `cost_microcents` converts "we cannot say" into "zero".
113
+ */
114
+ list: (params) => this.req("GET", "/statements", { query: params }),
115
+ get: (seq) => this.req("GET", `/statements/${encodeURIComponent(String(seq))}`),
116
+ /**
117
+ * One statement plus proof that `receiptId` is among the receipts it
118
+ * committed to. Pass the returned `inclusion.proof` and `inclusion.root` to
119
+ * `verifyInclusion` from the verifier.
120
+ *
121
+ * Three outcomes worth handling separately, because they are not all errors:
122
+ * a 404 `receipt_not_in_statement` means that call is simply not in this
123
+ * window; a 200 carrying `drift: "statement_window_grew"` means rows arrived
124
+ * after the window was attested, which is benign and expected; and a **409**
125
+ * (`statement_receipts_missing` / `statement_receipts_altered`) means the
126
+ * record no longer matches what was signed. The last is the finding this
127
+ * whole mechanism exists to surface — do not swallow it as a generic error.
128
+ */
129
+ inclusion: (seq, receiptId) => this.req("GET", `/statements/${encodeURIComponent(String(seq))}`, {
130
+ query: { receipt_id: receiptId },
131
+ }),
132
+ };
101
133
  spend = {
102
134
  get: () => this.req("GET", "/spend"),
103
135
  };
package/sdk/index.d.ts CHANGED
@@ -2,5 +2,5 @@ export { PassControl } from "./passcontrol.js";
2
2
  export type { PassControlOptions, ProviderId } from "./passcontrol.js";
3
3
  export { ControlClient, ControlApiError } from "./control.js";
4
4
  export type { ControlClientOptions, WriteOpts } from "./control.js";
5
- export { verifyReceipt, verifyAgentToken, matchesIssuer, RECEIPT_TYP, AGENT_TOKEN_TYP, SUPPORTED_VER, } from "./verify.js";
6
- export type { ReceiptClaims, AgentTokenClaims, VerifyOptions, VerifyAgentTokenOptions, VerifyResult, VerifyFailure, PublicJwk, } from "./verify.js";
5
+ export { verifyReceipt, verifyAgentToken, verifyStatement, verifyInclusion, matchesIssuer, RECEIPT_TYP, AGENT_TOKEN_TYP, STATEMENT_TYP, SUPPORTED_VER, STATEMENT_SUPPORTED_VER, } from "./verify.js";
6
+ export type { ReceiptClaims, AgentTokenClaims, StatementClaims, StatementAgentSubtotal, InclusionProofStep, VerifyOptions, VerifyAgentTokenOptions, VerifyResult, VerifyFailure, PublicJwk, } from "./verify.js";
package/sdk/index.js CHANGED
@@ -17,4 +17,4 @@
17
17
  // whole `sdk/` directory; it only needs @noble/curves + the platform fetch/crypto.
18
18
  export { PassControl } from "./passcontrol.js";
19
19
  export { ControlClient, ControlApiError } from "./control.js";
20
- export { verifyReceipt, verifyAgentToken, matchesIssuer, RECEIPT_TYP, AGENT_TOKEN_TYP, SUPPORTED_VER, } from "./verify.js";
20
+ export { verifyReceipt, verifyAgentToken, verifyStatement, verifyInclusion, matchesIssuer, RECEIPT_TYP, AGENT_TOKEN_TYP, STATEMENT_TYP, SUPPORTED_VER, STATEMENT_SUPPORTED_VER, } from "./verify.js";
package/sdk/verify.d.ts CHANGED
@@ -34,6 +34,8 @@ export interface ReceiptClaims {
34
34
  kind: "direct_key";
35
35
  kid: string;
36
36
  use: string;
37
+ } | {
38
+ kind: "passport_proof_per_request";
37
39
  };
38
40
  prov: string;
39
41
  mdl: string | null;
@@ -60,12 +62,24 @@ export interface ReceiptClaims {
60
62
  cw?: number;
61
63
  };
62
64
  cost: number;
65
+ /**
66
+ * Present and true only when the gateway could not price this call: it went to
67
+ * a custom endpoint, which may mark up, re-route, alias onto a local model, or
68
+ * be free. `cost` is then 0 because this field is required, AND THAT ZERO MEANS
69
+ * NOTHING — do not add it to a total or report it as a free call.
70
+ *
71
+ * Optional and added like `cr` / `cw` above, so receipts that predate it are
72
+ * unaffected and verifiers that predate it ignore it by design.
73
+ */
74
+ unp?: boolean;
63
75
  res: {
64
76
  status: string;
65
77
  http: number;
66
78
  };
67
79
  t0: number;
68
80
  lat: number;
81
+ /** Revision of the effective live policy, scope and budget rules. */
82
+ pol?: string;
69
83
  own?: {
70
84
  kind: string;
71
85
  sub: string;
@@ -162,12 +176,87 @@ export declare function matchesIssuer(iss: string, trusted: string[]): boolean;
162
176
  *
163
177
  * What a valid receipt proves: this issuer attests that the named passport or
164
178
  * Direct Agent Key authenticated this call, with this verdict and this cost.
165
- * A direct receipt proves bearer possession, not a passport signature. It does
179
+ * `auth.kind === "passport_proof_per_request"` additionally attests that the
180
+ * gateway verified the passport proof for this exact request. A direct receipt
181
+ * proves bearer possession, not a passport signature. It does
166
182
  * NOT prove:
167
183
  * anything about the response, and nothing at all by its absence — see
168
184
  * lib/receipt.ts for the limits, which are deliberate and documented.
169
185
  */
170
186
  export declare function verifyReceipt(jws: string, options: VerifyOptions): Promise<VerifyResult<ReceiptClaims>>;
187
+ export declare const STATEMENT_TYP = "passcontrol-statement+jws";
188
+ /** The newest statement version this verifier understands. See STATEMENT_PROTOCOL. */
189
+ export declare const STATEMENT_SUPPORTED_VER: number;
190
+ /** One agent's slice of a statement. `agid` is null for a deleted agent. */
191
+ export interface StatementAgentSubtotal {
192
+ agid: string | null;
193
+ n: number;
194
+ cost: number;
195
+ }
196
+ export interface StatementClaims {
197
+ iss: string;
198
+ sub: string;
199
+ jti: string;
200
+ iat: number;
201
+ fmt: string;
202
+ v: number;
203
+ /** Position in this workspace's chain. */
204
+ seq: number;
205
+ /** Half-open window `[from, to)`, epoch seconds. */
206
+ per: {
207
+ from: number;
208
+ to: number;
209
+ };
210
+ /** Calls the root covers. */
211
+ n: number;
212
+ /** Total rows in the window — may EXCEED `n`; the difference is disclosed, not hidden. */
213
+ nr: number;
214
+ cost: number;
215
+ /** Calls known to be unpriceable. Their cost is unknowable, not zero. */
216
+ unp: number;
217
+ /** Calls whose cost was never recorded, reason unrecorded. Also not zero. */
218
+ unk: number;
219
+ /** base64url SHA-256 Merkle root, or null when the window covered nothing. */
220
+ root: string | null;
221
+ /** Digest of the previous statement's JWS; null at the head of a chain. */
222
+ pst: string | null;
223
+ by: StatementAgentSubtotal[];
224
+ }
225
+ /** One step of an inclusion path. `hash` is raw bytes or base64url. */
226
+ export interface InclusionProofStep {
227
+ right: boolean;
228
+ hash: Uint8Array | string;
229
+ }
230
+ /**
231
+ * Verify a signed spend statement.
232
+ *
233
+ * WHAT A VALID STATEMENT PROVES: this issuer committed to a fixed set of
234
+ * receipts for the named window at the time it signed, and — via `pst` — that
235
+ * this statement follows a specific earlier one. Nothing was removed from or
236
+ * reordered in the chain without breaking that link.
237
+ *
238
+ * WHAT IT DOES NOT PROVE, and the distinction matters: it is NOT an independent
239
+ * audit of `cost` or `n`. Recomputing `root` requires every receipt in the
240
+ * window, which the holder of a statement does not have. A valid statement means
241
+ * the issuer cannot now change what it committed to — not that the totals were
242
+ * right when they were computed.
243
+ */
244
+ export declare function verifyStatement(jws: string, options: VerifyOptions): Promise<VerifyResult<StatementClaims>>;
245
+ /**
246
+ * Check that a receipt is one of the leaves a statement's root commits to.
247
+ *
248
+ * READ WHAT `false` MEANS BEFORE ACTING ON IT. It means "not in THIS root" — not
249
+ * "not attested". Pairing a receipt with the wrong day's statement returns a
250
+ * perfectly truthful `false` that reads like an accusation, and nothing in this
251
+ * signature stops a caller doing that: `root` and `proof` come from a statement
252
+ * the caller chose. Confirm the receipt's own timestamp falls inside that
253
+ * statement's `per` window before treating a `false` as a finding.
254
+ *
255
+ * Verification is pure and offline — no fetch, no clock, no key. Give it the
256
+ * receipt's compact JWS exactly as issued, the proof steps from the control API,
257
+ * and the statement's `root`.
258
+ */
259
+ export declare function verifyInclusion(receiptJws: string, proof: readonly InclusionProofStep[], root: Uint8Array | string): boolean;
171
260
  export interface VerifyAgentTokenOptions extends VerifyOptions {
172
261
  /** The audience YOU are. Required: a token minted for someone else is not for you. */
173
262
  audience: string;
package/sdk/verify.js CHANGED
@@ -8,7 +8,8 @@
8
8
  // Dependencies: only @noble/curves + the platform `fetch`. Runs on Node 18+,
9
9
  // edge runtimes, and the browser.
10
10
  import { ed25519 } from "@noble/curves/ed25519";
11
- import { RECEIPT_PROTOCOL } from "../cli/protocols.mjs";
11
+ import { sha256 } from "@noble/hashes/sha256";
12
+ import { RECEIPT_PROTOCOL, STATEMENT_PROTOCOL } from "../cli/protocols.mjs";
12
13
  export const RECEIPT_TYP = "passcontrol-receipt+jwt";
13
14
  export const AGENT_TOKEN_TYP = "passcontrol-agent+jwt";
14
15
  /** The newest artifact version this verifier understands. */
@@ -85,7 +86,7 @@ function tracer(onStep) {
85
86
  }
86
87
  };
87
88
  }
88
- async function verifySigned(token, typ, options) {
89
+ async function verifySigned(token, typ, options, version = { claim: "ver", max: SUPPORTED_VER }) {
89
90
  const trace = tracer(options.onStep);
90
91
  // Each gate below reports through `fail`, so the emitted reason and the
91
92
  // returned reason cannot drift apart.
@@ -131,8 +132,9 @@ async function verifySigned(token, typ, options) {
131
132
  // (it may rely on a claim we would ignore), but unknown claims within a
132
133
  // supported version are fine — that is what lets the issuer add a field
133
134
  // without invalidating verifiers already in the field.
134
- const ver = typeof claims.ver === "number" ? claims.ver : 0;
135
- if (ver > SUPPORTED_VER)
135
+ const declared = claims[version.claim];
136
+ const ver = typeof declared === "number" ? declared : 0;
137
+ if (ver > version.max)
136
138
  return fail("version", "unsupported_version");
137
139
  trace("version", true);
138
140
  const keys = await loadJwks(iss, options);
@@ -178,7 +180,9 @@ async function verifySigned(token, typ, options) {
178
180
  *
179
181
  * What a valid receipt proves: this issuer attests that the named passport or
180
182
  * Direct Agent Key authenticated this call, with this verdict and this cost.
181
- * A direct receipt proves bearer possession, not a passport signature. It does
183
+ * `auth.kind === "passport_proof_per_request"` additionally attests that the
184
+ * gateway verified the passport proof for this exact request. A direct receipt
185
+ * proves bearer possession, not a passport signature. It does
182
186
  * NOT prove:
183
187
  * anything about the response, and nothing at all by its absence — see
184
188
  * lib/receipt.ts for the limits, which are deliberate and documented.
@@ -186,6 +190,80 @@ async function verifySigned(token, typ, options) {
186
190
  export function verifyReceipt(jws, options) {
187
191
  return verifySigned(jws, RECEIPT_TYP, options);
188
192
  }
193
+ // ── Signed spend statements ────────────────────────────────────────────────
194
+ export const STATEMENT_TYP = "passcontrol-statement+jws";
195
+ /** The newest statement version this verifier understands. See STATEMENT_PROTOCOL. */
196
+ export const STATEMENT_SUPPORTED_VER = STATEMENT_PROTOCOL.maximum;
197
+ /**
198
+ * Verify a signed spend statement.
199
+ *
200
+ * WHAT A VALID STATEMENT PROVES: this issuer committed to a fixed set of
201
+ * receipts for the named window at the time it signed, and — via `pst` — that
202
+ * this statement follows a specific earlier one. Nothing was removed from or
203
+ * reordered in the chain without breaking that link.
204
+ *
205
+ * WHAT IT DOES NOT PROVE, and the distinction matters: it is NOT an independent
206
+ * audit of `cost` or `n`. Recomputing `root` requires every receipt in the
207
+ * window, which the holder of a statement does not have. A valid statement means
208
+ * the issuer cannot now change what it committed to — not that the totals were
209
+ * right when they were computed.
210
+ */
211
+ export function verifyStatement(jws, options) {
212
+ return verifySigned(jws, STATEMENT_TYP, options, {
213
+ claim: "v",
214
+ max: STATEMENT_SUPPORTED_VER,
215
+ });
216
+ }
217
+ /**
218
+ * Check that a receipt is one of the leaves a statement's root commits to.
219
+ *
220
+ * READ WHAT `false` MEANS BEFORE ACTING ON IT. It means "not in THIS root" — not
221
+ * "not attested". Pairing a receipt with the wrong day's statement returns a
222
+ * perfectly truthful `false` that reads like an accusation, and nothing in this
223
+ * signature stops a caller doing that: `root` and `proof` come from a statement
224
+ * the caller chose. Confirm the receipt's own timestamp falls inside that
225
+ * statement's `per` window before treating a `false` as a finding.
226
+ *
227
+ * Verification is pure and offline — no fetch, no clock, no key. Give it the
228
+ * receipt's compact JWS exactly as issued, the proof steps from the control API,
229
+ * and the statement's `root`.
230
+ */
231
+ export function verifyInclusion(receiptJws, proof, root) {
232
+ const asBytes = (v) => (typeof v === "string" ? b64urlToBytes(v) : v);
233
+ // Same domain separation as lib/merkle.ts, restated rather than imported: this
234
+ // file is vendored by people who take `sdk/` alone, so it must stand up with
235
+ // nothing but @noble/curves and the platform.
236
+ const hash = (prefix, ...parts) => {
237
+ const total = parts.reduce((sum, p) => sum + p.length, 1);
238
+ const buf = new Uint8Array(total);
239
+ buf[0] = prefix;
240
+ let at = 1;
241
+ for (const p of parts) {
242
+ buf.set(p, at);
243
+ at += p.length;
244
+ }
245
+ return sha256(buf);
246
+ };
247
+ try {
248
+ let node = hash(0x00, utf8(receiptJws));
249
+ for (const step of proof) {
250
+ const sibling = asBytes(step.hash);
251
+ node = step.right ? hash(0x01, node, sibling) : hash(0x01, sibling, node);
252
+ }
253
+ const target = asBytes(root);
254
+ if (node.length !== target.length)
255
+ return false;
256
+ for (let i = 0; i < node.length; i++)
257
+ if (node[i] !== target[i])
258
+ return false;
259
+ return true;
260
+ }
261
+ catch {
262
+ // A malformed proof step or root is "not proven", never a throw into a
263
+ // caller's verification path.
264
+ return false;
265
+ }
266
+ }
189
267
  /**
190
268
  * Verify an agent-to-agent token.
191
269
  *