passport-bridge 0.7.0 → 0.8.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.
@@ -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,24 @@ 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 () => {
294
+ writeProfile(profile, { refreshToken, endpoint, instanceId, client, target });
295
+ });
158
296
  out("");
159
297
  out(` ✓ Signed in. Saved profile "${profile}" to ${credsPath()}`);
160
298
  out(` Now point your AI app at: passport-bridge serve --profile ${profile}`);
@@ -168,10 +306,15 @@ async function status() {
168
306
  return;
169
307
  }
170
308
  for (const name of names) {
171
- const { endpoint, refreshToken } = creds[name];
309
+ const saved = creds[name];
172
310
  let state = "ok";
311
+ let endpoint = "invalid endpoint";
173
312
  try {
174
- await new TokenManager(endpoint, refreshToken).accessToken(true);
313
+ endpoint = legacyProfileEndpoint(saved.endpoint);
314
+ await new TokenManager(endpoint, saved.refreshToken, undefined, {
315
+ reload: () => recoverProfileRotation(name)?.refreshToken,
316
+ lock: (fn) => withProfileLock(name, fn)
317
+ }, LEGACY_REQUEST_TIMEOUT_MS).accessToken(true);
175
318
  }
176
319
  catch {
177
320
  state = "needs re-login";
@@ -181,32 +324,47 @@ async function status() {
181
324
  }
182
325
  async function logout() {
183
326
  const profile = arg("--profile", "default");
184
- const existing = removeProfile(profile);
327
+ const existing = await withProfileLock(profile, async () => {
328
+ const saved = getProfile(profile);
329
+ if (!saved)
330
+ return undefined;
331
+ try {
332
+ const endpoint = legacyProfileEndpoint(saved.endpoint);
333
+ await legacyFetch(`${new URL(endpoint).origin}/api/token/revoke`, {
334
+ method: "POST",
335
+ headers: { "content-type": "application/json" },
336
+ body: JSON.stringify({ refreshToken: saved.refreshToken })
337
+ });
338
+ }
339
+ catch {
340
+ /* Local removal remains authoritative when the server is unavailable. */
341
+ }
342
+ removeProfile(profile);
343
+ return saved;
344
+ });
185
345
  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
346
  process.stdout.write(`Signed out profile "${profile}".\n`);
193
347
  }
194
348
  else {
195
349
  process.stdout.write(`No profile "${profile}".\n`);
196
350
  }
197
351
  }
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));
352
+ function sleep(ms, signal) {
353
+ return new Promise((resolve, reject) => {
354
+ if (signal?.aborted) {
355
+ reject(signal.reason ?? new Error("Operation aborted."));
356
+ return;
357
+ }
358
+ const onAbort = () => {
359
+ clearTimeout(timer);
360
+ reject(signal?.reason ?? new Error("Operation aborted."));
361
+ };
362
+ const timer = setTimeout(() => {
363
+ signal?.removeEventListener("abort", onAbort);
364
+ resolve();
365
+ }, ms);
366
+ signal?.addEventListener("abort", onAbort, { once: true });
367
+ });
210
368
  }
211
369
  main().catch((error) => {
212
370
  process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
package/dist/cliArgs.js CHANGED
@@ -1,6 +1,8 @@
1
1
  export const COMMANDS = [
2
2
  "login",
3
3
  "logout",
4
+ "profiles",
5
+ "use",
4
6
  "status",
5
7
  "doctor",
6
8
  "search",
@@ -10,6 +12,7 @@ export const COMMANDS = [
10
12
  "resources",
11
13
  "prompts",
12
14
  "discover",
15
+ "session",
13
16
  "completion",
14
17
  "help",
15
18
  "version"
@@ -24,6 +27,7 @@ const FLAGS = {
24
27
  cloud: { kind: "value", commands: ["login"] },
25
28
  workspace: { kind: "value", commands: ["login"] },
26
29
  client: { kind: "value", commands: ["login"] },
30
+ "no-open": { kind: "boolean", commands: ["login"] },
27
31
  app: { kind: "value", commands: ["search"] },
28
32
  args: { kind: "value", commands: ["run"] },
29
33
  set: { kind: "repeat", commands: ["run", "prompts"] },
@@ -122,6 +126,8 @@ function validateShape(command, positionals) {
122
126
  const max = {
123
127
  login: 0,
124
128
  logout: 0,
129
+ profiles: 0,
130
+ use: 1,
125
131
  status: 0,
126
132
  doctor: 0,
127
133
  describe: 1,
@@ -129,11 +135,12 @@ function validateShape(command, positionals) {
129
135
  resources: 1,
130
136
  prompts: 1,
131
137
  discover: 0,
138
+ session: 0,
132
139
  completion: 1,
133
140
  help: 1,
134
141
  version: 0
135
142
  };
136
- const minimum = { describe: 1, run: 1, completion: 1 };
143
+ const minimum = { describe: 1, run: 1, use: 1, completion: 1 };
137
144
  if (positionals.length < (minimum[command] ?? 0)) {
138
145
  throw new ArgError(`${command} requires ${command === "run" ? "a tool name" : command === "completion" ? "bash, zsh, or fish" : "a name"}.`);
139
146
  }
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());