passcontrol 1.2.1 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/bin/passcontrol.mjs +397 -18
- package/cli/budget-format.mjs +76 -0
- package/cli/claude-code.mjs +160 -0
- package/cli/codex.mjs +102 -0
- package/cli/config.mjs +3 -3
- package/cli/declared-session.mjs +33 -0
- package/cli/integration-defaults.d.mts +1 -0
- package/cli/integration-defaults.mjs +5 -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 +3 -0
- package/cli/presets.mjs +15 -5
- package/cli/protocols.d.mts +2 -0
- package/cli/protocols.mjs +14 -0
- package/cli/proxy-policy.mjs +1 -0
- package/cli/sidecar.mjs +93 -5
- package/cli/statusline.mjs +89 -0
- package/cli/verify.mjs +215 -5
- package/package.json +2 -2
- package/sdk/README.md +1 -1
- package/sdk/passcontrol.d.ts +1 -1
- package/sdk/verify.d.ts +108 -0
- package/sdk/verify.js +219 -1
package/cli/sidecar.mjs
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
1
2
|
import http from "node:http";
|
|
2
3
|
import net from "node:net";
|
|
3
4
|
import { Readable } from "node:stream";
|
|
4
5
|
import { bareGatewayOrigin, fail, ok, step, warn } from "./config.mjs";
|
|
5
6
|
import { classifyConnect, classifyProxyRequest, isLoopbackBindHost } from "./proxy-policy.mjs";
|
|
6
7
|
import { createVisaClient } from "./visa-client.mjs";
|
|
8
|
+
import { declaredSession } from "./declared-session.mjs";
|
|
9
|
+
import { defaultJournalDir, openJournal } from "./journal.mjs";
|
|
7
10
|
|
|
8
11
|
// Hop-by-hop headers plus the ones the sidecar rebuilds itself. `proxy-connection`
|
|
9
12
|
// and friends only appear once something is used as a FORWARD proxy, which is
|
|
@@ -107,6 +110,11 @@ export function createSidecar({
|
|
|
107
110
|
refreshSkewSeconds = 30,
|
|
108
111
|
allowConnectHosts = [],
|
|
109
112
|
onRefusal = (verdict) => warn(`${verdict.code}: ${verdict.message} → ${verdict.help}`),
|
|
113
|
+
// This run's id: stamped on every forwarded request as `x-passcontrol-run`, the
|
|
114
|
+
// fallback session for a client that declares none (lib/client-lineage.ts).
|
|
115
|
+
runId = randomUUID(),
|
|
116
|
+
// cli/journal.mjs, or null for `--no-journal`.
|
|
117
|
+
journal = null,
|
|
110
118
|
}) {
|
|
111
119
|
// The upstream URL below is built from this, not from the argument: the
|
|
112
120
|
// sidecar forwards a bearer visa on every proxied request, so its destination
|
|
@@ -143,6 +151,8 @@ export function createSidecar({
|
|
|
143
151
|
if (!isStripped(k) && typeof v === "string") headers[k] = v;
|
|
144
152
|
}
|
|
145
153
|
headers["authorization"] = `Bearer ${visa}`;
|
|
154
|
+
// Set after the copy, so a client cannot name the run: only the sidecar can.
|
|
155
|
+
headers["x-passcontrol-run"] = runId;
|
|
146
156
|
headers["x-passcontrol-proof"] = visas.createProof(visa, req.method, new URL(path, origin));
|
|
147
157
|
headers["accept-encoding"] = "identity";
|
|
148
158
|
return fetch(`${origin}${path}`, { method: req.method, headers, body: body ?? undefined });
|
|
@@ -155,7 +165,19 @@ export function createSidecar({
|
|
|
155
165
|
// URL — codeload for an archive download — passes through untouched.
|
|
156
166
|
const toLocal = (value) => value.split(`${origin}/api/v1/`).join(`${localBaseUrl()}/api/v1/`);
|
|
157
167
|
|
|
158
|
-
function writeResponse(res, upstream) {
|
|
168
|
+
function writeResponse(res, upstream, reqHeaders) {
|
|
169
|
+
// At the headers, not at the end of the body: a streamed call whose client
|
|
170
|
+
// disconnects mid-stream still produced a receipt, and the user's record of
|
|
171
|
+
// it must not depend on how long they kept reading. With the session the call
|
|
172
|
+
// declared, read as the gateway reads it, so a seal is checked against its own.
|
|
173
|
+
journal?.record(
|
|
174
|
+
upstream.headers.get("x-passcontrol-receipt-id"),
|
|
175
|
+
upstream.status,
|
|
176
|
+
declaredSession((name) => {
|
|
177
|
+
const v = reqHeaders?.[name];
|
|
178
|
+
return Array.isArray(v) ? v[0] : v;
|
|
179
|
+
}, runId)
|
|
180
|
+
);
|
|
159
181
|
const outHeaders = {};
|
|
160
182
|
upstream.headers.forEach((v, k) => {
|
|
161
183
|
const name = k.toLowerCase();
|
|
@@ -181,7 +203,53 @@ export function createSidecar({
|
|
|
181
203
|
try {
|
|
182
204
|
const body = await readBody(req);
|
|
183
205
|
const upstream = await visas.fetchWithVisa((visa) => fetchUpstream(req, verdict.path, body, visa));
|
|
184
|
-
writeResponse(res, upstream);
|
|
206
|
+
writeResponse(res, upstream, req.headers);
|
|
207
|
+
} catch (e) {
|
|
208
|
+
if (!res.headersSent) {
|
|
209
|
+
res.writeHead(502, { "content-type": "application/json" });
|
|
210
|
+
res.end(JSON.stringify({ error: "sidecar_upstream_error", message: e.message }));
|
|
211
|
+
} else {
|
|
212
|
+
res.end();
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
// ── The Ollama listener (1.3.0 #3) ────────────────────────────────────────
|
|
218
|
+
//
|
|
219
|
+
// For apps that only take OLLAMA_HOST, which is host:port with no path. Every
|
|
220
|
+
// request on this port is the gateway's `local` provider: `/api/chat` becomes
|
|
221
|
+
// `/api/v1/local/api/chat`, and the OpenAI-compatible `/v1/...` paths map the
|
|
222
|
+
// same way. Its own port, so the main listener's forward-proxy handling is
|
|
223
|
+
// untouched; an absolute-form request (a proxy request for another host) is
|
|
224
|
+
// refused here rather than becoming a governed local call.
|
|
225
|
+
//
|
|
226
|
+
// The path is normalised by the URL parser BEFORE the prefix is added, so a
|
|
227
|
+
// `..` segment (encoded or not) resolves inside it and cannot carry the visa
|
|
228
|
+
// to another gateway route. The health probe (`/`, which the ollama CLI HEADs)
|
|
229
|
+
// is not answered here: it goes to the gateway as `/api/version`, so an app
|
|
230
|
+
// sees the gateway's real answer, including a refusal where `local` is off.
|
|
231
|
+
const ollamaServer = http.createServer(async (req, res) => {
|
|
232
|
+
if (!String(req.url ?? "").startsWith("/")) {
|
|
233
|
+
req.resume();
|
|
234
|
+
res.writeHead(400, { "content-type": "application/json" });
|
|
235
|
+
res.end(JSON.stringify({ error: "ollama_listener_absolute_form", message: "This port serves Ollama's API for the local provider only; it is not a proxy." }));
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
const url = new URL(req.url, "http://ollama.invalid");
|
|
239
|
+
const probe = url.pathname === "/";
|
|
240
|
+
const mapped = `/api/v1/local${probe ? "/api/version" : url.pathname}${probe ? "" : url.search}`;
|
|
241
|
+
const method = probe ? "GET" : req.method;
|
|
242
|
+
try {
|
|
243
|
+
const body = probe ? null : await readBody(req);
|
|
244
|
+
if (probe) req.resume();
|
|
245
|
+
const upstream = await visas.fetchWithVisa((visa) => fetchUpstream({ method, headers: req.headers }, mapped, body, visa));
|
|
246
|
+
if (req.method === "HEAD") {
|
|
247
|
+
res.writeHead(upstream.status);
|
|
248
|
+
res.end();
|
|
249
|
+
await upstream.body?.cancel().catch(() => {});
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
writeResponse(res, upstream, req.headers);
|
|
185
253
|
} catch (e) {
|
|
186
254
|
if (!res.headersSent) {
|
|
187
255
|
res.writeHead(502, { "content-type": "application/json" });
|
|
@@ -234,7 +302,7 @@ export function createSidecar({
|
|
|
234
302
|
clientSocket.on("close", () => upstream.destroy());
|
|
235
303
|
});
|
|
236
304
|
|
|
237
|
-
return { server, getVisa: visas.getVisa };
|
|
305
|
+
return { server, ollamaServer, getVisa: visas.getVisa, runId };
|
|
238
306
|
}
|
|
239
307
|
|
|
240
308
|
/**
|
|
@@ -255,14 +323,34 @@ export function assertBindHost(host, allowNonLoopback = false) {
|
|
|
255
323
|
}
|
|
256
324
|
|
|
257
325
|
export function startSidecar(opts) {
|
|
258
|
-
const { gateway, port = 8788, host = "127.0.0.1", allowNonLoopback = false, allowConnectHosts = [] } = opts;
|
|
326
|
+
const { gateway, port = 8788, host = "127.0.0.1", allowNonLoopback = false, allowConnectHosts = [], ollamaPort = null } = opts;
|
|
259
327
|
assertBindHost(host, allowNonLoopback);
|
|
260
|
-
const
|
|
328
|
+
const runId = randomUUID();
|
|
329
|
+
// On unless the operator said --no-journal (D3). See cli/journal.mjs.
|
|
330
|
+
const journal = opts.noJournal
|
|
331
|
+
? null
|
|
332
|
+
: openJournal({
|
|
333
|
+
dir: opts.journalDir ?? defaultJournalDir(),
|
|
334
|
+
runId,
|
|
335
|
+
onError: (e) =>
|
|
336
|
+
warn(`journal: could not write ${journal.path} (${e.message}). Calls are unaffected; this run is no longer being recorded.`),
|
|
337
|
+
});
|
|
338
|
+
const { server, ollamaServer, getVisa } = createSidecar({ ...opts, runId, journal });
|
|
339
|
+
if (ollamaPort != null) {
|
|
340
|
+
ollamaServer.listen(ollamaPort, host, () => {
|
|
341
|
+
step(`Ollama API (local models) on http://${host}:${ollamaPort}: set OLLAMA_HOST=${host}:${ollamaPort}`);
|
|
342
|
+
});
|
|
343
|
+
}
|
|
261
344
|
server.listen(port, host, () => {
|
|
262
345
|
step(`PassControl visa sidecar forwarding to ${gateway}`);
|
|
263
346
|
step(`Listening on http://${host}:${port}`);
|
|
264
347
|
step(`Point your agent at: http://${host}:${port}/api/v1/anthropic (or /api/v1/openai)`);
|
|
265
348
|
step("API key = anything (ignored). Visa is minted + refreshed automatically.");
|
|
349
|
+
step(
|
|
350
|
+
journal
|
|
351
|
+
? `Journal: ${journal.path} (receipt ids, times, statuses and declared sessions only; --no-journal turns it off)`
|
|
352
|
+
: "Journal: off (--no-journal). Session seals cannot be checked against this run."
|
|
353
|
+
);
|
|
266
354
|
// Said at startup rather than only in a refusal, because the whole point of
|
|
267
355
|
// HTTPS_PROXY is that nobody reads the docs first.
|
|
268
356
|
step("HTTPS_PROXY: CONNECT to a provider is refused, not tunnelled — PassControl cannot");
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// `passcontrol statusline`: the agent's budget as one line in Claude Code's status
|
|
2
|
+
// line (1.4.0 candidate 2).
|
|
3
|
+
//
|
|
4
|
+
// Claude Code runs the command after every assistant message, debounced 300ms, and
|
|
5
|
+
// cancels a run still going when the next one starts (code.claude.com/docs/en/statusline,
|
|
6
|
+
// read 2026-10-08). So:
|
|
7
|
+
// * a good answer is cached for TTL_MS and reused, so a busy session asks the
|
|
8
|
+
// gateway a few times a minute rather than every message;
|
|
9
|
+
// * it asks through the running sidecar, which already holds a warm visa: minting
|
|
10
|
+
// a visa per run would spend the passport's challenge allowance (20 a window),
|
|
11
|
+
// the same allowance the sidecar refreshes from;
|
|
12
|
+
// * it never throws. Every outcome is one line, and the caller exits 0.
|
|
13
|
+
// Only a good answer is cached. A failure is shown as the failure, never as an
|
|
14
|
+
// older budget that might read as current.
|
|
15
|
+
import fs from "node:fs";
|
|
16
|
+
import path from "node:path";
|
|
17
|
+
import { statusLine } from "./budget-format.mjs";
|
|
18
|
+
|
|
19
|
+
export const STATUSLINE_TTL_MS = 20_000;
|
|
20
|
+
const TIMEOUT_MS = 1_500;
|
|
21
|
+
|
|
22
|
+
function readCache(file, nowMs, ttlMs) {
|
|
23
|
+
try {
|
|
24
|
+
const cached = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
25
|
+
if (typeof cached?.line === "string" && typeof cached.at === "number" && nowMs - cached.at >= 0 && nowMs - cached.at < ttlMs) {
|
|
26
|
+
return cached.line;
|
|
27
|
+
}
|
|
28
|
+
} catch {
|
|
29
|
+
// No cache, or an unreadable one: ask.
|
|
30
|
+
}
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function writeCache(file, nowMs, line) {
|
|
35
|
+
try {
|
|
36
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
37
|
+
fs.writeFileSync(file, JSON.stringify({ at: nowMs, line }), { mode: 0o600 });
|
|
38
|
+
fs.chmodSync(file, 0o600);
|
|
39
|
+
} catch {
|
|
40
|
+
// A cache that cannot be written only costs the next run a request.
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The line to print. Never throws. */
|
|
45
|
+
export async function statuslineText({
|
|
46
|
+
port,
|
|
47
|
+
host = "127.0.0.1",
|
|
48
|
+
cacheFile,
|
|
49
|
+
now = () => Date.now(),
|
|
50
|
+
fetch: fetchImpl = globalThis.fetch,
|
|
51
|
+
timeoutMs = TIMEOUT_MS,
|
|
52
|
+
ttlMs = STATUSLINE_TTL_MS,
|
|
53
|
+
}) {
|
|
54
|
+
const cached = readCache(cacheFile, now(), ttlMs);
|
|
55
|
+
if (cached) return cached;
|
|
56
|
+
|
|
57
|
+
const controller = new AbortController();
|
|
58
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
59
|
+
try {
|
|
60
|
+
let response;
|
|
61
|
+
try {
|
|
62
|
+
response = await fetchImpl(`http://${host}:${port}/api/v1/self`, {
|
|
63
|
+
headers: { accept: "application/json" },
|
|
64
|
+
signal: controller.signal,
|
|
65
|
+
});
|
|
66
|
+
} catch {
|
|
67
|
+
return controller.signal.aborted
|
|
68
|
+
? "PassControl · no answer from the sidecar"
|
|
69
|
+
: `PassControl · sidecar not running on port ${port}`;
|
|
70
|
+
}
|
|
71
|
+
// The gateway's opaque refusal covers both a suspended agent and a kill switch.
|
|
72
|
+
if (response.status === 403) return "PassControl · agent stopped";
|
|
73
|
+
if (!response.ok) return `PassControl · unavailable (HTTP ${response.status})`;
|
|
74
|
+
let self;
|
|
75
|
+
try {
|
|
76
|
+
self = await response.json();
|
|
77
|
+
} catch {
|
|
78
|
+
return controller.signal.aborted ? "PassControl · no answer from the sidecar" : "PassControl · unreadable answer";
|
|
79
|
+
}
|
|
80
|
+
if (typeof self?.budget !== "object" || self.budget === null) return "PassControl · unreadable answer";
|
|
81
|
+
const line = statusLine(self);
|
|
82
|
+
writeCache(cacheFile, now(), line);
|
|
83
|
+
return line;
|
|
84
|
+
} catch {
|
|
85
|
+
return "PassControl · unavailable";
|
|
86
|
+
} finally {
|
|
87
|
+
clearTimeout(timer);
|
|
88
|
+
}
|
|
89
|
+
}
|
package/cli/verify.mjs
CHANGED
|
@@ -8,13 +8,16 @@
|
|
|
8
8
|
// the artifact and the issuer's origin. That is the whole point.
|
|
9
9
|
import { ed25519 } from "@noble/curves/ed25519";
|
|
10
10
|
import { sha256 } from "@noble/hashes/sha256";
|
|
11
|
-
import { RECEIPT_PROTOCOL, STATEMENT_PROTOCOL } from "./protocols.mjs";
|
|
11
|
+
import { RECEIPT_PROTOCOL, SESSION_PROTOCOL, STATEMENT_PROTOCOL } from "./protocols.mjs";
|
|
12
12
|
|
|
13
13
|
export const RECEIPT_TYP = "passcontrol-receipt+jwt";
|
|
14
14
|
export const AGENT_TOKEN_TYP = "passcontrol-agent+jwt";
|
|
15
15
|
export const STATEMENT_TYP = "passcontrol-statement+jws";
|
|
16
|
+
export const SESSION_TYP = "passcontrol-session+jws";
|
|
16
17
|
// Its own version line, separate from the receipt's — see protocols.mjs.
|
|
17
18
|
export const STATEMENT_SUPPORTED_VER = STATEMENT_PROTOCOL.maximum;
|
|
19
|
+
// Session seals: their own line too.
|
|
20
|
+
export const SESSION_SUPPORTED_VER = SESSION_PROTOCOL.maximum;
|
|
18
21
|
// Receipts v2 add Direct Agent identity claims. This is a maximum, not an
|
|
19
22
|
// equality check: v1 receipts remain independently verifiable forever.
|
|
20
23
|
export const SUPPORTED_VER = RECEIPT_PROTOCOL.maximum;
|
|
@@ -34,12 +37,15 @@ export function matchesIssuer(iss, trusted) {
|
|
|
34
37
|
return trusted.some((candidate) => strip(candidate) === strip(iss));
|
|
35
38
|
}
|
|
36
39
|
|
|
37
|
-
async function loadJwks(issuer, fetchImpl) {
|
|
40
|
+
async function loadJwks(issuer, fetchImpl, cache) {
|
|
41
|
+
if (cache?.has(issuer)) return cache.get(issuer);
|
|
38
42
|
try {
|
|
39
43
|
const res = await fetchImpl(new URL("/.well-known/jwks.json", issuer).toString());
|
|
40
44
|
if (!res.ok) return null;
|
|
41
45
|
const body = await res.json();
|
|
42
|
-
|
|
46
|
+
const keys = Array.isArray(body?.keys) ? body.keys : [];
|
|
47
|
+
cache?.set(issuer, keys);
|
|
48
|
+
return keys;
|
|
43
49
|
} catch {
|
|
44
50
|
return null;
|
|
45
51
|
}
|
|
@@ -59,7 +65,7 @@ async function loadJwks(issuer, fetchImpl) {
|
|
|
59
65
|
async function verifySigned(
|
|
60
66
|
token,
|
|
61
67
|
typ,
|
|
62
|
-
{ issuer, fetch: fetchImpl = fetch },
|
|
68
|
+
{ issuer, fetch: fetchImpl = fetch, jwksCache },
|
|
63
69
|
version = { claim: "ver", max: SUPPORTED_VER }
|
|
64
70
|
) {
|
|
65
71
|
const parts = String(token).split(".");
|
|
@@ -88,7 +94,7 @@ async function verifySigned(
|
|
|
88
94
|
return { ok: false, reason: "unsupported_version" };
|
|
89
95
|
}
|
|
90
96
|
|
|
91
|
-
const keys = await loadJwks(claims.iss, fetchImpl);
|
|
97
|
+
const keys = await loadJwks(claims.iss, fetchImpl, jwksCache);
|
|
92
98
|
if (!keys) return { ok: false, reason: "jwks_unreachable" };
|
|
93
99
|
|
|
94
100
|
const candidates = keys.filter(
|
|
@@ -184,6 +190,204 @@ export async function verifyAgentToken(token, options) {
|
|
|
184
190
|
return result;
|
|
185
191
|
}
|
|
186
192
|
|
|
193
|
+
// ── Session seals ────────────────────────────────────────────────────────────
|
|
194
|
+
|
|
195
|
+
/** Leaf and node hashing, the same domain separation as verifyInclusion above. */
|
|
196
|
+
function sessionHash(prefix, ...parts) {
|
|
197
|
+
const total = parts.reduce((sum, p) => sum + p.length, 1);
|
|
198
|
+
const buf = new Uint8Array(total);
|
|
199
|
+
buf[0] = prefix;
|
|
200
|
+
let at = 1;
|
|
201
|
+
for (const p of parts) {
|
|
202
|
+
buf.set(p, at);
|
|
203
|
+
at += p.length;
|
|
204
|
+
}
|
|
205
|
+
return sha256(buf);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** lib/merkle.ts's root: leaves in bundle order, an odd node promoted unchanged. */
|
|
209
|
+
function sessionRoot(bundle) {
|
|
210
|
+
if (bundle.length === 0) return null;
|
|
211
|
+
let level = bundle.map((jws) => sessionHash(0x00, new TextEncoder().encode(jws)));
|
|
212
|
+
while (level.length > 1) {
|
|
213
|
+
const next = [];
|
|
214
|
+
for (let i = 0; i < level.length; i += 2) {
|
|
215
|
+
next.push(level[i + 1] ? sessionHash(0x01, level[i], level[i + 1]) : level[i]);
|
|
216
|
+
}
|
|
217
|
+
level = next;
|
|
218
|
+
}
|
|
219
|
+
return Buffer.from(level[0]).toString("base64url");
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function decodePayload(jws) {
|
|
223
|
+
try {
|
|
224
|
+
const claims = decodeJson(String(jws).split(".")[1] ?? "");
|
|
225
|
+
return claims && typeof claims === "object" && !Array.isArray(claims) ? claims : null;
|
|
226
|
+
} catch {
|
|
227
|
+
return null;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : 0);
|
|
232
|
+
const orNull = (v) => (typeof v === "string" ? v : null);
|
|
233
|
+
|
|
234
|
+
/** Tree and model lists, compared as sets: one canonical string each. */
|
|
235
|
+
function canonical(entries, keys) {
|
|
236
|
+
if (!Array.isArray(entries)) return null;
|
|
237
|
+
return JSON.stringify(
|
|
238
|
+
entries
|
|
239
|
+
.map((e) => keys.map((k) => (k.text ? orNull(e?.[k.name]) : num(e?.[k.name]))))
|
|
240
|
+
.sort((a, b) => (JSON.stringify(a) < JSON.stringify(b) ? -1 : JSON.stringify(a) > JSON.stringify(b) ? 1 : 0))
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
const TREE_KEYS = [{ name: "agt", text: true }, { name: "par", text: true }, { name: "n" }, { name: "cost" }, { name: "refused" }];
|
|
244
|
+
const MODEL_KEYS = [{ name: "mdl", text: true }, { name: "n" }, { name: "cost" }];
|
|
245
|
+
|
|
246
|
+
/** What the bundle itself adds up to, from the receipts' own claims. */
|
|
247
|
+
function bundleTotals(decoded) {
|
|
248
|
+
const tree = new Map();
|
|
249
|
+
const models = new Map();
|
|
250
|
+
let cost = 0;
|
|
251
|
+
let unp = 0;
|
|
252
|
+
for (const c of decoded) {
|
|
253
|
+
if (!c) continue;
|
|
254
|
+
const ctx = c.ctx && typeof c.ctx === "object" ? c.ctx : {};
|
|
255
|
+
const agt = orNull(ctx.agt);
|
|
256
|
+
const par = orNull(ctx.par);
|
|
257
|
+
const refused = typeof c.res?.status === "string" && c.res.status.startsWith("blocked_") ? 1 : 0;
|
|
258
|
+
const key = JSON.stringify([agt, par]);
|
|
259
|
+
const node = tree.get(key) ?? { agt, par, n: 0, cost: 0, refused: 0 };
|
|
260
|
+
node.n += 1;
|
|
261
|
+
node.cost += num(c.cost);
|
|
262
|
+
node.refused += refused;
|
|
263
|
+
tree.set(key, node);
|
|
264
|
+
const mdl = orNull(c.mdl);
|
|
265
|
+
const m = models.get(JSON.stringify(mdl)) ?? { mdl, n: 0, cost: 0 };
|
|
266
|
+
m.n += 1;
|
|
267
|
+
m.cost += num(c.cost);
|
|
268
|
+
models.set(JSON.stringify(mdl), m);
|
|
269
|
+
cost += num(c.cost);
|
|
270
|
+
if (c.unp === true) unp += 1;
|
|
271
|
+
}
|
|
272
|
+
return { cost, unp, tree: [...tree.values()], mdl: [...models.values()] };
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* A journal entry is a receipt id, or `{ id, ... }` as the sidecar writes it. This
|
|
277
|
+
* session's ids (and lines naming no session), and how many named another (`ses`):
|
|
278
|
+
* one sidecar run serves many sessions.
|
|
279
|
+
*/
|
|
280
|
+
function journalIds(journal, session) {
|
|
281
|
+
if (!Array.isArray(journal)) return null;
|
|
282
|
+
const ids = [];
|
|
283
|
+
let other = 0;
|
|
284
|
+
for (const entry of journal) {
|
|
285
|
+
const id = typeof entry === "string" ? entry : entry && typeof entry === "object" ? entry.id : undefined;
|
|
286
|
+
if (typeof id !== "string" || id.length === 0) return null;
|
|
287
|
+
const ses = entry && typeof entry === "object" ? entry.ses : undefined;
|
|
288
|
+
if (typeof ses === "string" && ses !== session) {
|
|
289
|
+
other += 1;
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
ids.push(id);
|
|
293
|
+
}
|
|
294
|
+
return { ids, other };
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Verify a session seal against its bundle and, when given, the user's journal.
|
|
299
|
+
*
|
|
300
|
+
* Four checks: (1) the seal's signature; (2) its root and totals recompute from
|
|
301
|
+
* the bundle; (3) every receipt in the bundle verifies and belongs to this
|
|
302
|
+
* session, agent and window; (4) every receipt id the user's sidecar journaled is
|
|
303
|
+
* in the bundle, directly or through a receipt's `prev` link.
|
|
304
|
+
*
|
|
305
|
+
* Without a journal a seal is no stronger than a statement: `checks.journal` is
|
|
306
|
+
* null and says so. A journaled id that is absent is MISSING, not tampering: the
|
|
307
|
+
* gateway's log write is best-effort, so a lost row and an omission look alike.
|
|
308
|
+
* Receipts in the bundle but not the journal are reported in `unjournaled` and
|
|
309
|
+
* never fail the session.
|
|
310
|
+
*/
|
|
311
|
+
export async function verifySession(input, options) {
|
|
312
|
+
const jwksCache = new Map();
|
|
313
|
+
const opts = { ...options, jwksCache };
|
|
314
|
+
const result = {
|
|
315
|
+
ok: false,
|
|
316
|
+
checks: { signature: false, bundle: null, receipts: null, journal: null },
|
|
317
|
+
mismatched: [],
|
|
318
|
+
rejected: [],
|
|
319
|
+
missing: [],
|
|
320
|
+
unjournaled: [],
|
|
321
|
+
otherSessions: 0,
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
const sealed = await verifySigned(input?.seal, SESSION_TYP, opts, { claim: "v", max: SESSION_SUPPORTED_VER });
|
|
325
|
+
if (!sealed.ok) return { ...result, reason: sealed.reason };
|
|
326
|
+
const claims = sealed.claims;
|
|
327
|
+
result.claims = claims;
|
|
328
|
+
result.checks.signature = true;
|
|
329
|
+
|
|
330
|
+
const bundle = Array.isArray(input?.bundle) && input.bundle.every((j) => typeof j === "string") ? input.bundle : null;
|
|
331
|
+
if (!bundle) {
|
|
332
|
+
return { ...result, reason: "malformed_bundle", checks: { ...result.checks, bundle: false } };
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// 2. The root and every total, recomputed from the bundle.
|
|
336
|
+
const decoded = bundle.map(decodePayload);
|
|
337
|
+
const totals = bundleTotals(decoded);
|
|
338
|
+
if (sessionRoot(bundle) !== (claims.root ?? null)) result.mismatched.push("root");
|
|
339
|
+
if (claims.n !== bundle.length) result.mismatched.push("n");
|
|
340
|
+
if (claims.cost !== totals.cost) result.mismatched.push("cost");
|
|
341
|
+
if (claims.unp !== totals.unp) result.mismatched.push("unp");
|
|
342
|
+
if (canonical(claims.tree, TREE_KEYS) !== canonical(totals.tree, TREE_KEYS)) result.mismatched.push("tree");
|
|
343
|
+
if (canonical(claims.mdl, MODEL_KEYS) !== canonical(totals.mdl, MODEL_KEYS)) result.mismatched.push("mdl");
|
|
344
|
+
result.checks.bundle = result.mismatched.length === 0;
|
|
345
|
+
|
|
346
|
+
// 3. Every receipt verifies, and belongs to this session, agent and window.
|
|
347
|
+
const seen = new Set();
|
|
348
|
+
for (let index = 0; index < bundle.length; index++) {
|
|
349
|
+
const id = orNull(decoded[index]?.jti);
|
|
350
|
+
const verified = await verifyReceipt(bundle[index], opts);
|
|
351
|
+
let reason = verified.ok ? null : verified.reason;
|
|
352
|
+
if (verified.ok) {
|
|
353
|
+
const c = verified.claims;
|
|
354
|
+
const t = Math.floor(num(c.t0) / 1000);
|
|
355
|
+
if (seen.has(c.jti)) reason = "duplicate";
|
|
356
|
+
else if (c.ctx?.ses !== claims.ses?.id) reason = "other_session";
|
|
357
|
+
else if (c.agid !== claims.sub) reason = "other_agent";
|
|
358
|
+
else if (!(t >= num(claims.per?.from) && t < num(claims.per?.to))) reason = "outside_period";
|
|
359
|
+
seen.add(c.jti);
|
|
360
|
+
}
|
|
361
|
+
if (reason) result.rejected.push({ index, id, reason });
|
|
362
|
+
}
|
|
363
|
+
result.checks.receipts = result.rejected.length === 0;
|
|
364
|
+
|
|
365
|
+
// 4. The user's own record.
|
|
366
|
+
if (input.journal !== undefined) {
|
|
367
|
+
const journaled = journalIds(input.journal, claims.ses?.id);
|
|
368
|
+
if (!journaled) {
|
|
369
|
+
result.reason = "malformed_journal";
|
|
370
|
+
result.checks.journal = false;
|
|
371
|
+
} else {
|
|
372
|
+
const inBundle = new Set(decoded.map((c) => orNull(c?.jti)).filter(Boolean));
|
|
373
|
+
const predecessors = new Set(decoded.map((c) => orNull(c?.prev)).filter(Boolean));
|
|
374
|
+
result.otherSessions = journaled.other;
|
|
375
|
+
const ids = new Set(journaled.ids);
|
|
376
|
+
result.missing = [...ids].filter((id) => !inBundle.has(id) && !predecessors.has(id));
|
|
377
|
+
for (const id of inBundle) {
|
|
378
|
+
if (!ids.has(id)) {
|
|
379
|
+
result.unjournaled.push({ id, why: predecessors.has(id) ? "failover_predecessor" : "not_in_journal" });
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
result.checks.journal = result.missing.length === 0;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
const { signature, bundle: b, receipts, journal } = result.checks;
|
|
387
|
+
result.ok = signature && b === true && receipts === true && journal !== false;
|
|
388
|
+
return result;
|
|
389
|
+
}
|
|
390
|
+
|
|
187
391
|
/** Human-readable one-liners. Kept here so the CLI and its tests agree on wording. */
|
|
188
392
|
export const FAILURE_REASONS = {
|
|
189
393
|
malformed: "not a compact JWS",
|
|
@@ -195,4 +399,10 @@ export const FAILURE_REASONS = {
|
|
|
195
399
|
unsupported_version: "signed by a newer PassControl than this CLI understands",
|
|
196
400
|
wrong_audience: "minted for a different audience",
|
|
197
401
|
expired: "expired",
|
|
402
|
+
malformed_bundle: "the bundle is not a list of receipts",
|
|
403
|
+
malformed_journal: "the journal could not be read as a list of receipt ids",
|
|
404
|
+
other_session: "this receipt is not from the sealed session",
|
|
405
|
+
other_agent: "this receipt is from a different agent than the seal names",
|
|
406
|
+
outside_period: "this receipt falls outside the seal's time window",
|
|
407
|
+
duplicate: "the same receipt appears twice in the bundle",
|
|
198
408
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "passcontrol",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.0",
|
|
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",
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
"./package.json": "./package.json"
|
|
42
42
|
},
|
|
43
43
|
"dependencies": {
|
|
44
|
-
"@modelcontextprotocol/sdk": "^1.
|
|
44
|
+
"@modelcontextprotocol/sdk": "^1.32.1",
|
|
45
45
|
"@noble/curves": "^1.6.0",
|
|
46
46
|
"@noble/hashes": "^1.5.0",
|
|
47
47
|
"jose": "^5.9.3",
|
package/sdk/README.md
CHANGED
|
@@ -158,7 +158,7 @@ The full reference lives in [the public OpenAPI document](https://github.com/Ver
|
|
|
158
158
|
## Compatibility and assurance
|
|
159
159
|
|
|
160
160
|
`clientOptions` accepts `openai`, `anthropic`, `groq`, `mistral`, `together`, `deepseek`,
|
|
161
|
-
`gemini`, `xai`, `azure` and `local` (a model server you run, such as Ollama; self-host only). OpenAI POST Responses works through `pc.fetch`/the OpenAI SDK as well as
|
|
161
|
+
`gemini`, `xai`, `openrouter`, `azure` and `local` (a model server you run, such as Ollama; self-host only). OpenAI POST Responses works through `pc.fetch`/the OpenAI SDK as well as
|
|
162
162
|
Chat Completions. xAI is served through its Responses API only (`client.responses.create`);
|
|
163
163
|
its legacy Chat Completions endpoint is refused. Gemini uses Google's OpenAI-compatible endpoint; native
|
|
164
164
|
`generateContent` is not supported. Azure OpenAI takes the plain OpenAI client (not
|
package/sdk/passcontrol.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type ProviderId = "openai" | "anthropic" | "groq" | "mistral" | "together" | "deepseek" | "gemini" | "xai" | "azure" | "local";
|
|
1
|
+
export type ProviderId = "openai" | "anthropic" | "groq" | "mistral" | "together" | "deepseek" | "gemini" | "xai" | "openrouter" | "azure" | "local";
|
|
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
|
@@ -257,6 +257,114 @@ export declare function verifyStatement(jws: string, options: VerifyOptions): Pr
|
|
|
257
257
|
* and the statement's `root`.
|
|
258
258
|
*/
|
|
259
259
|
export declare function verifyInclusion(receiptJws: string, proof: readonly InclusionProofStep[], root: Uint8Array | string): boolean;
|
|
260
|
+
export declare const SESSION_TYP = "passcontrol-session+jws";
|
|
261
|
+
/** The newest session-seal version this verifier understands. See SESSION_PROTOCOL. */
|
|
262
|
+
export declare const SESSION_SUPPORTED_VER: number;
|
|
263
|
+
/** One node of a session's agent tree. `agt: null` is the main agent; `par: null` is "spawned by the main agent". */
|
|
264
|
+
export interface SessionTreeNode {
|
|
265
|
+
agt: string | null;
|
|
266
|
+
par: string | null;
|
|
267
|
+
n: number;
|
|
268
|
+
cost: number;
|
|
269
|
+
/** Calls the gateway refused (`res.status` starting `blocked_`). */
|
|
270
|
+
refused: number;
|
|
271
|
+
}
|
|
272
|
+
export interface SessionClaims {
|
|
273
|
+
iss: string;
|
|
274
|
+
/** The agent id. */
|
|
275
|
+
sub: string;
|
|
276
|
+
jti: string;
|
|
277
|
+
iat: number;
|
|
278
|
+
fmt: string;
|
|
279
|
+
v: number;
|
|
280
|
+
/** The session id and who declared it (`claude-code`, `codex`, `sidecar`). Declared by the client, never authenticated. */
|
|
281
|
+
ses: {
|
|
282
|
+
id: string;
|
|
283
|
+
src: string;
|
|
284
|
+
};
|
|
285
|
+
/** Half-open window `[from, to)`, epoch seconds. */
|
|
286
|
+
per: {
|
|
287
|
+
from: number;
|
|
288
|
+
to: number;
|
|
289
|
+
};
|
|
290
|
+
n: number;
|
|
291
|
+
nr: number;
|
|
292
|
+
cost: number;
|
|
293
|
+
unp: number;
|
|
294
|
+
unk: number;
|
|
295
|
+
root: string | null;
|
|
296
|
+
tree: SessionTreeNode[];
|
|
297
|
+
mdl: {
|
|
298
|
+
mdl: string | null;
|
|
299
|
+
n: number;
|
|
300
|
+
cost: number;
|
|
301
|
+
}[];
|
|
302
|
+
}
|
|
303
|
+
/** Why one receipt in a bundle was not accepted as part of the session. */
|
|
304
|
+
export type SessionReceiptRejection = VerifyFailure | "duplicate" | "other_session" | "other_agent" | "outside_period";
|
|
305
|
+
export interface SessionVerifyResult {
|
|
306
|
+
/** All of: signature, bundle and receipts pass, and the journal check did not fail. */
|
|
307
|
+
ok: boolean;
|
|
308
|
+
/** Set when the seal itself failed, or when the bundle or journal could not be read. */
|
|
309
|
+
reason?: VerifyFailure | "malformed_bundle" | "malformed_journal";
|
|
310
|
+
claims?: SessionClaims;
|
|
311
|
+
/** null = not run. `journal` is null when no journal was given: the seal is then no stronger than a statement. */
|
|
312
|
+
checks: {
|
|
313
|
+
signature: boolean;
|
|
314
|
+
bundle: boolean | null;
|
|
315
|
+
receipts: boolean | null;
|
|
316
|
+
journal: boolean | null;
|
|
317
|
+
};
|
|
318
|
+
/** Seal claims that do not match what the bundle adds up to: root, n, cost, unp, tree, mdl. */
|
|
319
|
+
mismatched: string[];
|
|
320
|
+
rejected: {
|
|
321
|
+
index: number;
|
|
322
|
+
id: string | null;
|
|
323
|
+
reason: SessionReceiptRejection;
|
|
324
|
+
}[];
|
|
325
|
+
/** Journaled receipt ids the bundle does not contain. MISSING, not proof of tampering: see verifySession. */
|
|
326
|
+
missing: string[];
|
|
327
|
+
/** Bundle receipts the journal never saw. Reported, never a failure. */
|
|
328
|
+
unjournaled: {
|
|
329
|
+
id: string;
|
|
330
|
+
why: "failover_predecessor" | "not_in_journal";
|
|
331
|
+
}[];
|
|
332
|
+
/**
|
|
333
|
+
* Journal lines that name ANOTHER session (`ses`), left out of check 4: one sidecar
|
|
334
|
+
* run serves many sessions. A line that names none is checked as before.
|
|
335
|
+
*/
|
|
336
|
+
otherSessions: number;
|
|
337
|
+
}
|
|
338
|
+
export interface SessionBundle {
|
|
339
|
+
seal: string;
|
|
340
|
+
/** Every receipt the seal covers, as compact JWS, in seal order. */
|
|
341
|
+
bundle: string[];
|
|
342
|
+
/** The user's sidecar journal: receipt ids, or `{ id, ... }` entries. */
|
|
343
|
+
journal?: unknown;
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* Verify a session seal against its bundle and, when given, the user's journal.
|
|
347
|
+
*
|
|
348
|
+
* Four checks: (1) the seal's signature; (2) its root and totals recompute from
|
|
349
|
+
* the bundle; (3) every receipt in the bundle verifies and belongs to this
|
|
350
|
+
* session, agent and window; (4) every receipt id the user's sidecar journaled is
|
|
351
|
+
* in the bundle, directly or through a receipt's `prev` link.
|
|
352
|
+
*
|
|
353
|
+
* WHAT CHECK 4 ADDS. A statement can only show the issuer committed to a set. The
|
|
354
|
+
* journal is the user's own independent list of their calls, so a call left out
|
|
355
|
+
* of the seal is caught. Without a journal a seal is no stronger than a statement,
|
|
356
|
+
* and `checks.journal` is null to say so.
|
|
357
|
+
*
|
|
358
|
+
* WHAT `missing` MEANS. A journaled id that is absent is MISSING, never proof of
|
|
359
|
+
* tampering: the gateway's log write is best-effort, so a lost row and an
|
|
360
|
+
* omission look the same from here. Receipts in the bundle but not the journal
|
|
361
|
+
* (failover predecessors, direct calls, another machine) are reported in
|
|
362
|
+
* `unjournaled` and never fail the session.
|
|
363
|
+
*
|
|
364
|
+
* The session id inside each receipt is DECLARED by the client. Check 3 shows the
|
|
365
|
+
* issuer grouped what the client declared; it does not show who made the call.
|
|
366
|
+
*/
|
|
367
|
+
export declare function verifySession(input: SessionBundle, options: VerifyOptions): Promise<SessionVerifyResult>;
|
|
260
368
|
export interface VerifyAgentTokenOptions extends VerifyOptions {
|
|
261
369
|
/** The audience YOU are. Required: a token minted for someone else is not for you. */
|
|
262
370
|
audience: string;
|