passport-bridge 0.6.0 → 0.7.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
@@ -30,7 +30,7 @@ Remote Passport servers must use HTTPS. Plain HTTP is accepted only for local
30
30
  development on `localhost`, `127.0.0.0/8`, or `::1`. Self-hosted deployments
31
31
  should terminate HTTPS before using interactive profiles or agent keys.
32
32
 
33
- Passport CLI 0.6.0 requires gateway MCP serverInfo `passport` version 0.5.0 or
33
+ Passport CLI 0.7.0 requires gateway MCP serverInfo `passport` version 0.5.0 or
34
34
  newer and the exact four-tool governed CLI protocol. Older servers fail clearly
35
35
  before the CLI makes a tool call.
36
36
 
@@ -48,12 +48,20 @@ before the CLI makes a tool call.
48
48
  | `connect [app...]` | Show secure member connection links and optionally wait for completion. |
49
49
  | `resources [uri]` | List or read MCP resources. |
50
50
  | `prompts [name]` | List or get MCP prompts. |
51
+ | `discover` | Scan supported global MCP configuration and submit a privacy-minimized fleet report. |
51
52
  | `completion <shell>` | Generate completion for Bash, Zsh, or Fish without a profile or network. |
52
53
  | `help [command]` | Show general or command-specific help. |
53
54
  | `version` | Show the package version and locally resolvable profile context. |
54
55
 
55
56
  Every command accepts `--profile <name>`, `--json`, `--timeout <seconds>`, `--quiet`, and `--caller <id>` where applicable.
56
57
 
58
+ `passport discover` is the cross-platform, headless Passport Discover scanner.
59
+ It uploads no paths, commands or arguments, environment values, headers,
60
+ credentials, endpoint paths or query strings, prompts, files, tool payloads,
61
+ or traffic. Managed-policy violations return exit `5`, so endpoint management
62
+ can use it as a compliance gate without Passport silently editing client
63
+ configuration.
64
+
57
65
  ### Diagnostics
58
66
 
59
67
  Run diagnostics before opening a support ticket or promoting a CLI release:
@@ -157,6 +165,7 @@ With `--json`, stdout contains exactly one JSON value and no progress text. Hint
157
165
  | `connect` | The gateway connection payload, including `connections` and optional `connectAllUrl`. |
158
166
  | `resources` | The MCP list or read result. |
159
167
  | `prompts` | The MCP list or get result. |
168
+ | `discover` | `{snapshot,report,compliant}`. The snapshot contains privacy-minimized metadata only. |
160
169
  | `completion` | `{shell,script}`. Human mode emits the raw completion script. |
161
170
  | `help` | `{command, help}` |
162
171
  | `version` | `{version, endpoint?, profile?}` |
@@ -268,3 +277,6 @@ passport-bridge serve --profile cursor@ws_example
268
277
  ```
269
278
 
270
279
  The bridge exchanges its file-backed refresh credential for short-lived access tokens, persists rotations, coordinates concurrent processes, and forwards tools, resources, prompts, cancellation, progress, and tool-list changes over stdio. `passport-bridge status` checks stored bridge profiles, and `passport-bridge logout --profile <name>` revokes one.
280
+
281
+ Run `passport-bridge --help` for the complete bridge command surface or
282
+ `passport-bridge --version` to print the installed package version.
package/dist/cli.js CHANGED
@@ -1,7 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import { spawn } from "node:child_process";
3
+ import { randomUUID } from "node:crypto";
3
4
  import { getProfile, writeProfile, removeProfile, readCreds, credsPath, withProfileLock } from "./credentials.js";
4
5
  import { TokenManager, runBridge, log } from "./bridge.js";
6
+ import { VERSION } from "./version.js";
5
7
  /**
6
8
  * passport-bridge — the local tier.
7
9
  *
@@ -20,6 +22,10 @@ function arg(flag, fallback = "") {
20
22
  }
21
23
  async function main() {
22
24
  const command = process.argv[2] ?? "serve";
25
+ if (process.argv.includes("--help") || process.argv.includes("-h") || command === "help")
26
+ return help();
27
+ if (command === "--version" || command === "-V" || command === "version")
28
+ return version();
23
29
  if (command === "serve")
24
30
  return serve();
25
31
  if (command === "login")
@@ -28,9 +34,33 @@ async function main() {
28
34
  return logout();
29
35
  if (command === "status")
30
36
  return status();
31
- process.stderr.write(`Unknown command: ${command}\nUsage: passport-bridge <login|serve|status|logout>\n`);
37
+ process.stderr.write(`Unknown command: ${command}\nRun \`passport-bridge --help\` for usage.\n`);
32
38
  process.exit(1);
33
39
  }
40
+ function help() {
41
+ process.stdout.write(`Passport bridge ${VERSION}
42
+
43
+ Usage: passport-bridge [command] [options]
44
+
45
+ Commands:
46
+ serve Connect an MCP client using a saved profile (default)
47
+ login Sign in and save a rotating bridge credential
48
+ status Check saved bridge profiles
49
+ logout Revoke and remove a saved profile
50
+
51
+ Options:
52
+ --profile <name> Use a named profile (default: default)
53
+ --cloud <url> Passport URL for login
54
+ --workspace <id> Workspace for login
55
+ --client <name> AI client identity for login
56
+ --target <target> Credential target for login
57
+ -h, --help Show this help
58
+ -V, --version Show the package version
59
+ `);
60
+ }
61
+ function version() {
62
+ process.stdout.write(`${VERSION}\n`);
63
+ }
34
64
  async function serve() {
35
65
  const profile = arg("--profile", "default");
36
66
  let endpoint = process.env.PASSPORT_ENDPOINT ?? "";
@@ -78,6 +108,8 @@ async function login() {
78
108
  // resolve a tenant from a bare device/start (there's no session yet), so the
79
109
  // install instructions always pass this; the whole approve chain stays in it.
80
110
  const workspace = arg("--workspace", "");
111
+ const storedInstanceId = getProfile(profile)?.instanceId;
112
+ const instanceId = storedInstanceId && /^[A-Za-z0-9._:-]{1,128}$/.test(storedInstanceId) ? storedInstanceId : randomUUID();
81
113
  const out = (s) => process.stdout.write(s + "\n");
82
114
  const ws = workspace ? `?ws=${encodeURIComponent(workspace)}` : "";
83
115
  const start = await fetch(`${cloud}/api/auth/device/start${ws}`, { method: "POST" });
@@ -117,12 +149,12 @@ async function login() {
117
149
  const cred = await fetch(`${cloud}/api/my/bridge-credential`, {
118
150
  method: "POST",
119
151
  headers: { "content-type": "application/json", authorization: `Bearer ${sessionToken}` },
120
- body: JSON.stringify({ client, target })
152
+ body: JSON.stringify({ client, target, instanceId, instanceLabel: profile })
121
153
  });
122
154
  if (!cred.ok)
123
155
  throw new Error("Couldn't get a credential. Is your account active?");
124
156
  const { refreshToken, endpoint } = (await cred.json());
125
- writeProfile(profile, { refreshToken, endpoint });
157
+ writeProfile(profile, { refreshToken, endpoint, instanceId });
126
158
  out("");
127
159
  out(` ✓ Signed in. Saved profile "${profile}" to ${credsPath()}`);
128
160
  out(` Now point your AI app at: passport-bridge serve --profile ${profile}`);
package/dist/cliArgs.js CHANGED
@@ -9,6 +9,7 @@ export const COMMANDS = [
9
9
  "connect",
10
10
  "resources",
11
11
  "prompts",
12
+ "discover",
12
13
  "completion",
13
14
  "help",
14
15
  "version"
@@ -127,6 +128,7 @@ function validateShape(command, positionals) {
127
128
  run: 2,
128
129
  resources: 1,
129
130
  prompts: 1,
131
+ discover: 0,
130
132
  completion: 1,
131
133
  help: 1,
132
134
  version: 0
package/dist/cliClient.js CHANGED
@@ -55,10 +55,13 @@ export class CliGateway {
55
55
  transport;
56
56
  timeoutMs;
57
57
  signal;
58
+ apiFetch;
59
+ origin;
58
60
  closed = false;
59
61
  constructor(options) {
60
62
  this.timeoutMs = options.timeoutMs;
61
63
  this.signal = options.signal;
64
+ this.origin = new URL(options.auth.endpoint).origin;
62
65
  let authedFetch;
63
66
  if (options.auth.kind === "agent-key") {
64
67
  authedFetch = decorateFetch(fetch, {
@@ -77,6 +80,7 @@ export class CliGateway {
77
80
  ? decorateFetch(manager.authedFetch, { "x-passport-caller": options.caller })
78
81
  : manager.authedFetch;
79
82
  }
83
+ this.apiFetch = authedFetch;
80
84
  this.transport = new StreamableHTTPClientTransport(new URL(options.auth.endpoint), { fetch: authedFetch });
81
85
  }
82
86
  static async connect(options) {
@@ -116,6 +120,14 @@ export class CliGateway {
116
120
  callTool(name, args, timeoutMs = this.timeoutMs) {
117
121
  return this.client.callTool({ name, arguments: args }, undefined, this.requestOptions(timeoutMs));
118
122
  }
123
+ /** Authenticated same-origin REST call for control-plane commands such as
124
+ * fleet discovery. The caller supplies only a path; credentials never leave
125
+ * the Passport origin pinned by the saved profile. */
126
+ fetchApi(path, init) {
127
+ if (!path.startsWith("/") || path.startsWith("//"))
128
+ throw new Error("Passport API path must be relative.");
129
+ return this.apiFetch(`${this.origin}${path}`, init);
130
+ }
119
131
  async listResources() {
120
132
  const resources = [];
121
133
  let cursor;
@@ -10,6 +10,7 @@ const DESCRIPTIONS = {
10
10
  connect: "Connect member MCP accounts",
11
11
  resources: "List or read MCP resources",
12
12
  prompts: "List or get MCP prompts",
13
+ discover: "Scan local MCP configuration for fleet governance",
13
14
  completion: "Generate shell completion",
14
15
  help: "Show command help",
15
16
  version: "Show CLI version and local context"
@@ -36,7 +36,10 @@ export function writeProfile(name, profile) {
36
36
  assertProfileName(name);
37
37
  withStoreWriteLock(() => {
38
38
  const creds = readCreds();
39
- creds[name] = profile;
39
+ // Token rotation rewrites only the credential fields. Preserve the stable
40
+ // profile instance id so repeated CLI processes and re-logins remain one
41
+ // independently revocable connection instead of creating phantom devices.
42
+ creds[name] = { ...creds[name], ...profile };
40
43
  writeCredsAtomic(creds);
41
44
  });
42
45
  }
@@ -0,0 +1,234 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
3
+ import { homedir, hostname, platform } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+ /**
6
+ * A managed scanner is the enforcement boundary Passport can verify today.
7
+ * `require_passport` fails every active direct connection unless an admin has
8
+ * explicitly approved it or granted an exception. `block` is narrower: it
9
+ * fails entries an admin explicitly denied. Endpoint management can use the
10
+ * exit code as a compliance gate without Passport editing client config.
11
+ */
12
+ export function evaluateDiscoveryCompliance(report) {
13
+ const active = (report.assets ?? []).filter((asset) => (asset.connectionCount ?? 0) > 0);
14
+ const routeRequired = active.filter((asset) => !["approved", "exception"].includes(String(asset.decision?.state ?? "review"))).length;
15
+ const denied = active.filter((asset) => asset.decision?.state === "denied").length;
16
+ const enforcement = String(report.policy?.enforcement ?? "observe");
17
+ const noncompliant = report.policy?.fleetMode === "managed" &&
18
+ ((enforcement === "require_passport" && routeRequired > 0) ||
19
+ (enforcement === "block" && denied > 0));
20
+ return { compliant: !noncompliant, routeRequired, denied };
21
+ }
22
+ function appConfigRoot(env) {
23
+ if (platform() === "darwin")
24
+ return join(homedir(), "Library", "Application Support");
25
+ if (platform() === "win32")
26
+ return env.APPDATA || join(homedir(), "AppData", "Roaming");
27
+ return env.XDG_CONFIG_HOME || join(homedir(), ".config");
28
+ }
29
+ function jsonSpecs(env) {
30
+ const app = appConfigRoot(env);
31
+ return [
32
+ { client: "claude", path: join(app, "Claude", "claude_desktop_config.json"), root: "mcpServers" },
33
+ { client: "claude-code", path: join(homedir(), ".claude.json"), root: "mcpServers" },
34
+ { client: "cursor", path: join(homedir(), ".cursor", "mcp.json"), root: "mcpServers" },
35
+ { client: "vscode", path: join(app, "Code", "User", "mcp.json"), root: "servers" }
36
+ ];
37
+ }
38
+ function safeName(raw) {
39
+ const value = raw.replace(/[\u0000-\u001f\u007f]/g, "").trim().slice(0, 80);
40
+ if (!value ||
41
+ value.startsWith("/") ||
42
+ value.includes("\\") ||
43
+ value.includes("://") ||
44
+ /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value) ||
45
+ (value.length >= 40 && !/\s/.test(value) && /^[A-Za-z0-9_-]+$/.test(value))) {
46
+ return "MCP name hidden";
47
+ }
48
+ return value;
49
+ }
50
+ function executableClass(command) {
51
+ const leaf = command.trim().split(/[\\/]/).pop()?.split(/\s+/)[0]?.toLowerCase() ?? "";
52
+ const allow = new Set(["npx", "npm", "node", "uvx", "uv", "python", "python3", "docker", "deno", "bun", "passport", "passport-bridge"]);
53
+ return allow.has(leaf) ? leaf : "executable hidden";
54
+ }
55
+ export function inspectDiscoveryEntry(client, rawName, raw, passportOrigin) {
56
+ const entry = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
57
+ const name = safeName(rawName);
58
+ const urlValue = [entry.url, entry.serverUrl].find((value) => typeof value === "string");
59
+ const command = typeof entry.command === "string" ? entry.command : "";
60
+ const protectedSettings = Boolean(entry.env && typeof entry.env === "object" && Object.keys(entry.env).length) ||
61
+ Boolean(entry.headers && typeof entry.headers === "object" && Object.keys(entry.headers).length) ||
62
+ Boolean(urlValue && /[?#]|https?:\/\/[^/\s]*@/i.test(urlValue));
63
+ if (urlValue) {
64
+ let host = "address hidden";
65
+ let governed = false;
66
+ let safe = false;
67
+ try {
68
+ const parsed = new URL(urlValue);
69
+ if (parsed.protocol === "http:" || parsed.protocol === "https:") {
70
+ host = parsed.hostname.slice(0, 253) || host;
71
+ safe = !parsed.username && !parsed.password && !parsed.search && !parsed.hash;
72
+ const passport = new URL(passportOrigin);
73
+ governed =
74
+ parsed.origin === passport.origin &&
75
+ (/^\/(?:w\/[^/]+\/)?mcp$/.test(parsed.pathname) || /^\/(?:s|b)\/[^/]+\/mcp$/.test(parsed.pathname));
76
+ }
77
+ }
78
+ catch {
79
+ /* classified without retaining the invalid address */
80
+ }
81
+ const transport = typeof entry.type === "string" && entry.type.toLowerCase() === "sse" ? "sse" : "http";
82
+ return {
83
+ client,
84
+ name,
85
+ governance: governed ? "governed" : "unmanaged",
86
+ transport,
87
+ detail: `Remote server · ${host}`,
88
+ canImport: safe && !governed && rawName !== "passport",
89
+ protectedSettings
90
+ };
91
+ }
92
+ if (command) {
93
+ const commandClass = executableClass(command);
94
+ const args = Array.isArray(entry.args) ? entry.args.filter((value) => typeof value === "string") : [];
95
+ const governed = commandClass === "passport" ||
96
+ commandClass === "passport-bridge" ||
97
+ args.some((value) => /(?:^|[\\/])passport-bridge(?:\.exe)?$/i.test(value));
98
+ return {
99
+ client,
100
+ name,
101
+ governance: governed ? "governed" : "unmanaged",
102
+ transport: "stdio",
103
+ detail: `Local command · ${commandClass}`,
104
+ canImport: false,
105
+ protectedSettings
106
+ };
107
+ }
108
+ return {
109
+ client,
110
+ name,
111
+ governance: "unmanaged",
112
+ transport: "unknown",
113
+ detail: "Configuration · details hidden",
114
+ canImport: false,
115
+ protectedSettings
116
+ };
117
+ }
118
+ function readJsonSource(spec, passportOrigin) {
119
+ if (!existsSync(spec.path))
120
+ return { client: spec.client, status: "missing", servers: [] };
121
+ try {
122
+ const parsed = JSON.parse(readFileSync(spec.path, "utf8"));
123
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
124
+ return { client: spec.client, status: "invalid", servers: [] };
125
+ }
126
+ const root = parsed[spec.root];
127
+ if (root === undefined)
128
+ return { client: spec.client, status: "ready", servers: [] };
129
+ if (!root || typeof root !== "object" || Array.isArray(root)) {
130
+ return { client: spec.client, status: "invalid", servers: [] };
131
+ }
132
+ return {
133
+ client: spec.client,
134
+ status: "ready",
135
+ servers: Object.entries(root)
136
+ .slice(0, 100)
137
+ .map(([name, entry]) => inspectDiscoveryEntry(spec.client, name, entry, passportOrigin))
138
+ };
139
+ }
140
+ catch (error) {
141
+ const code = error.code;
142
+ return {
143
+ client: spec.client,
144
+ status: code === "EACCES" || code === "EPERM" ? "permission_denied" : error instanceof SyntaxError ? "invalid" : "unreadable",
145
+ servers: []
146
+ };
147
+ }
148
+ }
149
+ function unquoteToml(value) {
150
+ const trimmed = value.trim();
151
+ if ((trimmed.startsWith('"') && trimmed.endsWith('"')) ||
152
+ (trimmed.startsWith("'") && trimmed.endsWith("'"))) {
153
+ return trimmed.slice(1, -1);
154
+ }
155
+ return trimmed;
156
+ }
157
+ function readCodex(passportOrigin) {
158
+ const path = join(homedir(), ".codex", "config.toml");
159
+ if (!existsSync(path))
160
+ return { client: "codex", status: "missing", servers: [] };
161
+ try {
162
+ const text = readFileSync(path, "utf8");
163
+ const entries = new Map();
164
+ let current = "";
165
+ for (const line of text.split(/\r?\n/)) {
166
+ const section = line.match(/^\s*\[mcp_servers\.((?:"[^"]+")|(?:'[^']+')|(?:[A-Za-z0-9_.-]+))\]\s*(?:#.*)?$/);
167
+ if (section) {
168
+ current = unquoteToml(section[1]);
169
+ if (!entries.has(current))
170
+ entries.set(current, {});
171
+ continue;
172
+ }
173
+ if (!current)
174
+ continue;
175
+ const field = line.match(/^\s*(command|url|server_url)\s*=\s*(.+?)\s*(?:#.*)?$/);
176
+ if (!field)
177
+ continue;
178
+ entries.get(current)[field[1] === "server_url" ? "serverUrl" : field[1]] = unquoteToml(field[2]);
179
+ }
180
+ return {
181
+ client: "codex",
182
+ status: "ready",
183
+ servers: [...entries.entries()].slice(0, 100).map(([name, entry]) => inspectDiscoveryEntry("codex", name, entry, passportOrigin))
184
+ };
185
+ }
186
+ catch (error) {
187
+ const code = error.code;
188
+ return {
189
+ client: "codex",
190
+ status: code === "EACCES" || code === "EPERM" ? "permission_denied" : "unreadable",
191
+ servers: []
192
+ };
193
+ }
194
+ }
195
+ function installationFile(env) {
196
+ const base = platform() === "win32"
197
+ ? env.LOCALAPPDATA || join(homedir(), "AppData", "Local")
198
+ : env.XDG_STATE_HOME || join(homedir(), ".local", "state");
199
+ return join(base, "passport", "fleet-installation.json");
200
+ }
201
+ function installationId(env) {
202
+ const path = installationFile(env);
203
+ try {
204
+ const saved = JSON.parse(readFileSync(path, "utf8"));
205
+ if (typeof saved.id === "string" && /^[A-Za-z0-9._:-]{1,128}$/.test(saved.id))
206
+ return saved.id;
207
+ }
208
+ catch {
209
+ /* create below */
210
+ }
211
+ const id = `fleet-${randomUUID()}`;
212
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
213
+ const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
214
+ writeFileSync(temporary, `${JSON.stringify({ id })}\n`, { mode: 0o600 });
215
+ renameSync(temporary, path);
216
+ return id;
217
+ }
218
+ export function scanLocalMcpConfigs(passportOrigin, env = process.env) {
219
+ const sources = [
220
+ ...jsonSpecs(env).map((spec) => readJsonSource(spec, passportOrigin)),
221
+ readCodex(passportOrigin)
222
+ ];
223
+ return {
224
+ scanId: `dscan_${randomUUID()}`,
225
+ scannedAt: Date.now(),
226
+ installationId: installationId(env),
227
+ installationLabel: hostname().replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 80) || "Managed computer",
228
+ sources
229
+ };
230
+ }
231
+ /** Contract helper: no prohibited local detail may enter the wire snapshot. */
232
+ export function discoverySnapshotFingerprint(snapshot) {
233
+ return createHash("sha256").update(JSON.stringify(snapshot)).digest("hex");
234
+ }
@@ -0,0 +1,51 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { evaluateDiscoveryCompliance, inspectDiscoveryEntry } from "./discover.js";
4
+ test("fleet discovery reduces remote configuration to safe metadata", () => {
5
+ const finding = inspectDiscoveryEntry("cursor", "Private docs", {
6
+ url: "https://api.example.test/private/customer/path?token=do-not-upload",
7
+ headers: { authorization: "Bearer do-not-upload" }
8
+ }, "https://passportmcp.com");
9
+ assert.deepEqual(finding, {
10
+ client: "cursor",
11
+ name: "Private docs",
12
+ governance: "unmanaged",
13
+ transport: "http",
14
+ detail: "Remote server · api.example.test",
15
+ canImport: false,
16
+ protectedSettings: true
17
+ });
18
+ assert.equal(JSON.stringify(finding).includes("customer/path"), false);
19
+ assert.equal(JSON.stringify(finding).includes("do-not-upload"), false);
20
+ });
21
+ test("fleet discovery never uploads local command arguments or environment values", () => {
22
+ const finding = inspectDiscoveryEntry("claude-code", "Local database", {
23
+ command: "/Users/alice/private/bin/custom-server",
24
+ args: ["--database", "customer-production"],
25
+ env: { DATABASE_URL: "postgres://secret" }
26
+ }, "https://passportmcp.com");
27
+ assert.equal(finding.detail, "Local command · executable hidden");
28
+ assert.equal(finding.protectedSettings, true);
29
+ assert.equal(JSON.stringify(finding).includes("/Users/alice"), false);
30
+ assert.equal(JSON.stringify(finding).includes("customer-production"), false);
31
+ assert.equal(JSON.stringify(finding).includes("postgres://secret"), false);
32
+ });
33
+ test("fleet discovery recognizes only exact Passport MCP paths as governed", () => {
34
+ const governed = inspectDiscoveryEntry("codex", "passport", { url: "https://passportmcp.com/w/ws_example/mcp" }, "https://passportmcp.com");
35
+ const lookalike = inspectDiscoveryEntry("codex", "lookalike", { url: "https://passportmcp.com.evil.example/mcp" }, "https://passportmcp.com");
36
+ assert.equal(governed.governance, "governed");
37
+ assert.equal(lookalike.governance, "unmanaged");
38
+ });
39
+ test("managed compliance distinguishes required routing from explicit denial", () => {
40
+ const assets = [
41
+ { connectionCount: 1, decision: null },
42
+ { connectionCount: 1, decision: { state: "approved" } },
43
+ { connectionCount: 1, decision: { state: "denied" } },
44
+ { connectionCount: 0, decision: { state: "denied" } }
45
+ ];
46
+ assert.deepEqual(evaluateDiscoveryCompliance({ assets, policy: { fleetMode: "managed", enforcement: "require_passport" } }), { compliant: false, routeRequired: 2, denied: 1 });
47
+ assert.deepEqual(evaluateDiscoveryCompliance({
48
+ assets: assets.map((asset) => asset.decision?.state === "denied" ? { ...asset, decision: { state: "exception" } } : asset),
49
+ policy: { fleetMode: "managed", enforcement: "block" }
50
+ }), { compliant: true, routeRequired: 1, denied: 0 });
51
+ });
package/dist/passport.js CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { spawn } from "node:child_process";
3
+ import { randomUUID } from "node:crypto";
3
4
  import { readFileSync, realpathSync, writeFileSync } from "node:fs";
4
5
  import { fileURLToPath } from "node:url";
5
6
  import { ArgError, bool, parseArgs, repeated, value } from "./cliArgs.js";
@@ -196,8 +197,8 @@ async function login(args, runtime) {
196
197
  }
197
198
  const explicitProfile = value(args, "profile");
198
199
  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 : "");
200
+ const requestedExisting = requestedProfile ? getProfile(requestedProfile) : undefined;
201
+ const cloudRaw = value(args, "cloud") || runtime.env.PASSPORT_CLOUD || (requestedExisting ? new URL(endpoint(requestedExisting.endpoint)).origin : "");
201
202
  if (!cloudRaw)
202
203
  return failure("--cloud <origin> is required for the first login.", 6, "usage");
203
204
  const cloud = cloudOrigin(cloudRaw);
@@ -240,10 +241,20 @@ async function login(args, runtime) {
240
241
  }
241
242
  if (!sessionToken)
242
243
  return failure("Timed out waiting for sign-in approval.", 2, "auth");
244
+ const tokenWorkspace = workspace || (await import("./bridge.js")).workspaceOfToken(sessionToken) || "workspace";
245
+ const profile = profileName(requestedProfile || `cli@${tokenWorkspace}`);
246
+ const storedInstanceId = getProfile(profile)?.instanceId;
247
+ const instanceId = storedInstanceId && /^[A-Za-z0-9._:-]{1,128}$/.test(storedInstanceId) ? storedInstanceId : randomUUID();
243
248
  const credential = await timedFetch(`${cloud}/api/my/bridge-credential`, {
244
249
  method: "POST",
245
250
  headers: { "content-type": "application/json", authorization: `Bearer ${sessionToken}` },
246
- body: JSON.stringify({ client, target: "workspace", surface: "cli" })
251
+ body: JSON.stringify({
252
+ client,
253
+ target: "workspace",
254
+ surface: "cli",
255
+ instanceId,
256
+ instanceLabel: profile
257
+ })
247
258
  }, timeoutMs(args), runtime.signal);
248
259
  if (!credential.ok) {
249
260
  const message = await safeApiError(credential, "Could not create a CLI credential.");
@@ -254,9 +265,11 @@ async function login(args, runtime) {
254
265
  return failure("Passport returned an invalid credential response.", 1, "invalid_server_response");
255
266
  }
256
267
  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 }));
268
+ await withProfileLock(profile, async () => writeProfile(profile, {
269
+ refreshToken: body.refreshToken,
270
+ endpoint: credentialEndpoint,
271
+ instanceId
272
+ }));
260
273
  return {
261
274
  json: { profile, endpoint: credentialEndpoint, client, surface: "cli" },
262
275
  human: `Signed in as profile "${profile}".\nCredential saved to ${credsPath()}.`
@@ -350,6 +363,40 @@ async function doctor(args, runtime) {
350
363
  exitCode: report.ok ? 0 : 1
351
364
  };
352
365
  }
366
+ async function discover(args, runtime) {
367
+ return withGateway(args, runtime, async (gateway) => {
368
+ const { evaluateDiscoveryCompliance, scanLocalMcpConfigs } = await import("./discover.js");
369
+ const snapshot = scanLocalMcpConfigs(gateway.origin, runtime.env);
370
+ const response = await gateway.fetchApi("/api/my/discovery/scan", {
371
+ method: "POST",
372
+ headers: { "content-type": "application/json" },
373
+ body: JSON.stringify(snapshot),
374
+ signal: runtime.signal
375
+ });
376
+ if (!response.ok) {
377
+ const message = await safeApiError(response, "Could not submit the fleet discovery scan.");
378
+ return failure(message, response.status === 401 || response.status === 403 ? 2 : 1, "server");
379
+ }
380
+ const report = (await response.json());
381
+ const direct = Number(report.stats?.directConnections ?? 0);
382
+ const review = Number(report.stats?.needsReview ?? 0);
383
+ const enforcement = String(report.policy?.enforcement ?? "observe");
384
+ const compliance = evaluateDiscoveryCompliance(report);
385
+ return {
386
+ json: { snapshot, report, compliant: compliance.compliant },
387
+ human: [
388
+ `Fleet discovery scan submitted from ${snapshot.installationLabel}.`,
389
+ `${direct} direct MCP configuration${direct === 1 ? "" : "s"} · ${review} awaiting review.`,
390
+ `Workspace policy: ${String(report.policy?.fleetMode ?? "personal")} / ${enforcement}.`,
391
+ !compliance.compliant
392
+ ? `${compliance.routeRequired} must route through Passport · ${compliance.denied} denied.`
393
+ : "No enforced fleet-policy violation was reported."
394
+ ].join("\n"),
395
+ essential: true,
396
+ exitCode: compliance.compliant ? 0 : 5
397
+ };
398
+ });
399
+ }
353
400
  async function search(args, runtime) {
354
401
  const query = args.positionals.join(" ").trim();
355
402
  if (value(args, "app") !== undefined && !value(args, "app").trim())
@@ -741,6 +788,8 @@ async function dispatch(args, runtime) {
741
788
  return resources(args, runtime);
742
789
  case "prompts":
743
790
  return prompts(args, runtime);
791
+ case "discover":
792
+ return discover(args, runtime);
744
793
  case "completion":
745
794
  return completion(args);
746
795
  case "help":
@@ -761,6 +810,7 @@ function helpText(verb) {
761
810
  connect: "passport connect [app...] [--alias <name>] [--open] [--wait <sec>]\nShows member-bound connection links and can wait for sign-in to finish. JSON is the manage_connections payload.",
762
811
  resources: "passport resources [uri] [--out <file>]\nLists or reads workspace MCP resources. Binary content requires --out or --json.",
763
812
  prompts: "passport prompts [name] [--set key=value] [--out <file>]\nLists or gets workspace MCP prompts. Binary content requires --out or --json.",
813
+ discover: "passport discover\nScans supported local MCP configuration, submits privacy-minimized inventory, and exits 5 when a managed policy reports a violation.",
764
814
  completion: "passport completion <bash|zsh|fish>\nPrints an offline shell-completion script to stdout.",
765
815
  help: "passport help [verb]",
766
816
  version: "passport version\nWorks without a profile or network."
@@ -781,6 +831,7 @@ Usage: passport <command> [options]
781
831
  connect Connect member MCP accounts
782
832
  resources List or read MCP resources
783
833
  prompts List or get MCP prompts
834
+ discover Scan this computer for direct MCP configuration
784
835
  completion Generate bash, zsh, or fish completion
785
836
  help Show command help
786
837
  version Show CLI version and local context
package/dist/version.js CHANGED
@@ -1,3 +1,3 @@
1
1
  // Keep in lockstep with bridge/package.json. The published bridge can run from
2
2
  // a compiled sidecar where package.json is not available at runtime.
3
- export const VERSION = "0.6.0";
3
+ export const VERSION = "0.7.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "passport-bridge",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Passport CLI for governed terminal and CI agents, plus the local stdio-to-cloud MCP bridge.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -45,8 +45,8 @@
45
45
  "@modelcontextprotocol/sdk": "^1.29.0"
46
46
  },
47
47
  "devDependencies": {
48
- "@types/node": "^24.10.1",
49
- "tsx": "^4.20.6",
48
+ "@types/node": "^24.13.1",
49
+ "tsx": "^4.23.1",
50
50
  "typescript": "^5.9.3"
51
51
  }
52
52
  }