passcontrol 0.5.3 → 0.6.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/LICENSE +2 -2
- package/README.md +90 -22
- package/bin/passcontrol.mjs +270 -73
- package/cli/config.mjs +124 -1
- package/cli/mcp/gateway.mjs +4 -4
- package/cli/presets.mjs +1 -0
- package/cli/proxy-policy.mjs +276 -0
- package/cli/sidecar.mjs +186 -9
- package/cli/visa-client.mjs +10 -2
- package/package.json +11 -3
- package/sdk/README.md +152 -0
- package/sdk/control.d.ts +103 -0
- package/sdk/control.js +102 -0
- package/sdk/gateway.d.ts +22 -0
- package/sdk/gateway.js +66 -0
- package/sdk/index.d.ts +6 -0
- package/sdk/index.js +20 -0
- package/sdk/passcontrol.d.ts +47 -0
- package/sdk/passcontrol.js +197 -0
- package/sdk/verify.d.ts +182 -0
- package/sdk/verify.js +238 -0
package/sdk/gateway.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Validate a `gateway` option and return the origin to build URLs from.
|
|
3
|
+
*
|
|
4
|
+
* Accepts a **bare HTTPS origin** — scheme, host, optional port — with nothing
|
|
5
|
+
* else attached: no path beyond `/`, no query, no fragment, and no embedded
|
|
6
|
+
* username or password. HTTP is accepted only on the loopback hosts above.
|
|
7
|
+
*
|
|
8
|
+
* The value is parsed, then the return value is re-derived from `URL.origin`
|
|
9
|
+
* rather than echoed back. That is what stops attacker-controlled path material
|
|
10
|
+
* from surviving into a later concatenation, and it is why a deceptive
|
|
11
|
+
* `https://trusted.example@attacker.example` cannot be laundered into looking
|
|
12
|
+
* like the trusted host: the parser assigns `trusted.example` to `username`, and
|
|
13
|
+
* userinfo is rejected outright.
|
|
14
|
+
*
|
|
15
|
+
* Throws synchronously, and the message never quotes the offending value — a
|
|
16
|
+
* rejected gateway can itself contain a credential (`https://user:pass@host`),
|
|
17
|
+
* and a refusal that lands in a log should not be the thing that leaks it.
|
|
18
|
+
*
|
|
19
|
+
* @param clientName Prefix for the thrown message, so the caller can tell which
|
|
20
|
+
* client refused (`PassControl` / `ControlClient`).
|
|
21
|
+
*/
|
|
22
|
+
export declare function requireGatewayOrigin(clientName: string, gateway: string): string;
|
package/sdk/gateway.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// The gateway rule, shared by both credential-bearing SDK clients.
|
|
2
|
+
//
|
|
3
|
+
// `PassControl` carries a short-lived visa and `ControlClient` carries a
|
|
4
|
+
// long-lived `pc_` control-plane key, but the question each one asks of its
|
|
5
|
+
// `gateway` option is identical: *is this a destination I may hand a bearer
|
|
6
|
+
// credential to?* That answer used to exist in one client and not the other —
|
|
7
|
+
// ControlClient accepted any non-empty string and concatenated it — so this file
|
|
8
|
+
// exists to make drift between the two impossible rather than merely unlikely.
|
|
9
|
+
//
|
|
10
|
+
// It is internal. `sdk/index.ts` deliberately does not re-export it, and the
|
|
11
|
+
// generated package's `exports` map exposes only `./sdk`, so no consumer gains a
|
|
12
|
+
// new supported surface from it.
|
|
13
|
+
/**
|
|
14
|
+
* The only hosts allowed to speak plain HTTP.
|
|
15
|
+
*
|
|
16
|
+
* Deliberately an exact-match set, never a prefix, suffix or regex: `localhost.`,
|
|
17
|
+
* `localhost.example` and `127.0.0.1.attacker.example` are all *someone else's*
|
|
18
|
+
* hostnames that a looser test would read as local. Docker service names,
|
|
19
|
+
* `host.docker.internal` and LAN addresses are excluded on purpose — they are
|
|
20
|
+
* real networks, and a credential crossing one in cleartext is on the wire.
|
|
21
|
+
* Matched against the parsed `hostname`, which the URL parser has already
|
|
22
|
+
* lowercased and canonicalised (`127.1` → `127.0.0.1`, `[0:0:0:0:0:0:0:1]` →
|
|
23
|
+
* `[::1]`), so shorthand spellings of loopback resolve here instead of slipping
|
|
24
|
+
* past a string comparison.
|
|
25
|
+
*/
|
|
26
|
+
const LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
27
|
+
/**
|
|
28
|
+
* Validate a `gateway` option and return the origin to build URLs from.
|
|
29
|
+
*
|
|
30
|
+
* Accepts a **bare HTTPS origin** — scheme, host, optional port — with nothing
|
|
31
|
+
* else attached: no path beyond `/`, no query, no fragment, and no embedded
|
|
32
|
+
* username or password. HTTP is accepted only on the loopback hosts above.
|
|
33
|
+
*
|
|
34
|
+
* The value is parsed, then the return value is re-derived from `URL.origin`
|
|
35
|
+
* rather than echoed back. That is what stops attacker-controlled path material
|
|
36
|
+
* from surviving into a later concatenation, and it is why a deceptive
|
|
37
|
+
* `https://trusted.example@attacker.example` cannot be laundered into looking
|
|
38
|
+
* like the trusted host: the parser assigns `trusted.example` to `username`, and
|
|
39
|
+
* userinfo is rejected outright.
|
|
40
|
+
*
|
|
41
|
+
* Throws synchronously, and the message never quotes the offending value — a
|
|
42
|
+
* rejected gateway can itself contain a credential (`https://user:pass@host`),
|
|
43
|
+
* and a refusal that lands in a log should not be the thing that leaks it.
|
|
44
|
+
*
|
|
45
|
+
* @param clientName Prefix for the thrown message, so the caller can tell which
|
|
46
|
+
* client refused (`PassControl` / `ControlClient`).
|
|
47
|
+
*/
|
|
48
|
+
export function requireGatewayOrigin(clientName, gateway) {
|
|
49
|
+
let url;
|
|
50
|
+
try {
|
|
51
|
+
url = new URL(gateway);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
throw new Error(`${clientName}: gateway must be an absolute URL.`);
|
|
55
|
+
}
|
|
56
|
+
const loopback = LOOPBACK_HOSTNAMES.has(url.hostname);
|
|
57
|
+
if ((url.protocol !== "https:" && !(loopback && url.protocol === "http:")) ||
|
|
58
|
+
url.username ||
|
|
59
|
+
url.password ||
|
|
60
|
+
url.search ||
|
|
61
|
+
url.hash ||
|
|
62
|
+
url.pathname !== "/") {
|
|
63
|
+
throw new Error(`${clientName}: gateway must be a bare HTTPS origin (HTTP is allowed only for localhost).`);
|
|
64
|
+
}
|
|
65
|
+
return url.origin;
|
|
66
|
+
}
|
package/sdk/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { PassControl } from "./passcontrol.js";
|
|
2
|
+
export type { PassControlOptions, ProviderId } from "./passcontrol.js";
|
|
3
|
+
export { ControlClient, ControlApiError } from "./control.js";
|
|
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";
|
package/sdk/index.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// PassControl SDK — single entry point.
|
|
2
|
+
//
|
|
3
|
+
// Two clients and a verifier, one import:
|
|
4
|
+
// • PassControl (data plane) — hides visa minting; re-point your OpenAI/
|
|
5
|
+
// Anthropic SDK at the gateway, don't rewrite.
|
|
6
|
+
// • ControlClient (control plane) — typed wrapper over /api/control/v1 (pc_ key)
|
|
7
|
+
// to manage the fleet.
|
|
8
|
+
// • verifyReceipt (verification) — check a signed call receipt against the
|
|
9
|
+
// issuer's published JWKS. This one is for
|
|
10
|
+
// people OUTSIDE your deployment: it needs
|
|
11
|
+
// no key, no account, and no callback here.
|
|
12
|
+
//
|
|
13
|
+
// npm consumers load this entry point through the `passcontrol/sdk` export;
|
|
14
|
+
// the dashboard consumes the same source through its local path alias.
|
|
15
|
+
//
|
|
16
|
+
// Self-hosting and want a flat copy? This folder is self-contained — vendor the
|
|
17
|
+
// whole `sdk/` directory; it only needs @noble/curves + the platform fetch/crypto.
|
|
18
|
+
export { PassControl } from "./passcontrol.js";
|
|
19
|
+
export { ControlClient, ControlApiError } from "./control.js";
|
|
20
|
+
export { verifyReceipt, verifyAgentToken, matchesIssuer, RECEIPT_TYP, AGENT_TOKEN_TYP, SUPPORTED_VER, } from "./verify.js";
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export type ProviderId = "openai" | "anthropic" | "groq" | "mistral" | "together" | "deepseek";
|
|
2
|
+
export interface PassControlOptions {
|
|
3
|
+
/**
|
|
4
|
+
* Gateway origin, e.g. https://passcontrol.example.com — scheme, host and
|
|
5
|
+
* optional port only. Validated at construction against the same bare-origin
|
|
6
|
+
* rule as `ControlClient`; plain HTTP is accepted only on loopback. See
|
|
7
|
+
* ./gateway.
|
|
8
|
+
*/
|
|
9
|
+
gateway: string;
|
|
10
|
+
/** base64url Ed25519 public key (the passport id). */
|
|
11
|
+
passportId: string;
|
|
12
|
+
/** base64url Ed25519 private key (32-byte seed). Stays on the agent; only signs. */
|
|
13
|
+
passportSecret: string;
|
|
14
|
+
/** Re-mint when fewer than this many seconds remain on the visa. Default 30. */
|
|
15
|
+
refreshSkewSeconds?: number;
|
|
16
|
+
/** Override the transport (tests / custom fetch). Defaults to global fetch. */
|
|
17
|
+
fetch?: typeof fetch;
|
|
18
|
+
}
|
|
19
|
+
export declare class PassControl {
|
|
20
|
+
private readonly gateway;
|
|
21
|
+
private readonly gatewayOrigin;
|
|
22
|
+
private readonly passportId;
|
|
23
|
+
private readonly secret;
|
|
24
|
+
private readonly skewMs;
|
|
25
|
+
private readonly transport;
|
|
26
|
+
private cached;
|
|
27
|
+
private inflight;
|
|
28
|
+
constructor(opts: PassControlOptions);
|
|
29
|
+
/** Sign a fresh challenge and exchange it for a visa. */
|
|
30
|
+
private mint;
|
|
31
|
+
/** Return a valid visa, minting or refreshing as needed. Concurrent callers
|
|
32
|
+
* share a single in-flight mint (no thundering herd of challenges). */
|
|
33
|
+
getVisa(): Promise<string>;
|
|
34
|
+
/** Drop the cached visa so the next getVisa() re-mints. */
|
|
35
|
+
invalidate(): void;
|
|
36
|
+
/** A `fetch` that injects the visa and refreshes it transparently. Pass this as
|
|
37
|
+
* the `fetch` option to the OpenAI/Anthropic SDK. Retries once on a 401 (the
|
|
38
|
+
* visa was rejected/expired) after forcing a re-mint. */
|
|
39
|
+
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
|
|
40
|
+
/** Options to spread into an OpenAI/Anthropic SDK constructor. The fetch wrapper
|
|
41
|
+
* owns auth, so `apiKey` is a non-secret placeholder (the SDK requires one). */
|
|
42
|
+
clientOptions(provider: ProviderId): {
|
|
43
|
+
baseURL: string;
|
|
44
|
+
apiKey: string;
|
|
45
|
+
fetch: typeof fetch;
|
|
46
|
+
};
|
|
47
|
+
}
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
// PassControl client SDK — the thin layer that hides visa minting.
|
|
2
|
+
//
|
|
3
|
+
// A PassControl-issued passport holds an Ed25519 private key. To call a provider
|
|
4
|
+
// the agent must sign a challenge, mint a short-lived (5 min) work-visa, and send
|
|
5
|
+
// it instead of the real provider key. This SDK does that — and refreshes the visa
|
|
6
|
+
// transparently — so integration is *re-pointing* an existing OpenAI/Anthropic SDK,
|
|
7
|
+
// not rewriting the agent:
|
|
8
|
+
//
|
|
9
|
+
// Construct PassControl with gateway, passportId and passportSecret, then pass
|
|
10
|
+
// pc.clientOptions("openai") to the existing OpenAI client constructor.
|
|
11
|
+
// // …use `openai` normally. Visas mint/refresh under the hood.
|
|
12
|
+
//
|
|
13
|
+
// Dependencies: only @noble/curves (Ed25519) + the platform `fetch`/`crypto`.
|
|
14
|
+
// Runs on Node 18+ and edge/server runtimes. Do not place a passport secret in
|
|
15
|
+
// an end-user browser bundle even though the underlying Web APIs are portable.
|
|
16
|
+
import { ed25519 } from "@noble/curves/ed25519";
|
|
17
|
+
import { requireGatewayOrigin } from "./gateway.js";
|
|
18
|
+
// --- base64url over raw bytes (no Buffer dependency; works everywhere) -------
|
|
19
|
+
function bytesToB64url(bytes) {
|
|
20
|
+
let bin = "";
|
|
21
|
+
for (const b of bytes)
|
|
22
|
+
bin += String.fromCharCode(b);
|
|
23
|
+
const b64 = typeof btoa !== "undefined" ? btoa(bin) : Buffer.from(bin, "binary").toString("base64");
|
|
24
|
+
return b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
25
|
+
}
|
|
26
|
+
function b64urlToBytes(s) {
|
|
27
|
+
const b64 = s.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(s.length / 4) * 4, "=");
|
|
28
|
+
const bin = typeof atob !== "undefined" ? atob(b64) : Buffer.from(b64, "base64").toString("binary");
|
|
29
|
+
return Uint8Array.from(bin, (c) => c.charCodeAt(0));
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Can this `init.body` be sent a second time?
|
|
33
|
+
*
|
|
34
|
+
* Only matters for the one-time 401 retry, and it is the whole question — because
|
|
35
|
+
* `init.body`, when it is non-null, IS the body each attempt sends. `send()` passes
|
|
36
|
+
* `{ ...init, headers }` next to the cloned `Request` template, and per the fetch
|
|
37
|
+
* spec an init body overrides the input request's; the clone's teed copy is then
|
|
38
|
+
* never read. So a `Request` input does not make a retry safe on its own: what
|
|
39
|
+
* decides is the *effective* body, which is `init.body` whenever one is supplied.
|
|
40
|
+
*
|
|
41
|
+
* Every shape below is a re-readable value. Anything else (a ReadableStream, an
|
|
42
|
+
* async iterable, a Node stream) is consumed by the first attempt; replaying one
|
|
43
|
+
* either throws a platform TypeError or, worse, sends an empty body to the
|
|
44
|
+
* provider — so we don't.
|
|
45
|
+
*
|
|
46
|
+
* `null`/`undefined` answer true, and that is what makes the caller's single call
|
|
47
|
+
* to this function complete: with no init body the effective body is the template
|
|
48
|
+
* `Request`'s own, which `clone()` tees and can therefore be sent again — or there
|
|
49
|
+
* is no template and no body at all. (It also means the answer does not hinge on
|
|
50
|
+
* whether a given runtime treats an explicit `body: null` as an override: both
|
|
51
|
+
* readings leave a replay-safe body.)
|
|
52
|
+
*
|
|
53
|
+
* Deliberately an allow-list. A body shape this does not recognise is treated as
|
|
54
|
+
* single-use, which costs one avoidable retry and can never send a wrong body.
|
|
55
|
+
*/
|
|
56
|
+
function isReplayableBody(body) {
|
|
57
|
+
if (body === null || body === undefined || typeof body === "string")
|
|
58
|
+
return true;
|
|
59
|
+
if (typeof ArrayBuffer !== "undefined" && (ArrayBuffer.isView(body) || body instanceof ArrayBuffer))
|
|
60
|
+
return true;
|
|
61
|
+
if (typeof Blob !== "undefined" && body instanceof Blob)
|
|
62
|
+
return true;
|
|
63
|
+
if (typeof FormData !== "undefined" && body instanceof FormData)
|
|
64
|
+
return true;
|
|
65
|
+
if (typeof URLSearchParams !== "undefined" && body instanceof URLSearchParams)
|
|
66
|
+
return true;
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
export class PassControl {
|
|
70
|
+
gateway;
|
|
71
|
+
gatewayOrigin;
|
|
72
|
+
passportId;
|
|
73
|
+
secret;
|
|
74
|
+
skewMs;
|
|
75
|
+
transport;
|
|
76
|
+
cached = null;
|
|
77
|
+
inflight = null;
|
|
78
|
+
constructor(opts) {
|
|
79
|
+
if (!opts.gateway || !opts.passportId || !opts.passportSecret) {
|
|
80
|
+
throw new Error("PassControl: gateway, passportId, and passportSecret are required.");
|
|
81
|
+
}
|
|
82
|
+
// Same rule, same code as ControlClient's `pc_` key — see ./gateway. Both
|
|
83
|
+
// clients hand a bearer credential to whatever this option names, so the two
|
|
84
|
+
// must not be allowed to drift apart.
|
|
85
|
+
const origin = requireGatewayOrigin("PassControl", opts.gateway);
|
|
86
|
+
this.gateway = origin;
|
|
87
|
+
this.gatewayOrigin = origin;
|
|
88
|
+
this.passportId = opts.passportId;
|
|
89
|
+
this.secret = b64urlToBytes(opts.passportSecret);
|
|
90
|
+
if (b64urlToBytes(opts.passportId).length !== 32 || this.secret.length !== 32) {
|
|
91
|
+
throw new Error("PassControl: passportId and passportSecret must each encode 32 bytes.");
|
|
92
|
+
}
|
|
93
|
+
this.skewMs = Math.max(0, (opts.refreshSkewSeconds ?? 30) * 1000);
|
|
94
|
+
// Bind so the global fetch keeps its expected `this`.
|
|
95
|
+
const f = opts.fetch ?? globalThis.fetch;
|
|
96
|
+
if (!f)
|
|
97
|
+
throw new Error("PassControl: no fetch available; pass options.fetch.");
|
|
98
|
+
this.transport = (...args) => f(...args);
|
|
99
|
+
}
|
|
100
|
+
/** Sign a fresh challenge and exchange it for a visa. */
|
|
101
|
+
async mint() {
|
|
102
|
+
const payloadObj = { passport_id: this.passportId, ts: Date.now(), nonce: crypto.randomUUID() };
|
|
103
|
+
const payloadBytes = new TextEncoder().encode(JSON.stringify(payloadObj));
|
|
104
|
+
const payload = bytesToB64url(payloadBytes);
|
|
105
|
+
const signature = bytesToB64url(ed25519.sign(payloadBytes, this.secret));
|
|
106
|
+
const res = await this.transport(`${this.gateway}/api/auth/challenge`, {
|
|
107
|
+
method: "POST",
|
|
108
|
+
headers: { "content-type": "application/json" },
|
|
109
|
+
body: JSON.stringify({ payload, signature }),
|
|
110
|
+
});
|
|
111
|
+
if (!res.ok) {
|
|
112
|
+
const detail = await res.text().catch(() => "");
|
|
113
|
+
throw new Error(`PassControl: challenge failed (${res.status}) ${detail}`.trim());
|
|
114
|
+
}
|
|
115
|
+
const data = (await res.json());
|
|
116
|
+
if (!data.visa)
|
|
117
|
+
throw new Error("PassControl: challenge returned no visa.");
|
|
118
|
+
return { token: data.visa, expiresAt: Date.now() + (data.expires_in ?? 300) * 1000 };
|
|
119
|
+
}
|
|
120
|
+
/** Return a valid visa, minting or refreshing as needed. Concurrent callers
|
|
121
|
+
* share a single in-flight mint (no thundering herd of challenges). */
|
|
122
|
+
async getVisa() {
|
|
123
|
+
if (this.cached && Date.now() < this.cached.expiresAt - this.skewMs) {
|
|
124
|
+
return this.cached.token;
|
|
125
|
+
}
|
|
126
|
+
if (this.inflight)
|
|
127
|
+
return this.inflight;
|
|
128
|
+
this.inflight = this.mint()
|
|
129
|
+
.then((v) => {
|
|
130
|
+
this.cached = v;
|
|
131
|
+
return v.token;
|
|
132
|
+
})
|
|
133
|
+
.finally(() => {
|
|
134
|
+
this.inflight = null;
|
|
135
|
+
});
|
|
136
|
+
return this.inflight;
|
|
137
|
+
}
|
|
138
|
+
/** Drop the cached visa so the next getVisa() re-mints. */
|
|
139
|
+
invalidate() {
|
|
140
|
+
this.cached = null;
|
|
141
|
+
}
|
|
142
|
+
/** A `fetch` that injects the visa and refreshes it transparently. Pass this as
|
|
143
|
+
* the `fetch` option to the OpenAI/Anthropic SDK. Retries once on a 401 (the
|
|
144
|
+
* visa was rejected/expired) after forcing a re-mint. */
|
|
145
|
+
fetch = async (input, init = {}) => {
|
|
146
|
+
const inputRequest = typeof Request !== "undefined" && input instanceof Request ? input : null;
|
|
147
|
+
const rawUrl = inputRequest ? inputRequest.url : String(input);
|
|
148
|
+
const target = new URL(rawUrl, `${this.gateway}/`);
|
|
149
|
+
// `URL.origin` discards userinfo, so `https://a:b@gateway/...` compares equal to
|
|
150
|
+
// the gateway and would otherwise pass. Reject it here for the same reason the
|
|
151
|
+
// constructor does, instead of relying on the platform's Request to throw.
|
|
152
|
+
if (target.origin !== this.gatewayOrigin ||
|
|
153
|
+
target.username ||
|
|
154
|
+
target.password ||
|
|
155
|
+
!target.pathname.startsWith("/api/v1/")) {
|
|
156
|
+
throw new Error("PassControl: refusing to send a visa outside the configured gateway provider path.");
|
|
157
|
+
}
|
|
158
|
+
// Keep a pristine template so a Request input retains its method and body and
|
|
159
|
+
// each send gets an unread clone — clone() tees the body, streams included.
|
|
160
|
+
// That tee only covers the template's OWN body: a non-null `init.body` travels
|
|
161
|
+
// beside the clone and overrides it, so the effective body of every attempt is
|
|
162
|
+
// `init.body` when there is one. isReplayableBody decides on that basis alone.
|
|
163
|
+
const requestTemplate = inputRequest?.clone() ?? null;
|
|
164
|
+
const canReplay = isReplayableBody(init.body);
|
|
165
|
+
const send = async (visa) => {
|
|
166
|
+
const requestHeaders = inputRequest?.headers;
|
|
167
|
+
const headers = new Headers(init.headers ?? requestHeaders);
|
|
168
|
+
// The visa is the credential. Set it as Authorization (the gateway prefers
|
|
169
|
+
// Bearer) and strip any x-api-key the SDK added so only the visa travels.
|
|
170
|
+
headers.set("authorization", `Bearer ${visa}`);
|
|
171
|
+
headers.delete("x-api-key");
|
|
172
|
+
return this.transport(requestTemplate?.clone() ?? target.toString(), { ...init, headers });
|
|
173
|
+
};
|
|
174
|
+
let res = await send(await this.getVisa());
|
|
175
|
+
if (res.status === 401) {
|
|
176
|
+
// The gateway rejected this visa, so stop serving it either way — a caller
|
|
177
|
+
// we cannot retry for still deserves a fresh visa on its next call.
|
|
178
|
+
this.invalidate();
|
|
179
|
+
if (canReplay) {
|
|
180
|
+
// Release the rejected response's body before replacing it; an unread
|
|
181
|
+
// body holds its connection open until the runtime collects it.
|
|
182
|
+
void res.body?.cancel().catch(() => { });
|
|
183
|
+
res = await send(await this.getVisa());
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return res;
|
|
187
|
+
};
|
|
188
|
+
/** Options to spread into an OpenAI/Anthropic SDK constructor. The fetch wrapper
|
|
189
|
+
* owns auth, so `apiKey` is a non-secret placeholder (the SDK requires one). */
|
|
190
|
+
clientOptions(provider) {
|
|
191
|
+
return {
|
|
192
|
+
baseURL: `${this.gateway}/api/v1/${provider}`,
|
|
193
|
+
apiKey: "passcontrol-visa",
|
|
194
|
+
fetch: this.fetch,
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
}
|
package/sdk/verify.d.ts
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
export declare const RECEIPT_TYP = "passcontrol-receipt+jwt";
|
|
2
|
+
export declare const AGENT_TOKEN_TYP = "passcontrol-agent+jwt";
|
|
3
|
+
/** The newest artifact version this verifier understands. */
|
|
4
|
+
export declare const SUPPORTED_VER = 2;
|
|
5
|
+
export type VerifyFailure = "malformed" | "untrusted_issuer" | "unknown_key" | "bad_signature" | "wrong_type" | "unsupported_version" | "jwks_unreachable" | "expired" | "wrong_audience" | "revoked" | "status_unavailable";
|
|
6
|
+
export type VerifyResult<T> = {
|
|
7
|
+
ok: true;
|
|
8
|
+
claims: T;
|
|
9
|
+
} | {
|
|
10
|
+
ok: false;
|
|
11
|
+
reason: VerifyFailure;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* The checks this verifier runs, in the order it runs them. Exposed so a UI can
|
|
15
|
+
* show what it actually did rather than a spinner — see `onStep`.
|
|
16
|
+
*/
|
|
17
|
+
export type VerifyStepName = "parse" | "algorithm" | "type" | "issuer" | "version" | "jwks" | "key" | "signature";
|
|
18
|
+
export interface VerifyStep {
|
|
19
|
+
step: VerifyStepName;
|
|
20
|
+
ok: boolean;
|
|
21
|
+
/** Present only on the failing step; equals the reason the caller receives. */
|
|
22
|
+
reason?: VerifyFailure;
|
|
23
|
+
/** Real elapsed milliseconds for this step. Not a target, not a minimum. */
|
|
24
|
+
ms: number;
|
|
25
|
+
}
|
|
26
|
+
export interface ReceiptClaims {
|
|
27
|
+
iss: string;
|
|
28
|
+
sub: string;
|
|
29
|
+
jti: string;
|
|
30
|
+
iat: number;
|
|
31
|
+
agid: string;
|
|
32
|
+
vjti?: string;
|
|
33
|
+
auth?: {
|
|
34
|
+
kind: "direct_key";
|
|
35
|
+
kid: string;
|
|
36
|
+
use: string;
|
|
37
|
+
};
|
|
38
|
+
prov: string;
|
|
39
|
+
mdl: string | null;
|
|
40
|
+
mth: string;
|
|
41
|
+
path: string;
|
|
42
|
+
req?: {
|
|
43
|
+
alg: string;
|
|
44
|
+
dig: string;
|
|
45
|
+
len: number;
|
|
46
|
+
};
|
|
47
|
+
use: {
|
|
48
|
+
in: number;
|
|
49
|
+
out: number;
|
|
50
|
+
};
|
|
51
|
+
cost: number;
|
|
52
|
+
res: {
|
|
53
|
+
status: string;
|
|
54
|
+
http: number;
|
|
55
|
+
};
|
|
56
|
+
t0: number;
|
|
57
|
+
lat: number;
|
|
58
|
+
own?: {
|
|
59
|
+
kind: string;
|
|
60
|
+
sub: string;
|
|
61
|
+
tier: string;
|
|
62
|
+
vat: string | null;
|
|
63
|
+
};
|
|
64
|
+
/**
|
|
65
|
+
* Present only on an attempt that followed a failed one: the `jti` of the
|
|
66
|
+
* receipt for the attempt this one replaced. Walk it backwards to read the
|
|
67
|
+
* whole chain — a receipt binds ONE call to ONE provider decision, so a
|
|
68
|
+
* failover is two receipts linked, never one compound artifact.
|
|
69
|
+
*
|
|
70
|
+
* Both attempts carry the same `req` digest, because that digest covers the
|
|
71
|
+
* bytes the CLIENT sent and those do not change between attempts. Matching
|
|
72
|
+
* two receipts by a shared digest is therefore a guess; this claim is the
|
|
73
|
+
* link.
|
|
74
|
+
*
|
|
75
|
+
* Optional, and `ver` stays 1: a verifier that predates these claims ignores
|
|
76
|
+
* what it does not recognise, and must not be invalidated for a feature it
|
|
77
|
+
* does not need to understand.
|
|
78
|
+
*/
|
|
79
|
+
prev?: string;
|
|
80
|
+
/**
|
|
81
|
+
* Why the gateway moved on. An allowlisted enum at the issuing end, but treat
|
|
82
|
+
* it as an arbitrary string here — a receipt you verify may come from a
|
|
83
|
+
* different deployment or a newer version. Do not switch on it exhaustively.
|
|
84
|
+
*
|
|
85
|
+
* `upstream_5xx` and `unreachable` are the values where the attempt this
|
|
86
|
+
* receipt replaced MAY ALREADY HAVE BEEN BILLED by the other provider: it may
|
|
87
|
+
* have run the call before failing, and no one can tell. The other values mean
|
|
88
|
+
* the earlier provider refused before doing any work.
|
|
89
|
+
*/
|
|
90
|
+
why?: string;
|
|
91
|
+
ver: number;
|
|
92
|
+
[claim: string]: unknown;
|
|
93
|
+
}
|
|
94
|
+
export interface AgentTokenClaims {
|
|
95
|
+
iss: string;
|
|
96
|
+
sub: string;
|
|
97
|
+
aud: string;
|
|
98
|
+
jti: string;
|
|
99
|
+
iat: number;
|
|
100
|
+
exp: number;
|
|
101
|
+
agid: string;
|
|
102
|
+
own?: {
|
|
103
|
+
kind: string;
|
|
104
|
+
sub: string;
|
|
105
|
+
tier: string;
|
|
106
|
+
vat: string | null;
|
|
107
|
+
} | null;
|
|
108
|
+
ver: number;
|
|
109
|
+
[claim: string]: unknown;
|
|
110
|
+
}
|
|
111
|
+
export interface VerifyOptions {
|
|
112
|
+
/**
|
|
113
|
+
* Origins whose signatures this verifier accepts. REQUIRED, with no default,
|
|
114
|
+
* ever — a verifier that trusts whatever issuer the token names is not
|
|
115
|
+
* verifying anything. Compared by exact string match (see matchesIssuer).
|
|
116
|
+
*/
|
|
117
|
+
trustedIssuers: string[];
|
|
118
|
+
fetch?: typeof fetch;
|
|
119
|
+
/** Cache of issuer origin -> JWK Set, reused across calls. */
|
|
120
|
+
jwksCache?: Map<string, PublicJwk[]>;
|
|
121
|
+
/**
|
|
122
|
+
* Called as each check resolves, in order, stopping at the first failure.
|
|
123
|
+
*
|
|
124
|
+
* Purely observational: supplying it cannot change the outcome, and a callback
|
|
125
|
+
* that throws is swallowed rather than turned into a verification failure — a
|
|
126
|
+
* presentation bug must never be able to answer a security question.
|
|
127
|
+
*
|
|
128
|
+
* Note the trace covers the SIGNATURE checks only. verifyAgentToken's audience
|
|
129
|
+
* and expiry checks run after these and are not reported here.
|
|
130
|
+
*/
|
|
131
|
+
onStep?: (step: VerifyStep) => void;
|
|
132
|
+
}
|
|
133
|
+
export interface PublicJwk {
|
|
134
|
+
kty: string;
|
|
135
|
+
crv: string;
|
|
136
|
+
x: string;
|
|
137
|
+
alg?: string;
|
|
138
|
+
use?: string;
|
|
139
|
+
kid?: string;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Exact string match, deliberately. Prefix or substring matching here is the
|
|
143
|
+
* classic issuer-confusion bug: `https://good.com.evil.com` starts with nothing
|
|
144
|
+
* useful but ends the way a naive `endsWith` would like, and
|
|
145
|
+
* `https://evil.com/?x=https://good.com` contains a trusted origin outright.
|
|
146
|
+
* A trailing slash is the one normalisation worth allowing.
|
|
147
|
+
*/
|
|
148
|
+
export declare function matchesIssuer(iss: string, trusted: string[]): boolean;
|
|
149
|
+
/**
|
|
150
|
+
* Verify a signed call receipt.
|
|
151
|
+
*
|
|
152
|
+
* What a valid receipt proves: this issuer attests that the named passport or
|
|
153
|
+
* Direct Agent Key authenticated this call, with this verdict and this cost.
|
|
154
|
+
* A direct receipt proves bearer possession, not a passport signature. It does
|
|
155
|
+
* NOT prove:
|
|
156
|
+
* anything about the response, and nothing at all by its absence — see
|
|
157
|
+
* lib/receipt.ts for the limits, which are deliberate and documented.
|
|
158
|
+
*/
|
|
159
|
+
export declare function verifyReceipt(jws: string, options: VerifyOptions): Promise<VerifyResult<ReceiptClaims>>;
|
|
160
|
+
export interface VerifyAgentTokenOptions extends VerifyOptions {
|
|
161
|
+
/** The audience YOU are. Required: a token minted for someone else is not for you. */
|
|
162
|
+
audience: string;
|
|
163
|
+
/**
|
|
164
|
+
* Additionally ask the issuer whether the passport is still active. Off by
|
|
165
|
+
* default — the whole point of this design is that verification needs no
|
|
166
|
+
* callback — but a long-lived decision may want live revocation state.
|
|
167
|
+
*/
|
|
168
|
+
requireOnline?: boolean;
|
|
169
|
+
now?: () => number;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Verify an agent-to-agent token.
|
|
173
|
+
*
|
|
174
|
+
* ── Replay is YOUR problem, deliberately ────────────────────────────────────
|
|
175
|
+
*
|
|
176
|
+
* There is no server-side jti denylist, because there is no server in this
|
|
177
|
+
* path: verification is offline by design. A token is a bearer credential for
|
|
178
|
+
* its (short) lifetime, so if replay matters to you, dedupe on `claims.jti` —
|
|
179
|
+
* which is why it is returned. The short TTL bounds the window; it does not
|
|
180
|
+
* close it.
|
|
181
|
+
*/
|
|
182
|
+
export declare function verifyAgentToken(token: string, options: VerifyAgentTokenOptions): Promise<VerifyResult<AgentTokenClaims>>;
|