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/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 { 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,15 +40,91 @@ 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
+ }) {
109
+ // The upstream URL below is built from this, not from the argument: the
110
+ // sidecar forwards a bearer visa on every proxied request, so its destination
111
+ // is part of the credential's security rather than a formatting detail.
112
+ const origin = bareGatewayOrigin(gateway);
25
113
  const visas = createVisaClient({
26
- gateway,
114
+ gateway: origin,
27
115
  passportId,
28
116
  passportSecret,
29
117
  refreshSkewSeconds,
30
118
  missingVisaMessage: "challenge returned no visa",
31
119
  });
32
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
+
33
128
  function readBody(req) {
34
129
  return new Promise((resolve, reject) => {
35
130
  const chunks = [];
@@ -39,14 +134,14 @@ export function createSidecar({ gateway, passportId, passportSecret, port = 8788
39
134
  });
40
135
  }
41
136
 
42
- async function fetchUpstream(req, body, visa) {
137
+ async function fetchUpstream(req, path, body, visa) {
43
138
  const headers = {};
44
139
  for (const [k, v] of Object.entries(req.headers)) {
45
140
  if (!isStripped(k) && typeof v === "string") headers[k] = v;
46
141
  }
47
142
  headers["authorization"] = `Bearer ${visa}`;
48
143
  headers["accept-encoding"] = "identity";
49
- return fetch(`${gateway}${req.url}`, { method: req.method, headers, body: body ?? undefined });
144
+ return fetch(`${origin}${path}`, { method: req.method, headers, body: body ?? undefined });
50
145
  }
51
146
 
52
147
  function writeResponse(res, upstream) {
@@ -60,9 +155,19 @@ export function createSidecar({ gateway, passportId, passportSecret, port = 8788
60
155
  }
61
156
 
62
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
+
63
168
  try {
64
169
  const body = await readBody(req);
65
- const upstream = await visas.fetchWithVisa((visa) => fetchUpstream(req, body, visa));
170
+ const upstream = await visas.fetchWithVisa((visa) => fetchUpstream(req, verdict.path, body, visa));
66
171
  writeResponse(res, upstream);
67
172
  } catch (e) {
68
173
  if (!res.headersSent) {
@@ -74,17 +179,89 @@ export function createSidecar({ gateway, passportId, passportSecret, port = 8788
74
179
  }
75
180
  });
76
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
+
77
224
  return { server, getVisa: visas.getVisa };
78
225
  }
79
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
+
80
244
  export function startSidecar(opts) {
81
- 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);
82
247
  const { server, getVisa } = createSidecar(opts);
83
248
  server.listen(port, host, () => {
84
249
  step(`PassControl visa sidecar forwarding to ${gateway}`);
85
250
  step(`Listening on http://${host}:${port}`);
86
251
  step(`Point your agent at: http://${host}:${port}/api/v1/anthropic (or /api/v1/openai)`);
87
- 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
+ );
88
265
  getVisa()
89
266
  .then(() => ok("visa warmed"))
90
267
  .catch((e) => fail(`could not mint initial visa: ${e.message}`));
@@ -1,5 +1,5 @@
1
1
  import { ed25519 } from "@noble/curves/ed25519";
2
- import { formatChallengeError } from "./config.mjs";
2
+ import { bareGatewayOrigin, formatChallengeError } from "./config.mjs";
3
3
 
4
4
  const b64url = (bytes) =>
5
5
  Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
@@ -16,6 +16,14 @@ export function createVisaClient({
16
16
  refreshSkewSeconds = 30,
17
17
  missingVisaMessage = "Challenge returned no visa.",
18
18
  }) {
19
+ // Both callers (`sidecar`, `mcp`) already hand this a validated origin, and it
20
+ // is validated AGAIN here on purpose. This is the one function in the CLI that
21
+ // signs with the passport private key, so the guard belongs where the
22
+ // signature is produced rather than only where the caller happened to
23
+ // remember it — that omission is exactly how the passport paths ended up on
24
+ // the raw string while the control plane was guarded. Idempotent: an origin
25
+ // that passed the rule passes it unchanged.
26
+ const origin = bareGatewayOrigin(gateway);
19
27
  const skewMs = Math.max(0, Number(refreshSkewSeconds) * 1000);
20
28
  let cached = null;
21
29
  let inflight = null;
@@ -24,7 +32,7 @@ export function createVisaClient({
24
32
  const payloadObject = { passport_id: passportId, ts: now(), nonce: randomUUID() };
25
33
  const payload = b64url(new TextEncoder().encode(JSON.stringify(payloadObject)));
26
34
  const signature = b64url(ed25519.sign(fromB64url(payload), fromB64url(passportSecret)));
27
- const response = await fetchImpl(`${gateway}/api/auth/challenge`, {
35
+ const response = await fetchImpl(`${origin}/api/auth/challenge`, {
28
36
  method: "POST",
29
37
  headers: { "content-type": "application/json" },
30
38
  body: JSON.stringify({ payload, signature }),
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "passcontrol",
3
- "version": "0.5.3",
4
- "description": "Secure Agent Control Plane & Passport Vault — identity-aware reverse proxy for AI agent credentials.",
3
+ "version": "0.6.1",
4
+ "description": "Identity, scope and budget controls for AI agents while provider keys stay server-side.",
5
5
  "license": "BUSL-1.1",
6
- "homepage": "https://github.com/Vertias3u/PassControl#readme",
6
+ "homepage": "https://passcontrol.vertias.eu",
7
7
  "repository": {
8
8
  "type": "git",
9
9
  "url": "git+https://github.com/Vertias3u/PassControl.git"
@@ -32,6 +32,14 @@
32
32
  "bin": {
33
33
  "passcontrol": "bin/passcontrol.mjs"
34
34
  },
35
+ "type": "module",
36
+ "exports": {
37
+ "./sdk": {
38
+ "types": "./sdk/index.d.ts",
39
+ "import": "./sdk/index.js"
40
+ },
41
+ "./package.json": "./package.json"
42
+ },
35
43
  "dependencies": {
36
44
  "@modelcontextprotocol/sdk": "^1.30.0",
37
45
  "@noble/curves": "^1.6.0",
package/sdk/README.md ADDED
@@ -0,0 +1,152 @@
1
+ # PassControl client SDK
2
+
3
+ The thin client that hides **visa minting**. Your agent holds an Ed25519 passport;
4
+ this SDK signs the challenge, mints the short-lived work-visa, refreshes it before it
5
+ expires, and injects it into requests — so integrating PassControl means *re-pointing*
6
+ your existing OpenAI/Anthropic SDK, **not rewriting the agent**.
7
+
8
+ Install it beside the provider SDK used by your agent:
9
+
10
+ ```bash
11
+ npm install passcontrol@^0.6.0 openai
12
+ # or: npm install passcontrol@^0.6.0 @anthropic-ai/sdk
13
+ ```
14
+
15
+ Dependencies: only [`@noble/curves`](https://github.com/paulmillr/noble-curves) and the
16
+ platform `fetch`/`crypto`. Runs on Node 18+ and edge/server runtimes.
17
+
18
+ > Keep `passportSecret` in the trusted agent runtime and out of source control, logs,
19
+ > browser bundles and `NEXT_PUBLIC_`/`VITE_` variables. It only ever *signs*; it never
20
+ > travels to the gateway.
21
+
22
+ ### `gateway` must be a bare origin
23
+
24
+ Scheme + host + optional port. No path, query, fragment or embedded credentials, and **HTTPS
25
+ except on loopback** — `localhost`, `127.0.0.1` and `[::1]` may use plain HTTP for local
26
+ development. The constructor throws otherwise, before any network access.
27
+
28
+ **Both credential-bearing clients enforce this identical rule, from one shared implementation**
29
+ (`PassControl` for the visa, `ControlClient` for the `pc_` control-plane key). The value is
30
+ parsed as a URL — never prefix- or suffix-matched — and the origin the client uses is re-derived
31
+ from the parse, so `https://trusted.example@attacker.example` is refused rather than read as the
32
+ host it imitates. Neither secret belongs anywhere but a trusted server runtime.
33
+
34
+ That rejects two self-host shapes worth knowing about up front:
35
+
36
+ - **Plain HTTP on a non-loopback host** — a Docker Compose service name
37
+ (`http://passcontrol:3000`), `http://host.docker.internal:3000`, or a LAN address. Front the
38
+ gateway with TLS, or reach it through a loopback port-forward.
39
+ - **A gateway served under a sub-path** (`https://example.com/passcontrol`). Give it its own
40
+ origin or subdomain.
41
+
42
+ The rule exists because the visa is a bearer credential: the SDK pins it to exactly this origin
43
+ and refuses to attach it anywhere else, so a gateway value that is loose about scheme or path
44
+ would weaken the pin it is used to define.
45
+
46
+ ## Drop-in with the OpenAI SDK
47
+
48
+ ```ts
49
+ import OpenAI from "openai";
50
+ import { PassControl } from "passcontrol/sdk";
51
+
52
+ const pc = new PassControl({
53
+ gateway: process.env.PASSCONTROL_GATEWAY!, // https://your-gateway.example.com
54
+ passportId: process.env.PASSPORT_ID!, // base64url Ed25519 public key
55
+ passportSecret: process.env.PASSPORT_SECRET!,// base64url Ed25519 private key
56
+ });
57
+
58
+ const openai = new OpenAI(pc.clientOptions("openai"));
59
+
60
+ const r = await openai.chat.completions.create({
61
+ model: "gpt-4o-mini",
62
+ messages: [{ role: "user", content: "Say hello in 3 words." }],
63
+ });
64
+ ```
65
+
66
+ ## Drop-in with the Anthropic SDK
67
+
68
+ ```ts
69
+ import Anthropic from "@anthropic-ai/sdk";
70
+ import { PassControl } from "passcontrol/sdk";
71
+
72
+ const pc = new PassControl({ gateway, passportId, passportSecret });
73
+ const anthropic = new Anthropic(pc.clientOptions("anthropic"));
74
+
75
+ const msg = await anthropic.messages.create({
76
+ model: "claude-haiku-4-5",
77
+ max_tokens: 128,
78
+ messages: [{ role: "user", content: "Say hello in 3 words." }],
79
+ });
80
+ ```
81
+
82
+ `clientOptions(provider)` returns `{ baseURL, apiKey, fetch }`. The `fetch` wrapper owns
83
+ auth (it sets `Authorization: Bearer <visa>` and strips any `x-api-key`), so the `apiKey`
84
+ is a non-secret placeholder the SDK constructor requires — your real provider key never
85
+ leaves the gateway's vault. It also refuses to attach a visa to any origin or non-provider
86
+ path outside the configured PassControl gateway.
87
+
88
+ ## Raw usage (no provider SDK)
89
+
90
+ ```ts
91
+ const pc = new PassControl({ gateway, passportId, passportSecret });
92
+
93
+ // Mint/refresh a visa yourself:
94
+ const visa = await pc.getVisa();
95
+
96
+ // …or use the wrapped fetch directly against the proxy:
97
+ const res = await pc.fetch(`${gateway}/api/v1/anthropic/v1/messages`, {
98
+ method: "POST",
99
+ headers: { "content-type": "application/json" },
100
+ body: JSON.stringify({ model: "claude-haiku-4-5", max_tokens: 64,
101
+ messages: [{ role: "user", content: "hi" }] }),
102
+ });
103
+ ```
104
+
105
+ ## Control-plane SDK (manage your fleet)
106
+
107
+ Separate from the data-plane client above: `ControlClient` (in `./control`) is a typed
108
+ wrapper over the developer API (`/api/control/v1`), authenticated with a `pc_` API key.
109
+ It mirrors the REST resources, unwraps the `{ data }` envelope, and throws
110
+ `ControlApiError` (with `status`, `code`, `requestId`) on failure.
111
+
112
+ ```ts
113
+ import { ControlClient } from "passcontrol/sdk";
114
+
115
+ const pc = new ControlClient({
116
+ gateway: process.env.PASSCONTROL_GATEWAY!,
117
+ apiKey: process.env.PASSCONTROL_API_KEY!, // pc_… (server-side only)
118
+ });
119
+
120
+ const agents = await pc.agents.list({ status: "active" });
121
+ const created = await pc.agents.create(
122
+ { name: "billing-bot", passportPubkey, scopes: [{ provider: "anthropic", models: ["claude-*"] }] },
123
+ { idempotencyKey: "create-billing-bot" } // safe retries
124
+ );
125
+ await pc.agents.suspend(created.id);
126
+ await pc.killSwitch.set(true); // arm the tenant master kill
127
+
128
+ const spend = await pc.spend.get(); // micro-cents; USD = µ¢ / 100_000_000
129
+ ```
130
+
131
+ Its `gateway` follows [the same bare-origin rule](#gateway-must-be-a-bare-origin) as the
132
+ data-plane client, and for a stronger reason: a `pc_` key is long-lived and manages the whole
133
+ fleet, so it is only ever attached to `<origin>/api/control/v1` on the validated origin. Plain
134
+ HTTP off loopback, a sub-path, or embedded userinfo throw at construction, before the transport
135
+ — default or custom — is called. Keep the key server-side; it is never printed by the client.
136
+
137
+ Resources: `agents.{list,get,create,update,suspend,resume,revoke}`, `logs.list`,
138
+ `audit.list`, `spend.get`, `killSwitch.{get,set}`. Writes accept `{ idempotencyKey }`.
139
+ The full reference lives in [the public OpenAPI document](https://github.com/Vertias3u/PassControl/blob/main/openapi.yaml).
140
+
141
+ ## Behavior
142
+
143
+ - **Cache + refresh.** A minted visa is cached and reused until it is within
144
+ `refreshSkewSeconds` (default 30s) of expiry, then re-minted automatically.
145
+ - **Single-flight.** Concurrent `getVisa()` calls share one challenge request.
146
+ - **401 retry.** If a proxied call returns `401` (visa rejected/expired), the SDK
147
+ invalidates the cache, re-mints once, and retries.
148
+ - **Origin pinning.** A visa is attached only to `/api/v1/*` on the configured gateway origin.
149
+ Any other origin, scheme, port or path — including the challenge endpoint and the control
150
+ plane — is refused before the request leaves the process.
151
+ - **No secret on the wire.** The passport private key only signs the challenge locally;
152
+ the gateway only ever sees the public key and the signature.
@@ -0,0 +1,103 @@
1
+ export interface ControlClientOptions {
2
+ /**
3
+ * Gateway origin, e.g. https://gateway.example.com — scheme, host and optional
4
+ * port only. Validated at construction against the same bare-origin rule as
5
+ * `PassControl`; plain HTTP is accepted only on loopback. See ./gateway.
6
+ */
7
+ gateway: string;
8
+ /** Developer API key (`pc_…`). Keep server-side. */
9
+ apiKey: string;
10
+ /** Override the transport (tests / custom fetch). Defaults to global fetch. */
11
+ fetch?: typeof fetch;
12
+ }
13
+ export declare class ControlApiError extends Error {
14
+ readonly status: number;
15
+ readonly code: string;
16
+ readonly requestId?: string | undefined;
17
+ constructor(status: number, code: string, message: string, requestId?: string | undefined);
18
+ }
19
+ export interface WriteOpts {
20
+ /** Idempotency-Key — a retry with the same key won't re-apply the mutation. */
21
+ idempotencyKey?: string;
22
+ }
23
+ export declare class ControlClient {
24
+ #private;
25
+ private readonly base;
26
+ private readonly transport;
27
+ constructor(opts: ControlClientOptions);
28
+ private req;
29
+ readonly agents: {
30
+ list: (params?: {
31
+ status?: string;
32
+ limit?: number;
33
+ }) => Promise<any[]>;
34
+ get: (id: string) => Promise<any>;
35
+ create: (body: {
36
+ name: string;
37
+ passportPubkey: string;
38
+ scopes: {
39
+ provider: string;
40
+ models: string[];
41
+ }[];
42
+ budget_tokens?: number | null;
43
+ budget_cents?: number | null;
44
+ }, opts?: WriteOpts) => Promise<{
45
+ id: string;
46
+ name: string;
47
+ }>;
48
+ update: (id: string, patch: {
49
+ name?: string;
50
+ scopes?: {
51
+ provider: string;
52
+ models: string[];
53
+ }[];
54
+ budget_tokens?: number | null;
55
+ budget_cents?: number | null;
56
+ }, opts?: WriteOpts) => Promise<{
57
+ id: string;
58
+ }>;
59
+ suspend: (id: string, opts?: WriteOpts) => Promise<{
60
+ id: string;
61
+ status: string;
62
+ }>;
63
+ resume: (id: string, opts?: WriteOpts) => Promise<{
64
+ id: string;
65
+ status: string;
66
+ }>;
67
+ revoke: (id: string, opts?: WriteOpts) => Promise<{
68
+ id: string;
69
+ status: string;
70
+ }>;
71
+ };
72
+ readonly logs: {
73
+ list: (params?: {
74
+ agent_id?: string;
75
+ status?: string;
76
+ limit?: number;
77
+ }) => Promise<any[]>;
78
+ };
79
+ readonly audit: {
80
+ list: (params?: {
81
+ limit?: number;
82
+ }) => Promise<any[]>;
83
+ };
84
+ readonly spend: {
85
+ get: () => Promise<{
86
+ fleet: {
87
+ spent_tokens: number;
88
+ spent_microcents: number;
89
+ };
90
+ agents: any[];
91
+ }>;
92
+ };
93
+ readonly killSwitch: {
94
+ get: () => Promise<{
95
+ armed: boolean;
96
+ platform_kill: boolean;
97
+ }>;
98
+ set: (armed: boolean, opts?: WriteOpts) => Promise<{
99
+ armed: boolean;
100
+ affected: number;
101
+ }>;
102
+ };
103
+ }
package/sdk/control.js ADDED
@@ -0,0 +1,102 @@
1
+ // PassControl control-plane SDK — a typed client for the developer API
2
+ // (/api/control/v1), authenticated with a `pc_` API key. Mirrors the REST
3
+ // resources 1:1. Distinct from the data-plane client in ./passcontrol (visa
4
+ // minting for agents); this manages the fleet.
5
+ //
6
+ // Load ControlClient from the package SDK export, then construct it with the
7
+ // gateway and a server-side developer API key.
8
+ // const agents = await pc.agents.list({ status: "active" });
9
+ //
10
+ // Responses are unwrapped (the API's `{ data }` envelope → the value); non-2xx
11
+ // throws ControlApiError carrying the API error code + request id.
12
+ import { requireGatewayOrigin } from "./gateway.js";
13
+ export class ControlApiError extends Error {
14
+ status;
15
+ code;
16
+ requestId;
17
+ constructor(status, code, message, requestId) {
18
+ super(message);
19
+ this.status = status;
20
+ this.code = code;
21
+ this.requestId = requestId;
22
+ this.name = "ControlApiError";
23
+ }
24
+ }
25
+ export class ControlClient {
26
+ base;
27
+ /**
28
+ * A real `#private` field, not a TypeScript `private` one.
29
+ *
30
+ * `private` is erased at compile time: the key would be an ordinary own
31
+ * property, so `console.log(client)` and `JSON.stringify(client)` — the two
32
+ * things every debugging session and error reporter does to an object —
33
+ * would print a long-lived, tenant-wide control-plane credential. A `#` field
34
+ * is invisible to both.
35
+ */
36
+ #apiKey;
37
+ transport;
38
+ constructor(opts) {
39
+ if (!opts.gateway || !opts.apiKey)
40
+ throw new Error("ControlClient: gateway and apiKey are required.");
41
+ // First, and before anything else in this constructor: the `pc_` key is
42
+ // long-lived, tenant-wide, and the only credential the control plane
43
+ // accepts, so `gateway` is not configuration — it decides who receives it.
44
+ // Validating here means an invalid value never reaches a stored base, never
45
+ // has the key held beside it, and never touches the default *or* a
46
+ // caller-supplied transport. The base is then built from the parsed origin,
47
+ // so no path material from the option survives into the request URL.
48
+ const origin = requireGatewayOrigin("ControlClient", opts.gateway);
49
+ this.base = `${origin}/api/control/v1`;
50
+ this.#apiKey = opts.apiKey;
51
+ const f = opts.fetch ?? globalThis.fetch;
52
+ if (!f)
53
+ throw new Error("ControlClient: no fetch available; pass options.fetch.");
54
+ this.transport = (...a) => f(...a);
55
+ }
56
+ async req(method, path, opts = {}) {
57
+ const url = new URL(this.base + path);
58
+ for (const [k, v] of Object.entries(opts.query ?? {})) {
59
+ if (v !== undefined && v !== null)
60
+ url.searchParams.set(k, String(v));
61
+ }
62
+ const headers = { authorization: `Bearer ${this.#apiKey}` };
63
+ if (opts.body !== undefined)
64
+ headers["content-type"] = "application/json";
65
+ if (opts.idempotencyKey)
66
+ headers["idempotency-key"] = opts.idempotencyKey;
67
+ const res = await this.transport(url.toString(), {
68
+ method,
69
+ headers,
70
+ body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
71
+ });
72
+ const text = await res.text();
73
+ const json = text ? JSON.parse(text) : {};
74
+ if (!res.ok) {
75
+ const e = (json?.error ?? {});
76
+ throw new ControlApiError(res.status, e.code ?? "error", e.message ?? res.statusText, e.request_id);
77
+ }
78
+ return json.data;
79
+ }
80
+ agents = {
81
+ list: (params) => this.req("GET", "/agents", { query: params }),
82
+ get: (id) => this.req("GET", `/agents/${encodeURIComponent(id)}`),
83
+ create: (body, opts) => this.req("POST", "/agents", { body, idempotencyKey: opts?.idempotencyKey }),
84
+ update: (id, patch, opts) => this.req("PATCH", `/agents/${encodeURIComponent(id)}`, { body: patch, idempotencyKey: opts?.idempotencyKey }),
85
+ suspend: (id, opts) => this.req("POST", `/agents/${encodeURIComponent(id)}/suspend`, { idempotencyKey: opts?.idempotencyKey }),
86
+ resume: (id, opts) => this.req("POST", `/agents/${encodeURIComponent(id)}/resume`, { idempotencyKey: opts?.idempotencyKey }),
87
+ revoke: (id, opts) => this.req("DELETE", `/agents/${encodeURIComponent(id)}`, { idempotencyKey: opts?.idempotencyKey }),
88
+ };
89
+ logs = {
90
+ list: (params) => this.req("GET", "/logs", { query: params }),
91
+ };
92
+ audit = {
93
+ list: (params) => this.req("GET", "/audit", { query: params }),
94
+ };
95
+ spend = {
96
+ get: () => this.req("GET", "/spend"),
97
+ };
98
+ killSwitch = {
99
+ get: () => this.req("GET", "/kill-switch"),
100
+ set: (armed, opts) => this.req("PUT", "/kill-switch", { body: { armed }, idempotencyKey: opts?.idempotencyKey }),
101
+ };
102
+ }