passport-bridge 0.8.2 → 0.10.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.
Files changed (65) hide show
  1. package/README.md +100 -3
  2. package/dist/accessClient.d.ts +128 -0
  3. package/dist/accessClient.js +436 -0
  4. package/dist/activeProfile.d.ts +21 -0
  5. package/dist/boundedFile.d.ts +2 -0
  6. package/dist/boundedMcpFetch.d.ts +6 -0
  7. package/dist/boundedResponse.d.ts +4 -0
  8. package/dist/bridge.d.ts +98 -0
  9. package/dist/bridge.js +49 -42
  10. package/dist/bridgeConfig.d.ts +1 -0
  11. package/dist/bridgePoller.d.ts +34 -0
  12. package/dist/bridgePoller.js +123 -0
  13. package/dist/bridgeShutdown.d.ts +20 -0
  14. package/dist/bridgeShutdown.js +5 -1
  15. package/dist/cli.d.ts +2 -0
  16. package/dist/cli.js +4 -0
  17. package/dist/cliAccess.d.ts +3 -0
  18. package/dist/cliAccess.js +119 -0
  19. package/dist/cliArgs.d.ts +16 -0
  20. package/dist/cliArgs.js +14 -3
  21. package/dist/cliClient.d.ts +62 -0
  22. package/dist/cliConnect.d.ts +22 -0
  23. package/dist/cliDeadline.d.ts +9 -0
  24. package/dist/cliDescribe.d.ts +8 -0
  25. package/dist/cliLogin.d.ts +3 -0
  26. package/dist/cliOffline.d.ts +6 -0
  27. package/dist/cliOutput.d.ts +7 -0
  28. package/dist/cliOutput.js +4 -0
  29. package/dist/cliPagination.d.ts +15 -0
  30. package/dist/cliProtocol.d.ts +4 -0
  31. package/dist/cliReady.d.ts +9 -0
  32. package/dist/cliResult.d.ts +7 -0
  33. package/dist/cliSession.d.ts +20 -0
  34. package/dist/cliSetup.d.ts +10 -0
  35. package/dist/cliSetup.js +157 -0
  36. package/dist/cliSupport.d.ts +102 -0
  37. package/dist/completion.d.ts +2 -0
  38. package/dist/completion.js +20 -2
  39. package/dist/credentialStorage.d.ts +12 -0
  40. package/dist/credentials.d.ts +64 -0
  41. package/dist/discover.d.ts +52 -0
  42. package/dist/doctor.d.ts +34 -0
  43. package/dist/index.d.ts +2 -0
  44. package/dist/index.js +1 -0
  45. package/dist/legacyCliSecurity.d.ts +10 -0
  46. package/dist/managedSkills.d.ts +7 -0
  47. package/dist/managedSkills.js +268 -0
  48. package/dist/managedSkillsContract.generated.d.ts +82 -0
  49. package/dist/managedSkillsContract.generated.js +32 -0
  50. package/dist/managedSkillsFiles.d.ts +23 -0
  51. package/dist/managedSkillsFiles.js +215 -0
  52. package/dist/managedSkillsIpc.d.ts +5 -0
  53. package/dist/managedSkillsIpc.js +44 -0
  54. package/dist/managedSkillsValidation.d.ts +14 -0
  55. package/dist/managedSkillsValidation.js +118 -0
  56. package/dist/passport.d.ts +7 -0
  57. package/dist/passport.js +4 -0
  58. package/dist/privateStableFile.d.ts +13 -0
  59. package/dist/recoveryCleanup.d.ts +5 -0
  60. package/dist/recoveryIdentity.d.ts +22 -0
  61. package/dist/tokenWorkspace.d.ts +3 -0
  62. package/dist/version.d.ts +1 -0
  63. package/dist/version.js +1 -1
  64. package/npm-shrinkwrap.json +2 -2
  65. package/package.json +13 -2
@@ -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
+ }
@@ -0,0 +1,21 @@
1
+ type AssertProfileName = (name: string) => void;
2
+ export type ActiveProfileDocument = {
3
+ kind: "missing";
4
+ } | {
5
+ kind: "present";
6
+ profile: string;
7
+ };
8
+ export declare function activeProfilePath(): string;
9
+ export declare function readActiveProfileDocument(assertName: AssertProfileName): ActiveProfileDocument;
10
+ /** Best-effort read for command resolution. A stale or damaged pointer must
11
+ * never make the CLI guess a credential; callers can fall back to the normal
12
+ * sole-profile rule or report ambiguity. */
13
+ export declare function readActiveProfile(assertName: AssertProfileName): string | undefined;
14
+ export declare function writeActiveProfileAtomic(name: string, assertName: AssertProfileName): void;
15
+ /** The active-profile pointer contains no credential material. If an old or
16
+ * damaged installation left a symlink at that exact path, selecting a profile
17
+ * may safely unlink the symlink itself (never its target) before recreating the
18
+ * owner-only regular file. Other non-regular targets still fail closed. */
19
+ export declare function prepareActiveProfileForSelection(): void;
20
+ export declare function clearActiveProfileAtomic(): void;
21
+ export {};
@@ -0,0 +1,2 @@
1
+ export declare function readBoundedUtf8Descriptor(descriptor: number, maxBytes: number): string;
2
+ export declare function readBoundedUtf8File(path: string, maxBytes: number): string;
@@ -0,0 +1,6 @@
1
+ export declare const CLI_MCP_RESPONSE_MAX_BYTES: number;
2
+ /** Bound one-shot MCP JSON responses in total and long-lived SSE responses per
3
+ * event. The wrapper always cancels and unlocks the original reader on every
4
+ * terminal path so failed or abandoned CLI calls release their socket. */
5
+ export declare function boundMcpResponse(response: Response, maxBytes?: number): Promise<Response>;
6
+ export declare function boundedMcpFetch(base: typeof fetch, maxBytes?: number): typeof fetch;
@@ -0,0 +1,4 @@
1
+ export declare const DEFAULT_API_RESPONSE_BYTES: number;
2
+ /** Parse a Fetch JSON response without trusting Content-Length or allowing a
3
+ * chunked Passport response to grow the client process without bound. */
4
+ export declare function readBoundedJson<T>(response: Response, maxBytes?: number): Promise<T>;
@@ -0,0 +1,98 @@
1
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2
+ import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
3
+ export { workspaceOfToken } from "./tokenWorkspace.js";
4
+ /** Everything but the MCP protocol goes to stderr — stdout is the transport. */
5
+ export declare function log(...args: unknown[]): void;
6
+ /**
7
+ * Shown to the AI client (and logged) when the bridge refuses to switch tenants:
8
+ * the on-disk credential now belongs to a DIFFERENT workspace than this process
9
+ * started serving. We fail closed rather than silently attribute activity to the
10
+ * wrong workspace.
11
+ */
12
+ export declare const TENANT_FLIP_MESSAGE = "This machine's Passport credential now belongs to a different workspace. Reconnect this client from the Passport app.";
13
+ export declare class BridgeCredentialError extends Error {
14
+ readonly status: 401;
15
+ constructor(status: 401);
16
+ }
17
+ /**
18
+ * Holds the long-lived refresh token and mints short-lived access tokens
19
+ * from the cloud, transparently refreshing on expiry or a 401.
20
+ */
21
+ export declare class TokenManager {
22
+ private readonly onRotate?;
23
+ private readonly coordinate?;
24
+ private readonly requestTimeoutMs?;
25
+ private readonly requestSignal?;
26
+ private readonly fetcher;
27
+ private origin;
28
+ private refreshToken;
29
+ private access?;
30
+ private expiresAt;
31
+ private inflight?;
32
+ private pendingRotation?;
33
+ /** The workspace this process started serving, read from its initial refresh
34
+ * token. The tenant-flip guard refuses to adopt an on-disk credential whose
35
+ * workspace differs from this. */
36
+ private readonly homeWorkspace;
37
+ private tenantFlipLogged;
38
+ /**
39
+ * @param onRotate durably persist a rotated refresh token before its access
40
+ * token is usable. Rejection leaves the child pending for local retry.
41
+ * Without it (e.g. env-only auth), the server is told not to rotate.
42
+ * @param coordinate cross-process coordination for a shared profile (Cursor
43
+ * runs one bridge per window): `reload` returns the freshest persisted
44
+ * refresh token, `lock` serializes the exchange across processes. Without
45
+ * them, a sibling process's rotation makes our in-memory token a replay —
46
+ * which the server treats as theft and answers by revoking the family.
47
+ */
48
+ constructor(endpoint: string, refreshToken: string, onRotate?: ((next: string, previous: string) => void | Promise<void>) | undefined, coordinate?: {
49
+ reload: () => string | undefined;
50
+ lock: <T>(fn: () => Promise<T>) => Promise<T>;
51
+ } | undefined, requestTimeoutMs?: number | undefined, requestSignal?: AbortSignal | undefined, fetcher?: typeof fetch);
52
+ private assertHomeWorkspace;
53
+ private settlePendingRotation;
54
+ accessToken(force?: boolean): Promise<string>;
55
+ /** Adopt a newly persisted credential after an interactive recovery. The
56
+ * original workspace remains authoritative for this running bridge. */
57
+ replaceRefreshToken(next: string): void;
58
+ /** Adopt a newly persisted credential and its approved gateway endpoint. */
59
+ replaceCredential(next: string, endpoint: string): void;
60
+ private exchange;
61
+ /** fetch wrapper that attaches the current access token and refreshes on 401. */
62
+ authedFetch: (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
63
+ }
64
+ export type BridgeRecoveryFlow = {
65
+ verifyUrl: string;
66
+ userCode: string;
67
+ /** Waits for device approval and durably replaces the saved credential. */
68
+ waitForCredential: (signal: AbortSignal) => Promise<{
69
+ refreshToken: string;
70
+ endpoint: string;
71
+ }>;
72
+ };
73
+ export type BridgeRecovery = {
74
+ start: () => Promise<BridgeRecoveryFlow>;
75
+ };
76
+ export type BridgeRunOptions = {
77
+ /** Test hook for an in-process downstream transport. */
78
+ downstreamTransport?: Transport;
79
+ /** Test hook for an in-process upstream connection. */
80
+ connectUpstream?: (client: Client) => Promise<void>;
81
+ recovery?: BridgeRecovery;
82
+ };
83
+ /**
84
+ * The proxy: a stdio MCP server (what the AI client talks to) that forwards
85
+ * verbatim to the cloud gateway over Streamable HTTP. Tool definitions and
86
+ * arguments pass through unchanged; cancellation and progress are forwarded;
87
+ * a periodic re-list notifies the client when the toolset changes.
88
+ */
89
+ export declare function runBridge(endpoint: string, tokens: TokenManager, options?: BridgeRunOptions): Promise<void>;
90
+ export type ToolSignatureDefinition = {
91
+ name: string;
92
+ description?: string;
93
+ inputSchema?: unknown;
94
+ };
95
+ /** Canonical hash of the complete visible tool definitions. Kept pure so the
96
+ * bridge can prove hashing cost independently from MCP transport latency. */
97
+ export declare function canonicalToolSignature(tools: readonly ToolSignatureDefinition[]): string;
98
+ export declare function toolSignature(client: Client, signal?: AbortSignal): Promise<string>;