passport-bridge 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/doctor.js ADDED
@@ -0,0 +1,208 @@
1
+ import { lstatSync, readFileSync } from "node:fs";
2
+ import { CliGateway, CLI_PROTOCOL_TOOLS, MIN_CLI_SERVER_VERSION } from "./cliClient.js";
3
+ import { assertProfileName, credsPath } from "./credentials.js";
4
+ function check(checks, id, status, summary, action) {
5
+ checks.push({ id, status, summary, ...(action ? { action } : {}) });
6
+ }
7
+ function inspectStore(checks, agentMode) {
8
+ const empty = Object.create(null);
9
+ let stat;
10
+ try {
11
+ stat = lstatSync(credsPath());
12
+ }
13
+ catch (error) {
14
+ 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);
16
+ return { profiles: empty, count: 0 };
17
+ }
18
+ if (stat.isSymbolicLink() || !stat.isFile()) {
19
+ check(checks, "credential_store", "fail", "The credential store is not an owner-controlled regular file.", "Replace it with a regular file owned by this account.");
20
+ return { profiles: empty, count: 0 };
21
+ }
22
+ const permissionBits = stat.mode & 0o777;
23
+ if (process.platform !== "win32" && (permissionBits & 0o077) !== 0) {
24
+ check(checks, "credential_permissions", "fail", `Credential-file permissions are ${permissionBits.toString(8).padStart(3, "0")}, not 600.`, "Restrict the credential file to mode 0600.");
25
+ }
26
+ else if (typeof process.getuid === "function" && stat.uid !== process.getuid()) {
27
+ check(checks, "credential_permissions", "fail", "The credential file is owned by another account.", "Move credentials into a file owned by this account.");
28
+ }
29
+ 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).");
31
+ }
32
+ let parsed;
33
+ try {
34
+ parsed = JSON.parse(readFileSync(credsPath(), "utf8"));
35
+ }
36
+ catch {
37
+ check(checks, "credential_store", "fail", "The credential store is not valid JSON.", "Move the damaged file aside, then run `passport login` again.");
38
+ return { profiles: empty, count: 0 };
39
+ }
40
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
41
+ check(checks, "credential_store", "fail", "The credential store has an invalid top-level shape.", "Move the damaged file aside, then run `passport login` again.");
42
+ return { profiles: empty, count: 0 };
43
+ }
44
+ const profiles = Object.create(null);
45
+ const invalid = [];
46
+ for (const [name, raw] of Object.entries(parsed)) {
47
+ try {
48
+ assertProfileName(name);
49
+ }
50
+ catch {
51
+ invalid.push("profile name");
52
+ continue;
53
+ }
54
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
55
+ invalid.push(name);
56
+ continue;
57
+ }
58
+ const record = raw;
59
+ if (typeof record.refreshToken !== "string" || !record.refreshToken || typeof record.endpoint !== "string" || !record.endpoint) {
60
+ invalid.push(name);
61
+ continue;
62
+ }
63
+ profiles[name] = { refreshToken: record.refreshToken, endpoint: record.endpoint };
64
+ }
65
+ const count = Object.keys(profiles).length;
66
+ if (invalid.length) {
67
+ check(checks, "credential_store", "fail", `The credential store contains ${invalid.length} invalid profile record${invalid.length === 1 ? "" : "s"}.`, "Remove the damaged record or recreate the store with `passport login`.");
68
+ }
69
+ else {
70
+ check(checks, "credential_store", "pass", `Credential store parsed cleanly with ${count} profile${count === 1 ? "" : "s"}.`);
71
+ }
72
+ return { profiles, count };
73
+ }
74
+ function errorText(error, redact) {
75
+ return redact(error instanceof Error ? error.message : String(error)) || "Unknown failure.";
76
+ }
77
+ export async function runDoctor(options) {
78
+ 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.");
81
+ const hasAgentKey = Boolean(options.env.PASSPORT_AGENT_KEY);
82
+ const hasAgentEndpoint = Boolean(options.env.PASSPORT_ENDPOINT);
83
+ const agentMode = hasAgentKey && hasAgentEndpoint;
84
+ const store = inspectStore(checks, agentMode);
85
+ let auth;
86
+ let selectedProfile;
87
+ if (hasAgentKey !== hasAgentEndpoint) {
88
+ check(checks, "auth_config", "fail", "Agent-key configuration is incomplete.", "Set both PASSPORT_AGENT_KEY and PASSPORT_ENDPOINT, or unset both.");
89
+ }
90
+ else if (agentMode) {
91
+ if (options.profile !== undefined) {
92
+ check(checks, "auth_config", "fail", "--profile cannot be combined with agent-key environment authentication.", "Remove --profile or unset the agent-key variables.");
93
+ }
94
+ else {
95
+ try {
96
+ const normalized = options.normalizeEndpoint(options.env.PASSPORT_ENDPOINT);
97
+ auth = { kind: "agent-key", endpoint: normalized, agentKey: options.env.PASSPORT_AGENT_KEY };
98
+ check(checks, "auth_config", "pass", "Agent-key environment variables are complete (secret value not shown).");
99
+ }
100
+ catch (error) {
101
+ check(checks, "auth_config", "fail", errorText(error, options.redactError), "Set PASSPORT_ENDPOINT to the HTTPS workspace MCP endpoint.");
102
+ }
103
+ }
104
+ }
105
+ else {
106
+ const names = Object.keys(store.profiles).sort();
107
+ const candidate = options.profile ?? options.env.PASSPORT_PROFILE ?? (names.length === 1 ? names[0] : undefined);
108
+ 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>`.");
110
+ }
111
+ else {
112
+ try {
113
+ assertProfileName(candidate);
114
+ const saved = store.profiles[candidate];
115
+ if (!saved) {
116
+ check(checks, "auth_config", "fail", "The selected profile does not exist or is malformed.", "Choose another profile or run `passport login` to recreate it.");
117
+ }
118
+ else {
119
+ const normalized = options.normalizeEndpoint(saved.endpoint);
120
+ selectedProfile = candidate;
121
+ auth = { kind: "profile", endpoint: normalized, profile: candidate, refreshToken: saved.refreshToken };
122
+ check(checks, "auth_config", "pass", `Profile "${candidate}" has a credential and a secure endpoint (secret value not shown).`);
123
+ }
124
+ }
125
+ catch (error) {
126
+ check(checks, "auth_config", "fail", errorText(error, options.redactError), "Choose a valid profile whose endpoint uses HTTPS.");
127
+ }
128
+ }
129
+ }
130
+ let endpointOrigin;
131
+ let server;
132
+ if (!auth) {
133
+ check(checks, "server_reachability", "skip", "Server checks were skipped because authentication is not configured.");
134
+ check(checks, "server_protocol", "skip", "CLI protocol checks were skipped.");
135
+ }
136
+ else {
137
+ endpointOrigin = new URL(auth.endpoint).origin;
138
+ try {
139
+ const health = await fetch(new URL("/healthz", endpointOrigin), {
140
+ signal: AbortSignal.any([options.signal, AbortSignal.timeout(options.timeoutMs)])
141
+ });
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.");
143
+ }
144
+ catch (error) {
145
+ 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
+ }
147
+ let gateway;
148
+ try {
149
+ gateway = await CliGateway.connect({ auth, caller: options.caller, timeoutMs: options.timeoutMs, signal: options.signal });
150
+ }
151
+ 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.");
153
+ check(checks, "server_protocol", "skip", "CLI protocol checks could not run because the authenticated handshake failed.");
154
+ }
155
+ if (gateway) {
156
+ check(checks, "authentication", "pass", `Authenticated as ${auth.kind === "profile" ? `profile "${auth.profile}"` : "an agent key"} (credential value not shown).`);
157
+ try {
158
+ const protocol = await gateway.protocolDiagnostics();
159
+ const safeServer = protocol.server
160
+ ? {
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)
163
+ }
164
+ : undefined;
165
+ server = safeServer;
166
+ if (!protocol.serverCompatible) {
167
+ const actual = safeServer ? `${safeServer.name} ${safeServer.version}` : "missing serverInfo";
168
+ check(checks, "server_protocol", "fail", `Incompatible MCP serverInfo: ${actual}.`, `Deploy Passport gateway ${MIN_CLI_SERVER_VERSION} or newer.`);
169
+ }
170
+ else if (!protocol.toolsExact) {
171
+ const missing = CLI_PROTOCOL_TOOLS.filter((tool) => !protocol.tools.includes(tool)).length;
172
+ const extra = protocol.tools.filter((tool) => !CLI_PROTOCOL_TOOLS.includes(tool)).length;
173
+ check(checks, "server_protocol", "fail", `CLI tool surface is not exact (${missing} missing, ${extra} extra).`, "Deploy the matching Passport gateway release.");
174
+ }
175
+ else {
176
+ check(checks, "server_protocol", "pass", `${safeServer.name} ${safeServer.version} exposes the exact governed CLI protocol.`);
177
+ }
178
+ }
179
+ catch (error) {
180
+ check(checks, "server_protocol", "fail", `Could not inspect the CLI protocol: ${errorText(error, options.redactError)}`, "Verify gateway compatibility and proxy support for MCP tools/list.");
181
+ }
182
+ finally {
183
+ await gateway.close();
184
+ }
185
+ }
186
+ }
187
+ return {
188
+ version: options.version,
189
+ ok: !checks.some((item) => item.status === "fail"),
190
+ auth: auth?.kind ?? "none",
191
+ ...(selectedProfile ? { profile: selectedProfile } : {}),
192
+ profileCount: store.count,
193
+ ...(endpointOrigin ? { endpointOrigin } : {}),
194
+ ...(server ? { server } : {}),
195
+ checks
196
+ };
197
+ }
198
+ export function formatDoctorReport(report) {
199
+ const icon = { pass: "✓", warn: "!", fail: "✗", skip: "-" };
200
+ const lines = [`Passport doctor ${report.version}`];
201
+ for (const item of report.checks) {
202
+ lines.push(`${icon[item.status]} ${item.summary}`);
203
+ if (item.action)
204
+ lines.push(` Fix: ${item.action}`);
205
+ }
206
+ lines.push(report.ok ? "Healthy: all required checks passed." : "Needs attention: fix the failed checks above.");
207
+ return lines.join("\n");
208
+ }