passport-bridge 0.7.1 → 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.
package/README.md CHANGED
@@ -17,20 +17,34 @@ Node.js 22.23.2 or newer is required.
17
17
  Sign in once, then search and run the tools your workspace permits:
18
18
 
19
19
  ```sh
20
- passport login --cloud https://passport.example.com --workspace ws_example
20
+ passport login --cloud https://passport.example.com --workspace ws_example --profile cli@ws_example
21
21
  passport status
22
22
  passport search "open issues"
23
23
  passport describe github_search_issues
24
24
  passport run github_search_issues '{"query":"SSO"}'
25
25
  ```
26
26
 
27
+ A successful login makes the new profile active. On a machine with more than
28
+ one stored profile, inspect or switch the active profile without a network
29
+ request:
30
+
31
+ ```sh
32
+ passport profiles
33
+ passport use cli@ws_example
34
+ passport status
35
+ ```
36
+
37
+ For Passport Cloud, `passport login --workspace <id>` can omit `--cloud`.
38
+ Self-hosted deployments pass their origin explicitly. Add `--no-open` to print
39
+ the device URL without launching a browser.
40
+
27
41
  `passport help [command]` documents every option. `passport help` and `passport version` work without a profile or network connection.
28
42
 
29
43
  Remote Passport servers must use HTTPS. Plain HTTP is accepted only for local
30
44
  development on `localhost`, `127.0.0.0/8`, or `::1`. Self-hosted deployments
31
45
  should terminate HTTPS before using interactive profiles or agent keys.
32
46
 
33
- Passport CLI 0.7.1 requires gateway MCP serverInfo `passport` version 0.5.0 or
47
+ Passport CLI 0.8.0 requires gateway MCP serverInfo `passport` version 0.5.0 or
34
48
  newer and the exact four-tool governed CLI protocol. Older servers fail clearly
35
49
  before the CLI makes a tool call.
36
50
 
@@ -51,6 +65,8 @@ before the CLI makes a tool call.
51
65
  | `discover` | Scan supported global MCP configuration and submit a privacy-minimized fleet report. |
52
66
  | `session` | Process NDJSON commands through one authenticated MCP session. |
53
67
  | `completion <shell>` | Generate completion for Bash, Zsh, or Fish without a profile or network. |
68
+ | `profiles` | List stored profiles and show the active profile without a network request. |
69
+ | `use <name>` | Select the active stored profile without a network request. |
54
70
  | `help [command]` | Show general or command-specific help. |
55
71
  | `version` | Show the package version and locally resolvable profile context. |
56
72
 
@@ -72,6 +88,11 @@ passport doctor --profile cli@ws_example
72
88
  passport doctor --profile cli@ws_example --json
73
89
  ```
74
90
 
91
+ When profile selection is unclear, start with `passport profiles` and choose
92
+ one with `passport use <name>`. Use `--profile <name>` for a one-off command or
93
+ `PASSPORT_PROFILE=<name>` for a shell scope; explicit selectors take precedence
94
+ over the active profile.
95
+
75
96
  `doctor` checks Node.js, the credential file's shape/ownership/mode, auth
76
97
  configuration, HTTPS policy, `/healthz`, the authenticated MCP handshake,
77
98
  serverInfo compatibility, and the exact four-tool CLI protocol. It never prints
@@ -160,7 +181,7 @@ The CLI never retries a call after a network failure or timeout because the exec
160
181
  For an MCP that needs member sign-in:
161
182
 
162
183
  ```sh
163
- passport connect github --open --wait 120
184
+ passport connect github --wait 120
164
185
  ```
165
186
 
166
187
  Without app names, `connect` uses one aggregate link when several visible MCPs need sign-in. Agent-key principals receive status and member guidance but cannot mint browser links.
@@ -184,9 +205,11 @@ With `--json`, stdout contains exactly one JSON value and no progress text. Hint
184
205
 
185
206
  | Command | JSON value |
186
207
  | ------------ | --------------------------------------------------------------------------------------------------------- |
187
- | `login` | `{profile, endpoint, client, surface}` |
208
+ | `login` | `{profile, endpoint, client, surface, active, next}` |
209
+ | `profiles` | `{profiles:[{name,active,client?}],active?}` |
210
+ | `use` | `{profile,active:true}` |
188
211
  | `logout` | `{profile, removed, revoked}` |
189
- | `status` | `{workspace, member, endpoint, auth, profile?, client, mcps}` |
212
+ | `status` | `{workspace, member, endpoint, auth, profile?, client, mcps, next?}` |
190
213
  | `doctor` | `{version,ok,auth,profile?,profileCount,endpointOrigin?,server?,checks}` (also emitted when checks fail). |
191
214
  | `search` | The gateway search payload, including `results` or `catalog` and `note`. |
192
215
  | `describe` | One tool definition. |
@@ -200,7 +223,9 @@ With `--json`, stdout contains exactly one JSON value and no progress text. Hint
200
223
  | `help` | `{command, help}` |
201
224
  | `version` | `{version, endpoint?, profile?}` |
202
225
 
203
- JSON errors have a stable shape:
226
+ JSON errors have a stable base shape and may add safe remediation fields such
227
+ as `hint`, `profiles`, `next` (`argv` plus a description), `remediation`,
228
+ `retry`, `requiredInput`, or `connectUrl`:
204
229
 
205
230
  ```json
206
231
  { "error": "...", "cause": "blocked", "exitCode": 5, "app": "github" }
@@ -224,9 +249,13 @@ Credentials are named slots in one file, `~/.passport/credentials.json`, with mo
224
249
 
225
250
  1. `--profile <name>`
226
251
  2. `PASSPORT_PROFILE`
227
- 3. the sole stored profile
252
+ 3. the active profile selected by `passport use <name>`
253
+ 4. the sole stored profile
228
254
 
229
- If several profiles exist, select one explicitly. The credential store is shared with `passport-bridge` and refresh exchanges are coordinated across processes.
255
+ If several profiles exist and none is active, select one explicitly. The
256
+ credential store is shared with `passport-bridge` and refresh exchanges are
257
+ coordinated across processes. The active-profile pointer contains no
258
+ credential and is local to this Passport credential store.
230
259
 
231
260
  Profile names are 1-80 letters, numbers, dots, underscores, `@` signs, or hyphens, and must start with a letter or number. Credential updates are atomically replaced at mode `0600`, including when several profiles rotate concurrently.
232
261
 
@@ -0,0 +1,122 @@
1
+ import { closeSync, constants, fchmodSync, fstatSync, lstatSync, openSync, readFileSync, unlinkSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { credentialDir, enforceOwner, ensurePrivateDirectory, isMissing, syncDirectory, writePrivateAtomic } from "./credentialStorage.js";
4
+ const MAX_ACTIVE_PROFILE_BYTES = 512;
5
+ function activeFile() {
6
+ return join(credentialDir(), ".active-profile");
7
+ }
8
+ export function activeProfilePath() {
9
+ return activeFile();
10
+ }
11
+ export function readActiveProfileDocument(assertName) {
12
+ if (!ensurePrivateDirectory(false))
13
+ return { kind: "missing" };
14
+ let pathStat;
15
+ try {
16
+ pathStat = lstatSync(activeFile());
17
+ }
18
+ catch (error) {
19
+ if (isMissing(error))
20
+ return { kind: "missing" };
21
+ throw error;
22
+ }
23
+ if (pathStat.isSymbolicLink() || !pathStat.isFile()) {
24
+ throw new Error("Passport active profile must be a regular file, not a symlink.");
25
+ }
26
+ enforceOwner(pathStat, "active profile");
27
+ if (pathStat.size > MAX_ACTIVE_PROFILE_BYTES) {
28
+ throw new Error("Passport active profile is unexpectedly large; refusing to read it.");
29
+ }
30
+ let descriptor;
31
+ try {
32
+ descriptor = openSync(activeFile(), constants.O_RDONLY | constants.O_NOFOLLOW);
33
+ const stat = fstatSync(descriptor);
34
+ if (!stat.isFile())
35
+ throw new Error("Passport active profile must be a regular file, not a symlink.");
36
+ if (stat.dev !== pathStat.dev || stat.ino !== pathStat.ino) {
37
+ throw new Error("Passport active profile changed while it was being opened; refusing to read it.");
38
+ }
39
+ enforceOwner(stat, "active profile");
40
+ if (stat.size > MAX_ACTIVE_PROFILE_BYTES) {
41
+ throw new Error("Passport active profile is unexpectedly large; refusing to read it.");
42
+ }
43
+ if (process.platform !== "win32")
44
+ fchmodSync(descriptor, 0o600);
45
+ const profile = readFileSync(descriptor, "utf8").trim();
46
+ if (!profile)
47
+ return { kind: "missing" };
48
+ try {
49
+ assertName(profile);
50
+ }
51
+ catch {
52
+ throw new Error("Passport active profile is invalid; choose a profile with `passport use <name>`.");
53
+ }
54
+ return { kind: "present", profile };
55
+ }
56
+ catch (error) {
57
+ if (isMissing(error))
58
+ return { kind: "missing" };
59
+ throw error;
60
+ }
61
+ finally {
62
+ if (descriptor !== undefined)
63
+ closeSync(descriptor);
64
+ }
65
+ }
66
+ /** Best-effort read for command resolution. A stale or damaged pointer must
67
+ * never make the CLI guess a credential; callers can fall back to the normal
68
+ * sole-profile rule or report ambiguity. */
69
+ export function readActiveProfile(assertName) {
70
+ try {
71
+ const result = readActiveProfileDocument(assertName);
72
+ return result.kind === "missing" ? undefined : result.profile;
73
+ }
74
+ catch {
75
+ return undefined;
76
+ }
77
+ }
78
+ export function writeActiveProfileAtomic(name, assertName) {
79
+ assertName(name);
80
+ writePrivateAtomic(activeFile(), ".active-profile", `${name}\n`, "active profile");
81
+ }
82
+ /** The active-profile pointer contains no credential material. If an old or
83
+ * damaged installation left a symlink at that exact path, selecting a profile
84
+ * may safely unlink the symlink itself (never its target) before recreating the
85
+ * owner-only regular file. Other non-regular targets still fail closed. */
86
+ export function prepareActiveProfileForSelection() {
87
+ let stat;
88
+ try {
89
+ stat = lstatSync(activeFile());
90
+ }
91
+ catch (error) {
92
+ if (isMissing(error))
93
+ return;
94
+ throw error;
95
+ }
96
+ if (stat.isSymbolicLink()) {
97
+ unlinkSync(activeFile());
98
+ syncDirectory();
99
+ return;
100
+ }
101
+ if (!stat.isFile()) {
102
+ throw new Error("Passport active profile must be a regular file, not a symlink.");
103
+ }
104
+ enforceOwner(stat, "active profile");
105
+ }
106
+ export function clearActiveProfileAtomic() {
107
+ let stat;
108
+ try {
109
+ stat = lstatSync(activeFile());
110
+ }
111
+ catch (error) {
112
+ if (isMissing(error))
113
+ return;
114
+ throw error;
115
+ }
116
+ if (stat.isSymbolicLink() || !stat.isFile()) {
117
+ throw new Error("Passport active profile must be a regular file, not a symlink.");
118
+ }
119
+ enforceOwner(stat, "active profile");
120
+ unlinkSync(activeFile());
121
+ syncDirectory();
122
+ }
package/dist/bridge.js CHANGED
@@ -9,6 +9,8 @@ import { VERSION } from "./version.js";
9
9
  import { bridgePollIntervalMs } from "./bridgeConfig.js";
10
10
  import { readBoundedJson } from "./boundedResponse.js";
11
11
  import { createBoundedBridgeShutdown } from "./bridgeShutdown.js";
12
+ import { workspaceOfToken } from "./tokenWorkspace.js";
13
+ export { workspaceOfToken } from "./tokenWorkspace.js";
12
14
  /** Everything but the MCP protocol goes to stderr — stdout is the transport. */
13
15
  export function log(...args) {
14
16
  process.stderr.write(`[passport-bridge] ${args.join(" ")}\n`);
@@ -21,15 +23,6 @@ function safeHostname() {
21
23
  return "unknown";
22
24
  }
23
25
  }
24
- /**
25
- * The workspace a Passport token belongs to. Every token the server mints is
26
- * workspace-prefixed (`<wsId>~...`, see server store.mintToken), so the tenant
27
- * is recoverable from the string itself. Returns "" for an env-supplied or
28
- * malformed token with no recognizable prefix.
29
- */
30
- export function workspaceOfToken(token) {
31
- return token.match(/^(ws_[A-Za-z0-9][A-Za-z0-9_-]{0,124})~/)?.[1] ?? "";
32
- }
33
26
  /**
34
27
  * Shown to the AI client (and logged) when the bridge refuses to switch tenants:
35
28
  * the on-disk credential now belongs to a DIFFERENT workspace than this process
package/dist/cli.js CHANGED
@@ -290,7 +290,9 @@ async function login() {
290
290
  }
291
291
  const refreshToken = credential.refreshToken;
292
292
  const endpoint = legacyCredentialEndpoint(credential.endpoint, cloud);
293
- await withProfileLock(profile, async () => writeProfile(profile, { refreshToken, endpoint, instanceId, client, target }));
293
+ await withProfileLock(profile, async () => {
294
+ writeProfile(profile, { refreshToken, endpoint, instanceId, client, target });
295
+ });
294
296
  out("");
295
297
  out(` ✓ Signed in. Saved profile "${profile}" to ${credsPath()}`);
296
298
  out(` Now point your AI app at: passport-bridge serve --profile ${profile}`);
package/dist/cliArgs.js CHANGED
@@ -1,6 +1,8 @@
1
1
  export const COMMANDS = [
2
2
  "login",
3
3
  "logout",
4
+ "profiles",
5
+ "use",
4
6
  "status",
5
7
  "doctor",
6
8
  "search",
@@ -25,6 +27,7 @@ const FLAGS = {
25
27
  cloud: { kind: "value", commands: ["login"] },
26
28
  workspace: { kind: "value", commands: ["login"] },
27
29
  client: { kind: "value", commands: ["login"] },
30
+ "no-open": { kind: "boolean", commands: ["login"] },
28
31
  app: { kind: "value", commands: ["search"] },
29
32
  args: { kind: "value", commands: ["run"] },
30
33
  set: { kind: "repeat", commands: ["run", "prompts"] },
@@ -123,6 +126,8 @@ function validateShape(command, positionals) {
123
126
  const max = {
124
127
  login: 0,
125
128
  logout: 0,
129
+ profiles: 0,
130
+ use: 1,
126
131
  status: 0,
127
132
  doctor: 0,
128
133
  describe: 1,
@@ -135,7 +140,7 @@ function validateShape(command, positionals) {
135
140
  help: 1,
136
141
  version: 0
137
142
  };
138
- const minimum = { describe: 1, run: 1, completion: 1 };
143
+ const minimum = { describe: 1, run: 1, use: 1, completion: 1 };
139
144
  if (positionals.length < (minimum[command] ?? 0)) {
140
145
  throw new ArgError(`${command} requires ${command === "run" ? "a tool name" : command === "completion" ? "bash, zsh, or fish" : "a name"}.`);
141
146
  }
@@ -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
+ }
package/dist/cliLogin.js CHANGED
@@ -1,25 +1,73 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { value } from "./cliArgs.js";
3
- import { assertCredentialStoreMutationReady, credsPath, getProfile, getProfileStrict, withProfileLock, writeProfile } from "./credentials.js";
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";
4
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
+ }
5
17
  function loginOptions(args, runtime) {
6
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();
7
28
  const requestedProfile = explicitProfile !== undefined
8
29
  ? profileName(explicitProfile)
9
30
  : runtime.env.PASSPORT_PROFILE
10
31
  ? profileName(runtime.env.PASSPORT_PROFILE)
11
- : "";
32
+ : explicitWorkspace
33
+ ? `cli@${workspaceFromOption}`
34
+ : active && creds[active]
35
+ ? active
36
+ : names.length === 1
37
+ ? names[0]
38
+ : "";
12
39
  const existing = requestedProfile ? getProfile(requestedProfile) : undefined;
13
- const cloudRaw = value(args, "cloud") || runtime.env.PASSPORT_CLOUD || (existing ? new URL(endpoint(existing.endpoint)).origin : "");
14
- if (!cloudRaw)
15
- return failure("--cloud <origin> is required for the first login.", 6, "usage");
16
- const workspaceOption = value(args, "workspace");
17
- const workspace = workspaceOption?.trim() ?? "";
18
- if (workspaceOption !== undefined && !/^[A-Za-z0-9_-]{1,80}$/.test(workspace)) {
19
- return failure("--workspace must be a valid workspace id.", 6, "usage");
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
+ });
20
68
  }
21
69
  const clientOption = value(args, "client");
22
- const client = clientOption === undefined ? "cli" : clientOption.trim();
70
+ const client = clientOption === undefined ? existing?.client || "cli" : clientOption.trim();
23
71
  if (!/^[A-Za-z0-9._-]{1,40}$/.test(client)) {
24
72
  return failure("--client must be a valid client id (1-40 characters).", 6, "usage");
25
73
  }
@@ -61,11 +109,18 @@ export async function login(args, runtime) {
61
109
  return failure("Passport returned an invalid device sign-in response.", 1, "invalid_server_response");
62
110
  }
63
111
  const verifyUrl = sameOriginWebUrl(started.verifyUrl, cloud, "a sign-in URL");
64
- runtime.stderr.write(`Sign in to Passport\nOpen: ${verifyUrl}\nConfirm code: ${started.userCode}\nWaiting for approval...\n`);
65
- if (!runtime.env.PASSPORT_NO_OPEN)
66
- openUrl(verifyUrl);
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
+ }
67
117
  const sessionToken = await waitForDeviceApproval(cloud, started.code, args, runtime);
68
- const tokenWorkspace = workspace || (await import("./bridge.js")).workspaceOfToken(sessionToken) || "workspace";
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";
69
124
  const profile = profileName(requestedProfile || `cli@${tokenWorkspace}`);
70
125
  const storedInstanceId = getProfileStrict(profile)?.instanceId;
71
126
  const instanceId = storedInstanceId && /^[A-Za-z0-9._:-]{1,128}$/.test(storedInstanceId) ? storedInstanceId : randomUUID();
@@ -89,15 +144,32 @@ export async function login(args, runtime) {
89
144
  return failure("Passport returned an invalid credential response.", 1, "invalid_server_response");
90
145
  }
91
146
  const credentialEndpoint = sameOriginWebUrl(body.endpoint, cloud, "a credential endpoint");
92
- await withProfileLock(profile, async () => writeProfile(profile, {
93
- refreshToken: body.refreshToken,
94
- endpoint: credentialEndpoint,
95
- instanceId,
96
- client,
97
- target: "workspace"
98
- }));
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
+ });
99
164
  return {
100
- json: { profile, endpoint: credentialEndpoint, client, surface: "cli" },
101
- human: `Signed in as profile "${profile}".\nCredential saved to ${credsPath()}.`
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`
102
174
  };
103
175
  }