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.
package/dist/discover.js CHANGED
@@ -1,7 +1,9 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
+ import { existsSync } from "node:fs";
3
3
  import { homedir, hostname, platform } from "node:os";
4
- import { dirname, join } from "node:path";
4
+ import { join } from "node:path";
5
+ import { readOrCreatePrivateStableFile } from "./privateStableFile.js";
6
+ import { readBoundedUtf8File } from "./boundedFile.js";
5
7
  /**
6
8
  * A managed scanner is the enforcement boundary Passport can verify today.
7
9
  * `require_passport` fails every active direct connection unless an admin has
@@ -15,10 +17,10 @@ export function evaluateDiscoveryCompliance(report) {
15
17
  const denied = active.filter((asset) => asset.decision?.state === "denied").length;
16
18
  const enforcement = String(report.policy?.enforcement ?? "observe");
17
19
  const noncompliant = report.policy?.fleetMode === "managed" &&
18
- ((enforcement === "require_passport" && routeRequired > 0) ||
19
- (enforcement === "block" && denied > 0));
20
+ ((enforcement === "require_passport" && routeRequired > 0) || (enforcement === "block" && denied > 0));
20
21
  return { compliant: !noncompliant, routeRequired, denied };
21
22
  }
23
+ const LOCAL_MCP_CONFIG_MAX_BYTES = 2 * 1024 * 1024;
22
24
  function appConfigRoot(env) {
23
25
  if (platform() === "darwin")
24
26
  return join(homedir(), "Library", "Application Support");
@@ -36,7 +38,10 @@ function jsonSpecs(env) {
36
38
  ];
37
39
  }
38
40
  function safeName(raw) {
39
- const value = raw.replace(/[\u0000-\u001f\u007f]/g, "").trim().slice(0, 80);
41
+ const value = raw
42
+ .replace(/[\u0000-\u001f\u007f]/g, "")
43
+ .trim()
44
+ .slice(0, 80);
40
45
  if (!value ||
41
46
  value.startsWith("/") ||
42
47
  value.includes("\\") ||
@@ -49,7 +54,20 @@ function safeName(raw) {
49
54
  }
50
55
  function executableClass(command) {
51
56
  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"]);
57
+ const allow = new Set([
58
+ "npx",
59
+ "npm",
60
+ "node",
61
+ "uvx",
62
+ "uv",
63
+ "python",
64
+ "python3",
65
+ "docker",
66
+ "deno",
67
+ "bun",
68
+ "passport",
69
+ "passport-bridge"
70
+ ]);
53
71
  return allow.has(leaf) ? leaf : "executable hidden";
54
72
  }
55
73
  export function inspectDiscoveryEntry(client, rawName, raw, passportOrigin) {
@@ -91,7 +109,9 @@ export function inspectDiscoveryEntry(client, rawName, raw, passportOrigin) {
91
109
  }
92
110
  if (command) {
93
111
  const commandClass = executableClass(command);
94
- const args = Array.isArray(entry.args) ? entry.args.filter((value) => typeof value === "string") : [];
112
+ const args = Array.isArray(entry.args)
113
+ ? entry.args.filter((value) => typeof value === "string")
114
+ : [];
95
115
  const governed = commandClass === "passport" ||
96
116
  commandClass === "passport-bridge" ||
97
117
  args.some((value) => /(?:^|[\\/])passport-bridge(?:\.exe)?$/i.test(value));
@@ -119,7 +139,7 @@ function readJsonSource(spec, passportOrigin) {
119
139
  if (!existsSync(spec.path))
120
140
  return { client: spec.client, status: "missing", servers: [] };
121
141
  try {
122
- const parsed = JSON.parse(readFileSync(spec.path, "utf8"));
142
+ const parsed = JSON.parse(readBoundedUtf8File(spec.path, LOCAL_MCP_CONFIG_MAX_BYTES));
123
143
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
124
144
  return { client: spec.client, status: "invalid", servers: [] };
125
145
  }
@@ -141,15 +161,18 @@ function readJsonSource(spec, passportOrigin) {
141
161
  const code = error.code;
142
162
  return {
143
163
  client: spec.client,
144
- status: code === "EACCES" || code === "EPERM" ? "permission_denied" : error instanceof SyntaxError ? "invalid" : "unreadable",
164
+ status: code === "EACCES" || code === "EPERM"
165
+ ? "permission_denied"
166
+ : error instanceof SyntaxError
167
+ ? "invalid"
168
+ : "unreadable",
145
169
  servers: []
146
170
  };
147
171
  }
148
172
  }
149
173
  function unquoteToml(value) {
150
174
  const trimmed = value.trim();
151
- if ((trimmed.startsWith('"') && trimmed.endsWith('"')) ||
152
- (trimmed.startsWith("'") && trimmed.endsWith("'"))) {
175
+ if ((trimmed.startsWith('"') && trimmed.endsWith('"')) || (trimmed.startsWith("'") && trimmed.endsWith("'"))) {
153
176
  return trimmed.slice(1, -1);
154
177
  }
155
178
  return trimmed;
@@ -159,7 +182,7 @@ function readCodex(passportOrigin) {
159
182
  if (!existsSync(path))
160
183
  return { client: "codex", status: "missing", servers: [] };
161
184
  try {
162
- const text = readFileSync(path, "utf8");
185
+ const text = readBoundedUtf8File(path, LOCAL_MCP_CONFIG_MAX_BYTES);
163
186
  const entries = new Map();
164
187
  let current = "";
165
188
  for (const line of text.split(/\r?\n/)) {
@@ -180,7 +203,9 @@ function readCodex(passportOrigin) {
180
203
  return {
181
204
  client: "codex",
182
205
  status: "ready",
183
- servers: [...entries.entries()].slice(0, 100).map(([name, entry]) => inspectDiscoveryEntry("codex", name, entry, passportOrigin))
206
+ servers: [...entries.entries()]
207
+ .slice(0, 100)
208
+ .map(([name, entry]) => inspectDiscoveryEntry("codex", name, entry, passportOrigin))
184
209
  };
185
210
  }
186
211
  catch (error) {
@@ -198,33 +223,34 @@ function installationFile(env) {
198
223
  : env.XDG_STATE_HOME || join(homedir(), ".local", "state");
199
224
  return join(base, "passport", "fleet-installation.json");
200
225
  }
201
- function installationId(env) {
226
+ export function fleetInstallationId(env = process.env) {
202
227
  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;
228
+ return readOrCreatePrivateStableFile({
229
+ target: path,
230
+ label: "fleet installation identity",
231
+ temporaryPrefix: ".fleet-installation",
232
+ maxBytes: 4096,
233
+ create: () => `${JSON.stringify({ id: `fleet-${randomUUID()}` })}\n`,
234
+ parse(contents) {
235
+ try {
236
+ const saved = JSON.parse(contents);
237
+ return typeof saved.id === "string" && /^[A-Za-z0-9._:-]{1,128}$/.test(saved.id) ? saved.id : undefined;
238
+ }
239
+ catch {
240
+ return undefined;
241
+ }
242
+ }
243
+ });
217
244
  }
218
245
  export function scanLocalMcpConfigs(passportOrigin, env = process.env) {
219
- const sources = [
220
- ...jsonSpecs(env).map((spec) => readJsonSource(spec, passportOrigin)),
221
- readCodex(passportOrigin)
222
- ];
246
+ const sources = [...jsonSpecs(env).map((spec) => readJsonSource(spec, passportOrigin)), readCodex(passportOrigin)];
223
247
  return {
224
248
  scanId: `dscan_${randomUUID()}`,
225
249
  scannedAt: Date.now(),
226
- installationId: installationId(env),
227
- installationLabel: hostname().replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 80) || "Managed computer",
250
+ installationId: fleetInstallationId(env),
251
+ installationLabel: hostname()
252
+ .replace(/[\u0000-\u001f\u007f]/g, "")
253
+ .slice(0, 80) || "Managed computer",
228
254
  sources
229
255
  };
230
256
  }
package/dist/doctor.js CHANGED
@@ -1,18 +1,33 @@
1
- import { lstatSync, readFileSync } from "node:fs";
1
+ import { lstatSync } from "node:fs";
2
+ import { readBoundedUtf8File } from "./boundedFile.js";
2
3
  import { CliGateway, CLI_PROTOCOL_TOOLS, MIN_CLI_SERVER_VERSION } from "./cliClient.js";
3
- import { assertProfileName, credsPath } from "./credentials.js";
4
+ import { activeProfilePath, assertProfileName, credsPath } from "./credentials.js";
5
+ import { ensurePrivateDirectory } from "./credentialStorage.js";
6
+ const DOCTOR_CREDENTIAL_MAX_BYTES = 1024 * 1024;
7
+ const DOCTOR_ACTIVE_PROFILE_MAX_BYTES = 512;
4
8
  function check(checks, id, status, summary, action) {
5
9
  checks.push({ id, status, summary, ...(action ? { action } : {}) });
6
10
  }
7
11
  function inspectStore(checks, agentMode) {
8
12
  const empty = Object.create(null);
13
+ try {
14
+ ensurePrivateDirectory(false);
15
+ }
16
+ catch {
17
+ check(checks, "credential_store", "fail", "The Passport credential directory is not an owner-controlled regular directory.", "Replace it with a regular directory owned by this account.");
18
+ return { profiles: empty, count: 0 };
19
+ }
9
20
  let stat;
10
21
  try {
11
22
  stat = lstatSync(credsPath());
12
23
  }
13
24
  catch (error) {
14
25
  const missing = error.code === "ENOENT";
15
- check(checks, "credential_store", agentMode && missing ? "skip" : "fail", missing ? (agentMode ? "No local credential store is needed in agent-key mode." : "No local credential store exists.") : "The credential store could not be inspected.", missing && !agentMode ? "Run `passport login --cloud <origin> --workspace <id>`." : undefined);
26
+ check(checks, "credential_store", agentMode && missing ? "skip" : "fail", missing
27
+ ? agentMode
28
+ ? "No local credential store is needed in agent-key mode."
29
+ : "No local credential store exists."
30
+ : "The credential store could not be inspected.", missing && !agentMode ? "Run `passport login --workspace <workspace-id>`." : undefined);
16
31
  return { profiles: empty, count: 0 };
17
32
  }
18
33
  if (stat.isSymbolicLink() || !stat.isFile()) {
@@ -27,11 +42,13 @@ function inspectStore(checks, agentMode) {
27
42
  check(checks, "credential_permissions", "fail", "The credential file is owned by another account.", "Move credentials into a file owned by this account.");
28
43
  }
29
44
  else {
30
- check(checks, "credential_permissions", "pass", process.platform === "win32" ? "Credential file is a regular file (Windows ACLs apply)." : "Credential file is owner-only (0600).");
45
+ check(checks, "credential_permissions", "pass", process.platform === "win32"
46
+ ? "Credential file is a regular file (Windows ACLs apply)."
47
+ : "Credential file is owner-only (0600).");
31
48
  }
32
49
  let parsed;
33
50
  try {
34
- parsed = JSON.parse(readFileSync(credsPath(), "utf8"));
51
+ parsed = JSON.parse(readBoundedUtf8File(credsPath(), DOCTOR_CREDENTIAL_MAX_BYTES));
35
52
  }
36
53
  catch {
37
54
  check(checks, "credential_store", "fail", "The credential store is not valid JSON.", "Move the damaged file aside, then run `passport login` again.");
@@ -56,7 +73,10 @@ function inspectStore(checks, agentMode) {
56
73
  continue;
57
74
  }
58
75
  const record = raw;
59
- if (typeof record.refreshToken !== "string" || !record.refreshToken || typeof record.endpoint !== "string" || !record.endpoint) {
76
+ if (typeof record.refreshToken !== "string" ||
77
+ !record.refreshToken ||
78
+ typeof record.endpoint !== "string" ||
79
+ !record.endpoint) {
60
80
  invalid.push(name);
61
81
  continue;
62
82
  }
@@ -71,17 +91,85 @@ function inspectStore(checks, agentMode) {
71
91
  }
72
92
  return { profiles, count };
73
93
  }
94
+ function inspectActiveProfile(checks, store) {
95
+ try {
96
+ if (!ensurePrivateDirectory(false))
97
+ return undefined;
98
+ }
99
+ catch {
100
+ return undefined;
101
+ }
102
+ let stat;
103
+ try {
104
+ stat = lstatSync(activeProfilePath());
105
+ }
106
+ catch (error) {
107
+ if (error.code === "ENOENT")
108
+ return undefined;
109
+ check(checks, "active_profile", "fail", "The active-profile selection could not be inspected.", "Run `passport use <name>` to repair it.");
110
+ return undefined;
111
+ }
112
+ if (stat.isSymbolicLink() || !stat.isFile()) {
113
+ check(checks, "active_profile", "fail", "The active-profile selection is not a regular file.", "Run `passport use <name>` to repair it safely.");
114
+ return undefined;
115
+ }
116
+ if (typeof process.getuid === "function" && stat.uid !== process.getuid()) {
117
+ check(checks, "active_profile", "fail", "The active-profile selection is owned by another account.", "Remove it, then run `passport use <name>`.");
118
+ return undefined;
119
+ }
120
+ let active = "";
121
+ try {
122
+ active = readBoundedUtf8File(activeProfilePath(), DOCTOR_ACTIVE_PROFILE_MAX_BYTES).trim();
123
+ assertProfileName(active);
124
+ }
125
+ catch {
126
+ check(checks, "active_profile", "fail", "The active-profile selection is invalid.", "Run `passport use <name>` to repair it.");
127
+ return undefined;
128
+ }
129
+ if (!store.profiles[active]) {
130
+ check(checks, "active_profile", "fail", `The active profile "${active}" is not stored.`, "Run `passport profiles`, then `passport use <name>`.");
131
+ return undefined;
132
+ }
133
+ check(checks, "active_profile", "pass", `Active profile is "${active}".`);
134
+ return active;
135
+ }
74
136
  function errorText(error, redact) {
75
137
  return redact(error instanceof Error ? error.message : String(error)) || "Unknown failure.";
76
138
  }
139
+ export function nodeRuntimeSupported(version) {
140
+ const match = version.match(/^(\d+)\.(\d+)\.(\d+)/);
141
+ if (!match)
142
+ return false;
143
+ const [major, minor, patch] = match.slice(1).map(Number);
144
+ return major > 22 || (major === 22 && (minor > 23 || (minor === 23 && patch >= 2)));
145
+ }
146
+ function inspectRuntime(checks) {
147
+ const supported = nodeRuntimeSupported(process.versions.node);
148
+ check(checks, "runtime", supported ? "pass" : "fail", `Node.js ${process.versions.node}${supported ? " satisfies" : " does not satisfy"} the >=22.23.2 requirement.`, supported ? undefined : "Install Node.js 22.23.2 or newer.");
149
+ }
150
+ function selectedProfileCandidate(options, store, active) {
151
+ if (options.profile !== undefined)
152
+ return options.profile;
153
+ if (options.env.PASSPORT_PROFILE !== undefined)
154
+ return options.env.PASSPORT_PROFILE;
155
+ if (active && store.profiles[active])
156
+ return active;
157
+ const names = Object.keys(store.profiles);
158
+ return names.length === 1 ? names[0] : undefined;
159
+ }
77
160
  export async function runDoctor(options) {
78
161
  const checks = [];
79
- const nodeMajor = Number(process.versions.node.split(".")[0]);
80
- check(checks, "runtime", nodeMajor >= 20 ? "pass" : "fail", `Node.js ${process.versions.node}${nodeMajor >= 20 ? " satisfies" : " does not satisfy"} the >=20 requirement.`, nodeMajor >= 20 ? undefined : "Install Node.js 20 or newer.");
162
+ inspectRuntime(checks);
81
163
  const hasAgentKey = Boolean(options.env.PASSPORT_AGENT_KEY);
82
164
  const hasAgentEndpoint = Boolean(options.env.PASSPORT_ENDPOINT);
83
165
  const agentMode = hasAgentKey && hasAgentEndpoint;
84
- const store = inspectStore(checks, agentMode);
166
+ const store = agentMode
167
+ ? (() => {
168
+ check(checks, "credential_store", "skip", "Local profiles are not inspected in agent-key mode.");
169
+ return { profiles: Object.create(null), count: 0 };
170
+ })()
171
+ : inspectStore(checks, false);
172
+ const active = agentMode ? undefined : inspectActiveProfile(checks, store);
85
173
  let auth;
86
174
  let selectedProfile;
87
175
  if (hasAgentKey !== hasAgentEndpoint) {
@@ -104,9 +192,13 @@ export async function runDoctor(options) {
104
192
  }
105
193
  else {
106
194
  const names = Object.keys(store.profiles).sort();
107
- const candidate = options.profile ?? options.env.PASSPORT_PROFILE ?? (names.length === 1 ? names[0] : undefined);
195
+ const candidate = selectedProfileCandidate(options, store, active);
108
196
  if (!candidate) {
109
- check(checks, "auth_config", "fail", names.length > 1 ? `No profile was selected from ${names.length} stored profiles.` : "No usable profile is configured.", names.length > 1 ? "Run `passport doctor --profile <name>`." : "Run `passport login --cloud <origin> --workspace <id>`.");
197
+ check(checks, "auth_config", "fail", names.length > 1
198
+ ? `No profile was selected from ${names.length} stored profiles.`
199
+ : "No usable profile is configured.", names.length > 1
200
+ ? "Run `passport profiles`, then `passport use <name>` or retry with `--profile <name>`."
201
+ : "Run `passport login --workspace <workspace-id>`.");
110
202
  }
111
203
  else {
112
204
  try {
@@ -139,17 +231,29 @@ export async function runDoctor(options) {
139
231
  const health = await fetch(new URL("/healthz", endpointOrigin), {
140
232
  signal: AbortSignal.any([options.signal, AbortSignal.timeout(options.timeoutMs)])
141
233
  });
142
- check(checks, "server_reachability", health.ok ? "pass" : "fail", health.ok ? `Passport health endpoint responded at ${endpointOrigin}.` : `Passport health endpoint returned HTTP ${health.status}.`, health.ok ? undefined : "Verify the deployment and reverse-proxy health route.");
234
+ const healthy = health.ok;
235
+ const status = health.status;
236
+ await health.body?.cancel().catch(() => undefined);
237
+ check(checks, "server_reachability", healthy ? "pass" : "fail", healthy
238
+ ? `Passport health endpoint responded at ${endpointOrigin}.`
239
+ : `Passport health endpoint returned HTTP ${status}.`, healthy ? undefined : "Verify the deployment and reverse-proxy health route.");
143
240
  }
144
241
  catch (error) {
145
242
  check(checks, "server_reachability", "fail", `Could not reach the Passport health endpoint: ${errorText(error, options.redactError)}`, "Check DNS, TLS, proxy routing, and network access.");
146
243
  }
147
244
  let gateway;
148
245
  try {
149
- gateway = await CliGateway.connect({ auth, caller: options.caller, timeoutMs: options.timeoutMs, signal: options.signal });
246
+ gateway = await CliGateway.connect({
247
+ auth,
248
+ caller: options.caller,
249
+ timeoutMs: options.timeoutMs,
250
+ signal: options.signal
251
+ });
150
252
  }
151
253
  catch (error) {
152
- check(checks, "authentication", "fail", `Authenticated MCP handshake failed: ${errorText(error, options.redactError)}`, auth.kind === "profile" ? "Run `passport login` to refresh this profile, then retry." : "Verify PASSPORT_AGENT_KEY and its workspace access.");
254
+ check(checks, "authentication", "fail", `Authenticated MCP handshake failed: ${errorText(error, options.redactError)}`, auth.kind === "profile"
255
+ ? "Run `passport login` to refresh this profile, then retry."
256
+ : "Verify PASSPORT_AGENT_KEY and its workspace access.");
153
257
  check(checks, "server_protocol", "skip", "CLI protocol checks could not run because the authenticated handshake failed.");
154
258
  }
155
259
  if (gateway) {
@@ -158,8 +262,14 @@ export async function runDoctor(options) {
158
262
  const protocol = await gateway.protocolDiagnostics();
159
263
  const safeServer = protocol.server
160
264
  ? {
161
- name: options.redactError(protocol.server.name).replace(/[\r\n\t]/g, " ").slice(0, 80),
162
- version: options.redactError(protocol.server.version).replace(/[\r\n\t]/g, " ").slice(0, 40)
265
+ name: options
266
+ .redactError(protocol.server.name)
267
+ .replace(/[\r\n\t]/g, " ")
268
+ .slice(0, 80),
269
+ version: options
270
+ .redactError(protocol.server.version)
271
+ .replace(/[\r\n\t]/g, " ")
272
+ .slice(0, 40)
163
273
  }
164
274
  : undefined;
165
275
  server = safeServer;
@@ -0,0 +1,26 @@
1
+ import { cloudOrigin, endpoint, sameOriginWebUrl } from "./cliSupport.js";
2
+ /** Kept well below the profile lock's 30-second stale lease. */
3
+ export const LEGACY_REQUEST_TIMEOUT_MS = 10_000;
4
+ export function legacyCloudOrigin(raw) {
5
+ return cloudOrigin(raw);
6
+ }
7
+ export function legacyProfileEndpoint(raw) {
8
+ return endpoint(raw);
9
+ }
10
+ export function legacyCredentialEndpoint(raw, cloud) {
11
+ return sameOriginWebUrl(raw, cloud, "a credential endpoint");
12
+ }
13
+ export function legacyVerifyUrl(raw, cloud) {
14
+ return sameOriginWebUrl(raw, cloud, "a sign-in URL");
15
+ }
16
+ /** Every legacy network operation is finite and refuses redirects. In
17
+ * particular, a 307/308 can never replay a refresh token, session bearer, or
18
+ * device code to an origin selected by a response. */
19
+ export function legacyFetch(input, init = {}, fetcher = fetch, timeout = LEGACY_REQUEST_TIMEOUT_MS) {
20
+ const signals = [AbortSignal.timeout(timeout), ...(init.signal ? [init.signal] : [])];
21
+ return fetcher(input, {
22
+ ...init,
23
+ redirect: "error",
24
+ signal: signals.length === 1 ? signals[0] : AbortSignal.any(signals)
25
+ });
26
+ }