passcontrol 0.6.0 → 0.6.2

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/sidecar.mjs CHANGED
@@ -1,9 +1,28 @@
1
1
  import http from "node:http";
2
+ import net from "node:net";
2
3
  import { Readable } from "node:stream";
3
- import { bareGatewayOrigin, fail, ok, step } from "./config.mjs";
4
+ import { bareGatewayOrigin, fail, ok, step, warn } from "./config.mjs";
5
+ import { classifyConnect, classifyProxyRequest, isLoopbackBindHost } from "./proxy-policy.mjs";
4
6
  import { createVisaClient } from "./visa-client.mjs";
5
7
 
6
- const STRIP_REQ = new Set(["authorization", "x-api-key", "host", "content-length", "accept-encoding", "connection"]);
8
+ // Hop-by-hop headers plus the ones the sidecar rebuilds itself. `proxy-connection`
9
+ // and friends only appear once something is used as a FORWARD proxy, which is
10
+ // what HTTP_PROXY/HTTPS_PROXY make this: they are addressed to the proxy and
11
+ // have no meaning upstream.
12
+ const STRIP_REQ = new Set([
13
+ "authorization",
14
+ "x-api-key",
15
+ "host",
16
+ "content-length",
17
+ "accept-encoding",
18
+ "connection",
19
+ "proxy-connection",
20
+ "keep-alive",
21
+ "te",
22
+ "trailer",
23
+ "upgrade",
24
+ "proxy-authenticate",
25
+ ]);
7
26
 
8
27
  // The set above is a denylist over header NAMES, and a denylist over names loses
9
28
  // to spelling. A client that was previously configured with a raw provider key
@@ -21,7 +40,72 @@ function isStripped(name) {
21
40
  }
22
41
  const STRIP_RES = new Set(["content-encoding", "content-length", "transfer-encoding", "connection"]);
23
42
 
24
- export function createSidecar({ gateway, passportId, passportSecret, port = 8788, host = "127.0.0.1", refreshSkewSeconds = 30 }) {
43
+ const STATUS_TEXT = { 400: "Bad Request", 403: "Forbidden", 502: "Bad Gateway" };
44
+
45
+ /**
46
+ * A header value is a single line of printable ASCII, always.
47
+ *
48
+ * The refusal text below interpolates a hostname the CLIENT chose. `proxy-policy`
49
+ * already refuses a hostname containing whitespace or a delimiter, so this is the
50
+ * second of two gates rather than the only one — but a header writer that can be
51
+ * handed a newline is a response-splitting bug, and one that can be handed a
52
+ * non-latin1 byte is a crash, so neither is left to the caller's good behaviour.
53
+ */
54
+ function headerSafe(value) {
55
+ return String(value ?? "").replace(/[^\x20-\x7e]/g, " ").slice(0, 512);
56
+ }
57
+
58
+ function refusalBody(verdict) {
59
+ return JSON.stringify({ error: verdict.code, message: verdict.message, help: verdict.help });
60
+ }
61
+
62
+ /**
63
+ * Refusals travel on five channels because clients surface wildly different
64
+ * subsets of them: a status code, a machine-readable code header, a one-line fix
65
+ * header, a JSON body for `curl -v`, and a line on the sidecar's own console.
66
+ * A CONNECT client typically shows only the status, so the console line is the
67
+ * one an operator can always read.
68
+ */
69
+ function refusalHeaders(verdict) {
70
+ return {
71
+ "content-type": "application/json",
72
+ "x-passcontrol-refusal": headerSafe(verdict.code),
73
+ "x-passcontrol-help": headerSafe(verdict.help),
74
+ connection: "close",
75
+ };
76
+ }
77
+
78
+ function writeRefusal(res, verdict) {
79
+ const body = refusalBody(verdict);
80
+ res.writeHead(verdict.status, { ...refusalHeaders(verdict), "content-length": Buffer.byteLength(body) });
81
+ res.end(body);
82
+ }
83
+
84
+ /** The same refusal, hand-rolled: a CONNECT is answered on the raw socket. */
85
+ function writeConnectRefusal(socket, verdict) {
86
+ if (socket.destroyed) return;
87
+ const body = refusalBody(verdict);
88
+ const head = [
89
+ `HTTP/1.1 ${verdict.status} ${STATUS_TEXT[verdict.status] ?? "Error"}`,
90
+ ...Object.entries({ ...refusalHeaders(verdict), "content-length": Buffer.byteLength(body) }).map(
91
+ ([k, v]) => `${k}: ${v}`
92
+ ),
93
+ "",
94
+ "",
95
+ ].join("\r\n");
96
+ socket.end(head + body);
97
+ }
98
+
99
+ export function createSidecar({
100
+ gateway,
101
+ passportId,
102
+ passportSecret,
103
+ port = 8788,
104
+ host = "127.0.0.1",
105
+ refreshSkewSeconds = 30,
106
+ allowConnectHosts = [],
107
+ onRefusal = (verdict) => warn(`${verdict.code}: ${verdict.message} → ${verdict.help}`),
108
+ }) {
25
109
  // The upstream URL below is built from this, not from the argument: the
26
110
  // sidecar forwards a bearer visa on every proxied request, so its destination
27
111
  // is part of the credential's security rather than a formatting detail.
@@ -34,6 +118,13 @@ export function createSidecar({ gateway, passportId, passportSecret, port = 8788
34
118
  missingVisaMessage: "challenge returned no visa",
35
119
  });
36
120
 
121
+ // Used only to print the governed base URL back in a refusal. Read from the
122
+ // live listener when there is one so the advice names the port actually bound.
123
+ const localBaseUrl = () => {
124
+ const address = server?.listening ? server.address() : null;
125
+ return `http://${host}:${address?.port ?? port}`;
126
+ };
127
+
37
128
  function readBody(req) {
38
129
  return new Promise((resolve, reject) => {
39
130
  const chunks = [];
@@ -43,14 +134,14 @@ export function createSidecar({ gateway, passportId, passportSecret, port = 8788
43
134
  });
44
135
  }
45
136
 
46
- async function fetchUpstream(req, body, visa) {
137
+ async function fetchUpstream(req, path, body, visa) {
47
138
  const headers = {};
48
139
  for (const [k, v] of Object.entries(req.headers)) {
49
140
  if (!isStripped(k) && typeof v === "string") headers[k] = v;
50
141
  }
51
142
  headers["authorization"] = `Bearer ${visa}`;
52
143
  headers["accept-encoding"] = "identity";
53
- return fetch(`${origin}${req.url}`, { method: req.method, headers, body: body ?? undefined });
144
+ return fetch(`${origin}${path}`, { method: req.method, headers, body: body ?? undefined });
54
145
  }
55
146
 
56
147
  function writeResponse(res, upstream) {
@@ -64,9 +155,19 @@ export function createSidecar({ gateway, passportId, passportSecret, port = 8788
64
155
  }
65
156
 
66
157
  const server = http.createServer(async (req, res) => {
158
+ // Judge the destination before reading the body: a refused host should not
159
+ // get to make the sidecar buffer megabytes on its way to a 403.
160
+ const verdict = classifyProxyRequest({ url: req.url, gatewayOrigin: origin, localBaseUrl: localBaseUrl() });
161
+ if (!verdict.allow) {
162
+ req.resume();
163
+ onRefusal(verdict);
164
+ writeRefusal(res, verdict);
165
+ return;
166
+ }
167
+
67
168
  try {
68
169
  const body = await readBody(req);
69
- const upstream = await visas.fetchWithVisa((visa) => fetchUpstream(req, body, visa));
170
+ const upstream = await visas.fetchWithVisa((visa) => fetchUpstream(req, verdict.path, body, visa));
70
171
  writeResponse(res, upstream);
71
172
  } catch (e) {
72
173
  if (!res.headersSent) {
@@ -78,17 +179,89 @@ export function createSidecar({ gateway, passportId, passportSecret, port = 8788
78
179
  }
79
180
  });
80
181
 
182
+ // `CONNECT host:port` — what every client with HTTPS_PROXY set sends first.
183
+ // PassControl cannot govern what it cannot read, and it deliberately does not
184
+ // terminate TLS to make it readable, so a provider target is refused here
185
+ // rather than tunnelled into a call that is ungoverned while looking governed.
186
+ server.on("connect", (req, clientSocket, head) => {
187
+ clientSocket.on("error", () => {});
188
+
189
+ const verdict = classifyConnect({
190
+ target: req.url,
191
+ gatewayOrigin: origin,
192
+ allowHosts: allowConnectHosts,
193
+ localBaseUrl: localBaseUrl(),
194
+ });
195
+ if (!verdict.allow) {
196
+ onRefusal(verdict);
197
+ writeConnectRefusal(clientSocket, verdict);
198
+ return;
199
+ }
200
+
201
+ let established = false;
202
+ const upstream = net.connect(verdict.port, verdict.hostname, () => {
203
+ established = true;
204
+ clientSocket.write("HTTP/1.1 200 Connection Established\r\n\r\n");
205
+ if (head?.length) upstream.write(head);
206
+ upstream.pipe(clientSocket);
207
+ clientSocket.pipe(upstream);
208
+ });
209
+ upstream.on("error", () => {
210
+ if (established) {
211
+ clientSocket.destroy();
212
+ return;
213
+ }
214
+ writeConnectRefusal(clientSocket, {
215
+ status: 502,
216
+ code: "tunnel_unreachable",
217
+ message: `PassControl could not open a tunnel to ${verdict.hostname}.`,
218
+ help: "Check that the host is reachable from this machine.",
219
+ });
220
+ });
221
+ clientSocket.on("close", () => upstream.destroy());
222
+ });
223
+
81
224
  return { server, getVisa: visas.getVisa };
82
225
  }
83
226
 
227
+ /**
228
+ * Bind guard.
229
+ *
230
+ * The sidecar holds the passport and mints a visa for whoever connects, so a
231
+ * listener reachable off-host hands the agent's scope and budget to anyone who
232
+ * can route to it. Loopback is the default and a non-loopback bind is an
233
+ * explicit, named opt-in rather than a config value that quietly widens it.
234
+ */
235
+ export function assertBindHost(host, allowNonLoopback = false) {
236
+ if (isLoopbackBindHost(host) || allowNonLoopback) return host;
237
+ throw new Error(
238
+ `Refusing to bind the sidecar to ${host}: it is not a loopback address. The sidecar mints work-visas for ` +
239
+ "anything that connects to it, so a non-loopback bind exposes your agent's scope and budget to the " +
240
+ "network. Pass allowNonLoopback only if the listener is protected by something else."
241
+ );
242
+ }
243
+
84
244
  export function startSidecar(opts) {
85
- const { gateway, port = 8788, host = "127.0.0.1" } = opts;
245
+ const { gateway, port = 8788, host = "127.0.0.1", allowNonLoopback = false, allowConnectHosts = [] } = opts;
246
+ assertBindHost(host, allowNonLoopback);
86
247
  const { server, getVisa } = createSidecar(opts);
87
248
  server.listen(port, host, () => {
88
249
  step(`PassControl visa sidecar forwarding to ${gateway}`);
89
250
  step(`Listening on http://${host}:${port}`);
90
251
  step(`Point your agent at: http://${host}:${port}/api/v1/anthropic (or /api/v1/openai)`);
91
- step("API key = anything (ignored). Visa is minted + refreshed automatically.\n");
252
+ step("API key = anything (ignored). Visa is minted + refreshed automatically.");
253
+ // Said at startup rather than only in a refusal, because the whole point of
254
+ // HTTPS_PROXY is that nobody reads the docs first.
255
+ step("HTTPS_PROXY: CONNECT to a provider is refused, not tunnelled — PassControl cannot");
256
+ step("govern TLS it does not terminate, and does not install an intercepting CA.");
257
+ // Always printed, including when empty. An egress exception the operator
258
+ // cannot see is one they cannot audit, and this list is exactly the thing a
259
+ // checked-in config file used to be able to extend without saying so.
260
+ step(
261
+ allowConnectHosts.length
262
+ ? `CONNECT allowlist: ${allowConnectHosts.join(", ")} (provider hosts are never eligible).\n`
263
+ : "CONNECT allowlist: none — only the gateway.\n"
264
+ );
92
265
  getVisa()
93
266
  .then(() => ok("visa warmed"))
94
267
  .catch((e) => fail(`could not mint initial visa: ${e.message}`));
@@ -0,0 +1,169 @@
1
+ // "There is a newer PassControl" — the one outbound call this CLI makes on its
2
+ // own initiative, and the constraints that come with that.
3
+ //
4
+ // This is a credential tool. A registry lookup nobody asked for is the kind of
5
+ // thing a security reviewer finds and writes up, so every guard below exists to
6
+ // make the behaviour predictable rather than clever:
7
+ //
8
+ // * It never blocks. The check is fire-and-forget with a short timeout; a
9
+ // registry outage must not add a second to `passcontrol call`.
10
+ // * TTY only. If stdout is not a terminal there is no human to read a notice,
11
+ // which means an agent run, a CI job or a piped command never phones npm.
12
+ // * Never under --json. A notice on stdout would corrupt the document.
13
+ // * Opt-out honoured: PASSCONTROL_NO_UPDATE_CHECK, and NO_UPDATE_NOTIFIER
14
+ // because that is the variable people already set for this class of tool.
15
+ // * Cached for a day in the config directory, so the frequency is bounded by
16
+ // wall-clock time rather than by how often the CLI is run.
17
+ //
18
+ // It reports only that a newer version exists. It never downloads, installs or
19
+ // runs anything — upgrading stays a thing the operator types.
20
+ import fs from "node:fs";
21
+ import os from "node:os";
22
+ import path from "node:path";
23
+
24
+ export const REGISTRY_URL = "https://registry.npmjs.org/passcontrol/latest";
25
+ export const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
26
+
27
+ /** Beside the existing config and app.json, and created with the same 0700. */
28
+ export function updateCachePath(env = process.env) {
29
+ const base = env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
30
+ return path.join(base, "passcontrol", "update-check.json");
31
+ }
32
+
33
+ /**
34
+ * Compare two versions numerically, segment by segment.
35
+ *
36
+ * A string compare gets this wrong the moment a segment reaches double digits
37
+ * ("0.10.0" < "0.9.0"), which is precisely when an update notice starts to
38
+ * matter. Anything with a prerelease suffix is treated as NOT newer: someone
39
+ * running 0.7.0-rc.1 asked for it and should not be nagged back to 0.6.1.
40
+ */
41
+ export function isNewer(candidate, current) {
42
+ const parse = (value) => {
43
+ const match = /^(\d+)\.(\d+)\.(\d+)$/u.exec(String(value ?? "").trim());
44
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
45
+ };
46
+ const a = parse(candidate);
47
+ const b = parse(current);
48
+ if (!a || !b) return false;
49
+ for (let i = 0; i < 3; i += 1) {
50
+ if (a[i] !== b[i]) return a[i] > b[i];
51
+ }
52
+ return false;
53
+ }
54
+
55
+ // Two gates, and keeping them apart is load-bearing.
56
+ //
57
+ // They answer different questions — "may anything be printed?" and "may the
58
+ // network be touched?" — and a single predicate collapsing both got this
59
+ // wrong: a fresh cache made the combined check return false for the SAME
60
+ // reason a pipe did, so the cached-notice fallback happily printed a notice
61
+ // into a --json document and into piped output. Caught by running it, not by
62
+ // the unit test that asserted the non-TTY case against an empty cache.
63
+
64
+ /** May a notice be shown at all? Nothing here is about time or the network. */
65
+ export function mayAnnounce({ isTty, json = false, env = process.env } = {}) {
66
+ if (!isTty) return false;
67
+ if (json) return false;
68
+ if (env.PASSCONTROL_NO_UPDATE_CHECK || env.NO_UPDATE_NOTIFIER) return false;
69
+ if (env.CI) return false;
70
+ return true;
71
+ }
72
+
73
+ /** May we ask the registry again, or is the cached answer still fresh? */
74
+ export function shouldFetch({ now = Date.now(), cache = null, ttlMs = CACHE_TTL_MS } = {}) {
75
+ if (cache && typeof cache.checkedAt === "number" && now - cache.checkedAt < ttlMs) return false;
76
+ return true;
77
+ }
78
+
79
+ /** Both gates together: check the registry now? */
80
+ export function shouldCheck({
81
+ isTty,
82
+ json = false,
83
+ env = process.env,
84
+ now = Date.now(),
85
+ cache = null,
86
+ ttlMs = CACHE_TTL_MS,
87
+ } = {}) {
88
+ return mayAnnounce({ isTty, json, env }) && shouldFetch({ now, cache, ttlMs });
89
+ }
90
+
91
+ export function readCache(file) {
92
+ try {
93
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
94
+ return parsed && typeof parsed === "object" ? parsed : null;
95
+ } catch {
96
+ // A missing or corrupt cache means "check again", never a crash.
97
+ return null;
98
+ }
99
+ }
100
+
101
+ export function writeCache(file, data) {
102
+ try {
103
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
104
+ fs.writeFileSync(file, `${JSON.stringify(data)}\n`, { mode: 0o600 });
105
+ } catch {
106
+ // An unwritable config dir costs a repeat check, nothing more.
107
+ }
108
+ }
109
+
110
+ /** The notice itself, or null when there is nothing worth saying. */
111
+ export function updateNotice(current, latest) {
112
+ if (!isNewer(latest, current)) return null;
113
+ return `Update available ${current} → ${latest} npm install -g passcontrol@latest`;
114
+ }
115
+
116
+ /**
117
+ * Look up the latest published version. Resolves to null on ANY failure —
118
+ * offline, DNS, a 500, a slow registry, malformed JSON. There is no error path
119
+ * a user should ever see from a background nicety.
120
+ */
121
+ export async function fetchLatest(url = REGISTRY_URL, timeoutMs = 1500, fetchImpl = fetch) {
122
+ const controller = new AbortController();
123
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
124
+ try {
125
+ const res = await fetchImpl(url, {
126
+ signal: controller.signal,
127
+ headers: { accept: "application/vnd.npm.install-v1+json" },
128
+ });
129
+ if (!res.ok) return null;
130
+ const body = await res.json();
131
+ const version = body?.version;
132
+ return typeof version === "string" ? version : null;
133
+ } catch {
134
+ return null;
135
+ } finally {
136
+ clearTimeout(timer);
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Run the check and return the notice to print, or null.
142
+ *
143
+ * The caller decides WHEN to print it — after the command's own output, so a
144
+ * nicety never pushes the thing the operator ran off the top of the screen.
145
+ */
146
+ export async function checkForUpdate({
147
+ current,
148
+ isTty = Boolean(process.stdout.isTTY),
149
+ json = false,
150
+ env = process.env,
151
+ now = Date.now(),
152
+ file = updateCachePath(env),
153
+ fetchLatestImpl = fetchLatest,
154
+ } = {}) {
155
+ // Display gate FIRST, and it short-circuits everything: no cache read, no
156
+ // network, no notice. Under --json or a pipe this function does nothing at all.
157
+ if (!mayAnnounce({ isTty, json, env })) return null;
158
+
159
+ const cache = readCache(file);
160
+ if (!shouldFetch({ now, cache })) {
161
+ // Inside the daily window a cached answer is still worth showing — the TTL
162
+ // bounds the network call, not the notice, or an update discovered a minute
163
+ // ago would go unmentioned for the rest of the day.
164
+ return typeof cache?.latest === "string" ? updateNotice(current, cache.latest) : null;
165
+ }
166
+ const latest = await fetchLatestImpl();
167
+ writeCache(file, { checkedAt: now, latest: latest ?? cache?.latest ?? null });
168
+ return latest ? updateNotice(current, latest) : null;
169
+ }
package/cli/verify.mjs CHANGED
@@ -7,10 +7,13 @@
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
11
 
11
12
  export const RECEIPT_TYP = "passcontrol-receipt+jwt";
12
13
  export const AGENT_TOKEN_TYP = "passcontrol-agent+jwt";
13
- export const SUPPORTED_VER = 1;
14
+ // Receipts v2 add Direct Agent identity claims. This is a maximum, not an
15
+ // equality check: v1 receipts remain independently verifiable forever.
16
+ export const SUPPORTED_VER = RECEIPT_PROTOCOL.maximum;
14
17
 
15
18
  const fromB64url = (value) =>
16
19
  new Uint8Array(Buffer.from(String(value).replace(/-/g, "+").replace(/_/g, "/"), "base64"));
@@ -0,0 +1,24 @@
1
+ // Import reporting is shared as a tiny pure module so the CLI's terminal
2
+ // branch is tested as behaviour, not merely as a source-text string. In
3
+ // particular, a file whose agents were all REFUSED must never print the
4
+ // reassuring message reserved for a workspace that already owns every agent.
5
+
6
+ export function noAgentCreateMessage(agents) {
7
+ const rejected = Array.isArray(agents?.rejected) ? agents.rejected.length : 0;
8
+ const skipped = Array.isArray(agents?.skipped) ? agents.skipped.length : 0;
9
+
10
+ if (rejected > 0) {
11
+ return `Nothing was created. ${rejected} agent(s) were refused; review the reasons above before retrying.`;
12
+ }
13
+ if (skipped > 0) {
14
+ return "Nothing to create. The workspace already holds every agent in this file.";
15
+ }
16
+ return "Nothing to create.";
17
+ }
18
+
19
+ export function importCompletionMessage(report) {
20
+ const created = Array.isArray(report?.agents?.created) ? report.agents.created.length : 0;
21
+ return report?.complete === false
22
+ ? `Import completed partially: ${created} agent(s) created; review the refused entries above.`
23
+ : `Created ${created} agent(s).`;
24
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "passcontrol",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
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/control.d.ts CHANGED
@@ -70,9 +70,16 @@ export declare class ControlClient {
70
70
  }>;
71
71
  };
72
72
  readonly logs: {
73
+ /**
74
+ * `class` selects a view, never a different record: omitted returns every
75
+ * call, `inference` drops SDK housekeeping (startup model-listing probes),
76
+ * `housekeeping` returns only those. The limit is applied before the
77
+ * filter, so a filtered page can be shorter than the limit asked for.
78
+ */
73
79
  list: (params?: {
74
80
  agent_id?: string;
75
81
  status?: string;
82
+ class?: "inference" | "housekeeping";
76
83
  limit?: number;
77
84
  }) => Promise<any[]>;
78
85
  };
package/sdk/control.js CHANGED
@@ -87,6 +87,12 @@ export class ControlClient {
87
87
  revoke: (id, opts) => this.req("DELETE", `/agents/${encodeURIComponent(id)}`, { idempotencyKey: opts?.idempotencyKey }),
88
88
  };
89
89
  logs = {
90
+ /**
91
+ * `class` selects a view, never a different record: omitted returns every
92
+ * call, `inference` drops SDK housekeeping (startup model-listing probes),
93
+ * `housekeeping` returns only those. The limit is applied before the
94
+ * filter, so a filtered page can be shorter than the limit asked for.
95
+ */
90
96
  list: (params) => this.req("GET", "/logs", { query: params }),
91
97
  };
92
98
  audit = {
@@ -1,4 +1,4 @@
1
- export type ProviderId = "openai" | "anthropic" | "groq" | "mistral" | "together" | "deepseek";
1
+ export type ProviderId = "openai" | "anthropic" | "groq" | "mistral" | "together" | "deepseek" | "gemini";
2
2
  export interface PassControlOptions {
3
3
  /**
4
4
  * Gateway origin, e.g. https://passcontrol.example.com — scheme, host and
package/sdk/verify.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export declare const RECEIPT_TYP = "passcontrol-receipt+jwt";
2
2
  export declare const AGENT_TOKEN_TYP = "passcontrol-agent+jwt";
3
3
  /** The newest artifact version this verifier understands. */
4
- export declare const SUPPORTED_VER = 2;
4
+ export declare const SUPPORTED_VER: number;
5
5
  export type VerifyFailure = "malformed" | "untrusted_issuer" | "unknown_key" | "bad_signature" | "wrong_type" | "unsupported_version" | "jwks_unreachable" | "expired" | "wrong_audience" | "revoked" | "status_unavailable";
6
6
  export type VerifyResult<T> = {
7
7
  ok: true;
@@ -44,9 +44,20 @@ export interface ReceiptClaims {
44
44
  dig: string;
45
45
  len: number;
46
46
  };
47
+ /**
48
+ * Tokens the call consumed. `in` is the provider's own uncached input count;
49
+ * `cr` / `cw` are prompt-cache reads and writes, present only when the provider
50
+ * reported them, so the whole input is `in + (cr ?? 0) + (cw ?? 0)`. Do not sum
51
+ * them into `in` — it is already exclusive of both, and `cost` covers all three.
52
+ *
53
+ * Added after v2 shipped and readable by verifiers that predate them, because
54
+ * unknown claims inside a supported version are ignored by design.
55
+ */
47
56
  use: {
48
57
  in: number;
49
58
  out: number;
59
+ cr?: number;
60
+ cw?: number;
50
61
  };
51
62
  cost: number;
52
63
  res: {
package/sdk/verify.js CHANGED
@@ -8,10 +8,11 @@
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
12
  export const RECEIPT_TYP = "passcontrol-receipt+jwt";
12
13
  export const AGENT_TOKEN_TYP = "passcontrol-agent+jwt";
13
14
  /** The newest artifact version this verifier understands. */
14
- export const SUPPORTED_VER = 2;
15
+ export const SUPPORTED_VER = RECEIPT_PROTOCOL.maximum;
15
16
  const b64urlToBytes = (value) => {
16
17
  const b64 = value.replace(/-/g, "+").replace(/_/g, "/");
17
18
  const pad = b64.length % 4 === 0 ? "" : "=".repeat(4 - (b64.length % 4));