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,161 @@
1
+ import { bool, value } from "./cliArgs.js";
2
+ import { SERVER_TOO_OLD } from "./cliProtocol.js";
3
+ import { firstText, payloadOf, requireSuccess } from "./cliResult.js";
4
+ import { failure, openUrl, sleep } from "./cliSupport.js";
5
+ export function managePayload(result) {
6
+ requireSuccess(result);
7
+ const payload = payloadOf(result, "connection");
8
+ if (!payload.workspace ||
9
+ typeof payload.workspace !== "object" ||
10
+ !payload.member ||
11
+ typeof payload.member !== "object" ||
12
+ typeof payload.client !== "string" ||
13
+ payload.surface !== "cli" ||
14
+ typeof payload.auth !== "string" ||
15
+ !Array.isArray(payload.connections)) {
16
+ return failure(SERVER_TOO_OLD, 1, "server_too_old");
17
+ }
18
+ return payload;
19
+ }
20
+ function assertConnectionCanStart(auth, needSignin, urls, human, shouldOpen, shouldAct) {
21
+ if (auth.kind === "agent-key" && needSignin.length && shouldAct) {
22
+ return failure("Agent-key authentication cannot create a person's sign-in link.", 3, "member_profile_required", {
23
+ app: needSignin.length === 1 ? String(needSignin[0].app ?? "") || undefined : undefined,
24
+ hint: "Use an interactive member profile, delegate the agent to a member, or configure a company-managed connection.",
25
+ remediation: {
26
+ action: "use_member_profile_or_managed_connection",
27
+ description: "Use an interactive member profile, delegate the agent to a member, or configure a company-managed connection."
28
+ }
29
+ });
30
+ }
31
+ if (shouldOpen && needSignin.length && !urls.length) {
32
+ return failure(human.join("\n"), 3, "connection_action_required", {
33
+ app: needSignin.length === 1 ? String(needSignin[0].app ?? "") || undefined : undefined,
34
+ hint: "Complete the connection action reported by Passport, then retry.",
35
+ remediation: {
36
+ action: "complete_reported_connection_action",
37
+ description: "Complete the connection action reported by Passport, then retry."
38
+ }
39
+ });
40
+ }
41
+ }
42
+ export async function connect(args, runtime, withGateway) {
43
+ const alias = value(args, "alias");
44
+ if (alias !== undefined && !/^[A-Za-z0-9 -]{1,32}$/.test(alias.trim()))
45
+ return failure("--alias must contain 1-32 letters, numbers, spaces, or hyphens.", 6, "usage");
46
+ const requested = args.positionals;
47
+ return withGateway(args, runtime, async (gateway, auth) => {
48
+ let managed = managePayload(await gateway.callTool("passport_manage_connections", {
49
+ ...(alias !== undefined ? { alias: alias.trim() } : {}),
50
+ ...(requested.length ? { apps: requested } : {})
51
+ }));
52
+ const rows = requested.length
53
+ ? requested.map((app) => findConnection(managed.connections, app))
54
+ : managed.connections;
55
+ const human = connectionLines(managed, rows, requested.length > 0);
56
+ const urls = connectionUrls(managed, rows, requested.length > 0);
57
+ const needSignin = rows.filter((row) => row.status === "needs_your_signin");
58
+ const waitSeconds = value(args, "wait") ? Number(value(args, "wait")) : 0;
59
+ assertConnectionCanStart(auth, needSignin, urls, human, bool(args, "open"), bool(args, "open") || waitSeconds > 0);
60
+ if (bool(args, "open")) {
61
+ if (urls.length > 1)
62
+ return failure("--open requires a single connect URL. Name one MCP, or use the aggregate connect flow.", 6, "usage");
63
+ if (urls[0]) {
64
+ if (!bool(args, "quiet"))
65
+ runtime.stderr.write("Opening the connection page in your browser...\n");
66
+ if (!openUrl(urls[0]))
67
+ runtime.stderr.write(`Could not open a browser automatically. Open: ${urls[0]}\n`);
68
+ }
69
+ }
70
+ if (!waitSeconds)
71
+ return { json: managed, human: human.join("\n") };
72
+ const targets = rows.filter((row) => row.status === "needs_your_signin").map((row) => String(row.app));
73
+ if (!targets.length)
74
+ return { json: managed, human: human.join("\n") };
75
+ const aggregateFlow = !requested.length && Boolean(managed.connectAllUrl);
76
+ const allTargetsHaveFlow = aggregateFlow || needSignin.every((row) => typeof row.connectUrl === "string");
77
+ if (!allTargetsHaveFlow) {
78
+ return failure(human.join("\n"), 3, "connection_action_required", {
79
+ app: targets.length === 1 ? targets[0] : undefined,
80
+ hint: "Complete the connection action reported by Passport, then retry the command.",
81
+ remediation: {
82
+ action: "complete_reported_connection_action",
83
+ description: "Complete the connection action reported by Passport, then retry."
84
+ }
85
+ });
86
+ }
87
+ if (!bool(args, "json") && (!bool(args, "quiet") || !bool(args, "open")))
88
+ runtime.stdout.write(`${human.join("\n")}\n`);
89
+ if (!bool(args, "quiet")) {
90
+ runtime.stderr.write(`Waiting up to ${waitSeconds} seconds for ${targets.length === 1 ? targets[0] : "the connections"}...\n`);
91
+ }
92
+ const waitResult = await waitForConnections(gateway, targets, waitSeconds, runtime.signal);
93
+ if (!waitResult.connected) {
94
+ const note = typeof waitResult.note === "string" ? waitResult.note : "Timed out waiting for the MCP connection.";
95
+ return failure(note, 1, "connection_timeout", { app: targets.length === 1 ? targets[0] : undefined });
96
+ }
97
+ managed = managePayload(await gateway.callTool("passport_manage_connections", { includeLinks: false }));
98
+ return { json: managed, human: typeof waitResult.note === "string" ? waitResult.note : "Connection ready." };
99
+ });
100
+ }
101
+ function findConnection(rows, requested) {
102
+ const needle = requested.trim().toLowerCase();
103
+ const row = rows.find((entry) => String(entry.app ?? "").toLowerCase() === needle || String(entry.name ?? "").toLowerCase() === needle);
104
+ if (!row)
105
+ return failure(`Unknown MCP "${requested}". Run passport status to see visible MCPs.`, 6, "unknown_app", {
106
+ app: requested,
107
+ hint: "Run: passport status",
108
+ next: [{ argv: ["passport", "status"], description: "List visible MCP connections." }]
109
+ });
110
+ return row;
111
+ }
112
+ function connectionUrls(managed, rows, explicitlyNamed) {
113
+ const needSignin = rows.filter((row) => row.status === "needs_your_signin");
114
+ if (!explicitlyNamed && needSignin.length >= 2 && managed.connectAllUrl)
115
+ return [managed.connectAllUrl];
116
+ return needSignin.map((row) => row.connectUrl).filter((url) => typeof url === "string");
117
+ }
118
+ function connectionLines(managed, rows, explicitlyNamed) {
119
+ const urls = connectionUrls(managed, rows, explicitlyNamed);
120
+ if (!explicitlyNamed && urls.length === 1 && rows.filter((row) => row.status === "needs_your_signin").length >= 2) {
121
+ return [`Connect your MCPs: ${urls[0]}`];
122
+ }
123
+ const lines = [];
124
+ for (const row of rows) {
125
+ const name = String(row.name ?? row.app ?? "MCP");
126
+ if (row.status === "needs_your_signin" && typeof row.connectUrl === "string")
127
+ lines.push(`${name}: ${row.connectUrl}`);
128
+ else if (row.status === "connected" || row.status === "org_managed")
129
+ lines.push(`${name}: already connected`);
130
+ else if (typeof row.action === "string")
131
+ lines.push(`${name}: ${row.action}`);
132
+ else
133
+ lines.push(`${name}: ${String(row.status ?? "unknown")}`);
134
+ }
135
+ if (!lines.length || (!explicitlyNamed && !rows.some((row) => row.status === "needs_your_signin")))
136
+ lines.push(managed.note || "Nothing needs connecting.");
137
+ return lines;
138
+ }
139
+ async function waitForConnections(gateway, apps, seconds, signal) {
140
+ const deadlineAt = Date.now() + seconds * 1000;
141
+ let latest = { connected: false };
142
+ do {
143
+ const remaining = Math.max(1, Math.ceil((deadlineAt - Date.now()) / 1000));
144
+ const chunk = Math.min(120, remaining);
145
+ const result = requireSuccess(await gateway.callTool("passport_wait_for_connection", apps.length === 1 ? { app: apps[0], timeoutSeconds: chunk } : { apps, timeoutSeconds: chunk }, (chunk + 5) * 1000));
146
+ const text = firstText(result);
147
+ try {
148
+ latest = JSON.parse(text);
149
+ }
150
+ catch {
151
+ return failure("Passport returned an invalid connection wait payload.", 1, "invalid_server_response");
152
+ }
153
+ if (latest.connected === true || latest.status === "connected")
154
+ return { ...latest, connected: true };
155
+ if (latest.status === "needs_setup")
156
+ return { ...latest, connected: false };
157
+ if (Date.now() < deadlineAt)
158
+ await sleep(Math.min(250, deadlineAt - Date.now()), signal);
159
+ } while (Date.now() < deadlineAt);
160
+ return { ...latest, connected: false };
161
+ }
@@ -0,0 +1,27 @@
1
+ const systemClock = {
2
+ set: (callback, ms) => setTimeout(callback, ms),
3
+ clear: (timer) => clearTimeout(timer)
4
+ };
5
+ /** A CLI request deadline must keep the short-lived command alive. A pending
6
+ * Promise does not hold Node's event loop open, so this timer is intentionally
7
+ * referenced until the operation settles or the deadline fires. */
8
+ export async function withCliDeadline(promise, ms, onTimeout, clock = systemClock) {
9
+ if (!Number.isSafeInteger(ms) || ms < 1)
10
+ throw new Error("CLI request deadline must be a positive integer.");
11
+ let timer;
12
+ const expired = new Promise((_, reject) => {
13
+ timer = clock.set(() => {
14
+ onTimeout();
15
+ const error = new Error(`Request timed out after ${Math.ceil(ms / 1000)} seconds.`);
16
+ error.name = "TimeoutError";
17
+ reject(error);
18
+ }, ms);
19
+ });
20
+ try {
21
+ return await Promise.race([promise, expired]);
22
+ }
23
+ finally {
24
+ if (timer)
25
+ clock.clear(timer);
26
+ }
27
+ }
@@ -0,0 +1,175 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { workspaceOfToken } from "./tokenWorkspace.js";
3
+ import { bool, value } from "./cliArgs.js";
4
+ import { assertCredentialStoreMutationReady, credsPath, getProfile, getProfileStrict, readActiveProfile, readCreds, setActiveProfile, withProfileLock, writeProfile } from "./credentials.js";
5
+ import { cloudOrigin, endpoint, failure, openUrl, profileName, readBoundedJson, safeApiError, sameOriginWebUrl, sleep, timedFetch, timeoutMs } from "./cliSupport.js";
6
+ const PASSPORT_CLOUD = "https://passportmcp.com";
7
+ function workspaceFromEndpoint(raw) {
8
+ try {
9
+ const match = new URL(endpoint(raw)).pathname.match(/^\/w\/([^/]+)\/mcp\/?$/);
10
+ const workspace = match ? decodeURIComponent(match[1]) : "";
11
+ return /^[A-Za-z0-9_-]{1,80}$/.test(workspace) ? workspace : "";
12
+ }
13
+ catch {
14
+ return "";
15
+ }
16
+ }
17
+ function loginOptions(args, runtime) {
18
+ const explicitProfile = value(args, "profile");
19
+ const workspaceOption = value(args, "workspace");
20
+ const explicitWorkspace = workspaceOption !== undefined;
21
+ const workspaceFromOption = workspaceOption?.trim() ?? "";
22
+ if (explicitWorkspace && !/^[A-Za-z0-9_-]{1,80}$/.test(workspaceFromOption)) {
23
+ return failure("--workspace must be a valid workspace id.", 6, "usage");
24
+ }
25
+ const creds = readCreds();
26
+ const names = Object.keys(creds).sort();
27
+ const active = readActiveProfile();
28
+ const requestedProfile = explicitProfile !== undefined
29
+ ? profileName(explicitProfile)
30
+ : runtime.env.PASSPORT_PROFILE
31
+ ? profileName(runtime.env.PASSPORT_PROFILE)
32
+ : explicitWorkspace
33
+ ? `cli@${workspaceFromOption}`
34
+ : active && creds[active]
35
+ ? active
36
+ : names.length === 1
37
+ ? names[0]
38
+ : "";
39
+ const existing = requestedProfile ? getProfile(requestedProfile) : undefined;
40
+ if (explicitWorkspace && existing) {
41
+ const existingWorkspace = workspaceFromEndpoint(existing.endpoint) || workspaceOfToken(existing.refreshToken);
42
+ if (!existingWorkspace || existingWorkspace !== workspaceFromOption) {
43
+ return failure(`Profile "${requestedProfile}" belongs to another workspace and will not be overwritten. Choose a new --profile name.`, 6, "usage");
44
+ }
45
+ }
46
+ const workspace = explicitWorkspace ? workspaceFromOption : existing ? workspaceFromEndpoint(existing.endpoint) : "";
47
+ const cloudRaw = value(args, "cloud") ||
48
+ runtime.env.PASSPORT_CLOUD ||
49
+ (existing ? new URL(endpoint(existing.endpoint)).origin : workspace ? PASSPORT_CLOUD : "");
50
+ if (!cloudRaw) {
51
+ if (names.length > 1) {
52
+ return failure(`Choose a profile before signing in. Available profiles: ${names.join(", ")}.`, 2, "auth", {
53
+ hint: "Run: passport profiles\nThen: passport use <name>\nOr create another profile with --cloud and --workspace.",
54
+ profiles: names,
55
+ next: [
56
+ { argv: ["passport", "profiles"], description: "List saved profiles." },
57
+ ...names.map((name) => ({
58
+ argv: ["passport", "use", name],
59
+ description: `Select the saved profile "${name}" to refresh.`
60
+ }))
61
+ ]
62
+ });
63
+ }
64
+ return failure("Tell Passport which workspace to sign in to.", 6, "usage", {
65
+ hint: `Run: passport login --workspace <workspace-id>\nFor self-hosted Passport, also pass --cloud <origin>.`,
66
+ requiredInput: ["workspace-id"]
67
+ });
68
+ }
69
+ const clientOption = value(args, "client");
70
+ const client = clientOption === undefined ? existing?.client || "cli" : clientOption.trim();
71
+ if (!/^[A-Za-z0-9._-]{1,40}$/.test(client)) {
72
+ return failure("--client must be a valid client id (1-40 characters).", 6, "usage");
73
+ }
74
+ return { requestedProfile, cloud: cloudOrigin(cloudRaw), workspace, client };
75
+ }
76
+ async function waitForDeviceApproval(cloud, code, args, runtime) {
77
+ const deadlineAt = Date.now() + 10 * 60 * 1000;
78
+ while (Date.now() < deadlineAt) {
79
+ await sleep(1_500, runtime.signal);
80
+ const poll = await timedFetch(`${cloud}/api/auth/device/poll`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ code }) }, timeoutMs(args), runtime.signal);
81
+ if (!poll.ok)
82
+ return failure(`Could not check sign-in (${poll.status}).`, 1, "server");
83
+ const result = await readBoundedJson(poll);
84
+ if (result.status === "approved" && typeof result.token === "string")
85
+ return result.token;
86
+ if (result.status === "denied" || result.status === "expired") {
87
+ return failure(`Sign-in ${result.status}.`, 2, "auth");
88
+ }
89
+ }
90
+ return failure("Timed out waiting for sign-in approval.", 2, "auth");
91
+ }
92
+ export async function login(args, runtime) {
93
+ if (runtime.env.PASSPORT_AGENT_KEY || runtime.env.PASSPORT_ENDPOINT) {
94
+ return failure("Unset PASSPORT_AGENT_KEY and PASSPORT_ENDPOINT before interactive login.", 6, "usage");
95
+ }
96
+ assertCredentialStoreMutationReady();
97
+ const { requestedProfile, cloud, workspace, client } = loginOptions(args, runtime);
98
+ const workspaceQuery = workspace ? `?ws=${encodeURIComponent(workspace)}` : "";
99
+ const start = await timedFetch(`${cloud}/api/auth/device/start${workspaceQuery}`, { method: "POST" }, timeoutMs(args), runtime.signal);
100
+ if (start.status === 404) {
101
+ return failure("Passport could not find that workspace. Ask your admin for its workspace id.", 2, "auth");
102
+ }
103
+ if (!start.ok)
104
+ return failure(`Could not start sign-in (${start.status}).`, 1, "server");
105
+ const started = await readBoundedJson(start);
106
+ if (typeof started.code !== "string" ||
107
+ typeof started.userCode !== "string" ||
108
+ typeof started.verifyUrl !== "string") {
109
+ return failure("Passport returned an invalid device sign-in response.", 1, "invalid_server_response");
110
+ }
111
+ const verifyUrl = sameOriginWebUrl(started.verifyUrl, cloud, "a sign-in URL");
112
+ const shouldOpen = !bool(args, "no-open") && !runtime.env.PASSPORT_NO_OPEN;
113
+ runtime.stderr.write(`Sign in to Passport${workspace ? ` workspace ${workspace}` : ""}\n${shouldOpen ? "Opening your browser..." : "Browser opening is disabled."}\nOpen: ${verifyUrl}\nConfirm code: ${started.userCode}\nWaiting for approval (up to 10 minutes; press Ctrl-C to cancel)...\n`);
114
+ if (shouldOpen && !openUrl(verifyUrl)) {
115
+ runtime.stderr.write("Could not open a browser automatically. Open the URL above to continue.\n");
116
+ }
117
+ const sessionToken = await waitForDeviceApproval(cloud, started.code, args, runtime);
118
+ runtime.stderr.write("Sign-in approved. Creating your CLI credential...\n");
119
+ const approvedWorkspace = workspaceOfToken(sessionToken);
120
+ if (workspace && approvedWorkspace && approvedWorkspace !== workspace) {
121
+ return failure("Passport approved a different workspace than the one requested; no credential was saved.", 2, "auth");
122
+ }
123
+ const tokenWorkspace = workspace || approvedWorkspace || "workspace";
124
+ const profile = profileName(requestedProfile || `cli@${tokenWorkspace}`);
125
+ const storedInstanceId = getProfileStrict(profile)?.instanceId;
126
+ const instanceId = storedInstanceId && /^[A-Za-z0-9._:-]{1,128}$/.test(storedInstanceId) ? storedInstanceId : randomUUID();
127
+ const credential = await timedFetch(`${cloud}/api/my/bridge-credential`, {
128
+ method: "POST",
129
+ headers: { "content-type": "application/json", authorization: `Bearer ${sessionToken}` },
130
+ body: JSON.stringify({
131
+ client,
132
+ target: "workspace",
133
+ surface: "cli",
134
+ instanceId,
135
+ instanceLabel: profile
136
+ })
137
+ }, timeoutMs(args), runtime.signal);
138
+ if (!credential.ok) {
139
+ const message = await safeApiError(credential, "Could not create a CLI credential.");
140
+ return failure(message, credential.status === 401 || credential.status === 403 ? 2 : 1, "auth");
141
+ }
142
+ const body = await readBoundedJson(credential);
143
+ if (typeof body.refreshToken !== "string" || typeof body.endpoint !== "string") {
144
+ return failure("Passport returned an invalid credential response.", 1, "invalid_server_response");
145
+ }
146
+ const credentialEndpoint = sameOriginWebUrl(body.endpoint, cloud, "a credential endpoint");
147
+ const endpointWorkspace = workspaceFromEndpoint(credentialEndpoint);
148
+ if (workspace && endpointWorkspace && endpointWorkspace !== workspace) {
149
+ return failure("Passport returned a credential for a different workspace; no credential was saved.", 2, "auth");
150
+ }
151
+ await withProfileLock(profile, async () => {
152
+ writeProfile(profile, {
153
+ refreshToken: body.refreshToken,
154
+ endpoint: credentialEndpoint,
155
+ instanceId,
156
+ client,
157
+ target: "workspace"
158
+ });
159
+ // Login is an intentional profile choice. Persist it as the local
160
+ // default so the very next bare `passport status`/`search` works even
161
+ // when other client/workspace profiles already exist.
162
+ setActiveProfile(profile);
163
+ });
164
+ return {
165
+ json: {
166
+ profile,
167
+ endpoint: credentialEndpoint,
168
+ client,
169
+ surface: "cli",
170
+ active: true,
171
+ next: [{ argv: ["passport", "status", "--json"], description: "Verify the active profile and connections." }]
172
+ },
173
+ human: `Signed in as profile "${profile}".\nActive profile: "${profile}".\nCredential saved to ${credsPath()}.\nNext: passport status`
174
+ };
175
+ }
@@ -0,0 +1,119 @@
1
+ import { value } from "./cliArgs.js";
2
+ import { completionScript } from "./completion.js";
3
+ import { readActiveProfile, readCreds, setActiveProfile } from "./credentials.js";
4
+ import { endpoint, failure, profileName } from "./cliSupport.js";
5
+ import { VERSION } from "./version.js";
6
+ export function completionResult(args) {
7
+ const shell = args.positionals[0];
8
+ if (shell !== "bash" && shell !== "zsh" && shell !== "fish") {
9
+ return failure("completion requires bash, zsh, or fish.", 6, "usage");
10
+ }
11
+ const script = completionScript(shell);
12
+ return { json: { shell, script }, human: script, essential: true, raw: true };
13
+ }
14
+ export function profilesResult(_args) {
15
+ const creds = readCreds();
16
+ const names = Object.keys(creds).sort();
17
+ const selected = readActiveProfile();
18
+ const active = selected && creds[selected] ? selected : undefined;
19
+ const profiles = names.map((name) => ({
20
+ name,
21
+ active: name === active,
22
+ ...(creds[name].client ? { client: creds[name].client } : {})
23
+ }));
24
+ if (!profiles.length) {
25
+ return {
26
+ json: { profiles: [] },
27
+ human: "No Passport profiles saved.\nRun: passport login --workspace <workspace-id>.",
28
+ essential: true
29
+ };
30
+ }
31
+ const lines = [
32
+ "Passport profiles:",
33
+ ...profiles.map((profile) => ` ${profile.active ? "*" : " "} ${profile.name}${profile.active ? " (active)" : ""}`),
34
+ "",
35
+ "Use `passport use <name>` to select a profile."
36
+ ];
37
+ return {
38
+ json: { profiles, ...(active ? { active } : {}) },
39
+ human: lines.join("\n"),
40
+ essential: true
41
+ };
42
+ }
43
+ export function useProfileResult(args, env) {
44
+ const profile = profileName(args.positionals[0]);
45
+ const creds = readCreds();
46
+ const names = Object.keys(creds).sort();
47
+ if (!creds[profile]) {
48
+ const suffix = names.length ? ` Available profiles: ${names.join(", ")}.` : "";
49
+ return failure(`Passport profile "${profile}" does not exist.${suffix}`, 2, "auth", {
50
+ hint: names.length
51
+ ? `Choose one with: passport use <name> (available: ${names.join(", ")}).`
52
+ : "Run: passport login --workspace <workspace-id>.",
53
+ ...(names.length
54
+ ? {
55
+ profiles: names,
56
+ next: names.map((name) => ({
57
+ argv: ["passport", "use", name],
58
+ description: `Select the saved profile "${name}".`
59
+ }))
60
+ }
61
+ : { requiredInput: ["workspace-id"] })
62
+ });
63
+ }
64
+ setActiveProfile(profile);
65
+ const environmentProfile = env.PASSPORT_PROFILE ? profileName(env.PASSPORT_PROFILE) : undefined;
66
+ const overridden = environmentProfile && environmentProfile !== profile;
67
+ return {
68
+ json: {
69
+ profile,
70
+ active: true,
71
+ effectiveProfile: overridden ? environmentProfile : profile,
72
+ ...(overridden ? { overriddenBy: "PASSPORT_PROFILE" } : {})
73
+ },
74
+ human: overridden
75
+ ? `Saved active profile: "${profile}".\nPASSPORT_PROFILE still overrides it with "${environmentProfile}" for authenticated commands.`
76
+ : `Active profile: "${profile}".\nNext: passport status`
77
+ };
78
+ }
79
+ export function versionResult(args, env) {
80
+ let profile;
81
+ let resolvedEndpoint;
82
+ if (env.PASSPORT_AGENT_KEY && env.PASSPORT_ENDPOINT && value(args, "profile") !== undefined) {
83
+ return failure("--profile cannot be used with PASSPORT_AGENT_KEY.", 6, "usage");
84
+ }
85
+ if (env.PASSPORT_AGENT_KEY && env.PASSPORT_ENDPOINT) {
86
+ resolvedEndpoint = endpoint(env.PASSPORT_ENDPOINT);
87
+ }
88
+ else {
89
+ const creds = readCreds();
90
+ const names = Object.keys(creds);
91
+ const explicitProfile = value(args, "profile");
92
+ const candidate = explicitProfile !== undefined
93
+ ? profileName(explicitProfile)
94
+ : env.PASSPORT_PROFILE
95
+ ? profileName(env.PASSPORT_PROFILE)
96
+ : (() => {
97
+ const active = readActiveProfile();
98
+ return active && creds[active] ? profileName(active) : names.length === 1 ? profileName(names[0]) : "";
99
+ })();
100
+ if (candidate && creds[candidate]) {
101
+ profile = candidate;
102
+ resolvedEndpoint = endpoint(creds[candidate].endpoint);
103
+ }
104
+ }
105
+ const data = {
106
+ version: VERSION,
107
+ ...(resolvedEndpoint ? { endpoint: resolvedEndpoint } : {}),
108
+ ...(profile ? { profile } : {})
109
+ };
110
+ return {
111
+ json: data,
112
+ human: [
113
+ `passport ${VERSION}`,
114
+ ...(resolvedEndpoint ? [`Endpoint: ${resolvedEndpoint}`] : []),
115
+ ...(profile ? [`Profile: ${profile}`] : [])
116
+ ].join("\n"),
117
+ essential: true
118
+ };
119
+ }
@@ -0,0 +1,116 @@
1
+ import { ArgError, bool } from "./cliArgs.js";
2
+ import { SERVER_TOO_OLD } from "./cliProtocol.js";
3
+ import { CliFailure, sanitize } from "./cliSupport.js";
4
+ import { VERSION } from "./version.js";
5
+ function helpText(verb) {
6
+ const details = {
7
+ login: "passport login [--workspace <id>] [--cloud <origin>] [--client <id>] [--profile <name>] [--no-open]\nStarts device sign-in, stores a cli-surface rotating credential, and makes that profile active. Passport Cloud is used when --workspace is provided without --cloud.",
8
+ logout: "passport logout [--profile <name>]\nRevokes the rotating credential and always removes the local profile.",
9
+ profiles: "passport profiles\nLists saved profiles and marks the active profile. Works offline.",
10
+ use: "passport use <name>\nSelects a saved profile as the default for subsequent commands. Works offline.",
11
+ status: "passport status\nJSON: {workspace,member,endpoint,auth,profile?,client,mcps:[{app,name,status,toolCount}]}",
12
+ 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}.",
13
+ search: "passport search [query...] [--app <key>]\nEmpty query lists the complete permitted catalog. JSON is the server search payload.",
14
+ describe: "passport describe <tool>\nShows the exact tool definition and complete parameter schema.",
15
+ 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.",
16
+ 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.",
17
+ resources: "passport resources [uri] [--out <file>]\nLists or reads workspace MCP resources. Binary content requires --out or --json.",
18
+ prompts: "passport prompts [name] [--set key=value] [--out <file>]\nLists or gets workspace MCP prompts. Binary content requires --out or --json.",
19
+ discover: "passport discover\nScans supported local MCP configuration, submits privacy-minimized inventory, and exits 5 when a managed policy reports a violation.",
20
+ session: 'passport session\nReads newline-delimited {"id"?:string|number,"argv":string[]} requests from stdin and emits one JSON response per line. Reuses one authenticated MCP session. Supported request commands: status, search, describe, run, connect, resources, prompts, discover.',
21
+ completion: "passport completion <bash|zsh|fish>\nPrints an offline shell-completion script to stdout.",
22
+ help: "passport help [verb]",
23
+ version: "passport version\nWorks without a profile or network."
24
+ };
25
+ if (verb && details[verb])
26
+ return `${details[verb]}\n\nGlobal: --profile <name> --json --timeout <sec> --quiet --caller <id>`;
27
+ return `Passport CLI ${VERSION}
28
+
29
+ Usage: passport <command> [options]
30
+
31
+ login Sign in with the device flow
32
+ logout Revoke and remove a profile
33
+ profiles List saved profiles and the active selection
34
+ use Select a saved profile for subsequent commands
35
+ status Show identity and visible MCP connection state
36
+ doctor Diagnose local setup and server compatibility
37
+ search Find permitted tools or list the catalog
38
+ describe Show one exact tool definition
39
+ run Run a governed tool
40
+ connect Connect member MCP accounts
41
+ resources List or read MCP resources
42
+ prompts List or get MCP prompts
43
+ discover Scan this computer for direct MCP configuration
44
+ session Reuse one authenticated MCP session for NDJSON commands
45
+ completion Generate bash, zsh, or fish completion
46
+ help Show command help
47
+ version Show CLI version and local context
48
+
49
+ Global: --profile <name> --json --timeout <sec> --quiet --caller <id>
50
+
51
+ Exit codes: 0 success · 1 network/server · 2 auth · 3 needs-connect · 4 approval-pending · 5 policy/guardrail/selection/approval-denial · 6 usage/unknown
52
+ With --json, stdout is exactly one JSON value. Hints and warnings use stderr.`;
53
+ }
54
+ export function helpResult(args) {
55
+ const verb = args.positionals[0];
56
+ const text = helpText(verb);
57
+ return { json: { command: verb ?? null, help: text }, human: text, essential: true };
58
+ }
59
+ export function emitResult(result, args, runtime) {
60
+ if (bool(args, "json")) {
61
+ runtime.stdout.write(`${JSON.stringify(result.json)}\n`);
62
+ return;
63
+ }
64
+ if (result.human === undefined || (bool(args, "quiet") && !result.essential))
65
+ return;
66
+ if (Buffer.isBuffer(result.human))
67
+ runtime.stdout.write(result.human);
68
+ else
69
+ runtime.stdout.write(result.raw ? result.human : `${result.human}${result.human.endsWith("\n") ? "" : "\n"}`);
70
+ }
71
+ export function asFailure(error) {
72
+ if (error instanceof CliFailure)
73
+ return error;
74
+ if (error instanceof ArgError)
75
+ return new CliFailure(sanitize(error.message), 6, "usage");
76
+ const raw = error instanceof Error ? error.message : String(error);
77
+ const message = sanitize(raw);
78
+ if (message === SERVER_TOO_OLD || message.includes("CLI-compatible server")) {
79
+ return new CliFailure(SERVER_TOO_OLD, 1, "server_too_old");
80
+ }
81
+ if (/token exchange failed|invalid_or_revoked|unauthori[sz]ed|\b401\b/i.test(message)) {
82
+ return new CliFailure("Passport authentication expired or was revoked.", 2, "auth", {
83
+ hint: "Run: passport login"
84
+ });
85
+ }
86
+ if (/timeout|timed out|aborted|aborterror|requesttimeout/i.test(message)) {
87
+ return new CliFailure("The Passport request timed out; it was not retried.", 1, "timeout");
88
+ }
89
+ return new CliFailure(message || "Passport request failed.", 1, "network_or_server");
90
+ }
91
+ export function emitFailure(error, json, quiet, runtime) {
92
+ if (json) {
93
+ runtime.stdout.write(`${JSON.stringify(failurePayload(error))}\n`);
94
+ }
95
+ else {
96
+ runtime.stderr.write(`${error.message}\n`);
97
+ }
98
+ if (error.details.hint && !quiet)
99
+ runtime.stderr.write(`${error.details.hint}\n`);
100
+ }
101
+ export function failurePayload(error) {
102
+ return {
103
+ error: error.message,
104
+ cause: error.cause,
105
+ exitCode: error.exitCode,
106
+ ...(error.details.approvalId ? { approvalId: error.details.approvalId } : {}),
107
+ ...(error.details.app ? { app: error.details.app } : {}),
108
+ ...(error.details.connectUrl ? { connectUrl: error.details.connectUrl } : {}),
109
+ ...(error.details.hint ? { hint: error.details.hint } : {}),
110
+ ...(error.details.profiles ? { profiles: error.details.profiles } : {}),
111
+ ...(error.details.next ? { next: error.details.next } : {}),
112
+ ...(error.details.remediation ? { remediation: error.details.remediation } : {}),
113
+ ...(error.details.retry ? { retry: error.details.retry } : {}),
114
+ ...(error.details.requiredInput ? { requiredInput: error.details.requiredInput } : {})
115
+ };
116
+ }
@@ -0,0 +1,55 @@
1
+ export const DEFAULT_CLI_PAGINATION_LIMITS = Object.freeze({
2
+ maxPages: 32,
3
+ maxItems: 10_000,
4
+ maxSerializedBytes: 8 * 1024 * 1024,
5
+ maxCursorBytes: 1024
6
+ });
7
+ function validateLimits(limits) {
8
+ for (const [name, value] of Object.entries(limits)) {
9
+ if (!Number.isSafeInteger(value) || value < 1)
10
+ throw new Error(`Invalid CLI pagination limit: ${name}.`);
11
+ }
12
+ }
13
+ /** Aggregate the MCP pages a one-shot CLI command prints while bounding every
14
+ * attacker/provider-controlled dimension. Cursor cycles fail closed. */
15
+ export async function collectCliPages(kind, load, itemsFrom, limits = DEFAULT_CLI_PAGINATION_LIMITS) {
16
+ validateLimits(limits);
17
+ const items = [];
18
+ const seenCursors = new Set();
19
+ let cursor;
20
+ let serializedBytes = 2; // JSON array brackets.
21
+ for (let pageNumber = 0;; pageNumber += 1) {
22
+ if (pageNumber >= limits.maxPages) {
23
+ throw new Error(`Passport returned more ${kind} pages than the CLI can safely aggregate.`);
24
+ }
25
+ if (cursor !== undefined)
26
+ seenCursors.add(cursor);
27
+ const last = await load(cursor);
28
+ const pageItems = itemsFrom(last);
29
+ if (!Array.isArray(pageItems))
30
+ throw new Error(`Passport returned an invalid ${kind} page.`);
31
+ for (const item of pageItems) {
32
+ if (items.length >= limits.maxItems) {
33
+ throw new Error(`Passport returned more ${kind}s than the CLI can safely aggregate.`);
34
+ }
35
+ const serialized = JSON.stringify(item);
36
+ if (serialized === undefined)
37
+ throw new Error(`Passport returned an invalid ${kind}.`);
38
+ serializedBytes += Buffer.byteLength(serialized) + (items.length ? 1 : 0);
39
+ if (serializedBytes > limits.maxSerializedBytes) {
40
+ throw new Error(`Passport returned ${kind} data larger than the CLI can safely aggregate.`);
41
+ }
42
+ items.push(item);
43
+ }
44
+ const next = last.nextCursor;
45
+ if (next === undefined || next === "")
46
+ return { last, items };
47
+ if (typeof next !== "string" ||
48
+ Buffer.byteLength(next) > limits.maxCursorBytes ||
49
+ next === cursor ||
50
+ seenCursors.has(next)) {
51
+ throw new Error(`Passport returned invalid ${kind} pagination.`);
52
+ }
53
+ cursor = next;
54
+ }
55
+ }