passport-bridge 0.8.1 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +81 -3
- package/dist/accessClient.d.ts +128 -0
- package/dist/accessClient.js +436 -0
- package/dist/activeProfile.d.ts +21 -0
- package/dist/boundedFile.d.ts +2 -0
- package/dist/boundedMcpFetch.d.ts +6 -0
- package/dist/boundedResponse.d.ts +4 -0
- package/dist/bridge.d.ts +89 -0
- package/dist/bridgeConfig.d.ts +1 -0
- package/dist/bridgeShutdown.d.ts +17 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cliAccess.d.ts +3 -0
- package/dist/cliAccess.js +119 -0
- package/dist/cliArgs.d.ts +16 -0
- package/dist/cliArgs.js +10 -2
- package/dist/cliClient.d.ts +62 -0
- package/dist/cliConnect.d.ts +22 -0
- package/dist/cliDeadline.d.ts +9 -0
- package/dist/cliDescribe.d.ts +8 -0
- package/dist/cliLogin.d.ts +3 -0
- package/dist/cliOffline.d.ts +6 -0
- package/dist/cliOutput.d.ts +7 -0
- package/dist/cliOutput.js +2 -0
- package/dist/cliPagination.d.ts +15 -0
- package/dist/cliProtocol.d.ts +4 -0
- package/dist/cliReady.d.ts +9 -0
- package/dist/cliResult.d.ts +7 -0
- package/dist/cliSession.d.ts +20 -0
- package/dist/cliSupport.d.ts +102 -0
- package/dist/completion.d.ts +2 -0
- package/dist/completion.js +18 -2
- package/dist/credentialStorage.d.ts +12 -0
- package/dist/credentials.d.ts +64 -0
- package/dist/discover.d.ts +52 -0
- package/dist/doctor.d.ts +34 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/legacyCliSecurity.d.ts +10 -0
- package/dist/passport.d.ts +7 -0
- package/dist/passport.js +2 -0
- package/dist/privateStableFile.d.ts +13 -0
- package/dist/recoveryCleanup.d.ts +5 -0
- package/dist/recoveryIdentity.d.ts +22 -0
- package/dist/tokenWorkspace.d.ts +3 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +1 -1
- package/npm-shrinkwrap.json +15 -15
- package/package.json +13 -2
package/README.md
CHANGED
|
@@ -49,7 +49,7 @@ Remote Passport servers must use HTTPS. Plain HTTP is accepted only for local
|
|
|
49
49
|
development on `localhost`, `127.0.0.0/8`, or `::1`. Self-hosted deployments
|
|
50
50
|
should terminate HTTPS before using interactive profiles or agent keys.
|
|
51
51
|
|
|
52
|
-
Passport CLI 0.
|
|
52
|
+
Passport CLI 0.9.0 requires gateway MCP serverInfo `passport` version 0.5.0 or
|
|
53
53
|
newer and the exact four-tool governed CLI protocol. Older servers fail clearly
|
|
54
54
|
before the CLI makes a tool call.
|
|
55
55
|
|
|
@@ -70,6 +70,7 @@ before the CLI makes a tool call.
|
|
|
70
70
|
| `prompts [name]` | List or get MCP prompts. |
|
|
71
71
|
| `discover` | Scan supported global MCP configuration and submit a privacy-minimized fleet report. |
|
|
72
72
|
| `session` | Process NDJSON commands through one authenticated MCP session. |
|
|
73
|
+
| `access` | Use signed managed access (`keygen`, `actions`, `run`, `invoke`, `status`, or `cancel`). |
|
|
73
74
|
| `completion <shell>` | Generate completion for Bash, Zsh, or Fish without a profile or network. |
|
|
74
75
|
| `profiles` | List stored profiles and show the active profile without a network request. |
|
|
75
76
|
| `use <name>` | Select the active stored profile without a network request. |
|
|
@@ -181,9 +182,85 @@ The mode does not weaken authorization: every operation still executes through
|
|
|
181
182
|
the governed gateway, and cached access tokens retain the normal expiry and
|
|
182
183
|
401-refresh behavior.
|
|
183
184
|
|
|
185
|
+
### Managed access
|
|
186
|
+
|
|
187
|
+
Managed access uses a registered workload credential and a signed
|
|
188
|
+
`private_key_jwt` client assertion. It is separate from the interactive profile
|
|
189
|
+
commands above. Generate a key pair on the workload machine; `keygen` refuses
|
|
190
|
+
to overwrite existing files, writes the private PEM with owner-only
|
|
191
|
+
permissions, and writes the public JWK to a separate file:
|
|
192
|
+
|
|
193
|
+
```sh
|
|
194
|
+
passport access keygen --algorithm ES256
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
Register only the public JWK in **Agents & access**, then configure the
|
|
198
|
+
workload with the generated workspace-prefixed client ID and the local private
|
|
199
|
+
key path. Set the endpoint to the Passport origin, for example:
|
|
200
|
+
|
|
201
|
+
```sh
|
|
202
|
+
export PASSPORT_ENDPOINT=https://passport.example.com
|
|
203
|
+
export PASSPORT_WORKSPACE_ID=ws_example
|
|
204
|
+
export PASSPORT_CLIENT_ID=ws_example~awc_example
|
|
205
|
+
export PASSPORT_PRIVATE_KEY_FILE=/run/secrets/passport-access.pem
|
|
206
|
+
export PASSPORT_CALLER_ID=build-job-1
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
The client assertion uses `iss` and `sub` equal to `PASSPORT_CLIENT_ID` and
|
|
210
|
+
`aud` equal to `${PASSPORT_ENDPOINT}/oauth/token`. Passport returns a
|
|
211
|
+
short-lived access token for the protected resource
|
|
212
|
+
`${PASSPORT_ENDPOINT}/w/${PASSPORT_WORKSPACE_ID}/mcp`; the CLI and SDK do not
|
|
213
|
+
print that token.
|
|
214
|
+
|
|
215
|
+
Inspect the exact actions allowed by the credential and its grants, create a
|
|
216
|
+
bounded run, and invoke one action:
|
|
217
|
+
|
|
218
|
+
```sh
|
|
219
|
+
passport access actions --json
|
|
220
|
+
passport access run --input run.json --json
|
|
221
|
+
passport access invoke --input invocation.json --caller build-job-1 --json
|
|
222
|
+
passport access status <invocation-id> --json
|
|
223
|
+
passport access cancel <run-id> --json
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
`run.json` contains a non-empty `capabilities` list copied from `actions`,
|
|
227
|
+
with optional `delegationId`, `expiresInSeconds` (60 seconds to 24 hours), and
|
|
228
|
+
`callLimit` (1 to 10,000). `invocation.json` contains `runId`, a stable unique
|
|
229
|
+
`invocationId`, the selected `appId`, `tool`, `resource`, `connectionId`, and
|
|
230
|
+
the tool's `args` object. Keep the same invocation file when resuming a
|
|
231
|
+
definite approval-pending result. After a human approves it in Passport,
|
|
232
|
+
invoke again with the same caller and exact arguments. For a timeout or
|
|
233
|
+
unknown result, inspect `access status` before considering another write; the
|
|
234
|
+
CLI and SDK never retry provider writes automatically.
|
|
235
|
+
|
|
236
|
+
For delegated work, first run `passport access actions --delegation-id <id> --json`.
|
|
237
|
+
Copy those capabilities into the run input and include the same `delegationId`.
|
|
238
|
+
The agent and the delegated person both need matching allow grants.
|
|
239
|
+
|
|
240
|
+
The SDK is available from either the package root or the explicit access
|
|
241
|
+
subpath:
|
|
242
|
+
|
|
243
|
+
```js
|
|
244
|
+
import { accessClientFromEnv } from "passport-bridge/access";
|
|
245
|
+
|
|
246
|
+
const client = accessClientFromEnv(process.env, { callerId: "build-job-1" });
|
|
247
|
+
const actions = await client.actions();
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
`AccessGatewayClient` exposes `actions`, `createRun`, `invoke`, `status`, and
|
|
251
|
+
`cancel`. Invocations require a stable caller ID; pass it in the constructor or
|
|
252
|
+
to `invoke`. Inputs are read from bounded files by the CLI, and authentication
|
|
253
|
+
failures are reported without response bodies or credential values.
|
|
254
|
+
For delegated discovery, call `client.actions(delegationId)` and include that
|
|
255
|
+
same `delegationId` when calling `createRun`.
|
|
256
|
+
|
|
257
|
+
Managed execution requires PostgreSQL and Enterprise workspace controls. Set up
|
|
258
|
+
organization connections, grants, and delegations in **Agents & access** before
|
|
259
|
+
the workload requests actions.
|
|
260
|
+
|
|
184
261
|
### Approvals and connections
|
|
185
262
|
|
|
186
|
-
An approval-required call exits immediately with code 4 and its approval ID. `--wait <seconds>` retries only after a definite structured `approval_pending` response:
|
|
263
|
+
An approval-required `passport run` call exits immediately with code 4 and its approval ID. `--wait <seconds>` retries only after a definite structured `approval_pending` response:
|
|
187
264
|
|
|
188
265
|
```sh
|
|
189
266
|
passport run github_create_issue '{"title":"Customer report"}' --wait 90
|
|
@@ -233,6 +310,7 @@ With `--json`, stdout contains exactly one JSON value and no progress text. Hint
|
|
|
233
310
|
| `prompts` | The MCP list or get result. |
|
|
234
311
|
| `discover` | `{snapshot,report,compliant}`. The snapshot contains privacy-minimized metadata only. |
|
|
235
312
|
| `session` | NDJSON envelopes: `{id?,ok,exitCode,result?}` or `{id?,ok:false,error,cause,exitCode,...}`. |
|
|
313
|
+
| `access` | `keygen` returns algorithm, file paths, and the public JWK; `actions` returns `{actions}`; `run` returns `{run}`; `invoke` returns the governed result; `status` returns `{receipt}`; `cancel` returns `{run}`. |
|
|
236
314
|
| `completion` | `{shell,script}`. Human mode emits the raw completion script. |
|
|
237
315
|
| `help` | `{command, help}` |
|
|
238
316
|
| `version` | `{version,profileCount,profileSelected,selectionSource,next,requiredInput?,endpoint?,profile?}` |
|
|
@@ -271,7 +349,7 @@ credential store is shared with `passport-bridge` and refresh exchanges are
|
|
|
271
349
|
coordinated across processes. The active-profile pointer contains no
|
|
272
350
|
credential and is local to this Passport credential store.
|
|
273
351
|
|
|
274
|
-
When no explicit, environment, or active selector is present, CLI 0.
|
|
352
|
+
When no explicit, environment, or active selector is present, CLI 0.9.0
|
|
275
353
|
detects exactly one CLI-owned profile (`client: "cli"` or the exact legacy
|
|
276
354
|
`cli@<workspace>` shape) and makes that existing profile active. If more than
|
|
277
355
|
one CLI candidate remains, run `passport profiles`, choose with `passport use <name>`,
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
export type AccessAlgorithm = "ES256" | "RS256";
|
|
2
|
+
export type AccessCapability = {
|
|
3
|
+
appId: string;
|
|
4
|
+
tool: string;
|
|
5
|
+
resource: string;
|
|
6
|
+
connectionId: string;
|
|
7
|
+
actionRevision: string;
|
|
8
|
+
};
|
|
9
|
+
export type AccessAction = {
|
|
10
|
+
capability: AccessCapability;
|
|
11
|
+
tool: string;
|
|
12
|
+
actionRevision: string;
|
|
13
|
+
readonly: boolean;
|
|
14
|
+
inputSchema: Record<string, unknown>;
|
|
15
|
+
};
|
|
16
|
+
export type AccessRunInput = {
|
|
17
|
+
capabilities: AccessCapability[];
|
|
18
|
+
delegationId?: string;
|
|
19
|
+
expiresInSeconds?: number;
|
|
20
|
+
callLimit?: number;
|
|
21
|
+
};
|
|
22
|
+
export type AccessRun = AccessRunInput & {
|
|
23
|
+
id: string;
|
|
24
|
+
workspaceId: string;
|
|
25
|
+
actorId: string;
|
|
26
|
+
actorEpoch: number;
|
|
27
|
+
status: "active" | "cancelled";
|
|
28
|
+
createdAt: number;
|
|
29
|
+
expiresAt: number;
|
|
30
|
+
calls: number;
|
|
31
|
+
};
|
|
32
|
+
export type AccessInvocationInput = {
|
|
33
|
+
runId: string;
|
|
34
|
+
invocationId: string;
|
|
35
|
+
appId: string;
|
|
36
|
+
tool: string;
|
|
37
|
+
resource: string;
|
|
38
|
+
connectionId: string;
|
|
39
|
+
args: Record<string, unknown>;
|
|
40
|
+
};
|
|
41
|
+
export type AccessReceipt = {
|
|
42
|
+
id: string;
|
|
43
|
+
runId: string;
|
|
44
|
+
actorId: string;
|
|
45
|
+
subjectId?: string;
|
|
46
|
+
state: string;
|
|
47
|
+
createdAt: number;
|
|
48
|
+
expiresAt: number;
|
|
49
|
+
appId: string;
|
|
50
|
+
tool: string;
|
|
51
|
+
resource: string;
|
|
52
|
+
connectionId: string;
|
|
53
|
+
resultExposure?: string;
|
|
54
|
+
message?: string;
|
|
55
|
+
};
|
|
56
|
+
export type AccessInvocationResult = {
|
|
57
|
+
content?: unknown[];
|
|
58
|
+
isError?: boolean;
|
|
59
|
+
structuredContent?: Record<string, unknown>;
|
|
60
|
+
[key: string]: unknown;
|
|
61
|
+
};
|
|
62
|
+
export type AccessGatewayClientOptions = {
|
|
63
|
+
endpoint: string;
|
|
64
|
+
workspaceId: string;
|
|
65
|
+
clientId: string;
|
|
66
|
+
privateKeyFile: string;
|
|
67
|
+
/** Optional when the PEM's algorithm can be inspected. */
|
|
68
|
+
algorithm?: AccessAlgorithm;
|
|
69
|
+
/** Stable caller attribution is mandatory for invocations. */
|
|
70
|
+
callerId?: string;
|
|
71
|
+
timeoutMs?: number;
|
|
72
|
+
signal?: AbortSignal;
|
|
73
|
+
fetch?: typeof fetch;
|
|
74
|
+
now?: () => number;
|
|
75
|
+
};
|
|
76
|
+
export type GeneratedAccessKey = {
|
|
77
|
+
algorithm: AccessAlgorithm;
|
|
78
|
+
privateKeyPem: string;
|
|
79
|
+
publicJwk: Record<string, unknown>;
|
|
80
|
+
};
|
|
81
|
+
export declare class AccessGatewayError extends Error {
|
|
82
|
+
readonly status?: number | undefined;
|
|
83
|
+
readonly code?: string | undefined;
|
|
84
|
+
constructor(message: string, status?: number | undefined, code?: string | undefined);
|
|
85
|
+
}
|
|
86
|
+
export declare function assertCallerId(value: string): string;
|
|
87
|
+
export declare function defaultAccessPrivateKeyFile(env?: NodeJS.ProcessEnv): string;
|
|
88
|
+
export declare function defaultAccessPublicJwkFile(privateKeyFile: string): string;
|
|
89
|
+
export declare function generateAccessKey(algorithm: AccessAlgorithm): GeneratedAccessKey;
|
|
90
|
+
/** Publish a new workload key pair without ever printing private key material.
|
|
91
|
+
* The public file is a standalone JWK ready for the admin registration request. */
|
|
92
|
+
export declare function writeGeneratedAccessKey(generated: GeneratedAccessKey, privateKeyFile: string, publicJwkFile?: string): {
|
|
93
|
+
privateKeyFile: string;
|
|
94
|
+
publicJwkFile: string;
|
|
95
|
+
publicJwk: Record<string, unknown>;
|
|
96
|
+
};
|
|
97
|
+
export declare function parseAccessInputFile(path: string): Record<string, unknown>;
|
|
98
|
+
export declare class AccessGatewayClient {
|
|
99
|
+
private readonly base;
|
|
100
|
+
private readonly workspaceId;
|
|
101
|
+
private readonly clientId;
|
|
102
|
+
private readonly privateKey;
|
|
103
|
+
private readonly algorithm;
|
|
104
|
+
private readonly callerId?;
|
|
105
|
+
private readonly timeoutMs;
|
|
106
|
+
private readonly signal?;
|
|
107
|
+
private readonly httpFetch;
|
|
108
|
+
private readonly now;
|
|
109
|
+
private accessToken?;
|
|
110
|
+
private tokenInFlight?;
|
|
111
|
+
constructor(options: AccessGatewayClientOptions);
|
|
112
|
+
get resourceEndpoint(): string;
|
|
113
|
+
get protectedActionsEndpoint(): string;
|
|
114
|
+
actions(delegationId?: string): Promise<AccessAction[]>;
|
|
115
|
+
createRun(input: AccessRunInput): Promise<AccessRun>;
|
|
116
|
+
invoke(input: AccessInvocationInput, callerId?: string | undefined): Promise<AccessInvocationResult>;
|
|
117
|
+
status(invocationId: string): Promise<AccessReceipt>;
|
|
118
|
+
cancel(runId: string): Promise<AccessRun>;
|
|
119
|
+
/** Compatibility spelling for callers that mirror the HTTP route name. */
|
|
120
|
+
cancelRun(runId: string): Promise<AccessRun>;
|
|
121
|
+
private token;
|
|
122
|
+
private exchangeToken;
|
|
123
|
+
private request;
|
|
124
|
+
private fetchWithTimeout;
|
|
125
|
+
private readResponse;
|
|
126
|
+
private serverError;
|
|
127
|
+
}
|
|
128
|
+
export declare function accessClientFromEnv(env?: NodeJS.ProcessEnv, overrides?: Partial<Pick<AccessGatewayClientOptions, "endpoint" | "workspaceId" | "clientId" | "privateKeyFile" | "callerId" | "algorithm">>): AccessGatewayClient;
|
|
@@ -0,0 +1,436 @@
|
|
|
1
|
+
import { createPrivateKey, createSign, generateKeyPairSync, randomUUID } from "node:crypto";
|
|
2
|
+
import { closeSync, constants, fchmodSync, fsyncSync, lstatSync, mkdirSync, openSync, unlinkSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { readBoundedUtf8File } from "./boundedFile.js";
|
|
6
|
+
import { readBoundedJson } from "./boundedResponse.js";
|
|
7
|
+
import { endpoint } from "./cliSupport.js";
|
|
8
|
+
const PRIVATE_KEY_MAX_BYTES = 64 * 1024;
|
|
9
|
+
const ACCESS_INPUT_MAX_BYTES = 1024 * 1024;
|
|
10
|
+
const ASSERTION_TTL_SECONDS = 120;
|
|
11
|
+
const TOKEN_REFRESH_SKEW_MS = 5_000;
|
|
12
|
+
const CALLER_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
13
|
+
const WORKSPACE_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
14
|
+
const CLIENT_ID = /^[A-Za-z0-9][A-Za-z0-9._:~/-]{0,511}$/;
|
|
15
|
+
export class AccessGatewayError extends Error {
|
|
16
|
+
status;
|
|
17
|
+
code;
|
|
18
|
+
constructor(message, status, code) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.status = status;
|
|
21
|
+
this.code = code;
|
|
22
|
+
this.name = "AccessGatewayError";
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function ownerOf(stat, label) {
|
|
26
|
+
if (typeof process.getuid === "function" && stat.uid !== process.getuid()) {
|
|
27
|
+
throw new Error(`Passport ${label} is owned by another account.`);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function ensureKeyDirectory(path, label) {
|
|
31
|
+
mkdirSync(path, { recursive: true, mode: 0o700 });
|
|
32
|
+
const stat = lstatSync(path);
|
|
33
|
+
if (stat.isSymbolicLink() || !stat.isDirectory())
|
|
34
|
+
throw new Error(`Passport ${label} directory must be regular.`);
|
|
35
|
+
ownerOf(stat, `${label} directory`);
|
|
36
|
+
if (process.platform !== "win32") {
|
|
37
|
+
const mode = stat.mode & 0o777;
|
|
38
|
+
if ((mode & 0o077) !== 0)
|
|
39
|
+
throw new Error(`Passport ${label} directory must be owner-only.`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
function assertRegularOwnerFile(path, label) {
|
|
43
|
+
const stat = lstatSync(path);
|
|
44
|
+
if (stat.isSymbolicLink() || !stat.isFile())
|
|
45
|
+
throw new Error(`Passport ${label} must be a regular file.`);
|
|
46
|
+
ownerOf(stat, label);
|
|
47
|
+
if (process.platform !== "win32" && (stat.mode & 0o077) !== 0) {
|
|
48
|
+
throw new Error(`Passport ${label} must be owner-only.`);
|
|
49
|
+
}
|
|
50
|
+
if (stat.size > PRIVATE_KEY_MAX_BYTES)
|
|
51
|
+
throw new Error(`Passport ${label} is unexpectedly large.`);
|
|
52
|
+
}
|
|
53
|
+
function readPrivateKeyFile(path) {
|
|
54
|
+
assertRegularOwnerFile(path, "private key");
|
|
55
|
+
// boundedFile repeats the no-follow regular-file and inode checks at open;
|
|
56
|
+
// the permission/owner gate above prevents a permissive key from entering
|
|
57
|
+
// the signing path.
|
|
58
|
+
return readBoundedUtf8File(path, PRIVATE_KEY_MAX_BYTES);
|
|
59
|
+
}
|
|
60
|
+
function keyAlgorithm(key) {
|
|
61
|
+
if (key.asymmetricKeyType === "ec") {
|
|
62
|
+
const jwk = key.export({ format: "jwk" });
|
|
63
|
+
if (jwk.crv !== "P-256")
|
|
64
|
+
throw new Error("Only P-256 private keys are supported for ES256.");
|
|
65
|
+
return "ES256";
|
|
66
|
+
}
|
|
67
|
+
if (key.asymmetricKeyType === "rsa") {
|
|
68
|
+
const modulusLength = key.asymmetricKeyDetails?.modulusLength;
|
|
69
|
+
if (typeof modulusLength === "number" && modulusLength < 2048) {
|
|
70
|
+
throw new Error("RS256 private keys must use at least a 2048-bit modulus.");
|
|
71
|
+
}
|
|
72
|
+
return "RS256";
|
|
73
|
+
}
|
|
74
|
+
throw new Error("The private key must be an ES256 or RS256 key.");
|
|
75
|
+
}
|
|
76
|
+
function assertWorkspaceId(value) {
|
|
77
|
+
if (!WORKSPACE_ID.test(value))
|
|
78
|
+
throw new Error("Workspace id is invalid.");
|
|
79
|
+
return value;
|
|
80
|
+
}
|
|
81
|
+
function assertClientId(value) {
|
|
82
|
+
if (!CLIENT_ID.test(value) || value.includes(".."))
|
|
83
|
+
throw new Error("Client id is invalid.");
|
|
84
|
+
return value;
|
|
85
|
+
}
|
|
86
|
+
export function assertCallerId(value) {
|
|
87
|
+
const normalized = value.trim();
|
|
88
|
+
if (!CALLER_ID.test(normalized))
|
|
89
|
+
throw new Error("A stable caller id is required.");
|
|
90
|
+
return normalized;
|
|
91
|
+
}
|
|
92
|
+
function baseEndpoint(raw, expectedWorkspaceId) {
|
|
93
|
+
const normalized = endpoint(raw);
|
|
94
|
+
const parsed = new URL(normalized);
|
|
95
|
+
// The CLI's historical endpoint is often `/mcp`; access routes are rooted
|
|
96
|
+
// at the origin, so accept that one legacy suffix and reject arbitrary path
|
|
97
|
+
// prefixes that could redirect credentials to another application.
|
|
98
|
+
const path = parsed.pathname.replace(/\/+$/, "") || "/";
|
|
99
|
+
if (path !== "/" && path !== "/mcp") {
|
|
100
|
+
const workspacePath = path.match(/^\/w\/([^/]+)\/mcp$/);
|
|
101
|
+
if (!workspacePath || (expectedWorkspaceId && decodeURIComponent(workspacePath[1]) !== expectedWorkspaceId)) {
|
|
102
|
+
throw new Error("Passport endpoint must be an origin, /mcp, or matching /w/<workspace>/mcp URL.");
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
if (parsed.search || parsed.hash)
|
|
106
|
+
throw new Error("Passport endpoint cannot contain a query or fragment.");
|
|
107
|
+
return parsed.origin;
|
|
108
|
+
}
|
|
109
|
+
function segment(value, label) {
|
|
110
|
+
if (!value || value.length > 512 || value.includes("/") || value.includes("\\")) {
|
|
111
|
+
throw new Error(`${label} is invalid.`);
|
|
112
|
+
}
|
|
113
|
+
return encodeURIComponent(value);
|
|
114
|
+
}
|
|
115
|
+
function jsonObject(raw, label) {
|
|
116
|
+
let parsed;
|
|
117
|
+
try {
|
|
118
|
+
parsed = JSON.parse(raw);
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
throw new Error(`${label} must be valid JSON.`);
|
|
122
|
+
}
|
|
123
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
124
|
+
throw new Error(`${label} must be a JSON object.`);
|
|
125
|
+
return parsed;
|
|
126
|
+
}
|
|
127
|
+
function b64url(value) {
|
|
128
|
+
return Buffer.from(value).toString("base64url");
|
|
129
|
+
}
|
|
130
|
+
function signedAssertion(privateKey, algorithm, clientId, audience, nowMs) {
|
|
131
|
+
const now = Math.floor(nowMs / 1000);
|
|
132
|
+
const header = b64url(JSON.stringify({ alg: algorithm, typ: "JWT" }));
|
|
133
|
+
const payload = b64url(JSON.stringify({
|
|
134
|
+
iss: clientId,
|
|
135
|
+
sub: clientId,
|
|
136
|
+
aud: audience,
|
|
137
|
+
iat: now,
|
|
138
|
+
exp: now + ASSERTION_TTL_SECONDS,
|
|
139
|
+
jti: randomUUID()
|
|
140
|
+
}));
|
|
141
|
+
const input = `${header}.${payload}`;
|
|
142
|
+
const signer = createSign("SHA256");
|
|
143
|
+
signer.update(input);
|
|
144
|
+
signer.end();
|
|
145
|
+
const signature = algorithm === "ES256" ? signer.sign({ key: privateKey, dsaEncoding: "ieee-p1363" }) : signer.sign(privateKey);
|
|
146
|
+
return `${input}.${b64url(signature)}`;
|
|
147
|
+
}
|
|
148
|
+
function writeNoReplace(path, contents, mode, label) {
|
|
149
|
+
ensureKeyDirectory(dirname(path), label);
|
|
150
|
+
const noFollow = typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0;
|
|
151
|
+
let descriptor;
|
|
152
|
+
try {
|
|
153
|
+
descriptor = openSync(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | noFollow, mode);
|
|
154
|
+
if (process.platform !== "win32")
|
|
155
|
+
fchmodSync(descriptor, mode);
|
|
156
|
+
writeFileSync(descriptor, contents, "utf8");
|
|
157
|
+
fsyncSync(descriptor);
|
|
158
|
+
}
|
|
159
|
+
catch (error) {
|
|
160
|
+
if (error.code === "EEXIST") {
|
|
161
|
+
throw new Error(`Passport ${label} already exists; refusing to overwrite it.`);
|
|
162
|
+
}
|
|
163
|
+
throw error;
|
|
164
|
+
}
|
|
165
|
+
finally {
|
|
166
|
+
if (descriptor !== undefined)
|
|
167
|
+
closeSync(descriptor);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
export function defaultAccessPrivateKeyFile(env = process.env) {
|
|
171
|
+
const root = env.PASSPORT_HOME?.trim() || join(homedir(), ".passport");
|
|
172
|
+
return join(root, "access-workload-key.pem");
|
|
173
|
+
}
|
|
174
|
+
export function defaultAccessPublicJwkFile(privateKeyFile) {
|
|
175
|
+
return `${privateKeyFile}.jwk`;
|
|
176
|
+
}
|
|
177
|
+
export function generateAccessKey(algorithm) {
|
|
178
|
+
if (algorithm === "ES256") {
|
|
179
|
+
const pair = generateKeyPairSync("ec", { namedCurve: "prime256v1" });
|
|
180
|
+
return {
|
|
181
|
+
algorithm,
|
|
182
|
+
privateKeyPem: pair.privateKey.export({ type: "pkcs8", format: "pem" }).toString(),
|
|
183
|
+
publicJwk: { ...pair.publicKey.export({ format: "jwk" }), alg: algorithm, ext: true }
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
if (algorithm !== "RS256")
|
|
187
|
+
throw new Error("Access key algorithm must be ES256 or RS256.");
|
|
188
|
+
const pair = generateKeyPairSync("rsa", { modulusLength: 2048, publicExponent: 0x10001 });
|
|
189
|
+
return {
|
|
190
|
+
algorithm,
|
|
191
|
+
privateKeyPem: pair.privateKey.export({ type: "pkcs8", format: "pem" }).toString(),
|
|
192
|
+
publicJwk: { ...pair.publicKey.export({ format: "jwk" }), alg: algorithm, ext: true }
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
/** Publish a new workload key pair without ever printing private key material.
|
|
196
|
+
* The public file is a standalone JWK ready for the admin registration request. */
|
|
197
|
+
export function writeGeneratedAccessKey(generated, privateKeyFile, publicJwkFile = defaultAccessPublicJwkFile(privateKeyFile)) {
|
|
198
|
+
if (privateKeyFile === publicJwkFile)
|
|
199
|
+
throw new Error("Private and public key files must be different.");
|
|
200
|
+
// Fail before either write if either target is already present. This keeps a
|
|
201
|
+
// typo from consuming a fresh private key while leaving no public file.
|
|
202
|
+
for (const [path, label] of [[privateKeyFile, "private key"], [publicJwkFile, "public JWK"]]) {
|
|
203
|
+
try {
|
|
204
|
+
const stat = lstatSync(path);
|
|
205
|
+
if (stat.isSymbolicLink() || stat.isFile())
|
|
206
|
+
throw new Error(`Passport ${label} already exists; refusing to overwrite it.`);
|
|
207
|
+
throw new Error(`Passport ${label} path is not a regular file.`);
|
|
208
|
+
}
|
|
209
|
+
catch (error) {
|
|
210
|
+
if (error.code !== "ENOENT")
|
|
211
|
+
throw error;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
let privateCreated = false;
|
|
215
|
+
try {
|
|
216
|
+
writeNoReplace(privateKeyFile, generated.privateKeyPem, 0o600, "access private key");
|
|
217
|
+
privateCreated = true;
|
|
218
|
+
writeNoReplace(publicJwkFile, `${JSON.stringify(generated.publicJwk, null, 2)}\n`, 0o600, "access public JWK");
|
|
219
|
+
}
|
|
220
|
+
catch (error) {
|
|
221
|
+
if (privateCreated) {
|
|
222
|
+
try {
|
|
223
|
+
unlinkSync(privateKeyFile);
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
/* preserve the original publication error */
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
throw error;
|
|
230
|
+
}
|
|
231
|
+
return { privateKeyFile, publicJwkFile, publicJwk: generated.publicJwk };
|
|
232
|
+
}
|
|
233
|
+
export function parseAccessInputFile(path) {
|
|
234
|
+
return jsonObject(readBoundedUtf8File(path, ACCESS_INPUT_MAX_BYTES), "Access input");
|
|
235
|
+
}
|
|
236
|
+
export class AccessGatewayClient {
|
|
237
|
+
base;
|
|
238
|
+
workspaceId;
|
|
239
|
+
clientId;
|
|
240
|
+
privateKey;
|
|
241
|
+
algorithm;
|
|
242
|
+
callerId;
|
|
243
|
+
timeoutMs;
|
|
244
|
+
signal;
|
|
245
|
+
httpFetch;
|
|
246
|
+
now;
|
|
247
|
+
accessToken;
|
|
248
|
+
tokenInFlight;
|
|
249
|
+
constructor(options) {
|
|
250
|
+
this.workspaceId = assertWorkspaceId(options.workspaceId);
|
|
251
|
+
this.base = baseEndpoint(options.endpoint, this.workspaceId);
|
|
252
|
+
this.clientId = assertClientId(options.clientId);
|
|
253
|
+
const pem = readPrivateKeyFile(options.privateKeyFile);
|
|
254
|
+
try {
|
|
255
|
+
this.privateKey = createPrivateKey(pem);
|
|
256
|
+
}
|
|
257
|
+
catch {
|
|
258
|
+
throw new Error("Passport private key could not be parsed.");
|
|
259
|
+
}
|
|
260
|
+
this.algorithm = keyAlgorithm(this.privateKey);
|
|
261
|
+
if (options.algorithm && options.algorithm !== this.algorithm) {
|
|
262
|
+
throw new Error("The private key algorithm does not match the requested algorithm.");
|
|
263
|
+
}
|
|
264
|
+
this.callerId = options.callerId === undefined ? undefined : assertCallerId(options.callerId);
|
|
265
|
+
this.timeoutMs = options.timeoutMs ?? 30_000;
|
|
266
|
+
if (!Number.isFinite(this.timeoutMs) || this.timeoutMs <= 0 || this.timeoutMs > 10 * 60_000) {
|
|
267
|
+
throw new Error("Access request timeout is invalid.");
|
|
268
|
+
}
|
|
269
|
+
this.signal = options.signal;
|
|
270
|
+
this.httpFetch = options.fetch ?? fetch;
|
|
271
|
+
this.now = options.now ?? Date.now;
|
|
272
|
+
}
|
|
273
|
+
get resourceEndpoint() {
|
|
274
|
+
return `${this.base}/w/${encodeURIComponent(this.workspaceId)}/mcp`;
|
|
275
|
+
}
|
|
276
|
+
get protectedActionsEndpoint() {
|
|
277
|
+
return `${this.base}/w/${encodeURIComponent(this.workspaceId)}/actions`;
|
|
278
|
+
}
|
|
279
|
+
async actions(delegationId) {
|
|
280
|
+
const query = delegationId === undefined ? "" : `?delegationId=${encodeURIComponent(delegationId)}`;
|
|
281
|
+
const response = await this.request(`/w/${segment(this.workspaceId, "workspace id")}/actions${query}`, {
|
|
282
|
+
method: "GET"
|
|
283
|
+
});
|
|
284
|
+
if (!Array.isArray(response.actions))
|
|
285
|
+
throw new AccessGatewayError("Passport returned an invalid actions response.");
|
|
286
|
+
return response.actions;
|
|
287
|
+
}
|
|
288
|
+
async createRun(input) {
|
|
289
|
+
const response = await this.request(`/w/${segment(this.workspaceId, "workspace id")}/runs`, {
|
|
290
|
+
method: "POST",
|
|
291
|
+
body: JSON.stringify(input),
|
|
292
|
+
headers: { "content-type": "application/json" }
|
|
293
|
+
});
|
|
294
|
+
if (!response.run || typeof response.run !== "object")
|
|
295
|
+
throw new AccessGatewayError("Passport returned an invalid run response.");
|
|
296
|
+
return response.run;
|
|
297
|
+
}
|
|
298
|
+
async invoke(input, callerId = this.callerId) {
|
|
299
|
+
const caller = callerId === undefined ? undefined : assertCallerId(callerId);
|
|
300
|
+
if (!caller)
|
|
301
|
+
throw new AccessGatewayError("A stable caller id is required for invocations.");
|
|
302
|
+
return this.request(`/w/${segment(this.workspaceId, "workspace id")}/actions/invoke`, {
|
|
303
|
+
method: "POST",
|
|
304
|
+
body: JSON.stringify(input),
|
|
305
|
+
headers: { "content-type": "application/json", "x-passport-caller": caller }
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
async status(invocationId) {
|
|
309
|
+
const response = await this.request(`/w/${segment(this.workspaceId, "workspace id")}/invocations/${segment(invocationId, "invocation id")}`, { method: "GET" });
|
|
310
|
+
if (!response.receipt || typeof response.receipt !== "object") {
|
|
311
|
+
throw new AccessGatewayError("Passport returned an invalid invocation receipt.");
|
|
312
|
+
}
|
|
313
|
+
return response.receipt;
|
|
314
|
+
}
|
|
315
|
+
async cancel(runId) {
|
|
316
|
+
const response = await this.request(`/w/${segment(this.workspaceId, "workspace id")}/runs/${segment(runId, "run id")}/cancel`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" });
|
|
317
|
+
if (!response.run || typeof response.run !== "object")
|
|
318
|
+
throw new AccessGatewayError("Passport returned an invalid run response.");
|
|
319
|
+
return response.run;
|
|
320
|
+
}
|
|
321
|
+
/** Compatibility spelling for callers that mirror the HTTP route name. */
|
|
322
|
+
async cancelRun(runId) {
|
|
323
|
+
return this.cancel(runId);
|
|
324
|
+
}
|
|
325
|
+
async token() {
|
|
326
|
+
const now = this.now();
|
|
327
|
+
if (this.accessToken && this.accessToken.expiresAt > now + TOKEN_REFRESH_SKEW_MS)
|
|
328
|
+
return this.accessToken.value;
|
|
329
|
+
if (this.tokenInFlight)
|
|
330
|
+
return this.tokenInFlight;
|
|
331
|
+
this.tokenInFlight = this.exchangeToken();
|
|
332
|
+
try {
|
|
333
|
+
return await this.tokenInFlight;
|
|
334
|
+
}
|
|
335
|
+
finally {
|
|
336
|
+
this.tokenInFlight = undefined;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
async exchangeToken() {
|
|
340
|
+
const tokenEndpoint = `${this.base}/oauth/token`;
|
|
341
|
+
const assertion = signedAssertion(this.privateKey, this.algorithm, this.clientId, tokenEndpoint, this.now());
|
|
342
|
+
const form = new URLSearchParams({
|
|
343
|
+
grant_type: "client_credentials",
|
|
344
|
+
client_id: this.clientId,
|
|
345
|
+
client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
|
|
346
|
+
client_assertion: assertion
|
|
347
|
+
});
|
|
348
|
+
const response = await this.fetchWithTimeout(tokenEndpoint, {
|
|
349
|
+
method: "POST",
|
|
350
|
+
headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
|
|
351
|
+
body: form.toString()
|
|
352
|
+
});
|
|
353
|
+
const body = await this.readResponse(response);
|
|
354
|
+
if (!response.ok)
|
|
355
|
+
throw this.serverError(response.status, body);
|
|
356
|
+
const accessToken = body.access_token;
|
|
357
|
+
const expiresIn = body.expires_in;
|
|
358
|
+
if (typeof accessToken !== "string" ||
|
|
359
|
+
!accessToken ||
|
|
360
|
+
accessToken.length > 512 ||
|
|
361
|
+
typeof expiresIn !== "number" ||
|
|
362
|
+
!Number.isSafeInteger(expiresIn) ||
|
|
363
|
+
expiresIn < 1 ||
|
|
364
|
+
expiresIn > 24 * 3600) {
|
|
365
|
+
throw new AccessGatewayError("Passport returned an invalid access token response.");
|
|
366
|
+
}
|
|
367
|
+
const ttlMs = Math.max(1_000, Math.min(24 * 3600_000, expiresIn * 1000));
|
|
368
|
+
this.accessToken = { value: accessToken, expiresAt: this.now() + ttlMs };
|
|
369
|
+
return accessToken;
|
|
370
|
+
}
|
|
371
|
+
async request(path, init) {
|
|
372
|
+
const token = await this.token();
|
|
373
|
+
const response = await this.fetchWithTimeout(`${this.base}${path}`, {
|
|
374
|
+
...init,
|
|
375
|
+
headers: {
|
|
376
|
+
accept: "application/json",
|
|
377
|
+
...(init.headers ?? {}),
|
|
378
|
+
authorization: `Bearer ${token}`
|
|
379
|
+
}
|
|
380
|
+
});
|
|
381
|
+
const body = await this.readResponse(response);
|
|
382
|
+
if (!response.ok)
|
|
383
|
+
throw this.serverError(response.status, body);
|
|
384
|
+
return body;
|
|
385
|
+
}
|
|
386
|
+
async fetchWithTimeout(input, init) {
|
|
387
|
+
const timeout = AbortSignal.timeout(this.timeoutMs);
|
|
388
|
+
const signal = this.signal ? AbortSignal.any([this.signal, timeout]) : timeout;
|
|
389
|
+
return this.httpFetch(input, { ...init, redirect: "error", signal });
|
|
390
|
+
}
|
|
391
|
+
async readResponse(response) {
|
|
392
|
+
if (!response.body)
|
|
393
|
+
throw new AccessGatewayError("Passport returned an empty response.", response.status);
|
|
394
|
+
try {
|
|
395
|
+
return await readBoundedJson(response);
|
|
396
|
+
}
|
|
397
|
+
catch {
|
|
398
|
+
throw new AccessGatewayError("Passport returned an invalid JSON response.", response.status);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
serverError(status, body) {
|
|
402
|
+
const code = body && typeof body === "object" && typeof body.code === "string"
|
|
403
|
+
? body.code.slice(0, 80)
|
|
404
|
+
: body && typeof body === "object" && typeof body.error === "string"
|
|
405
|
+
? body.error.slice(0, 80)
|
|
406
|
+
: undefined;
|
|
407
|
+
return new AccessGatewayError(`Passport access request failed (${status}).`, status, code);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
export function accessClientFromEnv(env = process.env, overrides = {}) {
|
|
411
|
+
const clientId = overrides.clientId ?? env.PASSPORT_CLIENT_ID;
|
|
412
|
+
if (!clientId)
|
|
413
|
+
throw new Error("PASSPORT_CLIENT_ID is required.");
|
|
414
|
+
const workspaceId = overrides.workspaceId ?? env.PASSPORT_WORKSPACE_ID ?? clientId.split("~", 1)[0];
|
|
415
|
+
if (!workspaceId)
|
|
416
|
+
throw new Error("A workspace id is required.");
|
|
417
|
+
const endpointValue = overrides.endpoint ?? env.PASSPORT_ENDPOINT;
|
|
418
|
+
if (!endpointValue)
|
|
419
|
+
throw new Error("PASSPORT_ENDPOINT is required.");
|
|
420
|
+
const privateKeyFile = overrides.privateKeyFile ?? env.PASSPORT_PRIVATE_KEY_FILE;
|
|
421
|
+
if (!privateKeyFile)
|
|
422
|
+
throw new Error("PASSPORT_PRIVATE_KEY_FILE is required.");
|
|
423
|
+
const callerId = overrides.callerId ?? env.PASSPORT_CALLER_ID;
|
|
424
|
+
const configuredAlgorithm = overrides.algorithm ?? env.PASSPORT_ACCESS_ALGORITHM;
|
|
425
|
+
if (configuredAlgorithm !== undefined && configuredAlgorithm !== "ES256" && configuredAlgorithm !== "RS256") {
|
|
426
|
+
throw new Error("PASSPORT_ACCESS_ALGORITHM must be ES256 or RS256.");
|
|
427
|
+
}
|
|
428
|
+
return new AccessGatewayClient({
|
|
429
|
+
endpoint: endpointValue,
|
|
430
|
+
workspaceId,
|
|
431
|
+
clientId,
|
|
432
|
+
privateKeyFile,
|
|
433
|
+
...(configuredAlgorithm ? { algorithm: configuredAlgorithm } : {}),
|
|
434
|
+
...(callerId ? { callerId } : {})
|
|
435
|
+
});
|
|
436
|
+
}
|