passport-bridge 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +270 -0
- package/dist/bridge.js +53 -5
- package/dist/cliArgs.js +159 -0
- package/dist/cliClient.js +162 -0
- package/dist/cliProtocol.js +4 -0
- package/dist/completion.js +132 -0
- package/dist/credentials.js +90 -35
- package/dist/doctor.js +208 -0
- package/dist/passport.js +939 -0
- package/dist/version.js +3 -0
- package/package.json +20 -6
package/dist/passport.js
ADDED
|
@@ -0,0 +1,939 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { readFileSync, realpathSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { ArgError, bool, parseArgs, repeated, value } from "./cliArgs.js";
|
|
6
|
+
import { SERVER_TOO_OLD } from "./cliProtocol.js";
|
|
7
|
+
import { completionScript } from "./completion.js";
|
|
8
|
+
import { assertProfileName, credsPath, getProfile, readCreds, removeProfile, withProfileLock, writeProfile } from "./credentials.js";
|
|
9
|
+
import { VERSION } from "./version.js";
|
|
10
|
+
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
11
|
+
const APPROVAL_RETRY_MS = 3_000;
|
|
12
|
+
class CliFailure extends Error {
|
|
13
|
+
exitCode;
|
|
14
|
+
cause;
|
|
15
|
+
details;
|
|
16
|
+
constructor(message, exitCode, cause, details = {}) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.exitCode = exitCode;
|
|
19
|
+
this.cause = cause;
|
|
20
|
+
this.details = details;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
function failure(message, exitCode, cause, details = {}) {
|
|
24
|
+
throw new CliFailure(message, exitCode, cause, details);
|
|
25
|
+
}
|
|
26
|
+
function timeoutMs(args) {
|
|
27
|
+
return Math.ceil(Number(value(args, "timeout") ?? DEFAULT_TIMEOUT_MS / 1000) * 1000);
|
|
28
|
+
}
|
|
29
|
+
function profileName(raw) {
|
|
30
|
+
try {
|
|
31
|
+
assertProfileName(raw);
|
|
32
|
+
return raw;
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
return failure(error instanceof Error ? error.message : "Invalid profile name.", 6, "usage");
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function endpoint(raw) {
|
|
39
|
+
try {
|
|
40
|
+
const parsed = new URL(raw);
|
|
41
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
|
|
42
|
+
throw new Error();
|
|
43
|
+
if (parsed.username || parsed.password)
|
|
44
|
+
return failure("Passport endpoint URLs cannot contain a username or password.", 6, "usage");
|
|
45
|
+
const host = parsed.hostname.toLowerCase();
|
|
46
|
+
const loopback = host === "localhost" ||
|
|
47
|
+
host === "[::1]" ||
|
|
48
|
+
host === "::1" ||
|
|
49
|
+
/^127(?:\.\d{1,3}){3}$/.test(host);
|
|
50
|
+
if (parsed.protocol === "http:" && !loopback) {
|
|
51
|
+
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");
|
|
52
|
+
}
|
|
53
|
+
return parsed.toString().replace(/\/$/, "");
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
if (error instanceof CliFailure)
|
|
57
|
+
throw error;
|
|
58
|
+
return failure("Passport endpoint must be an http or https URL.", 6, "usage");
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function cloudOrigin(raw) {
|
|
62
|
+
const normalized = endpoint(raw);
|
|
63
|
+
const parsed = new URL(normalized);
|
|
64
|
+
if (parsed.pathname !== "/" || parsed.search || parsed.hash)
|
|
65
|
+
return failure("--cloud must be a Passport origin without a path, query, or fragment.", 6, "usage");
|
|
66
|
+
return parsed.origin;
|
|
67
|
+
}
|
|
68
|
+
function resolveAuth(args, env) {
|
|
69
|
+
const explicitProfile = value(args, "profile");
|
|
70
|
+
const agentKey = env.PASSPORT_AGENT_KEY ?? "";
|
|
71
|
+
const agentEndpoint = env.PASSPORT_ENDPOINT ?? "";
|
|
72
|
+
if (agentKey || agentEndpoint) {
|
|
73
|
+
if (!agentKey || !agentEndpoint) {
|
|
74
|
+
return failure("PASSPORT_AGENT_KEY and PASSPORT_ENDPOINT must be set together.", 2, "auth", { hint: "Set both variables, or run: passport login" });
|
|
75
|
+
}
|
|
76
|
+
if (explicitProfile !== undefined)
|
|
77
|
+
return failure("--profile cannot be used with PASSPORT_AGENT_KEY.", 6, "usage");
|
|
78
|
+
return { kind: "agent-key", endpoint: endpoint(agentEndpoint), agentKey };
|
|
79
|
+
}
|
|
80
|
+
const creds = readCreds();
|
|
81
|
+
const names = Object.keys(creds).sort();
|
|
82
|
+
const fallbackProfile = env.PASSPORT_PROFILE || (names.length === 1 ? names[0] : "");
|
|
83
|
+
const profile = explicitProfile !== undefined ? profileName(explicitProfile) : fallbackProfile ? profileName(fallbackProfile) : "";
|
|
84
|
+
if (!profile) {
|
|
85
|
+
const suffix = names.length ? ` Available profiles: ${names.join(", ")}.` : "";
|
|
86
|
+
return failure(`No Passport profile selected.${suffix}`, 2, "auth", { hint: "Run: passport login" });
|
|
87
|
+
}
|
|
88
|
+
const saved = creds[profile];
|
|
89
|
+
if (!saved) {
|
|
90
|
+
const suffix = names.length ? ` Available profiles: ${names.join(", ")}.` : "";
|
|
91
|
+
return failure(`Passport profile "${profile}" does not exist.${suffix}`, 2, "auth", { hint: "Run: passport login" });
|
|
92
|
+
}
|
|
93
|
+
return { kind: "profile", endpoint: endpoint(saved.endpoint), profile, refreshToken: saved.refreshToken };
|
|
94
|
+
}
|
|
95
|
+
export function callerFrom(args, env) {
|
|
96
|
+
const explicit = value(args, "caller");
|
|
97
|
+
if (explicit !== undefined) {
|
|
98
|
+
const normalized = explicit.trim().toLowerCase();
|
|
99
|
+
if (!/^[a-z0-9-]{1,24}$/.test(normalized))
|
|
100
|
+
return failure("--caller must contain 1-24 lowercase letters, numbers, or hyphens.", 6, "usage");
|
|
101
|
+
return normalized;
|
|
102
|
+
}
|
|
103
|
+
const keys = Object.keys(env);
|
|
104
|
+
if (Object.hasOwn(env, "CLAUDECODE") || keys.some((key) => key.startsWith("CLAUDE_CODE")))
|
|
105
|
+
return "claude-code";
|
|
106
|
+
if (Object.hasOwn(env, "CODEX_SANDBOX") || keys.some((key) => key.startsWith("CODEX_")))
|
|
107
|
+
return "codex";
|
|
108
|
+
if (Object.hasOwn(env, "OPENCODE") || keys.some((key) => key.startsWith("OPENCODE_")))
|
|
109
|
+
return "opencode";
|
|
110
|
+
if (Object.hasOwn(env, "CURSOR_TRACE_ID") || keys.some((key) => key.startsWith("CURSOR_")))
|
|
111
|
+
return "cursor";
|
|
112
|
+
if (Object.hasOwn(env, "GEMINI_CLI"))
|
|
113
|
+
return "gemini";
|
|
114
|
+
return undefined;
|
|
115
|
+
}
|
|
116
|
+
async function withGateway(args, runtime, fn) {
|
|
117
|
+
const auth = resolveAuth(args, runtime.env);
|
|
118
|
+
const { CliGateway } = await import("./cliClient.js");
|
|
119
|
+
const gateway = await CliGateway.connect({ auth, caller: callerFrom(args, runtime.env), timeoutMs: timeoutMs(args), signal: runtime.signal });
|
|
120
|
+
try {
|
|
121
|
+
await gateway.assertCliProtocol();
|
|
122
|
+
return await fn(gateway, auth);
|
|
123
|
+
}
|
|
124
|
+
finally {
|
|
125
|
+
await gateway.close();
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
function firstText(result) {
|
|
129
|
+
return result.content.filter((part) => part.type === "text").map((part) => part.text).join("");
|
|
130
|
+
}
|
|
131
|
+
function hasNonText(result) {
|
|
132
|
+
return result.content.some((part) => part.type !== "text");
|
|
133
|
+
}
|
|
134
|
+
function payloadOf(result, label) {
|
|
135
|
+
const text = firstText(result);
|
|
136
|
+
if (text) {
|
|
137
|
+
try {
|
|
138
|
+
const parsed = JSON.parse(text);
|
|
139
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
|
|
140
|
+
return parsed;
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
/* structured content may carry a future server payload */
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
if (result.structuredContent && !result.structuredContent.cause)
|
|
147
|
+
return result.structuredContent;
|
|
148
|
+
return failure(`Passport returned an invalid ${label} payload.`, 1, "invalid_server_response");
|
|
149
|
+
}
|
|
150
|
+
export function refusalOf(result) {
|
|
151
|
+
const structured = result.structuredContent;
|
|
152
|
+
// Upstream tools own arbitrary structuredContent and may legitimately use a
|
|
153
|
+
// business field named `cause`. Only Passport-stamped refusals control CLI
|
|
154
|
+
// exit/retry behavior; ordinary upstream errors remain tool errors.
|
|
155
|
+
if (result._meta?.["passport/refusal"] !== true) {
|
|
156
|
+
return result.isError ? new CliFailure(firstText(result) || "The tool returned an error.", 1, "tool_error") : undefined;
|
|
157
|
+
}
|
|
158
|
+
const cause = typeof structured?.cause === "string" ? structured.cause : "";
|
|
159
|
+
// approval_pending deliberately remains isError:false for compatibility with
|
|
160
|
+
// interactive MCP agents. A CLI refusal is identified by its trusted
|
|
161
|
+
// structured cause, never by isError or human prose.
|
|
162
|
+
if (!cause)
|
|
163
|
+
return new CliFailure("Passport returned an invalid refusal payload.", 1, "invalid_server_response");
|
|
164
|
+
const recognized = new Set(["needs_connect", "approval_pending", "approval_denied", "blocked", "unknown_tool"]);
|
|
165
|
+
if (!recognized.has(cause)) {
|
|
166
|
+
// Successful upstream tools may legitimately return a business field named
|
|
167
|
+
// `cause`; only Passport's reserved refusal values change CLI control flow.
|
|
168
|
+
return result.isError ? new CliFailure(firstText(result) || "The tool returned an error.", 1, "tool_error") : undefined;
|
|
169
|
+
}
|
|
170
|
+
const app = typeof structured?.app === "string" ? structured.app : undefined;
|
|
171
|
+
const approvalId = typeof structured?.approvalId === "string" ? structured.approvalId : undefined;
|
|
172
|
+
let message = firstText(result) || "Passport refused the call.";
|
|
173
|
+
if (cause === "needs_connect") {
|
|
174
|
+
return new CliFailure(message, 3, cause, { app, hint: `Run: passport connect ${app ?? "<app>"}` });
|
|
175
|
+
}
|
|
176
|
+
if (cause === "approval_pending") {
|
|
177
|
+
if (approvalId && !message.includes(approvalId))
|
|
178
|
+
message = `${message}\nApproval ID: ${approvalId}`;
|
|
179
|
+
return new CliFailure(message, 4, cause, { app, approvalId });
|
|
180
|
+
}
|
|
181
|
+
if (cause === "approval_denied" || cause === "blocked")
|
|
182
|
+
return new CliFailure(message, 5, cause, { app, approvalId });
|
|
183
|
+
if (cause === "unknown_tool")
|
|
184
|
+
return new CliFailure(message, 6, cause, { app });
|
|
185
|
+
return new CliFailure(`Passport returned an unsupported refusal cause: ${cause}.`, 1, "invalid_server_response", { app, approvalId });
|
|
186
|
+
}
|
|
187
|
+
function requireSuccess(result) {
|
|
188
|
+
const refusal = refusalOf(result);
|
|
189
|
+
if (refusal)
|
|
190
|
+
throw refusal;
|
|
191
|
+
return result;
|
|
192
|
+
}
|
|
193
|
+
async function login(args, runtime) {
|
|
194
|
+
if (runtime.env.PASSPORT_AGENT_KEY || runtime.env.PASSPORT_ENDPOINT) {
|
|
195
|
+
return failure("Unset PASSPORT_AGENT_KEY and PASSPORT_ENDPOINT before interactive login.", 6, "usage");
|
|
196
|
+
}
|
|
197
|
+
const explicitProfile = value(args, "profile");
|
|
198
|
+
const requestedProfile = explicitProfile !== undefined ? profileName(explicitProfile) : runtime.env.PASSPORT_PROFILE ? profileName(runtime.env.PASSPORT_PROFILE) : "";
|
|
199
|
+
const existing = requestedProfile ? getProfile(requestedProfile) : undefined;
|
|
200
|
+
const cloudRaw = value(args, "cloud") || runtime.env.PASSPORT_CLOUD || (existing ? new URL(endpoint(existing.endpoint)).origin : "");
|
|
201
|
+
if (!cloudRaw)
|
|
202
|
+
return failure("--cloud <origin> is required for the first login.", 6, "usage");
|
|
203
|
+
const cloud = cloudOrigin(cloudRaw);
|
|
204
|
+
const workspaceOption = value(args, "workspace");
|
|
205
|
+
const workspace = workspaceOption?.trim() ?? "";
|
|
206
|
+
if (workspaceOption !== undefined && !/^[A-Za-z0-9_-]{1,80}$/.test(workspace))
|
|
207
|
+
return failure("--workspace must be a valid workspace id.", 6, "usage");
|
|
208
|
+
const clientOption = value(args, "client");
|
|
209
|
+
const client = clientOption === undefined ? "cli" : clientOption.trim();
|
|
210
|
+
if (!/^[A-Za-z0-9._-]{1,40}$/.test(client))
|
|
211
|
+
return failure("--client must be a valid client id (1-40 characters).", 6, "usage");
|
|
212
|
+
const ws = workspace ? `?ws=${encodeURIComponent(workspace)}` : "";
|
|
213
|
+
const start = await timedFetch(`${cloud}/api/auth/device/start${ws}`, { method: "POST" }, timeoutMs(args), runtime.signal);
|
|
214
|
+
if (start.status === 404) {
|
|
215
|
+
return failure("Passport could not find that workspace. Ask your admin for its workspace id.", 2, "auth");
|
|
216
|
+
}
|
|
217
|
+
if (!start.ok)
|
|
218
|
+
return failure(`Could not start sign-in (${start.status}).`, 1, "server");
|
|
219
|
+
const started = (await start.json());
|
|
220
|
+
if (typeof started.code !== "string" || typeof started.userCode !== "string" || typeof started.verifyUrl !== "string") {
|
|
221
|
+
return failure("Passport returned an invalid device sign-in response.", 1, "invalid_server_response");
|
|
222
|
+
}
|
|
223
|
+
runtime.stderr.write(`Sign in to Passport\nOpen: ${started.verifyUrl}\nConfirm code: ${started.userCode}\nWaiting for approval...\n`);
|
|
224
|
+
if (!runtime.env.PASSPORT_NO_OPEN)
|
|
225
|
+
openUrl(started.verifyUrl);
|
|
226
|
+
const deadlineAt = Date.now() + 10 * 60 * 1000;
|
|
227
|
+
let sessionToken = "";
|
|
228
|
+
while (Date.now() < deadlineAt) {
|
|
229
|
+
await sleep(1_500, runtime.signal);
|
|
230
|
+
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);
|
|
231
|
+
if (!poll.ok)
|
|
232
|
+
return failure(`Could not check sign-in (${poll.status}).`, 1, "server");
|
|
233
|
+
const result = (await poll.json());
|
|
234
|
+
if (result.status === "approved" && typeof result.token === "string") {
|
|
235
|
+
sessionToken = result.token;
|
|
236
|
+
break;
|
|
237
|
+
}
|
|
238
|
+
if (result.status === "denied" || result.status === "expired")
|
|
239
|
+
return failure(`Sign-in ${result.status}.`, 2, "auth");
|
|
240
|
+
}
|
|
241
|
+
if (!sessionToken)
|
|
242
|
+
return failure("Timed out waiting for sign-in approval.", 2, "auth");
|
|
243
|
+
const credential = await timedFetch(`${cloud}/api/my/bridge-credential`, {
|
|
244
|
+
method: "POST",
|
|
245
|
+
headers: { "content-type": "application/json", authorization: `Bearer ${sessionToken}` },
|
|
246
|
+
body: JSON.stringify({ client, target: "workspace", surface: "cli" })
|
|
247
|
+
}, timeoutMs(args), runtime.signal);
|
|
248
|
+
if (!credential.ok) {
|
|
249
|
+
const message = await safeApiError(credential, "Could not create a CLI credential.");
|
|
250
|
+
return failure(message, credential.status === 401 || credential.status === 403 ? 2 : 1, "auth");
|
|
251
|
+
}
|
|
252
|
+
const body = (await credential.json());
|
|
253
|
+
if (typeof body.refreshToken !== "string" || typeof body.endpoint !== "string") {
|
|
254
|
+
return failure("Passport returned an invalid credential response.", 1, "invalid_server_response");
|
|
255
|
+
}
|
|
256
|
+
const credentialEndpoint = endpoint(body.endpoint);
|
|
257
|
+
const tokenWorkspace = workspace ? "" : (await import("./bridge.js")).workspaceOfToken(body.refreshToken);
|
|
258
|
+
const profile = profileName(requestedProfile || `cli@${workspace || tokenWorkspace || "workspace"}`);
|
|
259
|
+
await withProfileLock(profile, async () => writeProfile(profile, { refreshToken: body.refreshToken, endpoint: credentialEndpoint }));
|
|
260
|
+
return {
|
|
261
|
+
json: { profile, endpoint: credentialEndpoint, client, surface: "cli" },
|
|
262
|
+
human: `Signed in as profile "${profile}".\nCredential saved to ${credsPath()}.`
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
async function logout(args, runtime) {
|
|
266
|
+
if (runtime.env.PASSPORT_AGENT_KEY || runtime.env.PASSPORT_ENDPOINT) {
|
|
267
|
+
return failure("Agent-key authentication is not stored locally and cannot be logged out. Unset the environment variables instead.", 6, "usage");
|
|
268
|
+
}
|
|
269
|
+
const auth = resolveAuth(args, runtime.env);
|
|
270
|
+
if (auth.kind !== "profile")
|
|
271
|
+
return failure("No local profile is active.", 2, "auth");
|
|
272
|
+
const existing = await withProfileLock(auth.profile, async () => removeProfile(auth.profile));
|
|
273
|
+
let revoked = false;
|
|
274
|
+
let warning = "";
|
|
275
|
+
if (existing) {
|
|
276
|
+
try {
|
|
277
|
+
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);
|
|
278
|
+
revoked = response.ok;
|
|
279
|
+
if (!response.ok)
|
|
280
|
+
warning = `Warning: the server could not revoke the credential (${response.status}); the local profile was removed.`;
|
|
281
|
+
}
|
|
282
|
+
catch {
|
|
283
|
+
warning = "Warning: the server could not be reached; the local profile was removed.";
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
if (warning && !bool(args, "quiet"))
|
|
287
|
+
runtime.stderr.write(`${warning}\n`);
|
|
288
|
+
return { json: { profile: auth.profile, removed: true, revoked }, human: `Signed out profile "${auth.profile}".` };
|
|
289
|
+
}
|
|
290
|
+
function managePayload(result) {
|
|
291
|
+
requireSuccess(result);
|
|
292
|
+
const payload = payloadOf(result, "connection");
|
|
293
|
+
if (!payload.workspace ||
|
|
294
|
+
typeof payload.workspace !== "object" ||
|
|
295
|
+
!payload.member ||
|
|
296
|
+
typeof payload.member !== "object" ||
|
|
297
|
+
typeof payload.client !== "string" ||
|
|
298
|
+
payload.surface !== "cli" ||
|
|
299
|
+
typeof payload.auth !== "string" ||
|
|
300
|
+
!Array.isArray(payload.connections)) {
|
|
301
|
+
return failure(SERVER_TOO_OLD, 1, "server_too_old");
|
|
302
|
+
}
|
|
303
|
+
return payload;
|
|
304
|
+
}
|
|
305
|
+
async function status(args, runtime) {
|
|
306
|
+
return withGateway(args, runtime, async (gateway, auth) => {
|
|
307
|
+
const managed = managePayload(await gateway.callTool("passport_manage_connections", { includeLinks: false }));
|
|
308
|
+
const mcps = managed.connections.map((row) => ({
|
|
309
|
+
app: String(row.app ?? ""),
|
|
310
|
+
name: String(row.name ?? row.app ?? ""),
|
|
311
|
+
status: String(row.status ?? "unknown"),
|
|
312
|
+
toolCount: Number(row.toolCount ?? 0)
|
|
313
|
+
}));
|
|
314
|
+
const data = {
|
|
315
|
+
workspace: { id: String(managed.workspace.id), name: String(managed.workspace.name) },
|
|
316
|
+
member: { id: String(managed.member.id), email: String(managed.member.email) },
|
|
317
|
+
endpoint: auth.endpoint,
|
|
318
|
+
auth: managed.auth,
|
|
319
|
+
...(auth.kind === "profile" ? { profile: auth.profile } : {}),
|
|
320
|
+
client: managed.client,
|
|
321
|
+
mcps
|
|
322
|
+
};
|
|
323
|
+
const lines = [
|
|
324
|
+
`${data.workspace.name} (${data.workspace.id})`,
|
|
325
|
+
`${data.member.email} (${data.member.id})`,
|
|
326
|
+
`Endpoint: ${data.endpoint}`,
|
|
327
|
+
...(auth.kind === "profile" ? [`Profile: ${auth.profile}`] : []),
|
|
328
|
+
`Client: ${managed.client} · Surface: ${managed.surface} · Auth: ${managed.auth}`,
|
|
329
|
+
...(mcps.length ? mcps.map((mcp) => `${mcp.name} (${mcp.app}): ${mcp.status} · ${mcp.toolCount} permitted tool${mcp.toolCount === 1 ? "" : "s"}`) : ["No visible MCPs."])
|
|
330
|
+
];
|
|
331
|
+
return { json: data, human: lines.join("\n") };
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
async function doctor(args, runtime) {
|
|
335
|
+
const { formatDoctorReport, runDoctor } = await import("./doctor.js");
|
|
336
|
+
const report = await runDoctor({
|
|
337
|
+
version: VERSION,
|
|
338
|
+
profile: value(args, "profile"),
|
|
339
|
+
env: runtime.env,
|
|
340
|
+
timeoutMs: timeoutMs(args),
|
|
341
|
+
signal: runtime.signal,
|
|
342
|
+
caller: callerFrom(args, runtime.env),
|
|
343
|
+
normalizeEndpoint: endpoint,
|
|
344
|
+
redactError: sanitize
|
|
345
|
+
});
|
|
346
|
+
return {
|
|
347
|
+
json: report,
|
|
348
|
+
human: formatDoctorReport(report),
|
|
349
|
+
essential: true,
|
|
350
|
+
exitCode: report.ok ? 0 : 1
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
async function search(args, runtime) {
|
|
354
|
+
const query = args.positionals.join(" ").trim();
|
|
355
|
+
if (value(args, "app") !== undefined && !value(args, "app").trim())
|
|
356
|
+
return failure("--app cannot be empty.", 6, "usage");
|
|
357
|
+
return withGateway(args, runtime, async (gateway) => {
|
|
358
|
+
const result = requireSuccess(await gateway.callTool("passport_search_tools", { ...(query ? { query } : {}), ...(value(args, "app") ? { app: value(args, "app") } : {}) }));
|
|
359
|
+
const payload = payloadOf(result, "search");
|
|
360
|
+
const lines = [];
|
|
361
|
+
if (query) {
|
|
362
|
+
const results = Array.isArray(payload.results) ? payload.results : [];
|
|
363
|
+
for (const hit of results) {
|
|
364
|
+
lines.push(`${String(hit.tool ?? "")} · ${hit.readonly ? "read-only" : "write-capable"} · ${firstSentence(String(hit.description ?? ""))}`);
|
|
365
|
+
}
|
|
366
|
+
if (!results.length)
|
|
367
|
+
lines.push("No matching tools.");
|
|
368
|
+
}
|
|
369
|
+
else {
|
|
370
|
+
const catalog = Array.isArray(payload.catalog) ? payload.catalog : [];
|
|
371
|
+
for (const group of catalog) {
|
|
372
|
+
const tools = Array.isArray(group.tools) ? group.tools.map(String) : [];
|
|
373
|
+
lines.push(`${String(group.app ?? group.key ?? "MCP")} (${tools.length}, ${String(group.access ?? "access")}):`);
|
|
374
|
+
lines.push(...tools.map((tool) => ` ${tool}`));
|
|
375
|
+
}
|
|
376
|
+
if (!catalog.length)
|
|
377
|
+
lines.push("No permitted tools.");
|
|
378
|
+
}
|
|
379
|
+
if (typeof payload.note === "string")
|
|
380
|
+
lines.push(payload.note);
|
|
381
|
+
return { json: payload, human: lines.join("\n") };
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
async function describe(args, runtime) {
|
|
385
|
+
const name = args.positionals[0];
|
|
386
|
+
return withGateway(args, runtime, async (gateway) => {
|
|
387
|
+
const result = requireSuccess(await gateway.callTool("passport_search_tools", { query: name, limit: 25 }));
|
|
388
|
+
const payload = payloadOf(result, "search");
|
|
389
|
+
const results = Array.isArray(payload.results) ? payload.results : [];
|
|
390
|
+
const exact = results.find((hit) => hit.tool === name);
|
|
391
|
+
if (!exact) {
|
|
392
|
+
const suggestions = results.slice(0, 5).map((hit) => String(hit.tool ?? "")).filter(Boolean);
|
|
393
|
+
const suffix = suggestions.length ? ` Near matches: ${suggestions.join(", ")}.` : "";
|
|
394
|
+
return failure(`Unknown tool "${name}".${suffix}`, 6, "unknown_tool");
|
|
395
|
+
}
|
|
396
|
+
const schema = exact.parameters ?? {};
|
|
397
|
+
const human = [
|
|
398
|
+
String(exact.tool),
|
|
399
|
+
`${exact.readonly ? "Read-only" : "Write-capable"}`,
|
|
400
|
+
String(exact.description ?? ""),
|
|
401
|
+
"Parameters:",
|
|
402
|
+
JSON.stringify(schema, null, 2)
|
|
403
|
+
].join("\n");
|
|
404
|
+
return { json: exact, human };
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
async function run(args, runtime) {
|
|
408
|
+
const tool = args.positionals[0];
|
|
409
|
+
const toolArgs = runArguments(args);
|
|
410
|
+
const waitSeconds = value(args, "wait") ? Number(value(args, "wait")) : 0;
|
|
411
|
+
return withGateway(args, runtime, async (gateway) => {
|
|
412
|
+
const deadlineAt = waitSeconds ? Date.now() + waitSeconds * 1000 : 0;
|
|
413
|
+
let result = await gateway.callTool("passport_call", { tool, args: toolArgs });
|
|
414
|
+
for (;;) {
|
|
415
|
+
const refusal = refusalOf(result);
|
|
416
|
+
if (!refusal)
|
|
417
|
+
break;
|
|
418
|
+
if (refusal.cause !== "approval_pending" || !waitSeconds)
|
|
419
|
+
throw refusal;
|
|
420
|
+
const remaining = deadlineAt - Date.now();
|
|
421
|
+
if (remaining <= 0)
|
|
422
|
+
throw refusal;
|
|
423
|
+
await sleep(Math.min(APPROVAL_RETRY_MS, remaining), runtime.signal);
|
|
424
|
+
if (Date.now() >= deadlineAt)
|
|
425
|
+
throw refusal;
|
|
426
|
+
// Only a definite structured approval_pending reaches this retry. Any
|
|
427
|
+
// thrown timeout/network error leaves immediately because outcome is unknown.
|
|
428
|
+
result = await gateway.callTool("passport_call", { tool, args: toolArgs });
|
|
429
|
+
}
|
|
430
|
+
if (hasNonText(result) && !bool(args, "json")) {
|
|
431
|
+
return failure("The tool returned non-text content, which human mode cannot display. Use --json for calls that may return media or resources.", 1, "non_text_content");
|
|
432
|
+
}
|
|
433
|
+
return { json: result, human: firstText(result), essential: true, raw: true };
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
function runArguments(args) {
|
|
437
|
+
const positional = args.positionals[1];
|
|
438
|
+
const fromStdin = value(args, "args");
|
|
439
|
+
const sets = repeated(args, "set");
|
|
440
|
+
const jsonSets = repeated(args, "set-json");
|
|
441
|
+
if (fromStdin !== undefined && fromStdin !== "-")
|
|
442
|
+
return failure("--args only accepts '-' to read a JSON object from stdin.", 6, "usage");
|
|
443
|
+
const forms = Number(positional !== undefined) + Number(fromStdin !== undefined) + Number(sets.length + jsonSets.length > 0);
|
|
444
|
+
if (forms > 1)
|
|
445
|
+
return failure("Use one argument form: positional JSON, --args -, or --set/--set-json.", 6, "usage");
|
|
446
|
+
if (positional !== undefined)
|
|
447
|
+
return jsonObject(positional, "tool arguments");
|
|
448
|
+
if (fromStdin !== undefined)
|
|
449
|
+
return jsonObject(readFileSync(0, "utf8"), "stdin");
|
|
450
|
+
const out = Object.create(null);
|
|
451
|
+
const seen = new Set();
|
|
452
|
+
for (const raw of sets)
|
|
453
|
+
assign(raw, false, out, seen);
|
|
454
|
+
for (const raw of jsonSets)
|
|
455
|
+
assign(raw, true, out, seen);
|
|
456
|
+
return out;
|
|
457
|
+
}
|
|
458
|
+
function assign(raw, parseJson, out, seen) {
|
|
459
|
+
const equals = raw.indexOf("=");
|
|
460
|
+
if (equals <= 0)
|
|
461
|
+
return failure(`${parseJson ? "--set-json" : "--set"} expects key=value.`, 6, "usage");
|
|
462
|
+
const key = raw.slice(0, equals).trim();
|
|
463
|
+
if (!key || key === "__proto__" || key === "prototype" || key === "constructor")
|
|
464
|
+
return failure(`Invalid argument key: ${key || "<empty>"}.`, 6, "usage");
|
|
465
|
+
if (seen.has(key))
|
|
466
|
+
return failure(`Argument "${key}" was provided more than once.`, 6, "usage");
|
|
467
|
+
seen.add(key);
|
|
468
|
+
const rawValue = raw.slice(equals + 1);
|
|
469
|
+
if (!parseJson)
|
|
470
|
+
out[key] = rawValue;
|
|
471
|
+
else {
|
|
472
|
+
try {
|
|
473
|
+
out[key] = JSON.parse(rawValue);
|
|
474
|
+
}
|
|
475
|
+
catch {
|
|
476
|
+
return failure(`--set-json ${key} contains invalid JSON.`, 6, "usage");
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
function jsonObject(raw, label) {
|
|
481
|
+
try {
|
|
482
|
+
const parsed = JSON.parse(raw);
|
|
483
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
484
|
+
throw new Error();
|
|
485
|
+
return parsed;
|
|
486
|
+
}
|
|
487
|
+
catch {
|
|
488
|
+
return failure(`${label} must be a valid JSON object.`, 6, "usage");
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
async function connect(args, runtime) {
|
|
492
|
+
const alias = value(args, "alias");
|
|
493
|
+
if (alias !== undefined && !/^[A-Za-z0-9 -]{1,32}$/.test(alias.trim()))
|
|
494
|
+
return failure("--alias must contain 1-32 letters, numbers, spaces, or hyphens.", 6, "usage");
|
|
495
|
+
const requested = args.positionals;
|
|
496
|
+
return withGateway(args, runtime, async (gateway) => {
|
|
497
|
+
let managed = managePayload(await gateway.callTool("passport_manage_connections", {
|
|
498
|
+
...(alias !== undefined ? { alias: alias.trim() } : {}),
|
|
499
|
+
...(requested.length ? { apps: requested } : {})
|
|
500
|
+
}));
|
|
501
|
+
const rows = requested.length ? requested.map((app) => findConnection(managed.connections, app)) : managed.connections;
|
|
502
|
+
const human = connectionLines(managed, rows, requested.length > 0);
|
|
503
|
+
const urls = connectionUrls(managed, rows, requested.length > 0);
|
|
504
|
+
if (bool(args, "open")) {
|
|
505
|
+
if (urls.length > 1)
|
|
506
|
+
return failure("--open requires a single connect URL. Name one MCP, or use the aggregate connect flow.", 6, "usage");
|
|
507
|
+
if (urls[0])
|
|
508
|
+
openUrl(urls[0]);
|
|
509
|
+
}
|
|
510
|
+
const waitSeconds = value(args, "wait") ? Number(value(args, "wait")) : 0;
|
|
511
|
+
if (!waitSeconds)
|
|
512
|
+
return { json: managed, human: human.join("\n") };
|
|
513
|
+
const targets = requested.length
|
|
514
|
+
? rows.filter((row) => row.status === "needs_your_signin").map((row) => String(row.app))
|
|
515
|
+
: rows.filter((row) => row.status === "needs_your_signin").map((row) => String(row.app));
|
|
516
|
+
if (!targets.length)
|
|
517
|
+
return { json: managed, human: human.join("\n") };
|
|
518
|
+
if (!bool(args, "json") && (!bool(args, "quiet") || !bool(args, "open")))
|
|
519
|
+
runtime.stdout.write(`${human.join("\n")}\n`);
|
|
520
|
+
const waitResult = await waitForConnections(gateway, targets, waitSeconds, runtime.signal);
|
|
521
|
+
if (!waitResult.connected) {
|
|
522
|
+
const note = typeof waitResult.note === "string" ? waitResult.note : "Timed out waiting for the MCP connection.";
|
|
523
|
+
return failure(note, 1, "connection_timeout", { app: targets.length === 1 ? targets[0] : undefined });
|
|
524
|
+
}
|
|
525
|
+
managed = managePayload(await gateway.callTool("passport_manage_connections", { includeLinks: false }));
|
|
526
|
+
return { json: managed, human: typeof waitResult.note === "string" ? waitResult.note : "Connection ready." };
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
function findConnection(rows, requested) {
|
|
530
|
+
const needle = requested.trim().toLowerCase();
|
|
531
|
+
const row = rows.find((entry) => String(entry.app ?? "").toLowerCase() === needle || String(entry.name ?? "").toLowerCase() === needle);
|
|
532
|
+
if (!row)
|
|
533
|
+
return failure(`Unknown MCP "${requested}". Run passport status to see visible MCPs.`, 6, "unknown_app", { app: requested });
|
|
534
|
+
return row;
|
|
535
|
+
}
|
|
536
|
+
function connectionUrls(managed, rows, explicitlyNamed) {
|
|
537
|
+
const needSignin = rows.filter((row) => row.status === "needs_your_signin");
|
|
538
|
+
if (!explicitlyNamed && needSignin.length >= 2 && managed.connectAllUrl)
|
|
539
|
+
return [managed.connectAllUrl];
|
|
540
|
+
return needSignin.map((row) => row.connectUrl).filter((url) => typeof url === "string");
|
|
541
|
+
}
|
|
542
|
+
function connectionLines(managed, rows, explicitlyNamed) {
|
|
543
|
+
const urls = connectionUrls(managed, rows, explicitlyNamed);
|
|
544
|
+
if (!explicitlyNamed && urls.length === 1 && rows.filter((row) => row.status === "needs_your_signin").length >= 2) {
|
|
545
|
+
return [`Connect your MCPs: ${urls[0]}`];
|
|
546
|
+
}
|
|
547
|
+
const lines = [];
|
|
548
|
+
for (const row of rows) {
|
|
549
|
+
const name = String(row.name ?? row.app ?? "MCP");
|
|
550
|
+
if (row.status === "needs_your_signin" && typeof row.connectUrl === "string")
|
|
551
|
+
lines.push(`${name}: ${row.connectUrl}`);
|
|
552
|
+
else if (row.status === "connected" || row.status === "org_managed")
|
|
553
|
+
lines.push(`${name}: already connected`);
|
|
554
|
+
else if (typeof row.action === "string")
|
|
555
|
+
lines.push(`${name}: ${row.action}`);
|
|
556
|
+
else
|
|
557
|
+
lines.push(`${name}: ${String(row.status ?? "unknown")}`);
|
|
558
|
+
}
|
|
559
|
+
if (!lines.length || (!explicitlyNamed && !rows.some((row) => row.status === "needs_your_signin")))
|
|
560
|
+
lines.push(managed.note || "Nothing needs connecting.");
|
|
561
|
+
return lines;
|
|
562
|
+
}
|
|
563
|
+
async function waitForConnections(gateway, apps, seconds, signal) {
|
|
564
|
+
const deadlineAt = Date.now() + seconds * 1000;
|
|
565
|
+
let latest = { connected: false };
|
|
566
|
+
do {
|
|
567
|
+
const remaining = Math.max(1, Math.ceil((deadlineAt - Date.now()) / 1000));
|
|
568
|
+
const chunk = Math.min(120, remaining);
|
|
569
|
+
const result = requireSuccess(await gateway.callTool("passport_wait_for_connection", apps.length === 1 ? { app: apps[0], timeoutSeconds: chunk } : { apps, timeoutSeconds: chunk }, (chunk + 5) * 1000));
|
|
570
|
+
const text = firstText(result);
|
|
571
|
+
try {
|
|
572
|
+
latest = JSON.parse(text);
|
|
573
|
+
}
|
|
574
|
+
catch {
|
|
575
|
+
return failure("Passport returned an invalid connection wait payload.", 1, "invalid_server_response");
|
|
576
|
+
}
|
|
577
|
+
if (latest.connected === true || latest.status === "connected")
|
|
578
|
+
return { ...latest, connected: true };
|
|
579
|
+
if (latest.status === "needs_setup")
|
|
580
|
+
return { ...latest, connected: false };
|
|
581
|
+
if (Date.now() < deadlineAt)
|
|
582
|
+
await sleep(Math.min(250, deadlineAt - Date.now()), signal);
|
|
583
|
+
} while (Date.now() < deadlineAt);
|
|
584
|
+
return { ...latest, connected: false };
|
|
585
|
+
}
|
|
586
|
+
async function resources(args, runtime) {
|
|
587
|
+
if (value(args, "out") !== undefined && !value(args, "out"))
|
|
588
|
+
return failure("--out cannot be empty.", 6, "usage");
|
|
589
|
+
return withGateway(args, runtime, async (gateway) => {
|
|
590
|
+
const uri = args.positionals[0];
|
|
591
|
+
if (!uri) {
|
|
592
|
+
const listed = await gateway.listResources();
|
|
593
|
+
const human = listed.resources.length
|
|
594
|
+
? listed.resources.map((resource) => `${resource.uri} · ${resource.name}${resource.mimeType ? ` · ${resource.mimeType}` : ""}`).join("\n")
|
|
595
|
+
: "No resources are available.";
|
|
596
|
+
return { json: listed, human };
|
|
597
|
+
}
|
|
598
|
+
const read = await gateway.readResource(uri);
|
|
599
|
+
const out = value(args, "out");
|
|
600
|
+
if (out) {
|
|
601
|
+
const bytes = resourceBytes(read.contents);
|
|
602
|
+
writeFileSync(out, bytes);
|
|
603
|
+
return { json: { uri, out, bytes: bytes.byteLength }, human: `Wrote ${bytes.byteLength} bytes to ${out}.` };
|
|
604
|
+
}
|
|
605
|
+
if (bool(args, "json"))
|
|
606
|
+
return { json: read };
|
|
607
|
+
if (read.contents.some((content) => "blob" in content)) {
|
|
608
|
+
return failure("The resource is binary. Use --out <file> or --json.", 1, "non_text_content");
|
|
609
|
+
}
|
|
610
|
+
return { json: read, human: read.contents.map((content) => ("text" in content ? content.text : "")).join(""), essential: true, raw: true };
|
|
611
|
+
});
|
|
612
|
+
}
|
|
613
|
+
function resourceBytes(contents) {
|
|
614
|
+
if (!contents.length)
|
|
615
|
+
return Buffer.alloc(0);
|
|
616
|
+
if (contents.every((content) => "text" in content))
|
|
617
|
+
return Buffer.from(contents.map((content) => ("text" in content ? content.text : "")).join(""));
|
|
618
|
+
if (contents.length === 1 && "blob" in contents[0])
|
|
619
|
+
return Buffer.from(contents[0].blob, "base64");
|
|
620
|
+
return failure("A multi-part binary resource cannot be written to one file. Use --json.", 6, "usage");
|
|
621
|
+
}
|
|
622
|
+
async function prompts(args, runtime) {
|
|
623
|
+
if (value(args, "out") !== undefined && !value(args, "out"))
|
|
624
|
+
return failure("--out cannot be empty.", 6, "usage");
|
|
625
|
+
return withGateway(args, runtime, async (gateway) => {
|
|
626
|
+
const name = args.positionals[0];
|
|
627
|
+
if (!name) {
|
|
628
|
+
const listed = await gateway.listPrompts();
|
|
629
|
+
const human = listed.prompts.length
|
|
630
|
+
? listed.prompts
|
|
631
|
+
.map((prompt) => {
|
|
632
|
+
const names = prompt.arguments?.map((argument) => `${argument.name}${argument.required ? "*" : ""}`).join(", ");
|
|
633
|
+
return `${prompt.name}${names ? ` (${names})` : ""}${prompt.description ? ` · ${prompt.description}` : ""}`;
|
|
634
|
+
})
|
|
635
|
+
.join("\n")
|
|
636
|
+
: "No prompts are available.";
|
|
637
|
+
return { json: listed, human };
|
|
638
|
+
}
|
|
639
|
+
const promptArgs = Object.create(null);
|
|
640
|
+
const seen = new Set();
|
|
641
|
+
for (const raw of repeated(args, "set"))
|
|
642
|
+
assignPrompt(raw, promptArgs, seen);
|
|
643
|
+
const result = await gateway.getPrompt(name, promptArgs);
|
|
644
|
+
const out = value(args, "out");
|
|
645
|
+
if (out) {
|
|
646
|
+
const bytes = promptBytes(result.messages);
|
|
647
|
+
writeFileSync(out, bytes);
|
|
648
|
+
return { json: { name, out, bytes: bytes.byteLength }, human: `Wrote ${bytes.byteLength} bytes to ${out}.` };
|
|
649
|
+
}
|
|
650
|
+
if (bool(args, "json"))
|
|
651
|
+
return { json: result };
|
|
652
|
+
const contents = result.messages.map((message) => message.content);
|
|
653
|
+
if (contents.some((content) => content.type !== "text"))
|
|
654
|
+
return failure("The prompt contains non-text content. Use --out <file> or --json.", 1, "non_text_content");
|
|
655
|
+
return {
|
|
656
|
+
json: result,
|
|
657
|
+
human: contents.map((content) => (content.type === "text" ? content.text : "")).join(""),
|
|
658
|
+
essential: true,
|
|
659
|
+
raw: true
|
|
660
|
+
};
|
|
661
|
+
});
|
|
662
|
+
}
|
|
663
|
+
function assignPrompt(raw, out, seen) {
|
|
664
|
+
const equals = raw.indexOf("=");
|
|
665
|
+
if (equals <= 0)
|
|
666
|
+
return failure("--set expects key=value.", 6, "usage");
|
|
667
|
+
const key = raw.slice(0, equals).trim();
|
|
668
|
+
if (!key || key === "__proto__" || key === "prototype" || key === "constructor" || seen.has(key)) {
|
|
669
|
+
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");
|
|
670
|
+
}
|
|
671
|
+
seen.add(key);
|
|
672
|
+
out[key] = raw.slice(equals + 1);
|
|
673
|
+
}
|
|
674
|
+
function promptBytes(messages) {
|
|
675
|
+
const contents = messages.map((message) => message.content);
|
|
676
|
+
if (contents.every((content) => content.type === "text"))
|
|
677
|
+
return Buffer.from(contents.map((content) => content.text ?? "").join(""));
|
|
678
|
+
if (contents.length === 1 && (contents[0].type === "image" || contents[0].type === "audio") && contents[0].data) {
|
|
679
|
+
return Buffer.from(contents[0].data, "base64");
|
|
680
|
+
}
|
|
681
|
+
return failure("A multi-part binary prompt cannot be written to one file. Use --json.", 6, "usage");
|
|
682
|
+
}
|
|
683
|
+
function help(args) {
|
|
684
|
+
const verb = args.positionals[0];
|
|
685
|
+
const text = helpText(verb);
|
|
686
|
+
return { json: { command: verb ?? null, help: text }, human: text, essential: true };
|
|
687
|
+
}
|
|
688
|
+
function completion(args) {
|
|
689
|
+
const shell = args.positionals[0];
|
|
690
|
+
if (shell !== "bash" && shell !== "zsh" && shell !== "fish") {
|
|
691
|
+
return failure("completion requires bash, zsh, or fish.", 6, "usage");
|
|
692
|
+
}
|
|
693
|
+
const script = completionScript(shell);
|
|
694
|
+
return { json: { shell, script }, human: script, essential: true, raw: true };
|
|
695
|
+
}
|
|
696
|
+
function version(args, env) {
|
|
697
|
+
let profile;
|
|
698
|
+
let resolvedEndpoint;
|
|
699
|
+
if (env.PASSPORT_AGENT_KEY && env.PASSPORT_ENDPOINT && value(args, "profile") !== undefined) {
|
|
700
|
+
return failure("--profile cannot be used with PASSPORT_AGENT_KEY.", 6, "usage");
|
|
701
|
+
}
|
|
702
|
+
if (env.PASSPORT_AGENT_KEY && env.PASSPORT_ENDPOINT) {
|
|
703
|
+
resolvedEndpoint = endpoint(env.PASSPORT_ENDPOINT);
|
|
704
|
+
}
|
|
705
|
+
else {
|
|
706
|
+
const creds = readCreds();
|
|
707
|
+
const names = Object.keys(creds);
|
|
708
|
+
const explicitProfile = value(args, "profile");
|
|
709
|
+
const candidate = explicitProfile !== undefined ? profileName(explicitProfile) : env.PASSPORT_PROFILE ? profileName(env.PASSPORT_PROFILE) : names.length === 1 ? profileName(names[0]) : "";
|
|
710
|
+
if (candidate && creds[candidate]) {
|
|
711
|
+
profile = candidate;
|
|
712
|
+
resolvedEndpoint = endpoint(creds[candidate].endpoint);
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
const data = { version: VERSION, ...(resolvedEndpoint ? { endpoint: resolvedEndpoint } : {}), ...(profile ? { profile } : {}) };
|
|
716
|
+
return {
|
|
717
|
+
json: data,
|
|
718
|
+
human: [`passport ${VERSION}`, ...(resolvedEndpoint ? [`Endpoint: ${resolvedEndpoint}`] : []), ...(profile ? [`Profile: ${profile}`] : [])].join("\n"),
|
|
719
|
+
essential: true
|
|
720
|
+
};
|
|
721
|
+
}
|
|
722
|
+
async function dispatch(args, runtime) {
|
|
723
|
+
switch (args.command) {
|
|
724
|
+
case "login":
|
|
725
|
+
return login(args, runtime);
|
|
726
|
+
case "logout":
|
|
727
|
+
return logout(args, runtime);
|
|
728
|
+
case "status":
|
|
729
|
+
return status(args, runtime);
|
|
730
|
+
case "doctor":
|
|
731
|
+
return doctor(args, runtime);
|
|
732
|
+
case "search":
|
|
733
|
+
return search(args, runtime);
|
|
734
|
+
case "describe":
|
|
735
|
+
return describe(args, runtime);
|
|
736
|
+
case "run":
|
|
737
|
+
return run(args, runtime);
|
|
738
|
+
case "connect":
|
|
739
|
+
return connect(args, runtime);
|
|
740
|
+
case "resources":
|
|
741
|
+
return resources(args, runtime);
|
|
742
|
+
case "prompts":
|
|
743
|
+
return prompts(args, runtime);
|
|
744
|
+
case "completion":
|
|
745
|
+
return completion(args);
|
|
746
|
+
case "help":
|
|
747
|
+
return help(args);
|
|
748
|
+
case "version":
|
|
749
|
+
return version(args, runtime.env);
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
function helpText(verb) {
|
|
753
|
+
const details = {
|
|
754
|
+
login: "passport login --cloud <origin> [--workspace <id>] [--client <id>] [--profile <name>]\nStarts device sign-in and stores a cli-surface rotating credential.",
|
|
755
|
+
logout: "passport logout [--profile <name>]\nRevokes the rotating credential and always removes the local profile.",
|
|
756
|
+
status: "passport status\nJSON: {workspace,member,endpoint,auth,profile?,client,mcps:[{app,name,status,toolCount}]}",
|
|
757
|
+
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}.",
|
|
758
|
+
search: "passport search [query...] [--app <key>]\nEmpty query lists the complete permitted catalog. JSON is the server search payload.",
|
|
759
|
+
describe: "passport describe <tool>\nShows the exact tool definition and complete parameter schema.",
|
|
760
|
+
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.",
|
|
761
|
+
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.",
|
|
762
|
+
resources: "passport resources [uri] [--out <file>]\nLists or reads workspace MCP resources. Binary content requires --out or --json.",
|
|
763
|
+
prompts: "passport prompts [name] [--set key=value] [--out <file>]\nLists or gets workspace MCP prompts. Binary content requires --out or --json.",
|
|
764
|
+
completion: "passport completion <bash|zsh|fish>\nPrints an offline shell-completion script to stdout.",
|
|
765
|
+
help: "passport help [verb]",
|
|
766
|
+
version: "passport version\nWorks without a profile or network."
|
|
767
|
+
};
|
|
768
|
+
if (verb && details[verb])
|
|
769
|
+
return `${details[verb]}\n\nGlobal: --profile <name> --json --timeout <sec> --quiet --caller <id>`;
|
|
770
|
+
return `Passport CLI ${VERSION}
|
|
771
|
+
|
|
772
|
+
Usage: passport <command> [options]
|
|
773
|
+
|
|
774
|
+
login Sign in with the device flow
|
|
775
|
+
logout Revoke and remove a profile
|
|
776
|
+
status Show identity and visible MCP connection state
|
|
777
|
+
doctor Diagnose local setup and server compatibility
|
|
778
|
+
search Find permitted tools or list the catalog
|
|
779
|
+
describe Show one exact tool definition
|
|
780
|
+
run Run a governed tool
|
|
781
|
+
connect Connect member MCP accounts
|
|
782
|
+
resources List or read MCP resources
|
|
783
|
+
prompts List or get MCP prompts
|
|
784
|
+
completion Generate bash, zsh, or fish completion
|
|
785
|
+
help Show command help
|
|
786
|
+
version Show CLI version and local context
|
|
787
|
+
|
|
788
|
+
Global: --profile <name> --json --timeout <sec> --quiet --caller <id>
|
|
789
|
+
|
|
790
|
+
Exit codes: 0 success · 1 network/server · 2 auth · 3 needs-connect · 4 approval-pending · 5 policy/guardrail/selection/approval-denial · 6 usage/unknown
|
|
791
|
+
With --json, stdout is exactly one JSON value. Hints and warnings use stderr.`;
|
|
792
|
+
}
|
|
793
|
+
function emit(result, args, runtime) {
|
|
794
|
+
if (bool(args, "json")) {
|
|
795
|
+
runtime.stdout.write(`${JSON.stringify(result.json)}\n`);
|
|
796
|
+
return;
|
|
797
|
+
}
|
|
798
|
+
if (result.human === undefined || (bool(args, "quiet") && !result.essential))
|
|
799
|
+
return;
|
|
800
|
+
if (Buffer.isBuffer(result.human))
|
|
801
|
+
runtime.stdout.write(result.human);
|
|
802
|
+
else
|
|
803
|
+
runtime.stdout.write(result.raw ? result.human : `${result.human}${result.human.endsWith("\n") ? "" : "\n"}`);
|
|
804
|
+
}
|
|
805
|
+
function asFailure(error) {
|
|
806
|
+
if (error instanceof CliFailure)
|
|
807
|
+
return error;
|
|
808
|
+
if (error instanceof ArgError)
|
|
809
|
+
return new CliFailure(error.message, 6, "usage");
|
|
810
|
+
const raw = error instanceof Error ? error.message : String(error);
|
|
811
|
+
const message = sanitize(raw);
|
|
812
|
+
if (message === SERVER_TOO_OLD || message.includes("CLI-compatible server"))
|
|
813
|
+
return new CliFailure(SERVER_TOO_OLD, 1, "server_too_old");
|
|
814
|
+
if (/token exchange failed|invalid_or_revoked|unauthori[sz]ed|\b401\b/i.test(message)) {
|
|
815
|
+
return new CliFailure("Passport authentication expired or was revoked.", 2, "auth", { hint: "Run: passport login" });
|
|
816
|
+
}
|
|
817
|
+
if (/timeout|timed out|aborted|aborterror|requesttimeout/i.test(message))
|
|
818
|
+
return new CliFailure("The Passport request timed out; it was not retried.", 1, "timeout");
|
|
819
|
+
return new CliFailure(message || "Passport request failed.", 1, "network_or_server");
|
|
820
|
+
}
|
|
821
|
+
export function sanitize(message) {
|
|
822
|
+
// Bound work before applying redactors: SDK/network errors can contain a
|
|
823
|
+
// surprisingly large serialized cause. The final user-facing error is 500
|
|
824
|
+
// chars, so scanning a small prefix is sufficient and avoids regex work over
|
|
825
|
+
// an attacker-sized payload.
|
|
826
|
+
return message
|
|
827
|
+
.slice(0, 2_000)
|
|
828
|
+
.replace(/Bearer\s+\S+/gi, "Bearer [redacted]")
|
|
829
|
+
.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]\"")
|
|
830
|
+
.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]")
|
|
831
|
+
.replace(/\b(?:[A-Za-z0-9_-]+~)?(?:pak|ppr|ppa|pp)_[A-Za-z0-9_-]{12,}\b/g, "[redacted]")
|
|
832
|
+
.slice(0, 500);
|
|
833
|
+
}
|
|
834
|
+
function emitFailure(error, json, quiet, runtime) {
|
|
835
|
+
if (json) {
|
|
836
|
+
runtime.stdout.write(`${JSON.stringify({
|
|
837
|
+
error: error.message,
|
|
838
|
+
cause: error.cause,
|
|
839
|
+
exitCode: error.exitCode,
|
|
840
|
+
...(error.details.approvalId ? { approvalId: error.details.approvalId } : {}),
|
|
841
|
+
...(error.details.app ? { app: error.details.app } : {})
|
|
842
|
+
})}\n`);
|
|
843
|
+
}
|
|
844
|
+
else {
|
|
845
|
+
runtime.stderr.write(`${error.message}\n`);
|
|
846
|
+
}
|
|
847
|
+
if (error.details.hint && !quiet)
|
|
848
|
+
runtime.stderr.write(`${error.details.hint}\n`);
|
|
849
|
+
}
|
|
850
|
+
async function timedFetch(input, init, ms, parent) {
|
|
851
|
+
return fetch(input, { ...init, signal: AbortSignal.any([parent, AbortSignal.timeout(ms)]) });
|
|
852
|
+
}
|
|
853
|
+
async function safeApiError(response, fallback) {
|
|
854
|
+
try {
|
|
855
|
+
const body = (await response.json());
|
|
856
|
+
return typeof body.error === "string" ? sanitize(body.error) : fallback;
|
|
857
|
+
}
|
|
858
|
+
catch {
|
|
859
|
+
return fallback;
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
function sleep(ms, signal) {
|
|
863
|
+
return new Promise((resolve, reject) => {
|
|
864
|
+
if (signal.aborted) {
|
|
865
|
+
reject(signal.reason);
|
|
866
|
+
return;
|
|
867
|
+
}
|
|
868
|
+
const timer = setTimeout(done, ms);
|
|
869
|
+
function done() {
|
|
870
|
+
signal.removeEventListener("abort", cancelled);
|
|
871
|
+
resolve();
|
|
872
|
+
}
|
|
873
|
+
function cancelled() {
|
|
874
|
+
clearTimeout(timer);
|
|
875
|
+
signal.removeEventListener("abort", cancelled);
|
|
876
|
+
reject(signal.reason);
|
|
877
|
+
}
|
|
878
|
+
signal.addEventListener("abort", cancelled, { once: true });
|
|
879
|
+
});
|
|
880
|
+
}
|
|
881
|
+
function openUrl(url) {
|
|
882
|
+
const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
|
|
883
|
+
const argv = process.platform === "win32" ? ["/c", "start", "", url] : [url];
|
|
884
|
+
try {
|
|
885
|
+
const child = spawn(command, argv, { stdio: "ignore", detached: true, shell: false });
|
|
886
|
+
child.on("error", () => { });
|
|
887
|
+
child.unref();
|
|
888
|
+
}
|
|
889
|
+
catch {
|
|
890
|
+
/* the printed URL remains usable */
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
function firstSentence(value) {
|
|
894
|
+
const trimmed = value.trim().replace(/\s+/g, " ");
|
|
895
|
+
const match = trimmed.match(/^.*?[.!?](?:\s|$)/);
|
|
896
|
+
return (match?.[0] ?? trimmed).trim();
|
|
897
|
+
}
|
|
898
|
+
export async function main(argv = process.argv.slice(2), env = process.env) {
|
|
899
|
+
const controller = new AbortController();
|
|
900
|
+
const cancel = () => controller.abort(new Error("Cancelled."));
|
|
901
|
+
process.once("SIGINT", cancel);
|
|
902
|
+
process.once("SIGTERM", cancel);
|
|
903
|
+
const runtime = { env, stdout: process.stdout, stderr: process.stderr, signal: controller.signal };
|
|
904
|
+
let args;
|
|
905
|
+
const wantsJson = argv.some((item) => item === "--json" || item.startsWith("--json="));
|
|
906
|
+
const wantsQuiet = argv.includes("--quiet");
|
|
907
|
+
try {
|
|
908
|
+
args = parseArgs(argv);
|
|
909
|
+
const result = await dispatch(args, runtime);
|
|
910
|
+
emit(result, args, runtime);
|
|
911
|
+
return result.exitCode ?? 0;
|
|
912
|
+
}
|
|
913
|
+
catch (error) {
|
|
914
|
+
const cliError = asFailure(error);
|
|
915
|
+
emitFailure(cliError, args ? bool(args, "json") : wantsJson, args ? bool(args, "quiet") : wantsQuiet, runtime);
|
|
916
|
+
return cliError.exitCode;
|
|
917
|
+
}
|
|
918
|
+
finally {
|
|
919
|
+
process.removeListener("SIGINT", cancel);
|
|
920
|
+
process.removeListener("SIGTERM", cancel);
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
function isEntrypoint() {
|
|
924
|
+
if (!process.argv[1])
|
|
925
|
+
return false;
|
|
926
|
+
try {
|
|
927
|
+
// npm bins are symlinks, and macOS also aliases /tmp to /private/tmp.
|
|
928
|
+
// Compare canonical paths so an installed `passport` actually dispatches.
|
|
929
|
+
return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(process.argv[1]);
|
|
930
|
+
}
|
|
931
|
+
catch {
|
|
932
|
+
return false;
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
if (isEntrypoint()) {
|
|
936
|
+
void main().then((code) => {
|
|
937
|
+
process.exitCode = code;
|
|
938
|
+
});
|
|
939
|
+
}
|