passcontrol 0.5.3 → 0.6.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/LICENSE +2 -2
- package/README.md +90 -22
- package/bin/passcontrol.mjs +238 -71
- package/cli/config.mjs +95 -0
- package/cli/mcp/gateway.mjs +4 -4
- package/cli/presets.mjs +1 -0
- package/cli/sidecar.mjs +7 -3
- 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/cli/sidecar.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import http from "node:http";
|
|
2
2
|
import { Readable } from "node:stream";
|
|
3
|
-
import { fail, ok, step } from "./config.mjs";
|
|
3
|
+
import { bareGatewayOrigin, fail, ok, step } from "./config.mjs";
|
|
4
4
|
import { createVisaClient } from "./visa-client.mjs";
|
|
5
5
|
|
|
6
6
|
const STRIP_REQ = new Set(["authorization", "x-api-key", "host", "content-length", "accept-encoding", "connection"]);
|
|
@@ -22,8 +22,12 @@ function isStripped(name) {
|
|
|
22
22
|
const STRIP_RES = new Set(["content-encoding", "content-length", "transfer-encoding", "connection"]);
|
|
23
23
|
|
|
24
24
|
export function createSidecar({ gateway, passportId, passportSecret, port = 8788, host = "127.0.0.1", refreshSkewSeconds = 30 }) {
|
|
25
|
+
// The upstream URL below is built from this, not from the argument: the
|
|
26
|
+
// sidecar forwards a bearer visa on every proxied request, so its destination
|
|
27
|
+
// is part of the credential's security rather than a formatting detail.
|
|
28
|
+
const origin = bareGatewayOrigin(gateway);
|
|
25
29
|
const visas = createVisaClient({
|
|
26
|
-
gateway,
|
|
30
|
+
gateway: origin,
|
|
27
31
|
passportId,
|
|
28
32
|
passportSecret,
|
|
29
33
|
refreshSkewSeconds,
|
|
@@ -46,7 +50,7 @@ export function createSidecar({ gateway, passportId, passportSecret, port = 8788
|
|
|
46
50
|
}
|
|
47
51
|
headers["authorization"] = `Bearer ${visa}`;
|
|
48
52
|
headers["accept-encoding"] = "identity";
|
|
49
|
-
return fetch(`${
|
|
53
|
+
return fetch(`${origin}${req.url}`, { method: req.method, headers, body: body ?? undefined });
|
|
50
54
|
}
|
|
51
55
|
|
|
52
56
|
function writeResponse(res, upstream) {
|
package/cli/visa-client.mjs
CHANGED
|
@@ -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(`${
|
|
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.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.6.0",
|
|
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://
|
|
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.
|
package/sdk/control.d.ts
ADDED
|
@@ -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
|
+
}
|
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
|
+
}
|