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.
package/dist/passport.js CHANGED
@@ -1,123 +1,32 @@
1
1
  #!/usr/bin/env node
2
- import { spawn } from "node:child_process";
3
- import { randomUUID } from "node:crypto";
4
- import { readFileSync, realpathSync, writeFileSync } from "node:fs";
2
+ import { realpathSync, writeFileSync } from "node:fs";
5
3
  import { fileURLToPath } from "node:url";
6
- import { ArgError, bool, parseArgs, repeated, value } from "./cliArgs.js";
4
+ import { bool, parseArgs, repeated, value } from "./cliArgs.js";
7
5
  import { SERVER_TOO_OLD } from "./cliProtocol.js";
8
- import { completionScript } from "./completion.js";
9
- import { assertProfileName, credsPath, getProfile, readCreds, removeProfile, withProfileLock, writeProfile } from "./credentials.js";
6
+ import { removeProfile, withProfileLock } from "./credentials.js";
10
7
  import { VERSION } from "./version.js";
11
- const DEFAULT_TIMEOUT_MS = 30_000;
8
+ import { login } from "./cliLogin.js";
9
+ import { asFailure, emitFailure, emitResult, helpResult } from "./cliOutput.js";
10
+ import { completionResult, versionResult } from "./cliOffline.js";
11
+ import { firstText, hasNonText, payloadOf, refusalOf, requireSuccess } from "./cliResult.js";
12
+ import { callerFrom, endpoint, failure, firstSentence, openUrl, readBoundedJson, resolveCliAuth, safeApiError, sanitize, sleep, timedFetch, timeoutMs } from "./cliSupport.js";
13
+ import { readBoundedUtf8Descriptor } from "./boundedFile.js";
14
+ import { runCliSession, writeCliSessionFailure } from "./cliSession.js";
15
+ export { refusalOf } from "./cliResult.js";
16
+ export { callerFrom, sanitize } from "./cliSupport.js";
12
17
  const APPROVAL_RETRY_MS = 3_000;
13
- class CliFailure extends Error {
14
- exitCode;
15
- cause;
16
- details;
17
- constructor(message, exitCode, cause, details = {}) {
18
- super(message);
19
- this.exitCode = exitCode;
20
- this.cause = cause;
21
- this.details = details;
22
- }
23
- }
24
- function failure(message, exitCode, cause, details = {}) {
25
- throw new CliFailure(message, exitCode, cause, details);
26
- }
27
- function timeoutMs(args) {
28
- return Math.ceil(Number(value(args, "timeout") ?? DEFAULT_TIMEOUT_MS / 1000) * 1000);
29
- }
30
- function profileName(raw) {
31
- try {
32
- assertProfileName(raw);
33
- return raw;
34
- }
35
- catch (error) {
36
- return failure(error instanceof Error ? error.message : "Invalid profile name.", 6, "usage");
37
- }
38
- }
39
- function endpoint(raw) {
40
- try {
41
- const parsed = new URL(raw);
42
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
43
- throw new Error();
44
- if (parsed.username || parsed.password)
45
- return failure("Passport endpoint URLs cannot contain a username or password.", 6, "usage");
46
- const host = parsed.hostname.toLowerCase();
47
- const loopback = host === "localhost" ||
48
- host === "[::1]" ||
49
- host === "::1" ||
50
- /^127(?:\.\d{1,3}){3}$/.test(host);
51
- if (parsed.protocol === "http:" && !loopback) {
52
- return failure("Passport CLI requires HTTPS for remote servers. Configure HTTPS for your self-hosted Passport deployment; plain HTTP is allowed only on localhost, 127.0.0.0/8, or ::1.", 6, "usage");
53
- }
54
- return parsed.toString().replace(/\/$/, "");
55
- }
56
- catch (error) {
57
- if (error instanceof CliFailure)
58
- throw error;
59
- return failure("Passport endpoint must be an http or https URL.", 6, "usage");
60
- }
61
- }
62
- function cloudOrigin(raw) {
63
- const normalized = endpoint(raw);
64
- const parsed = new URL(normalized);
65
- if (parsed.pathname !== "/" || parsed.search || parsed.hash)
66
- return failure("--cloud must be a Passport origin without a path, query, or fragment.", 6, "usage");
67
- return parsed.origin;
68
- }
69
- function resolveAuth(args, env) {
70
- const explicitProfile = value(args, "profile");
71
- const agentKey = env.PASSPORT_AGENT_KEY ?? "";
72
- const agentEndpoint = env.PASSPORT_ENDPOINT ?? "";
73
- if (agentKey || agentEndpoint) {
74
- if (!agentKey || !agentEndpoint) {
75
- return failure("PASSPORT_AGENT_KEY and PASSPORT_ENDPOINT must be set together.", 2, "auth", { hint: "Set both variables, or run: passport login" });
76
- }
77
- if (explicitProfile !== undefined)
78
- return failure("--profile cannot be used with PASSPORT_AGENT_KEY.", 6, "usage");
79
- return { kind: "agent-key", endpoint: endpoint(agentEndpoint), agentKey };
80
- }
81
- const creds = readCreds();
82
- const names = Object.keys(creds).sort();
83
- const fallbackProfile = env.PASSPORT_PROFILE || (names.length === 1 ? names[0] : "");
84
- const profile = explicitProfile !== undefined ? profileName(explicitProfile) : fallbackProfile ? profileName(fallbackProfile) : "";
85
- if (!profile) {
86
- const suffix = names.length ? ` Available profiles: ${names.join(", ")}.` : "";
87
- return failure(`No Passport profile selected.${suffix}`, 2, "auth", { hint: "Run: passport login" });
88
- }
89
- const saved = creds[profile];
90
- if (!saved) {
91
- const suffix = names.length ? ` Available profiles: ${names.join(", ")}.` : "";
92
- return failure(`Passport profile "${profile}" does not exist.${suffix}`, 2, "auth", { hint: "Run: passport login" });
93
- }
94
- return { kind: "profile", endpoint: endpoint(saved.endpoint), profile, refreshToken: saved.refreshToken };
95
- }
96
- export function callerFrom(args, env) {
97
- const explicit = value(args, "caller");
98
- if (explicit !== undefined) {
99
- const normalized = explicit.trim().toLowerCase();
100
- if (!/^[a-z0-9-]{1,24}$/.test(normalized))
101
- return failure("--caller must contain 1-24 lowercase letters, numbers, or hyphens.", 6, "usage");
102
- return normalized;
103
- }
104
- const keys = Object.keys(env);
105
- if (Object.hasOwn(env, "CLAUDECODE") || keys.some((key) => key.startsWith("CLAUDE_CODE")))
106
- return "claude-code";
107
- if (Object.hasOwn(env, "CODEX_SANDBOX") || keys.some((key) => key.startsWith("CODEX_")))
108
- return "codex";
109
- if (Object.hasOwn(env, "OPENCODE") || keys.some((key) => key.startsWith("OPENCODE_")))
110
- return "opencode";
111
- if (Object.hasOwn(env, "CURSOR_TRACE_ID") || keys.some((key) => key.startsWith("CURSOR_")))
112
- return "cursor";
113
- if (Object.hasOwn(env, "GEMINI_CLI"))
114
- return "gemini";
115
- return undefined;
116
- }
18
+ const CLI_ARGUMENT_STDIN_MAX_BYTES = 1024 * 1024;
117
19
  async function withGateway(args, runtime, fn) {
118
- const auth = resolveAuth(args, runtime.env);
20
+ if (runtime.sharedGateway)
21
+ return fn(runtime.sharedGateway.gateway, runtime.sharedGateway.auth);
22
+ const auth = resolveCliAuth(args, runtime.env);
119
23
  const { CliGateway } = await import("./cliClient.js");
120
- const gateway = await CliGateway.connect({ auth, caller: callerFrom(args, runtime.env), timeoutMs: timeoutMs(args), signal: runtime.signal });
24
+ const gateway = await CliGateway.connect({
25
+ auth,
26
+ caller: callerFrom(args, runtime.env),
27
+ timeoutMs: timeoutMs(args),
28
+ signal: runtime.signal
29
+ });
121
30
  try {
122
31
  await gateway.assertCliProtocol();
123
32
  return await fn(gateway, auth);
@@ -126,160 +35,11 @@ async function withGateway(args, runtime, fn) {
126
35
  await gateway.close();
127
36
  }
128
37
  }
129
- function firstText(result) {
130
- return result.content.filter((part) => part.type === "text").map((part) => part.text).join("");
131
- }
132
- function hasNonText(result) {
133
- return result.content.some((part) => part.type !== "text");
134
- }
135
- function payloadOf(result, label) {
136
- const text = firstText(result);
137
- if (text) {
138
- try {
139
- const parsed = JSON.parse(text);
140
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
141
- return parsed;
142
- }
143
- catch {
144
- /* structured content may carry a future server payload */
145
- }
146
- }
147
- if (result.structuredContent && !result.structuredContent.cause)
148
- return result.structuredContent;
149
- return failure(`Passport returned an invalid ${label} payload.`, 1, "invalid_server_response");
150
- }
151
- export function refusalOf(result) {
152
- const structured = result.structuredContent;
153
- // Upstream tools own arbitrary structuredContent and may legitimately use a
154
- // business field named `cause`. Only Passport-stamped refusals control CLI
155
- // exit/retry behavior; ordinary upstream errors remain tool errors.
156
- if (result._meta?.["passport/refusal"] !== true) {
157
- return result.isError ? new CliFailure(firstText(result) || "The tool returned an error.", 1, "tool_error") : undefined;
158
- }
159
- const cause = typeof structured?.cause === "string" ? structured.cause : "";
160
- // approval_pending deliberately remains isError:false for compatibility with
161
- // interactive MCP agents. A CLI refusal is identified by its trusted
162
- // structured cause, never by isError or human prose.
163
- if (!cause)
164
- return new CliFailure("Passport returned an invalid refusal payload.", 1, "invalid_server_response");
165
- const recognized = new Set(["needs_connect", "approval_pending", "approval_denied", "blocked", "unknown_tool"]);
166
- if (!recognized.has(cause)) {
167
- // Successful upstream tools may legitimately return a business field named
168
- // `cause`; only Passport's reserved refusal values change CLI control flow.
169
- return result.isError ? new CliFailure(firstText(result) || "The tool returned an error.", 1, "tool_error") : undefined;
170
- }
171
- const app = typeof structured?.app === "string" ? structured.app : undefined;
172
- const approvalId = typeof structured?.approvalId === "string" ? structured.approvalId : undefined;
173
- let message = firstText(result) || "Passport refused the call.";
174
- if (cause === "needs_connect") {
175
- return new CliFailure(message, 3, cause, { app, hint: `Run: passport connect ${app ?? "<app>"}` });
176
- }
177
- if (cause === "approval_pending") {
178
- if (approvalId && !message.includes(approvalId))
179
- message = `${message}\nApproval ID: ${approvalId}`;
180
- return new CliFailure(message, 4, cause, { app, approvalId });
181
- }
182
- if (cause === "approval_denied" || cause === "blocked")
183
- return new CliFailure(message, 5, cause, { app, approvalId });
184
- if (cause === "unknown_tool")
185
- return new CliFailure(message, 6, cause, { app });
186
- return new CliFailure(`Passport returned an unsupported refusal cause: ${cause}.`, 1, "invalid_server_response", { app, approvalId });
187
- }
188
- function requireSuccess(result) {
189
- const refusal = refusalOf(result);
190
- if (refusal)
191
- throw refusal;
192
- return result;
193
- }
194
- async function login(args, runtime) {
195
- if (runtime.env.PASSPORT_AGENT_KEY || runtime.env.PASSPORT_ENDPOINT) {
196
- return failure("Unset PASSPORT_AGENT_KEY and PASSPORT_ENDPOINT before interactive login.", 6, "usage");
197
- }
198
- const explicitProfile = value(args, "profile");
199
- const requestedProfile = explicitProfile !== undefined ? profileName(explicitProfile) : runtime.env.PASSPORT_PROFILE ? profileName(runtime.env.PASSPORT_PROFILE) : "";
200
- const requestedExisting = requestedProfile ? getProfile(requestedProfile) : undefined;
201
- const cloudRaw = value(args, "cloud") || runtime.env.PASSPORT_CLOUD || (requestedExisting ? new URL(endpoint(requestedExisting.endpoint)).origin : "");
202
- if (!cloudRaw)
203
- return failure("--cloud <origin> is required for the first login.", 6, "usage");
204
- const cloud = cloudOrigin(cloudRaw);
205
- const workspaceOption = value(args, "workspace");
206
- const workspace = workspaceOption?.trim() ?? "";
207
- if (workspaceOption !== undefined && !/^[A-Za-z0-9_-]{1,80}$/.test(workspace))
208
- return failure("--workspace must be a valid workspace id.", 6, "usage");
209
- const clientOption = value(args, "client");
210
- const client = clientOption === undefined ? "cli" : clientOption.trim();
211
- if (!/^[A-Za-z0-9._-]{1,40}$/.test(client))
212
- return failure("--client must be a valid client id (1-40 characters).", 6, "usage");
213
- const ws = workspace ? `?ws=${encodeURIComponent(workspace)}` : "";
214
- const start = await timedFetch(`${cloud}/api/auth/device/start${ws}`, { method: "POST" }, timeoutMs(args), runtime.signal);
215
- if (start.status === 404) {
216
- return failure("Passport could not find that workspace. Ask your admin for its workspace id.", 2, "auth");
217
- }
218
- if (!start.ok)
219
- return failure(`Could not start sign-in (${start.status}).`, 1, "server");
220
- const started = (await start.json());
221
- if (typeof started.code !== "string" || typeof started.userCode !== "string" || typeof started.verifyUrl !== "string") {
222
- return failure("Passport returned an invalid device sign-in response.", 1, "invalid_server_response");
223
- }
224
- runtime.stderr.write(`Sign in to Passport\nOpen: ${started.verifyUrl}\nConfirm code: ${started.userCode}\nWaiting for approval...\n`);
225
- if (!runtime.env.PASSPORT_NO_OPEN)
226
- openUrl(started.verifyUrl);
227
- const deadlineAt = Date.now() + 10 * 60 * 1000;
228
- let sessionToken = "";
229
- while (Date.now() < deadlineAt) {
230
- await sleep(1_500, runtime.signal);
231
- const poll = await timedFetch(`${cloud}/api/auth/device/poll`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ code: started.code }) }, timeoutMs(args), runtime.signal);
232
- if (!poll.ok)
233
- return failure(`Could not check sign-in (${poll.status}).`, 1, "server");
234
- const result = (await poll.json());
235
- if (result.status === "approved" && typeof result.token === "string") {
236
- sessionToken = result.token;
237
- break;
238
- }
239
- if (result.status === "denied" || result.status === "expired")
240
- return failure(`Sign-in ${result.status}.`, 2, "auth");
241
- }
242
- if (!sessionToken)
243
- return failure("Timed out waiting for sign-in approval.", 2, "auth");
244
- const tokenWorkspace = workspace || (await import("./bridge.js")).workspaceOfToken(sessionToken) || "workspace";
245
- const profile = profileName(requestedProfile || `cli@${tokenWorkspace}`);
246
- const storedInstanceId = getProfile(profile)?.instanceId;
247
- const instanceId = storedInstanceId && /^[A-Za-z0-9._:-]{1,128}$/.test(storedInstanceId) ? storedInstanceId : randomUUID();
248
- const credential = await timedFetch(`${cloud}/api/my/bridge-credential`, {
249
- method: "POST",
250
- headers: { "content-type": "application/json", authorization: `Bearer ${sessionToken}` },
251
- body: JSON.stringify({
252
- client,
253
- target: "workspace",
254
- surface: "cli",
255
- instanceId,
256
- instanceLabel: profile
257
- })
258
- }, timeoutMs(args), runtime.signal);
259
- if (!credential.ok) {
260
- const message = await safeApiError(credential, "Could not create a CLI credential.");
261
- return failure(message, credential.status === 401 || credential.status === 403 ? 2 : 1, "auth");
262
- }
263
- const body = (await credential.json());
264
- if (typeof body.refreshToken !== "string" || typeof body.endpoint !== "string") {
265
- return failure("Passport returned an invalid credential response.", 1, "invalid_server_response");
266
- }
267
- const credentialEndpoint = endpoint(body.endpoint);
268
- await withProfileLock(profile, async () => writeProfile(profile, {
269
- refreshToken: body.refreshToken,
270
- endpoint: credentialEndpoint,
271
- instanceId
272
- }));
273
- return {
274
- json: { profile, endpoint: credentialEndpoint, client, surface: "cli" },
275
- human: `Signed in as profile "${profile}".\nCredential saved to ${credsPath()}.`
276
- };
277
- }
278
38
  async function logout(args, runtime) {
279
39
  if (runtime.env.PASSPORT_AGENT_KEY || runtime.env.PASSPORT_ENDPOINT) {
280
40
  return failure("Agent-key authentication is not stored locally and cannot be logged out. Unset the environment variables instead.", 6, "usage");
281
41
  }
282
- const auth = resolveAuth(args, runtime.env);
42
+ const auth = resolveCliAuth(args, runtime.env);
283
43
  if (auth.kind !== "profile")
284
44
  return failure("No local profile is active.", 2, "auth");
285
45
  const existing = await withProfileLock(auth.profile, async () => removeProfile(auth.profile));
@@ -287,7 +47,11 @@ async function logout(args, runtime) {
287
47
  let warning = "";
288
48
  if (existing) {
289
49
  try {
290
- const response = await timedFetch(`${new URL(existing.endpoint).origin}/api/token/revoke`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ refreshToken: existing.refreshToken }) }, timeoutMs(args), runtime.signal);
50
+ const response = await timedFetch(`${new URL(existing.endpoint).origin}/api/token/revoke`, {
51
+ method: "POST",
52
+ headers: { "content-type": "application/json" },
53
+ body: JSON.stringify({ refreshToken: existing.refreshToken })
54
+ }, timeoutMs(args), runtime.signal);
291
55
  revoked = response.ok;
292
56
  if (!response.ok)
293
57
  warning = `Warning: the server could not revoke the credential (${response.status}); the local profile was removed.`;
@@ -339,7 +103,9 @@ async function status(args, runtime) {
339
103
  `Endpoint: ${data.endpoint}`,
340
104
  ...(auth.kind === "profile" ? [`Profile: ${auth.profile}`] : []),
341
105
  `Client: ${managed.client} · Surface: ${managed.surface} · Auth: ${managed.auth}`,
342
- ...(mcps.length ? mcps.map((mcp) => `${mcp.name} (${mcp.app}): ${mcp.status} · ${mcp.toolCount} permitted tool${mcp.toolCount === 1 ? "" : "s"}`) : ["No visible MCPs."])
106
+ ...(mcps.length
107
+ ? mcps.map((mcp) => `${mcp.name} (${mcp.app}): ${mcp.status} · ${mcp.toolCount} permitted tool${mcp.toolCount === 1 ? "" : "s"}`)
108
+ : ["No visible MCPs."])
343
109
  ];
344
110
  return { json: data, human: lines.join("\n") };
345
111
  });
@@ -377,7 +143,7 @@ async function discover(args, runtime) {
377
143
  const message = await safeApiError(response, "Could not submit the fleet discovery scan.");
378
144
  return failure(message, response.status === 401 || response.status === 403 ? 2 : 1, "server");
379
145
  }
380
- const report = (await response.json());
146
+ const report = await readBoundedJson(response);
381
147
  const direct = Number(report.stats?.directConnections ?? 0);
382
148
  const review = Number(report.stats?.needsReview ?? 0);
383
149
  const enforcement = String(report.policy?.enforcement ?? "observe");
@@ -402,7 +168,10 @@ async function search(args, runtime) {
402
168
  if (value(args, "app") !== undefined && !value(args, "app").trim())
403
169
  return failure("--app cannot be empty.", 6, "usage");
404
170
  return withGateway(args, runtime, async (gateway) => {
405
- const result = requireSuccess(await gateway.callTool("passport_search_tools", { ...(query ? { query } : {}), ...(value(args, "app") ? { app: value(args, "app") } : {}) }));
171
+ const result = requireSuccess(await gateway.callTool("passport_search_tools", {
172
+ ...(query ? { query } : {}),
173
+ ...(value(args, "app") ? { app: value(args, "app") } : {})
174
+ }));
406
175
  const payload = payloadOf(result, "search");
407
176
  const lines = [];
408
177
  if (query) {
@@ -436,7 +205,10 @@ async function describe(args, runtime) {
436
205
  const results = Array.isArray(payload.results) ? payload.results : [];
437
206
  const exact = results.find((hit) => hit.tool === name);
438
207
  if (!exact) {
439
- const suggestions = results.slice(0, 5).map((hit) => String(hit.tool ?? "")).filter(Boolean);
208
+ const suggestions = results
209
+ .slice(0, 5)
210
+ .map((hit) => String(hit.tool ?? ""))
211
+ .filter(Boolean);
440
212
  const suffix = suggestions.length ? ` Near matches: ${suggestions.join(", ")}.` : "";
441
213
  return failure(`Unknown tool "${name}".${suffix}`, 6, "unknown_tool");
442
214
  }
@@ -493,7 +265,7 @@ function runArguments(args) {
493
265
  if (positional !== undefined)
494
266
  return jsonObject(positional, "tool arguments");
495
267
  if (fromStdin !== undefined)
496
- return jsonObject(readFileSync(0, "utf8"), "stdin");
268
+ return jsonObject(readBoundedUtf8Descriptor(0, CLI_ARGUMENT_STDIN_MAX_BYTES), "stdin");
497
269
  const out = Object.create(null);
498
270
  const seen = new Set();
499
271
  for (const raw of sets)
@@ -545,7 +317,9 @@ async function connect(args, runtime) {
545
317
  ...(alias !== undefined ? { alias: alias.trim() } : {}),
546
318
  ...(requested.length ? { apps: requested } : {})
547
319
  }));
548
- const rows = requested.length ? requested.map((app) => findConnection(managed.connections, app)) : managed.connections;
320
+ const rows = requested.length
321
+ ? requested.map((app) => findConnection(managed.connections, app))
322
+ : managed.connections;
549
323
  const human = connectionLines(managed, rows, requested.length > 0);
550
324
  const urls = connectionUrls(managed, rows, requested.length > 0);
551
325
  if (bool(args, "open")) {
@@ -577,7 +351,9 @@ function findConnection(rows, requested) {
577
351
  const needle = requested.trim().toLowerCase();
578
352
  const row = rows.find((entry) => String(entry.app ?? "").toLowerCase() === needle || String(entry.name ?? "").toLowerCase() === needle);
579
353
  if (!row)
580
- return failure(`Unknown MCP "${requested}". Run passport status to see visible MCPs.`, 6, "unknown_app", { app: requested });
354
+ return failure(`Unknown MCP "${requested}". Run passport status to see visible MCPs.`, 6, "unknown_app", {
355
+ app: requested
356
+ });
581
357
  return row;
582
358
  }
583
359
  function connectionUrls(managed, rows, explicitlyNamed) {
@@ -638,7 +414,9 @@ async function resources(args, runtime) {
638
414
  if (!uri) {
639
415
  const listed = await gateway.listResources();
640
416
  const human = listed.resources.length
641
- ? listed.resources.map((resource) => `${resource.uri} · ${resource.name}${resource.mimeType ? ` · ${resource.mimeType}` : ""}`).join("\n")
417
+ ? listed.resources
418
+ .map((resource) => `${resource.uri} · ${resource.name}${resource.mimeType ? ` · ${resource.mimeType}` : ""}`)
419
+ .join("\n")
642
420
  : "No resources are available.";
643
421
  return { json: listed, human };
644
422
  }
@@ -654,7 +432,12 @@ async function resources(args, runtime) {
654
432
  if (read.contents.some((content) => "blob" in content)) {
655
433
  return failure("The resource is binary. Use --out <file> or --json.", 1, "non_text_content");
656
434
  }
657
- return { json: read, human: read.contents.map((content) => ("text" in content ? content.text : "")).join(""), essential: true, raw: true };
435
+ return {
436
+ json: read,
437
+ human: read.contents.map((content) => ("text" in content ? content.text : "")).join(""),
438
+ essential: true,
439
+ raw: true
440
+ };
658
441
  });
659
442
  }
660
443
  function resourceBytes(contents) {
@@ -676,7 +459,9 @@ async function prompts(args, runtime) {
676
459
  const human = listed.prompts.length
677
460
  ? listed.prompts
678
461
  .map((prompt) => {
679
- const names = prompt.arguments?.map((argument) => `${argument.name}${argument.required ? "*" : ""}`).join(", ");
462
+ const names = prompt.arguments
463
+ ?.map((argument) => `${argument.name}${argument.required ? "*" : ""}`)
464
+ .join(", ");
680
465
  return `${prompt.name}${names ? ` (${names})` : ""}${prompt.description ? ` · ${prompt.description}` : ""}`;
681
466
  })
682
467
  .join("\n")
@@ -713,7 +498,11 @@ function assignPrompt(raw, out, seen) {
713
498
  return failure("--set expects key=value.", 6, "usage");
714
499
  const key = raw.slice(0, equals).trim();
715
500
  if (!key || key === "__proto__" || key === "prototype" || key === "constructor" || seen.has(key)) {
716
- return failure(!key ? "Prompt argument key cannot be empty." : seen.has(key) ? `Prompt argument "${key}" was provided more than once.` : `Invalid prompt argument key: ${key}.`, 6, "usage");
501
+ return failure(!key
502
+ ? "Prompt argument key cannot be empty."
503
+ : seen.has(key)
504
+ ? `Prompt argument "${key}" was provided more than once.`
505
+ : `Invalid prompt argument key: ${key}.`, 6, "usage");
717
506
  }
718
507
  seen.add(key);
719
508
  out[key] = raw.slice(equals + 1);
@@ -727,45 +516,6 @@ function promptBytes(messages) {
727
516
  }
728
517
  return failure("A multi-part binary prompt cannot be written to one file. Use --json.", 6, "usage");
729
518
  }
730
- function help(args) {
731
- const verb = args.positionals[0];
732
- const text = helpText(verb);
733
- return { json: { command: verb ?? null, help: text }, human: text, essential: true };
734
- }
735
- function completion(args) {
736
- const shell = args.positionals[0];
737
- if (shell !== "bash" && shell !== "zsh" && shell !== "fish") {
738
- return failure("completion requires bash, zsh, or fish.", 6, "usage");
739
- }
740
- const script = completionScript(shell);
741
- return { json: { shell, script }, human: script, essential: true, raw: true };
742
- }
743
- function version(args, env) {
744
- let profile;
745
- let resolvedEndpoint;
746
- if (env.PASSPORT_AGENT_KEY && env.PASSPORT_ENDPOINT && value(args, "profile") !== undefined) {
747
- return failure("--profile cannot be used with PASSPORT_AGENT_KEY.", 6, "usage");
748
- }
749
- if (env.PASSPORT_AGENT_KEY && env.PASSPORT_ENDPOINT) {
750
- resolvedEndpoint = endpoint(env.PASSPORT_ENDPOINT);
751
- }
752
- else {
753
- const creds = readCreds();
754
- const names = Object.keys(creds);
755
- const explicitProfile = value(args, "profile");
756
- const candidate = explicitProfile !== undefined ? profileName(explicitProfile) : env.PASSPORT_PROFILE ? profileName(env.PASSPORT_PROFILE) : names.length === 1 ? profileName(names[0]) : "";
757
- if (candidate && creds[candidate]) {
758
- profile = candidate;
759
- resolvedEndpoint = endpoint(creds[candidate].endpoint);
760
- }
761
- }
762
- const data = { version: VERSION, ...(resolvedEndpoint ? { endpoint: resolvedEndpoint } : {}), ...(profile ? { profile } : {}) };
763
- return {
764
- json: data,
765
- human: [`passport ${VERSION}`, ...(resolvedEndpoint ? [`Endpoint: ${resolvedEndpoint}`] : []), ...(profile ? [`Profile: ${profile}`] : [])].join("\n"),
766
- essential: true
767
- };
768
- }
769
519
  async function dispatch(args, runtime) {
770
520
  switch (args.command) {
771
521
  case "login":
@@ -790,180 +540,48 @@ async function dispatch(args, runtime) {
790
540
  return prompts(args, runtime);
791
541
  case "discover":
792
542
  return discover(args, runtime);
543
+ case "session":
544
+ return runCliSession(args, runtime, dispatch);
793
545
  case "completion":
794
- return completion(args);
546
+ return completionResult(args);
795
547
  case "help":
796
- return help(args);
548
+ return helpResult(args);
797
549
  case "version":
798
- return version(args, runtime.env);
799
- }
800
- }
801
- function helpText(verb) {
802
- const details = {
803
- login: "passport login --cloud <origin> [--workspace <id>] [--client <id>] [--profile <name>]\nStarts device sign-in and stores a cli-surface rotating credential.",
804
- logout: "passport logout [--profile <name>]\nRevokes the rotating credential and always removes the local profile.",
805
- status: "passport status\nJSON: {workspace,member,endpoint,auth,profile?,client,mcps:[{app,name,status,toolCount}]}",
806
- doctor: "passport doctor [--profile <name>]\nChecks Node, credential-store safety, endpoint security, server health, authentication, serverInfo, and the exact CLI protocol. JSON includes {ok,auth,profile?,profileCount,endpointOrigin?,server?,checks}.",
807
- search: "passport search [query...] [--app <key>]\nEmpty query lists the complete permitted catalog. JSON is the server search payload.",
808
- describe: "passport describe <tool>\nShows the exact tool definition and complete parameter schema.",
809
- run: "passport run <tool> [json-object]\n --args - read the JSON object from stdin\n --set key=value set a string argument (repeatable)\n --set-json key=<json> set a typed argument (repeatable)\n --wait <sec> retry only a definite approval_pending call\nJSON is the complete MCP tool result; human stdout is verbatim tool text.",
810
- connect: "passport connect [app...] [--alias <name>] [--open] [--wait <sec>]\nShows member-bound connection links and can wait for sign-in to finish. JSON is the manage_connections payload.",
811
- resources: "passport resources [uri] [--out <file>]\nLists or reads workspace MCP resources. Binary content requires --out or --json.",
812
- prompts: "passport prompts [name] [--set key=value] [--out <file>]\nLists or gets workspace MCP prompts. Binary content requires --out or --json.",
813
- discover: "passport discover\nScans supported local MCP configuration, submits privacy-minimized inventory, and exits 5 when a managed policy reports a violation.",
814
- completion: "passport completion <bash|zsh|fish>\nPrints an offline shell-completion script to stdout.",
815
- help: "passport help [verb]",
816
- version: "passport version\nWorks without a profile or network."
817
- };
818
- if (verb && details[verb])
819
- return `${details[verb]}\n\nGlobal: --profile <name> --json --timeout <sec> --quiet --caller <id>`;
820
- return `Passport CLI ${VERSION}
821
-
822
- Usage: passport <command> [options]
823
-
824
- login Sign in with the device flow
825
- logout Revoke and remove a profile
826
- status Show identity and visible MCP connection state
827
- doctor Diagnose local setup and server compatibility
828
- search Find permitted tools or list the catalog
829
- describe Show one exact tool definition
830
- run Run a governed tool
831
- connect Connect member MCP accounts
832
- resources List or read MCP resources
833
- prompts List or get MCP prompts
834
- discover Scan this computer for direct MCP configuration
835
- completion Generate bash, zsh, or fish completion
836
- help Show command help
837
- version Show CLI version and local context
838
-
839
- Global: --profile <name> --json --timeout <sec> --quiet --caller <id>
840
-
841
- Exit codes: 0 success · 1 network/server · 2 auth · 3 needs-connect · 4 approval-pending · 5 policy/guardrail/selection/approval-denial · 6 usage/unknown
842
- With --json, stdout is exactly one JSON value. Hints and warnings use stderr.`;
843
- }
844
- function emit(result, args, runtime) {
845
- if (bool(args, "json")) {
846
- runtime.stdout.write(`${JSON.stringify(result.json)}\n`);
847
- return;
848
- }
849
- if (result.human === undefined || (bool(args, "quiet") && !result.essential))
850
- return;
851
- if (Buffer.isBuffer(result.human))
852
- runtime.stdout.write(result.human);
853
- else
854
- runtime.stdout.write(result.raw ? result.human : `${result.human}${result.human.endsWith("\n") ? "" : "\n"}`);
855
- }
856
- function asFailure(error) {
857
- if (error instanceof CliFailure)
858
- return error;
859
- if (error instanceof ArgError)
860
- return new CliFailure(error.message, 6, "usage");
861
- const raw = error instanceof Error ? error.message : String(error);
862
- const message = sanitize(raw);
863
- if (message === SERVER_TOO_OLD || message.includes("CLI-compatible server"))
864
- return new CliFailure(SERVER_TOO_OLD, 1, "server_too_old");
865
- if (/token exchange failed|invalid_or_revoked|unauthori[sz]ed|\b401\b/i.test(message)) {
866
- return new CliFailure("Passport authentication expired or was revoked.", 2, "auth", { hint: "Run: passport login" });
867
- }
868
- if (/timeout|timed out|aborted|aborterror|requesttimeout/i.test(message))
869
- return new CliFailure("The Passport request timed out; it was not retried.", 1, "timeout");
870
- return new CliFailure(message || "Passport request failed.", 1, "network_or_server");
871
- }
872
- export function sanitize(message) {
873
- // Bound work before applying redactors: SDK/network errors can contain a
874
- // surprisingly large serialized cause. The final user-facing error is 500
875
- // chars, so scanning a small prefix is sufficient and avoids regex work over
876
- // an attacker-sized payload.
877
- return message
878
- .slice(0, 2_000)
879
- .replace(/Bearer\s+\S+/gi, "Bearer [redacted]")
880
- .replace(/("(?:refreshToken|refresh-token|accessToken|access-token|token|agentKey|agent_key|agent-key|apiKey|api_key|api-key|clientSecret|client_secret|client-secret)"\s*:\s*")[^"]*"/gi, "$1[redacted]\"")
881
- .replace(/((?:refreshToken|refresh-token|accessToken|access-token|token|agentKey|agent_key|agent-key|apiKey|api_key|api-key|agent-key|clientSecret|client_secret|client-secret)\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;&}]+)/gi, "$1[redacted]")
882
- .replace(/\b(?:[A-Za-z0-9_-]+~)?(?:pak|ppr|ppa|pp)_[A-Za-z0-9_-]{12,}\b/g, "[redacted]")
883
- .slice(0, 500);
884
- }
885
- function emitFailure(error, json, quiet, runtime) {
886
- if (json) {
887
- runtime.stdout.write(`${JSON.stringify({
888
- error: error.message,
889
- cause: error.cause,
890
- exitCode: error.exitCode,
891
- ...(error.details.approvalId ? { approvalId: error.details.approvalId } : {}),
892
- ...(error.details.app ? { app: error.details.app } : {})
893
- })}\n`);
550
+ return versionResult(args, runtime.env);
894
551
  }
895
- else {
896
- runtime.stderr.write(`${error.message}\n`);
897
- }
898
- if (error.details.hint && !quiet)
899
- runtime.stderr.write(`${error.details.hint}\n`);
900
- }
901
- async function timedFetch(input, init, ms, parent) {
902
- return fetch(input, { ...init, signal: AbortSignal.any([parent, AbortSignal.timeout(ms)]) });
903
552
  }
904
- async function safeApiError(response, fallback) {
905
- try {
906
- const body = (await response.json());
907
- return typeof body.error === "string" ? sanitize(body.error) : fallback;
908
- }
909
- catch {
910
- return fallback;
911
- }
912
- }
913
- function sleep(ms, signal) {
914
- return new Promise((resolve, reject) => {
915
- if (signal.aborted) {
916
- reject(signal.reason);
917
- return;
918
- }
919
- const timer = setTimeout(done, ms);
920
- function done() {
921
- signal.removeEventListener("abort", cancelled);
922
- resolve();
923
- }
924
- function cancelled() {
925
- clearTimeout(timer);
926
- signal.removeEventListener("abort", cancelled);
927
- reject(signal.reason);
928
- }
929
- signal.addEventListener("abort", cancelled, { once: true });
930
- });
931
- }
932
- function openUrl(url) {
933
- const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
934
- const argv = process.platform === "win32" ? ["/c", "start", "", url] : [url];
935
- try {
936
- const child = spawn(command, argv, { stdio: "ignore", detached: true, shell: false });
937
- child.on("error", () => { });
938
- child.unref();
939
- }
940
- catch {
941
- /* the printed URL remains usable */
942
- }
943
- }
944
- function firstSentence(value) {
945
- const trimmed = value.trim().replace(/\s+/g, " ");
946
- const match = trimmed.match(/^.*?[.!?](?:\s|$)/);
947
- return (match?.[0] ?? trimmed).trim();
948
- }
949
- export async function main(argv = process.argv.slice(2), env = process.env) {
553
+ export async function main(argv = process.argv.slice(2), env = process.env, io = {
554
+ stdin: process.stdin,
555
+ stdout: process.stdout,
556
+ stderr: process.stderr
557
+ }) {
950
558
  const controller = new AbortController();
951
559
  const cancel = () => controller.abort(new Error("Cancelled."));
952
560
  process.once("SIGINT", cancel);
953
561
  process.once("SIGTERM", cancel);
954
- const runtime = { env, stdout: process.stdout, stderr: process.stderr, signal: controller.signal };
562
+ const runtime = {
563
+ env,
564
+ stdin: io.stdin ?? process.stdin,
565
+ stdout: io.stdout,
566
+ stderr: io.stderr,
567
+ signal: controller.signal
568
+ };
955
569
  let args;
956
570
  const wantsJson = argv.some((item) => item === "--json" || item.startsWith("--json="));
957
571
  const wantsQuiet = argv.includes("--quiet");
958
572
  try {
959
573
  args = parseArgs(argv);
960
574
  const result = await dispatch(args, runtime);
961
- emit(result, args, runtime);
575
+ if (args.command !== "session")
576
+ emitResult(result, args, runtime);
962
577
  return result.exitCode ?? 0;
963
578
  }
964
579
  catch (error) {
965
580
  const cliError = asFailure(error);
966
- emitFailure(cliError, args ? bool(args, "json") : wantsJson, args ? bool(args, "quiet") : wantsQuiet, runtime);
581
+ if (args?.command === "session")
582
+ await writeCliSessionFailure(runtime, cliError);
583
+ else
584
+ emitFailure(cliError, args ? bool(args, "json") : wantsJson, args ? bool(args, "quiet") : wantsQuiet, runtime);
967
585
  return cliError.exitCode;
968
586
  }
969
587
  finally {