passport-bridge 0.7.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,19 @@
1
+ const BRIDGE_POLL_DEFAULT_MS = 15_000;
2
+ const BRIDGE_POLL_MIN_MS = 1_000;
3
+ const BRIDGE_POLL_MAX_MS = 60_000;
4
+ export function bridgePollIntervalMs(env = process.env) {
5
+ const configured = env.PASSPORT_BRIDGE_POLL_MS;
6
+ if (configured === undefined)
7
+ return BRIDGE_POLL_DEFAULT_MS;
8
+ const raw = configured.trim();
9
+ if (!/^-?\d+$/.test(raw))
10
+ throw invalidPollInterval();
11
+ const value = Number(raw);
12
+ if (!Number.isSafeInteger(value) || value < BRIDGE_POLL_MIN_MS || value > BRIDGE_POLL_MAX_MS) {
13
+ throw invalidPollInterval();
14
+ }
15
+ return value;
16
+ }
17
+ function invalidPollInterval() {
18
+ return new Error(`PASSPORT_BRIDGE_POLL_MS must be a base-10 integer from ${BRIDGE_POLL_MIN_MS} to ${BRIDGE_POLL_MAX_MS}`);
19
+ }
@@ -0,0 +1,30 @@
1
+ export const BRIDGE_SHUTDOWN_TIMEOUT_MS = 5_000;
2
+ /** Stop polling, await both MCP transports, and only then exit. The deadline
3
+ * prevents a broken transport from wedging a terminal client indefinitely;
4
+ * duplicate signals share the same close attempt and cannot race exits. */
5
+ export function createBoundedBridgeShutdown(options) {
6
+ const timeoutMs = options.timeoutMs ?? BRIDGE_SHUTDOWN_TIMEOUT_MS;
7
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1)
8
+ throw new Error("Invalid bridge shutdown timeout.");
9
+ const exit = options.exit ?? ((code) => process.exit(code));
10
+ let inFlight;
11
+ return () => {
12
+ inFlight ??= (async () => {
13
+ const pollTimer = typeof options.pollTimer === "function" ? options.pollTimer() : options.pollTimer;
14
+ if (pollTimer)
15
+ clearInterval(pollTimer);
16
+ let deadline;
17
+ const timedOut = new Promise((resolve) => {
18
+ deadline = setTimeout(() => resolve("timeout"), timeoutMs);
19
+ });
20
+ const closed = Promise.allSettled([options.server.close(), options.upstream.close()]).then((results) => results.every((result) => result.status === "fulfilled") ? "closed" : "failed");
21
+ const outcome = await Promise.race([closed, timedOut]);
22
+ if (deadline)
23
+ clearTimeout(deadline);
24
+ if (outcome !== "closed")
25
+ options.onFailure?.();
26
+ exit(outcome === "closed" ? 0 : 1);
27
+ })();
28
+ return inFlight;
29
+ };
30
+ }
package/dist/cli.js CHANGED
@@ -1,9 +1,13 @@
1
1
  #!/usr/bin/env node
2
- import { spawn } from "node:child_process";
3
2
  import { randomUUID } from "node:crypto";
4
- import { getProfile, writeProfile, removeProfile, readCreds, credsPath, withProfileLock } from "./credentials.js";
5
- import { TokenManager, runBridge, log } from "./bridge.js";
3
+ import { assertCredentialStoreMutationReady, getProfile, getProfileStrict, persistCurrentProfileRotation, recoverProfileRotation, replaceProfileAfterRecovery, writeProfile, removeProfile, readCreds, credsPath, withProfileLock } from "./credentials.js";
4
+ import { TokenManager, runBridge, log, workspaceOfToken } from "./bridge.js";
5
+ import { openUrl } from "./cliSupport.js";
6
+ import { readBoundedJson } from "./boundedResponse.js";
7
+ import { LEGACY_REQUEST_TIMEOUT_MS, legacyCloudOrigin, legacyCredentialEndpoint, legacyFetch, legacyProfileEndpoint, legacyVerifyUrl } from "./legacyCliSecurity.js";
6
8
  import { VERSION } from "./version.js";
9
+ import { recoveryIdentity } from "./recoveryIdentity.js";
10
+ import { revokeIssuedRecoveryCredential } from "./recoveryCleanup.js";
7
11
  /**
8
12
  * passport-bridge — the local tier.
9
13
  *
@@ -76,29 +80,141 @@ async function serve() {
76
80
  refreshToken = saved.refreshToken;
77
81
  fromProfile = true;
78
82
  }
83
+ endpoint = legacyProfileEndpoint(endpoint);
79
84
  // Persist rotated refresh tokens back to the profile (file-backed only). An
80
85
  // env-supplied credential can't be written back, so it opts out of rotation.
81
- const onRotate = fromProfile ? (next) => writeProfile(profile, { refreshToken: next, endpoint }) : undefined;
86
+ const onRotate = fromProfile
87
+ ? (next, previous) => persistCurrentProfileRotation(profile, previous, next, endpoint)
88
+ : undefined;
82
89
  // File-backed profiles can be shared by several live bridges (Cursor runs
83
90
  // one per window) — coordinate exchanges through the profile file + lock so
84
91
  // a sibling's rotation is adopted instead of replayed.
85
92
  const coordinate = fromProfile
86
93
  ? {
87
- reload: () => getProfile(profile)?.refreshToken,
94
+ reload: () => recoverProfileRotation(profile)?.refreshToken,
88
95
  lock: (fn) => withProfileLock(profile, fn)
89
96
  }
90
97
  : undefined;
91
98
  try {
92
- await runBridge(endpoint, new TokenManager(endpoint, refreshToken, onRotate, coordinate));
99
+ await runBridge(endpoint, new TokenManager(endpoint, refreshToken, onRotate, coordinate, LEGACY_REQUEST_TIMEOUT_MS), fromProfile ? { recovery: profileRecovery(profile, endpoint, refreshToken) } : undefined);
93
100
  }
94
101
  catch (error) {
95
102
  log(error instanceof Error ? error.message : String(error));
96
103
  process.exit(1);
97
104
  }
98
105
  }
106
+ /** Device recovery deliberately reuses the profile's installation id and
107
+ * workspace. The new credential is written before the bridge adopts it, so a
108
+ * crash cannot leave a usable in-memory child without durable recovery state. */
109
+ function profileRecovery(profile, endpoint, previousRefreshToken) {
110
+ const cloud = legacyCloudOrigin(new URL(endpoint).origin);
111
+ const workspace = workspaceOfToken(previousRefreshToken);
112
+ return {
113
+ start: async () => {
114
+ assertCredentialStoreMutationReady();
115
+ const workspaceQuery = workspace ? `?ws=${encodeURIComponent(workspace)}` : "";
116
+ const start = await legacyFetch(`${cloud}/api/auth/device/start${workspaceQuery}`, { method: "POST" });
117
+ if (!start.ok)
118
+ throw new Error("Passport device sign-in could not be started.");
119
+ const started = await readBoundedJson(start);
120
+ if (typeof started.code !== "string" ||
121
+ !started.code ||
122
+ typeof started.userCode !== "string" ||
123
+ !started.userCode ||
124
+ typeof started.verifyUrl !== "string") {
125
+ throw new Error("Passport returned an invalid device sign-in response.");
126
+ }
127
+ const verifyUrl = legacyVerifyUrl(started.verifyUrl, cloud);
128
+ openUrl(verifyUrl);
129
+ return {
130
+ verifyUrl,
131
+ userCode: started.userCode,
132
+ waitForCredential: async (signal) => {
133
+ const deadline = Date.now() + 10 * 60 * 1000;
134
+ let sessionToken = "";
135
+ while (Date.now() < deadline) {
136
+ await sleep(1_500, signal);
137
+ const poll = await legacyFetch(`${cloud}/api/auth/device/poll`, {
138
+ method: "POST",
139
+ headers: { "content-type": "application/json" },
140
+ body: JSON.stringify({ code: started.code }),
141
+ signal
142
+ });
143
+ if (!poll.ok)
144
+ throw new Error("Passport device sign-in could not be checked.");
145
+ const result = await readBoundedJson(poll);
146
+ if (result.status === "approved" && typeof result.token === "string") {
147
+ sessionToken = result.token;
148
+ break;
149
+ }
150
+ if (result.status === "denied" || result.status === "expired")
151
+ throw new Error("Passport device sign-in ended.");
152
+ }
153
+ if (!sessionToken)
154
+ throw new Error("Passport device sign-in timed out.");
155
+ const identity = recoveryIdentity(profile, getProfileStrict(profile), workspace || undefined, endpoint);
156
+ const credential = await legacyFetch(`${cloud}/api/my/bridge-credential`, {
157
+ method: "POST",
158
+ headers: { "content-type": "application/json", authorization: `Bearer ${sessionToken}` },
159
+ body: JSON.stringify({
160
+ client: identity.client,
161
+ target: identity.target,
162
+ ...(identity.instanceId ? { instanceId: identity.instanceId } : {}),
163
+ instanceLabel: profile,
164
+ // The server uses this only to correlate the replacement with
165
+ // the exact historical device. It is never logged or returned.
166
+ recoveryRefreshToken: previousRefreshToken
167
+ }),
168
+ signal
169
+ });
170
+ if (!credential.ok)
171
+ throw new Error("Passport could not replace the bridge credential.");
172
+ const body = await readBoundedJson(credential);
173
+ const issuedRefreshToken = typeof body.refreshToken === "string" && body.refreshToken ? body.refreshToken : "";
174
+ if (!issuedRefreshToken) {
175
+ throw new Error("Passport returned an invalid bridge credential response.");
176
+ }
177
+ try {
178
+ if (typeof body.endpoint !== "string") {
179
+ throw new Error("Passport returned an invalid bridge credential response.");
180
+ }
181
+ const recoveredWorkspace = workspaceOfToken(issuedRefreshToken);
182
+ if (!recoveredWorkspace || (workspace && recoveredWorkspace !== workspace)) {
183
+ throw new Error("Passport returned a credential for another workspace.");
184
+ }
185
+ const recoveredEndpoint = legacyCredentialEndpoint(body.endpoint, cloud);
186
+ // The server is authoritative for the device identity. An omitted
187
+ // value deliberately means a legacy device with no instance id; do
188
+ // not resurrect a locally guessed id in that case.
189
+ const recoveredInstanceId = typeof body.instanceId === "string" ? body.instanceId : undefined;
190
+ if (recoveredInstanceId !== undefined && !/^[A-Za-z0-9._:-]{1,128}$/.test(recoveredInstanceId)) {
191
+ throw new Error("Passport returned an invalid installation identity.");
192
+ }
193
+ await withProfileLock(profile, async () => replaceProfileAfterRecovery(profile, previousRefreshToken, {
194
+ refreshToken: issuedRefreshToken,
195
+ endpoint: recoveredEndpoint,
196
+ ...(recoveredInstanceId ? { instanceId: recoveredInstanceId } : {}),
197
+ client: identity.client,
198
+ target: identity.target
199
+ }));
200
+ return { refreshToken: issuedRefreshToken, endpoint: recoveredEndpoint };
201
+ }
202
+ catch (error) {
203
+ // Any failure after the server issued a replacement must retire it;
204
+ // this includes malformed responses, tenant mismatches, invalid
205
+ // metadata, and a local compare-and-swap losing a sibling race.
206
+ await revokeIssuedRecoveryCredential(cloud, issuedRefreshToken);
207
+ throw error;
208
+ }
209
+ }
210
+ };
211
+ }
212
+ };
213
+ }
99
214
  async function login() {
100
- const cloud = arg("--cloud", DEFAULT_CLOUD).replace(/\/$/, "");
215
+ const cloud = legacyCloudOrigin(arg("--cloud", DEFAULT_CLOUD));
101
216
  const profile = arg("--profile", "default");
217
+ assertCredentialStoreMutationReady();
102
218
  const target = arg("--target", "workspace");
103
219
  // The AI client this credential is for (claude-code, cursor, …). Defaults to
104
220
  // the profile name for back-compat; the install instructions always pass it
@@ -108,35 +224,48 @@ async function login() {
108
224
  // resolve a tenant from a bare device/start (there's no session yet), so the
109
225
  // install instructions always pass this; the whole approve chain stays in it.
110
226
  const workspace = arg("--workspace", "");
111
- const storedInstanceId = getProfile(profile)?.instanceId;
227
+ const storedInstanceId = getProfileStrict(profile)?.instanceId;
112
228
  const instanceId = storedInstanceId && /^[A-Za-z0-9._:-]{1,128}$/.test(storedInstanceId) ? storedInstanceId : randomUUID();
113
229
  const out = (s) => process.stdout.write(s + "\n");
114
230
  const ws = workspace ? `?ws=${encodeURIComponent(workspace)}` : "";
115
- const start = await fetch(`${cloud}/api/auth/device/start${ws}`, { method: "POST" });
231
+ const start = await legacyFetch(`${cloud}/api/auth/device/start${ws}`, { method: "POST" });
116
232
  if (start.status === 404) {
117
233
  throw new Error(`Passport at ${cloud} couldn't find your workspace. Ask your admin for your workspace id and run: passport-bridge login --cloud ${cloud} --workspace <ws_id>`);
118
234
  }
119
235
  if (!start.ok)
120
236
  throw new Error(`Couldn't reach Passport at ${cloud}`);
121
- const { code, userCode, verifyUrl } = (await start.json());
237
+ const started = await readBoundedJson(start);
238
+ if (typeof started.code !== "string" ||
239
+ !started.code ||
240
+ typeof started.userCode !== "string" ||
241
+ !started.userCode ||
242
+ typeof started.verifyUrl !== "string") {
243
+ throw new Error("Passport returned an invalid sign-in response.");
244
+ }
245
+ const { code, userCode } = started;
246
+ const verifyUrl = legacyVerifyUrl(started.verifyUrl, cloud);
122
247
  out("");
123
248
  out(" Sign in to Passport");
124
249
  out(` 1. Open: ${verifyUrl}`);
125
250
  out(` 2. Confirm the code: ${userCode}`);
126
251
  out("");
127
252
  out(" Waiting for approval…");
128
- openBrowser(verifyUrl);
253
+ openUrl(verifyUrl);
129
254
  const deadline = Date.now() + 10 * 60 * 1000;
130
255
  let sessionToken = "";
131
256
  while (Date.now() < deadline) {
132
257
  await sleep(1500);
133
- const poll = await fetch(`${cloud}/api/auth/device/poll`, {
258
+ const poll = await legacyFetch(`${cloud}/api/auth/device/poll`, {
134
259
  method: "POST",
135
260
  headers: { "content-type": "application/json" },
136
261
  body: JSON.stringify({ code })
137
262
  });
138
- const result = (await poll.json());
263
+ if (!poll.ok)
264
+ throw new Error(`Couldn't check sign-in status at ${cloud}`);
265
+ const result = await readBoundedJson(poll);
139
266
  if (result.status === "approved" && result.token) {
267
+ if (typeof result.token !== "string")
268
+ throw new Error("Passport returned an invalid sign-in response.");
140
269
  sessionToken = result.token;
141
270
  break;
142
271
  }
@@ -146,15 +275,22 @@ async function login() {
146
275
  }
147
276
  if (!sessionToken)
148
277
  throw new Error("Timed out waiting for approval.");
149
- const cred = await fetch(`${cloud}/api/my/bridge-credential`, {
278
+ const cred = await legacyFetch(`${cloud}/api/my/bridge-credential`, {
150
279
  method: "POST",
151
280
  headers: { "content-type": "application/json", authorization: `Bearer ${sessionToken}` },
152
281
  body: JSON.stringify({ client, target, instanceId, instanceLabel: profile })
153
282
  });
154
283
  if (!cred.ok)
155
284
  throw new Error("Couldn't get a credential. Is your account active?");
156
- const { refreshToken, endpoint } = (await cred.json());
157
- writeProfile(profile, { refreshToken, endpoint, instanceId });
285
+ const credential = await readBoundedJson(cred);
286
+ if (typeof credential.refreshToken !== "string" ||
287
+ !credential.refreshToken ||
288
+ typeof credential.endpoint !== "string") {
289
+ throw new Error("Passport returned an invalid credential response.");
290
+ }
291
+ const refreshToken = credential.refreshToken;
292
+ const endpoint = legacyCredentialEndpoint(credential.endpoint, cloud);
293
+ await withProfileLock(profile, async () => writeProfile(profile, { refreshToken, endpoint, instanceId, client, target }));
158
294
  out("");
159
295
  out(` ✓ Signed in. Saved profile "${profile}" to ${credsPath()}`);
160
296
  out(` Now point your AI app at: passport-bridge serve --profile ${profile}`);
@@ -168,10 +304,15 @@ async function status() {
168
304
  return;
169
305
  }
170
306
  for (const name of names) {
171
- const { endpoint, refreshToken } = creds[name];
307
+ const saved = creds[name];
172
308
  let state = "ok";
309
+ let endpoint = "invalid endpoint";
173
310
  try {
174
- await new TokenManager(endpoint, refreshToken).accessToken(true);
311
+ endpoint = legacyProfileEndpoint(saved.endpoint);
312
+ await new TokenManager(endpoint, saved.refreshToken, undefined, {
313
+ reload: () => recoverProfileRotation(name)?.refreshToken,
314
+ lock: (fn) => withProfileLock(name, fn)
315
+ }, LEGACY_REQUEST_TIMEOUT_MS).accessToken(true);
175
316
  }
176
317
  catch {
177
318
  state = "needs re-login";
@@ -181,32 +322,47 @@ async function status() {
181
322
  }
182
323
  async function logout() {
183
324
  const profile = arg("--profile", "default");
184
- const existing = removeProfile(profile);
325
+ const existing = await withProfileLock(profile, async () => {
326
+ const saved = getProfile(profile);
327
+ if (!saved)
328
+ return undefined;
329
+ try {
330
+ const endpoint = legacyProfileEndpoint(saved.endpoint);
331
+ await legacyFetch(`${new URL(endpoint).origin}/api/token/revoke`, {
332
+ method: "POST",
333
+ headers: { "content-type": "application/json" },
334
+ body: JSON.stringify({ refreshToken: saved.refreshToken })
335
+ });
336
+ }
337
+ catch {
338
+ /* Local removal remains authoritative when the server is unavailable. */
339
+ }
340
+ removeProfile(profile);
341
+ return saved;
342
+ });
185
343
  if (existing) {
186
- const origin = new URL(existing.endpoint).origin;
187
- await fetch(`${origin}/api/token/revoke`, {
188
- method: "POST",
189
- headers: { "content-type": "application/json" },
190
- body: JSON.stringify({ refreshToken: existing.refreshToken })
191
- }).catch(() => { });
192
344
  process.stdout.write(`Signed out profile "${profile}".\n`);
193
345
  }
194
346
  else {
195
347
  process.stdout.write(`No profile "${profile}".\n`);
196
348
  }
197
349
  }
198
- function openBrowser(url) {
199
- const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
200
- const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
201
- try {
202
- spawn(cmd, args, { stdio: "ignore", detached: true }).unref();
203
- }
204
- catch {
205
- /* user can open it manually */
206
- }
207
- }
208
- function sleep(ms) {
209
- return new Promise((resolve) => setTimeout(resolve, ms));
350
+ function sleep(ms, signal) {
351
+ return new Promise((resolve, reject) => {
352
+ if (signal?.aborted) {
353
+ reject(signal.reason ?? new Error("Operation aborted."));
354
+ return;
355
+ }
356
+ const onAbort = () => {
357
+ clearTimeout(timer);
358
+ reject(signal?.reason ?? new Error("Operation aborted."));
359
+ };
360
+ const timer = setTimeout(() => {
361
+ signal?.removeEventListener("abort", onAbort);
362
+ resolve();
363
+ }, ms);
364
+ signal?.addEventListener("abort", onAbort, { once: true });
365
+ });
210
366
  }
211
367
  main().catch((error) => {
212
368
  process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
package/dist/cliArgs.js CHANGED
@@ -10,6 +10,7 @@ export const COMMANDS = [
10
10
  "resources",
11
11
  "prompts",
12
12
  "discover",
13
+ "session",
13
14
  "completion",
14
15
  "help",
15
16
  "version"
@@ -129,6 +130,7 @@ function validateShape(command, positionals) {
129
130
  resources: 1,
130
131
  prompts: 1,
131
132
  discover: 0,
133
+ session: 0,
132
134
  completion: 1,
133
135
  help: 1,
134
136
  version: 0
package/dist/cliClient.js CHANGED
@@ -1,13 +1,21 @@
1
1
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2
2
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
3
3
  import { TokenManager } from "./bridge.js";
4
- import { getProfile, withProfileLock, writeProfile } from "./credentials.js";
4
+ import { persistCurrentProfileRotation, recoverProfileRotation, withProfileLock } from "./credentials.js";
5
5
  import { VERSION } from "./version.js";
6
6
  import { SERVER_TOO_OLD } from "./cliProtocol.js";
7
+ import { withCliDeadline } from "./cliDeadline.js";
8
+ import { collectCliPages } from "./cliPagination.js";
9
+ import { boundedMcpFetch } from "./boundedMcpFetch.js";
7
10
  export { SERVER_TOO_OLD } from "./cliProtocol.js";
8
11
  const MIN_CLI_SERVER = [0, 5, 0];
9
12
  export const MIN_CLI_SERVER_VERSION = MIN_CLI_SERVER.join(".");
10
- export const CLI_PROTOCOL_TOOLS = ["passport_search_tools", "passport_call", "passport_manage_connections", "passport_wait_for_connection"];
13
+ export const CLI_PROTOCOL_TOOLS = [
14
+ "passport_search_tools",
15
+ "passport_call",
16
+ "passport_manage_connections",
17
+ "passport_wait_for_connection"
18
+ ];
11
19
  export function supportsCliServerInfo(info) {
12
20
  if (info?.name !== "passport" || typeof info.version !== "string")
13
21
  return false;
@@ -30,25 +38,6 @@ function decorateFetch(base, headersToAdd) {
30
38
  return base(input, { ...init, headers });
31
39
  });
32
40
  }
33
- async function deadline(promise, ms, onTimeout) {
34
- let timer;
35
- const expired = new Promise((_, reject) => {
36
- timer = setTimeout(() => {
37
- onTimeout();
38
- const error = new Error(`Request timed out after ${Math.ceil(ms / 1000)} seconds.`);
39
- error.name = "TimeoutError";
40
- reject(error);
41
- }, ms);
42
- timer.unref?.();
43
- });
44
- try {
45
- return await Promise.race([promise, expired]);
46
- }
47
- finally {
48
- if (timer)
49
- clearTimeout(timer);
50
- }
51
- }
52
41
  /** One authenticated MCP session for one CLI invocation. */
53
42
  export class CliGateway {
54
43
  client = new Client({ name: "passport-cli", version: VERSION });
@@ -72,21 +61,24 @@ export class CliGateway {
72
61
  }
73
62
  else {
74
63
  const { endpoint, profile } = options.auth;
75
- const manager = new TokenManager(endpoint, options.auth.refreshToken, (next) => writeProfile(profile, { refreshToken: next, endpoint }), {
76
- reload: () => getProfile(profile)?.refreshToken,
64
+ const manager = new TokenManager(endpoint, options.auth.refreshToken, (next, previous) => persistCurrentProfileRotation(profile, previous, next, endpoint), {
65
+ reload: () => recoverProfileRotation(profile)?.refreshToken,
77
66
  lock: (fn) => withProfileLock(profile, fn)
78
67
  }, options.timeoutMs, options.signal);
79
- authedFetch = options.caller
80
- ? decorateFetch(manager.authedFetch, { "x-passport-caller": options.caller })
81
- : manager.authedFetch;
68
+ authedFetch = decorateFetch(manager.authedFetch, {
69
+ "x-passport-surface": "cli",
70
+ ...(options.caller ? { "x-passport-caller": options.caller } : {})
71
+ });
82
72
  }
83
73
  this.apiFetch = authedFetch;
84
- this.transport = new StreamableHTTPClientTransport(new URL(options.auth.endpoint), { fetch: authedFetch });
74
+ this.transport = new StreamableHTTPClientTransport(new URL(options.auth.endpoint), {
75
+ fetch: boundedMcpFetch(authedFetch)
76
+ });
85
77
  }
86
78
  static async connect(options) {
87
79
  const gateway = new CliGateway(options);
88
80
  try {
89
- await deadline(gateway.client.connect(gateway.transport), options.timeoutMs, () => {
81
+ await withCliDeadline(gateway.client.connect(gateway.transport), options.timeoutMs, () => {
90
82
  void gateway.transport.close().catch(() => { });
91
83
  });
92
84
  return gateway;
@@ -129,29 +121,15 @@ export class CliGateway {
129
121
  return this.apiFetch(`${this.origin}${path}`, init);
130
122
  }
131
123
  async listResources() {
132
- const resources = [];
133
- let cursor;
134
- let last;
135
- do {
136
- last = await this.client.listResources(cursor ? { cursor } : {}, this.requestOptions());
137
- resources.push(...last.resources);
138
- cursor = last.nextCursor;
139
- } while (cursor);
140
- return { ...(last ?? { resources: [] }), resources, nextCursor: undefined };
124
+ const result = await collectCliPages("resource", (cursor) => this.client.listResources(cursor ? { cursor } : {}, this.requestOptions()), (page) => page.resources);
125
+ return { ...result.last, resources: result.items, nextCursor: undefined };
141
126
  }
142
127
  readResource(uri) {
143
128
  return this.client.readResource({ uri }, this.requestOptions());
144
129
  }
145
130
  async listPrompts() {
146
- const prompts = [];
147
- let cursor;
148
- let last;
149
- do {
150
- last = await this.client.listPrompts(cursor ? { cursor } : {}, this.requestOptions());
151
- prompts.push(...last.prompts);
152
- cursor = last.nextCursor;
153
- } while (cursor);
154
- return { ...(last ?? { prompts: [] }), prompts, nextCursor: undefined };
131
+ const result = await collectCliPages("prompt", (cursor) => this.client.listPrompts(cursor ? { cursor } : {}, this.requestOptions()), (page) => page.prompts);
132
+ return { ...result.last, prompts: result.items, nextCursor: undefined };
155
133
  }
156
134
  getPrompt(name, args) {
157
135
  return this.client.getPrompt({ name, arguments: args }, this.requestOptions());
@@ -0,0 +1,27 @@
1
+ const systemClock = {
2
+ set: (callback, ms) => setTimeout(callback, ms),
3
+ clear: (timer) => clearTimeout(timer)
4
+ };
5
+ /** A CLI request deadline must keep the short-lived command alive. A pending
6
+ * Promise does not hold Node's event loop open, so this timer is intentionally
7
+ * referenced until the operation settles or the deadline fires. */
8
+ export async function withCliDeadline(promise, ms, onTimeout, clock = systemClock) {
9
+ if (!Number.isSafeInteger(ms) || ms < 1)
10
+ throw new Error("CLI request deadline must be a positive integer.");
11
+ let timer;
12
+ const expired = new Promise((_, reject) => {
13
+ timer = clock.set(() => {
14
+ onTimeout();
15
+ const error = new Error(`Request timed out after ${Math.ceil(ms / 1000)} seconds.`);
16
+ error.name = "TimeoutError";
17
+ reject(error);
18
+ }, ms);
19
+ });
20
+ try {
21
+ return await Promise.race([promise, expired]);
22
+ }
23
+ finally {
24
+ if (timer)
25
+ clock.clear(timer);
26
+ }
27
+ }
@@ -0,0 +1,103 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { value } from "./cliArgs.js";
3
+ import { assertCredentialStoreMutationReady, credsPath, getProfile, getProfileStrict, withProfileLock, writeProfile } from "./credentials.js";
4
+ import { cloudOrigin, endpoint, failure, openUrl, profileName, readBoundedJson, safeApiError, sameOriginWebUrl, sleep, timedFetch, timeoutMs } from "./cliSupport.js";
5
+ function loginOptions(args, runtime) {
6
+ const explicitProfile = value(args, "profile");
7
+ const requestedProfile = explicitProfile !== undefined
8
+ ? profileName(explicitProfile)
9
+ : runtime.env.PASSPORT_PROFILE
10
+ ? profileName(runtime.env.PASSPORT_PROFILE)
11
+ : "";
12
+ const existing = requestedProfile ? getProfile(requestedProfile) : undefined;
13
+ const cloudRaw = value(args, "cloud") || runtime.env.PASSPORT_CLOUD || (existing ? new URL(endpoint(existing.endpoint)).origin : "");
14
+ if (!cloudRaw)
15
+ return failure("--cloud <origin> is required for the first login.", 6, "usage");
16
+ const workspaceOption = value(args, "workspace");
17
+ const workspace = workspaceOption?.trim() ?? "";
18
+ if (workspaceOption !== undefined && !/^[A-Za-z0-9_-]{1,80}$/.test(workspace)) {
19
+ return failure("--workspace must be a valid workspace id.", 6, "usage");
20
+ }
21
+ const clientOption = value(args, "client");
22
+ const client = clientOption === undefined ? "cli" : clientOption.trim();
23
+ if (!/^[A-Za-z0-9._-]{1,40}$/.test(client)) {
24
+ return failure("--client must be a valid client id (1-40 characters).", 6, "usage");
25
+ }
26
+ return { requestedProfile, cloud: cloudOrigin(cloudRaw), workspace, client };
27
+ }
28
+ async function waitForDeviceApproval(cloud, code, args, runtime) {
29
+ const deadlineAt = Date.now() + 10 * 60 * 1000;
30
+ while (Date.now() < deadlineAt) {
31
+ await sleep(1_500, runtime.signal);
32
+ const poll = await timedFetch(`${cloud}/api/auth/device/poll`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ code }) }, timeoutMs(args), runtime.signal);
33
+ if (!poll.ok)
34
+ return failure(`Could not check sign-in (${poll.status}).`, 1, "server");
35
+ const result = await readBoundedJson(poll);
36
+ if (result.status === "approved" && typeof result.token === "string")
37
+ return result.token;
38
+ if (result.status === "denied" || result.status === "expired") {
39
+ return failure(`Sign-in ${result.status}.`, 2, "auth");
40
+ }
41
+ }
42
+ return failure("Timed out waiting for sign-in approval.", 2, "auth");
43
+ }
44
+ export async function login(args, runtime) {
45
+ if (runtime.env.PASSPORT_AGENT_KEY || runtime.env.PASSPORT_ENDPOINT) {
46
+ return failure("Unset PASSPORT_AGENT_KEY and PASSPORT_ENDPOINT before interactive login.", 6, "usage");
47
+ }
48
+ assertCredentialStoreMutationReady();
49
+ const { requestedProfile, cloud, workspace, client } = loginOptions(args, runtime);
50
+ const workspaceQuery = workspace ? `?ws=${encodeURIComponent(workspace)}` : "";
51
+ const start = await timedFetch(`${cloud}/api/auth/device/start${workspaceQuery}`, { method: "POST" }, timeoutMs(args), runtime.signal);
52
+ if (start.status === 404) {
53
+ return failure("Passport could not find that workspace. Ask your admin for its workspace id.", 2, "auth");
54
+ }
55
+ if (!start.ok)
56
+ return failure(`Could not start sign-in (${start.status}).`, 1, "server");
57
+ const started = await readBoundedJson(start);
58
+ if (typeof started.code !== "string" ||
59
+ typeof started.userCode !== "string" ||
60
+ typeof started.verifyUrl !== "string") {
61
+ return failure("Passport returned an invalid device sign-in response.", 1, "invalid_server_response");
62
+ }
63
+ const verifyUrl = sameOriginWebUrl(started.verifyUrl, cloud, "a sign-in URL");
64
+ runtime.stderr.write(`Sign in to Passport\nOpen: ${verifyUrl}\nConfirm code: ${started.userCode}\nWaiting for approval...\n`);
65
+ if (!runtime.env.PASSPORT_NO_OPEN)
66
+ openUrl(verifyUrl);
67
+ const sessionToken = await waitForDeviceApproval(cloud, started.code, args, runtime);
68
+ const tokenWorkspace = workspace || (await import("./bridge.js")).workspaceOfToken(sessionToken) || "workspace";
69
+ const profile = profileName(requestedProfile || `cli@${tokenWorkspace}`);
70
+ const storedInstanceId = getProfileStrict(profile)?.instanceId;
71
+ const instanceId = storedInstanceId && /^[A-Za-z0-9._:-]{1,128}$/.test(storedInstanceId) ? storedInstanceId : randomUUID();
72
+ const credential = await timedFetch(`${cloud}/api/my/bridge-credential`, {
73
+ method: "POST",
74
+ headers: { "content-type": "application/json", authorization: `Bearer ${sessionToken}` },
75
+ body: JSON.stringify({
76
+ client,
77
+ target: "workspace",
78
+ surface: "cli",
79
+ instanceId,
80
+ instanceLabel: profile
81
+ })
82
+ }, timeoutMs(args), runtime.signal);
83
+ if (!credential.ok) {
84
+ const message = await safeApiError(credential, "Could not create a CLI credential.");
85
+ return failure(message, credential.status === 401 || credential.status === 403 ? 2 : 1, "auth");
86
+ }
87
+ const body = await readBoundedJson(credential);
88
+ if (typeof body.refreshToken !== "string" || typeof body.endpoint !== "string") {
89
+ return failure("Passport returned an invalid credential response.", 1, "invalid_server_response");
90
+ }
91
+ const credentialEndpoint = sameOriginWebUrl(body.endpoint, cloud, "a credential endpoint");
92
+ await withProfileLock(profile, async () => writeProfile(profile, {
93
+ refreshToken: body.refreshToken,
94
+ endpoint: credentialEndpoint,
95
+ instanceId,
96
+ client,
97
+ target: "workspace"
98
+ }));
99
+ return {
100
+ json: { profile, endpoint: credentialEndpoint, client, surface: "cli" },
101
+ human: `Signed in as profile "${profile}".\nCredential saved to ${credsPath()}.`
102
+ };
103
+ }