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/README.md +115 -54
- package/dist/activeProfile.js +122 -0
- package/dist/boundedFile.js +46 -0
- package/dist/boundedMcpFetch.js +98 -0
- package/dist/boundedResponse.js +56 -0
- package/dist/bridge.js +427 -107
- package/dist/bridgeConfig.js +19 -0
- package/dist/bridgeShutdown.js +30 -0
- package/dist/cli.js +195 -37
- package/dist/cliArgs.js +8 -1
- package/dist/cliClient.js +24 -46
- package/dist/cliConnect.js +161 -0
- package/dist/cliDeadline.js +27 -0
- package/dist/cliLogin.js +175 -0
- package/dist/cliOffline.js +119 -0
- package/dist/cliOutput.js +116 -0
- package/dist/cliPagination.js +55 -0
- package/dist/cliResult.js +111 -0
- package/dist/cliSession.js +163 -0
- package/dist/cliSupport.js +232 -0
- package/dist/completion.js +25 -10
- package/dist/credentialStorage.js +293 -0
- package/dist/credentials.js +364 -108
- package/dist/discover.js +60 -34
- package/dist/doctor.js +126 -16
- package/dist/legacyCliSecurity.js +26 -0
- package/dist/passport.js +169 -584
- package/dist/privateStableFile.js +170 -0
- package/dist/recoveryCleanup.js +17 -0
- package/dist/recoveryIdentity.js +80 -0
- package/dist/tokenWorkspace.js +5 -0
- package/dist/version.js +1 -1
- package/npm-shrinkwrap.json +1740 -0
- package/package.json +21 -7
- package/dist/discover.test.js +0 -51
package/dist/bridge.js
CHANGED
|
@@ -4,8 +4,13 @@ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
|
4
4
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
5
5
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
6
6
|
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
7
|
-
import { ListToolsRequestSchema, CallToolRequestSchema, ListResourcesRequestSchema, ReadResourceRequestSchema, ListResourceTemplatesRequestSchema, ListPromptsRequestSchema, GetPromptRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
7
|
+
import { ListToolsRequestSchema, CallToolRequestSchema, ElicitRequestSchema, ListResourcesRequestSchema, ReadResourceRequestSchema, ListResourceTemplatesRequestSchema, ListPromptsRequestSchema, GetPromptRequestSchema, ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
|
|
8
8
|
import { VERSION } from "./version.js";
|
|
9
|
+
import { bridgePollIntervalMs } from "./bridgeConfig.js";
|
|
10
|
+
import { readBoundedJson } from "./boundedResponse.js";
|
|
11
|
+
import { createBoundedBridgeShutdown } from "./bridgeShutdown.js";
|
|
12
|
+
import { workspaceOfToken } from "./tokenWorkspace.js";
|
|
13
|
+
export { workspaceOfToken } from "./tokenWorkspace.js";
|
|
9
14
|
/** Everything but the MCP protocol goes to stderr — stdout is the transport. */
|
|
10
15
|
export function log(...args) {
|
|
11
16
|
process.stderr.write(`[passport-bridge] ${args.join(" ")}\n`);
|
|
@@ -18,15 +23,6 @@ function safeHostname() {
|
|
|
18
23
|
return "unknown";
|
|
19
24
|
}
|
|
20
25
|
}
|
|
21
|
-
/**
|
|
22
|
-
* The workspace a Passport token belongs to. Every token the server mints is
|
|
23
|
-
* workspace-prefixed (`<wsId>~...`, see server store.mintToken), so the tenant
|
|
24
|
-
* is recoverable from the string itself. Returns "" for an env-supplied or
|
|
25
|
-
* malformed token with no recognizable prefix.
|
|
26
|
-
*/
|
|
27
|
-
export function workspaceOfToken(token) {
|
|
28
|
-
return token.match(/^(ws_[A-Za-z0-9]+)~/)?.[1] ?? "";
|
|
29
|
-
}
|
|
30
26
|
/**
|
|
31
27
|
* Shown to the AI client (and logged) when the bridge refuses to switch tenants:
|
|
32
28
|
* the on-disk credential now belongs to a DIFFERENT workspace than this process
|
|
@@ -34,46 +30,112 @@ export function workspaceOfToken(token) {
|
|
|
34
30
|
* wrong workspace.
|
|
35
31
|
*/
|
|
36
32
|
export const TENANT_FLIP_MESSAGE = "This machine's Passport credential now belongs to a different workspace. Reconnect this client from the Passport app.";
|
|
33
|
+
const ROTATION_PERSISTENCE_MESSAGE = "Passport rotated the credential, but durable local recovery is still pending. Repair the credential store and retry.";
|
|
34
|
+
export class BridgeCredentialError extends Error {
|
|
35
|
+
status;
|
|
36
|
+
constructor(status) {
|
|
37
|
+
super(`token exchange failed (${status}); reconnect this client from the Passport app (or run \`passport-bridge login\`)`);
|
|
38
|
+
this.status = status;
|
|
39
|
+
this.name = "BridgeCredentialError";
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
function isBridgeCredentialError(error) {
|
|
43
|
+
return error instanceof BridgeCredentialError;
|
|
44
|
+
}
|
|
37
45
|
/**
|
|
38
46
|
* Holds the long-lived refresh token and mints short-lived access tokens
|
|
39
47
|
* from the cloud, transparently refreshing on expiry or a 401.
|
|
40
48
|
*/
|
|
41
49
|
export class TokenManager {
|
|
42
|
-
endpoint;
|
|
43
50
|
onRotate;
|
|
44
51
|
coordinate;
|
|
45
52
|
requestTimeoutMs;
|
|
46
53
|
requestSignal;
|
|
54
|
+
fetcher;
|
|
47
55
|
origin;
|
|
48
56
|
refreshToken;
|
|
49
57
|
access;
|
|
50
58
|
expiresAt = 0;
|
|
51
59
|
inflight;
|
|
60
|
+
pendingRotation;
|
|
52
61
|
/** The workspace this process started serving, read from its initial refresh
|
|
53
62
|
* token. The tenant-flip guard refuses to adopt an on-disk credential whose
|
|
54
63
|
* workspace differs from this. */
|
|
55
64
|
homeWorkspace;
|
|
56
65
|
tenantFlipLogged = false;
|
|
57
66
|
/**
|
|
58
|
-
* @param onRotate persist a rotated refresh token
|
|
59
|
-
*
|
|
60
|
-
*
|
|
67
|
+
* @param onRotate durably persist a rotated refresh token before its access
|
|
68
|
+
* token is usable. Rejection leaves the child pending for local retry.
|
|
69
|
+
* Without it (e.g. env-only auth), the server is told not to rotate.
|
|
61
70
|
* @param coordinate cross-process coordination for a shared profile (Cursor
|
|
62
71
|
* runs one bridge per window): `reload` returns the freshest persisted
|
|
63
72
|
* refresh token, `lock` serializes the exchange across processes. Without
|
|
64
73
|
* them, a sibling process's rotation makes our in-memory token a replay —
|
|
65
74
|
* which the server treats as theft and answers by revoking the family.
|
|
66
75
|
*/
|
|
67
|
-
constructor(endpoint, refreshToken, onRotate, coordinate, requestTimeoutMs, requestSignal) {
|
|
68
|
-
this.endpoint = endpoint;
|
|
76
|
+
constructor(endpoint, refreshToken, onRotate, coordinate, requestTimeoutMs, requestSignal, fetcher = fetch) {
|
|
69
77
|
this.onRotate = onRotate;
|
|
70
78
|
this.coordinate = coordinate;
|
|
71
79
|
this.requestTimeoutMs = requestTimeoutMs;
|
|
72
80
|
this.requestSignal = requestSignal;
|
|
81
|
+
this.fetcher = fetcher;
|
|
73
82
|
this.origin = new URL(endpoint).origin;
|
|
74
83
|
this.refreshToken = refreshToken;
|
|
75
84
|
this.homeWorkspace = workspaceOfToken(refreshToken);
|
|
76
85
|
}
|
|
86
|
+
assertHomeWorkspace(token) {
|
|
87
|
+
const workspace = workspaceOfToken(token);
|
|
88
|
+
if (!workspace || !this.homeWorkspace || workspace === this.homeWorkspace)
|
|
89
|
+
return;
|
|
90
|
+
if (!this.tenantFlipLogged) {
|
|
91
|
+
this.tenantFlipLogged = true;
|
|
92
|
+
log(`refusing to adopt an on-disk credential for ${workspace}; this bridge serves ${this.homeWorkspace}.`, "Reconnect this client from the Passport app.");
|
|
93
|
+
}
|
|
94
|
+
throw new Error(TENANT_FLIP_MESSAGE);
|
|
95
|
+
}
|
|
96
|
+
async settlePendingRotation(disk) {
|
|
97
|
+
const pending = this.pendingRotation;
|
|
98
|
+
if (!pending)
|
|
99
|
+
return undefined;
|
|
100
|
+
if (this.coordinate && !disk) {
|
|
101
|
+
throw new Error("Passport credential is unavailable on disk; refusing to recover its rotation. Repair the credential store or sign in again.");
|
|
102
|
+
}
|
|
103
|
+
if (disk && disk !== pending.previous && disk !== pending.next) {
|
|
104
|
+
this.assertHomeWorkspace(disk);
|
|
105
|
+
// A sibling recovered our child and advanced it while this process was
|
|
106
|
+
// waiting to retry. Its on-disk descendant is authoritative.
|
|
107
|
+
this.pendingRotation = undefined;
|
|
108
|
+
this.refreshToken = disk;
|
|
109
|
+
return undefined;
|
|
110
|
+
}
|
|
111
|
+
try {
|
|
112
|
+
if (disk !== pending.next) {
|
|
113
|
+
if (!this.onRotate)
|
|
114
|
+
throw new Error("No credential persistence callback is available.");
|
|
115
|
+
await this.onRotate(pending.next, pending.previous);
|
|
116
|
+
}
|
|
117
|
+
if (this.coordinate) {
|
|
118
|
+
const verified = this.coordinate.reload();
|
|
119
|
+
if (verified)
|
|
120
|
+
this.assertHomeWorkspace(verified);
|
|
121
|
+
if (!verified || verified !== pending.next) {
|
|
122
|
+
throw new Error("The credential store did not retain the rotated credential.");
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
catch (error) {
|
|
127
|
+
if (error instanceof Error && error.message === TENANT_FLIP_MESSAGE)
|
|
128
|
+
throw error;
|
|
129
|
+
throw new Error(ROTATION_PERSISTENCE_MESSAGE, { cause: error });
|
|
130
|
+
}
|
|
131
|
+
this.pendingRotation = undefined;
|
|
132
|
+
this.refreshToken = pending.next;
|
|
133
|
+
if (Date.now() >= pending.expiresAt)
|
|
134
|
+
return undefined;
|
|
135
|
+
this.access = pending.accessToken;
|
|
136
|
+
this.expiresAt = pending.expiresAt;
|
|
137
|
+
return pending.accessToken;
|
|
138
|
+
}
|
|
77
139
|
async accessToken(force = false) {
|
|
78
140
|
if (!force && this.access && Date.now() < this.expiresAt - 60_000)
|
|
79
141
|
return this.access;
|
|
@@ -93,12 +155,34 @@ export class TokenManager {
|
|
|
93
155
|
});
|
|
94
156
|
return this.inflight;
|
|
95
157
|
}
|
|
158
|
+
/** Adopt a newly persisted credential after an interactive recovery. The
|
|
159
|
+
* original workspace remains authoritative for this running bridge. */
|
|
160
|
+
replaceRefreshToken(next) {
|
|
161
|
+
this.replaceCredential(next, this.origin);
|
|
162
|
+
}
|
|
163
|
+
/** Adopt a newly persisted credential and its approved gateway endpoint. */
|
|
164
|
+
replaceCredential(next, endpoint) {
|
|
165
|
+
this.assertHomeWorkspace(next);
|
|
166
|
+
this.origin = new URL(endpoint).origin;
|
|
167
|
+
this.refreshToken = next;
|
|
168
|
+
this.access = undefined;
|
|
169
|
+
this.expiresAt = 0;
|
|
170
|
+
this.pendingRotation = undefined;
|
|
171
|
+
}
|
|
96
172
|
async exchange() {
|
|
97
173
|
// Adopt a sibling's rotation before burning anything: the on-disk token is
|
|
98
174
|
// the live one; ours may already be a would-be replay.
|
|
99
|
-
|
|
175
|
+
let disk = this.coordinate?.reload();
|
|
176
|
+
if (this.coordinate && !disk) {
|
|
177
|
+
throw new Error("Passport credential is unavailable on disk; refusing to rotate it. Repair the credential store or sign in again.");
|
|
178
|
+
}
|
|
179
|
+
if (this.pendingRotation) {
|
|
180
|
+
const recoveredAccess = await this.settlePendingRotation(disk);
|
|
181
|
+
if (recoveredAccess)
|
|
182
|
+
return recoveredAccess;
|
|
183
|
+
disk = this.coordinate?.reload() ?? this.refreshToken;
|
|
184
|
+
}
|
|
100
185
|
if (disk && disk !== this.refreshToken) {
|
|
101
|
-
const diskWorkspace = workspaceOfToken(disk);
|
|
102
186
|
// TENANT-FLIP GUARD (defense in depth — per-workspace slots make this
|
|
103
187
|
// rare). The on-disk credential in this slot now belongs to a DIFFERENT
|
|
104
188
|
// workspace than the one this process started serving. Refuse to adopt
|
|
@@ -106,38 +190,57 @@ export class TokenManager {
|
|
|
106
190
|
// current cached access token until it expires; this exchange fails
|
|
107
191
|
// closed with an MCP-visible error rather than routing to the wrong
|
|
108
192
|
// workspace. Log once to stderr.
|
|
109
|
-
|
|
110
|
-
if (!this.tenantFlipLogged) {
|
|
111
|
-
this.tenantFlipLogged = true;
|
|
112
|
-
log(`refusing to adopt an on-disk credential for ${diskWorkspace}; this bridge serves ${this.homeWorkspace}.`, "Reconnect this client from the Passport app.");
|
|
113
|
-
}
|
|
114
|
-
throw new Error(TENANT_FLIP_MESSAGE);
|
|
115
|
-
}
|
|
193
|
+
this.assertHomeWorkspace(disk);
|
|
116
194
|
this.refreshToken = disk;
|
|
117
195
|
}
|
|
118
196
|
const exchangeSignals = [
|
|
119
197
|
...(this.requestSignal ? [this.requestSignal] : []),
|
|
120
198
|
...(this.requestTimeoutMs ? [AbortSignal.timeout(this.requestTimeoutMs)] : [])
|
|
121
199
|
];
|
|
122
|
-
const res = await
|
|
200
|
+
const res = await this.fetcher(`${this.origin}/api/token`, {
|
|
123
201
|
method: "POST",
|
|
202
|
+
redirect: "error",
|
|
124
203
|
headers: { "content-type": "application/json" },
|
|
125
|
-
...(exchangeSignals.length
|
|
204
|
+
...(exchangeSignals.length
|
|
205
|
+
? { signal: exchangeSignals.length === 1 ? exchangeSignals[0] : AbortSignal.any(exchangeSignals) }
|
|
206
|
+
: {}),
|
|
126
207
|
// Report host + version so the device shows up in the admin inventory.
|
|
127
208
|
// rotate:false when we can't persist the new credential.
|
|
128
|
-
body: JSON.stringify({
|
|
209
|
+
body: JSON.stringify({
|
|
210
|
+
refreshToken: this.refreshToken,
|
|
211
|
+
host: safeHostname(),
|
|
212
|
+
version: VERSION,
|
|
213
|
+
rotate: Boolean(this.onRotate)
|
|
214
|
+
})
|
|
129
215
|
});
|
|
130
|
-
if (!res.ok)
|
|
131
|
-
|
|
132
|
-
|
|
216
|
+
if (!res.ok) {
|
|
217
|
+
await res.body?.cancel().catch(() => undefined);
|
|
218
|
+
if (res.status === 401)
|
|
219
|
+
throw new BridgeCredentialError(401);
|
|
220
|
+
throw new Error(`token exchange failed (${res.status}); Passport is unavailable, so try again shortly`);
|
|
221
|
+
}
|
|
222
|
+
const data = await readBoundedJson(res);
|
|
223
|
+
if (typeof data.accessToken !== "string" ||
|
|
224
|
+
!data.accessToken ||
|
|
225
|
+
typeof data.expiresInSec !== "number" ||
|
|
226
|
+
!Number.isFinite(data.expiresInSec) ||
|
|
227
|
+
data.expiresInSec <= 0 ||
|
|
228
|
+
data.expiresInSec > 365 * 24 * 60 * 60 ||
|
|
229
|
+
(data.refreshToken !== undefined && (typeof data.refreshToken !== "string" || !data.refreshToken))) {
|
|
230
|
+
throw new Error("Passport returned an invalid token exchange response.");
|
|
231
|
+
}
|
|
133
232
|
if (data.refreshToken && data.refreshToken !== this.refreshToken) {
|
|
134
|
-
this.
|
|
135
|
-
|
|
136
|
-
this.
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
}
|
|
233
|
+
this.assertHomeWorkspace(data.refreshToken);
|
|
234
|
+
this.pendingRotation = {
|
|
235
|
+
previous: this.refreshToken,
|
|
236
|
+
next: data.refreshToken,
|
|
237
|
+
accessToken: data.accessToken,
|
|
238
|
+
expiresAt: Date.now() + data.expiresInSec * 1000
|
|
239
|
+
};
|
|
240
|
+
const persistedAccess = await this.settlePendingRotation(disk);
|
|
241
|
+
if (persistedAccess)
|
|
242
|
+
return persistedAccess;
|
|
243
|
+
return this.exchange();
|
|
141
244
|
}
|
|
142
245
|
this.access = data.accessToken;
|
|
143
246
|
this.expiresAt = Date.now() + data.expiresInSec * 1000;
|
|
@@ -151,47 +254,263 @@ export class TokenManager {
|
|
|
151
254
|
// The SDK owns per-MCP-request deadlines via init.signal. The constructor
|
|
152
255
|
// timeout only bounds refresh exchange; applying it here would truncate an
|
|
153
256
|
// explicit `passport connect --wait 120` request at the default 30s.
|
|
154
|
-
return { ...init, headers };
|
|
257
|
+
return { ...init, headers, redirect: "error" };
|
|
155
258
|
};
|
|
156
|
-
let res = await
|
|
259
|
+
let res = await this.fetcher(input, apply(await this.accessToken()));
|
|
157
260
|
if (res.status === 401) {
|
|
158
|
-
|
|
261
|
+
await res.body?.cancel().catch(() => undefined);
|
|
262
|
+
res = await this.fetcher(input, apply(await this.accessToken(true)));
|
|
263
|
+
if (res.status === 401) {
|
|
264
|
+
await res.body?.cancel().catch(() => undefined);
|
|
265
|
+
throw new BridgeCredentialError(401);
|
|
266
|
+
}
|
|
159
267
|
}
|
|
160
268
|
return res;
|
|
161
269
|
};
|
|
162
270
|
}
|
|
271
|
+
const RECOVERY_TOOL = "passport_recover_session";
|
|
272
|
+
const RECOVERY_MESSAGE = "Passport is disconnected. Use this tool to sign in again; other Passport tools remain unavailable until recovery completes.";
|
|
163
273
|
/**
|
|
164
274
|
* The proxy: a stdio MCP server (what the AI client talks to) that forwards
|
|
165
275
|
* verbatim to the cloud gateway over Streamable HTTP. Tool definitions and
|
|
166
276
|
* arguments pass through unchanged; cancellation and progress are forwarded;
|
|
167
277
|
* a periodic re-list notifies the client when the toolset changes.
|
|
168
278
|
*/
|
|
169
|
-
export async function runBridge(endpoint, tokens) {
|
|
170
|
-
const
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
279
|
+
export async function runBridge(endpoint, tokens, options = {}) {
|
|
280
|
+
const pollMs = bridgePollIntervalMs();
|
|
281
|
+
let activeEndpoint = endpoint;
|
|
282
|
+
let upstream;
|
|
283
|
+
let upstreamHasUrlElicitation = false;
|
|
284
|
+
let connecting;
|
|
285
|
+
let state = "connecting";
|
|
286
|
+
let recoveryInFlight;
|
|
287
|
+
let recoveryAbort;
|
|
288
|
+
let pollTimer;
|
|
289
|
+
let lastSignature = "";
|
|
290
|
+
const connectCandidate = async (candidate) => {
|
|
291
|
+
if (options.connectUpstream) {
|
|
292
|
+
await options.connectUpstream(candidate);
|
|
293
|
+
}
|
|
294
|
+
else {
|
|
295
|
+
await candidate.connect(new StreamableHTTPClientTransport(new URL(activeEndpoint), { fetch: tokens.authedFetch }));
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
// Connect once before responding to initialize so healthy sessions retain the
|
|
299
|
+
// gateway's instructions. A bad credential is caught here and still proceeds
|
|
300
|
+
// to a live downstream session in fail-closed recovery mode.
|
|
301
|
+
let instructions;
|
|
302
|
+
let initial;
|
|
303
|
+
try {
|
|
304
|
+
initial = new Client({ name: "passport-bridge", version: VERSION });
|
|
305
|
+
await connectCandidate(initial);
|
|
306
|
+
upstream = initial;
|
|
307
|
+
state = "ready";
|
|
308
|
+
instructions = initial.getInstructions();
|
|
309
|
+
lastSignature = await toolSignature(initial);
|
|
310
|
+
}
|
|
311
|
+
catch (error) {
|
|
312
|
+
void initial?.close().catch(() => undefined);
|
|
313
|
+
state = "degraded";
|
|
314
|
+
upstream = undefined;
|
|
315
|
+
log(`Passport ${isBridgeCredentialError(error) ? "credential rejected" : "unavailable"}; serving fail-closed recovery mode.`);
|
|
316
|
+
}
|
|
183
317
|
const server = new Server({ name: "passport", version: VERSION }, {
|
|
184
318
|
capabilities: {
|
|
319
|
+
// Recovery can change the upstream surface after initialize. Advertise
|
|
320
|
+
// a supported local superset and return empty lists while degraded.
|
|
185
321
|
tools: { listChanged: true },
|
|
186
|
-
|
|
187
|
-
|
|
322
|
+
resources: { listChanged: true },
|
|
323
|
+
prompts: { listChanged: true }
|
|
188
324
|
},
|
|
189
325
|
...(instructions ? { instructions } : {})
|
|
190
326
|
});
|
|
191
|
-
|
|
327
|
+
const recoveryTool = () => ({
|
|
328
|
+
name: RECOVERY_TOOL,
|
|
329
|
+
title: "Reconnect Passport",
|
|
330
|
+
description: "Reconnect Passport with a browser-based device sign-in. This is the only Passport action available while disconnected.",
|
|
331
|
+
inputSchema: { type: "object", properties: {}, additionalProperties: false }
|
|
332
|
+
});
|
|
333
|
+
const degradedTools = () => ({ tools: [recoveryTool()] });
|
|
334
|
+
const notifySurfacesChanged = async () => {
|
|
335
|
+
await Promise.all([
|
|
336
|
+
server.notification({ method: "notifications/tools/list_changed" }),
|
|
337
|
+
server.notification({ method: "notifications/resources/list_changed" }),
|
|
338
|
+
server.notification({ method: "notifications/prompts/list_changed" })
|
|
339
|
+
]);
|
|
340
|
+
};
|
|
341
|
+
const enterDegraded = async (error) => {
|
|
342
|
+
const hadUpstream = Boolean(upstream);
|
|
343
|
+
const previous = upstream;
|
|
344
|
+
state = "degraded";
|
|
345
|
+
upstream = undefined;
|
|
346
|
+
upstreamHasUrlElicitation = false;
|
|
347
|
+
if (pollTimer)
|
|
348
|
+
clearInterval(pollTimer);
|
|
349
|
+
pollTimer = undefined;
|
|
350
|
+
void previous?.close().catch(() => undefined);
|
|
351
|
+
const status = isBridgeCredentialError(error) ? "credential rejected" : "unavailable";
|
|
352
|
+
log(`Passport ${status}; serving fail-closed recovery mode.`);
|
|
353
|
+
if (hadUpstream)
|
|
354
|
+
await notifySurfacesChanged().catch(() => undefined);
|
|
355
|
+
};
|
|
356
|
+
const startPolling = () => {
|
|
357
|
+
pollTimer = setInterval(() => {
|
|
358
|
+
void (async () => {
|
|
359
|
+
if (!upstream || state !== "ready")
|
|
360
|
+
return;
|
|
361
|
+
try {
|
|
362
|
+
const sig = await toolSignature(upstream);
|
|
363
|
+
if (sig !== lastSignature) {
|
|
364
|
+
lastSignature = sig;
|
|
365
|
+
await notifySurfacesChanged();
|
|
366
|
+
log("tools changed; notified client");
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
catch (error) {
|
|
370
|
+
if (isBridgeCredentialError(error))
|
|
371
|
+
await enterDegraded(error);
|
|
372
|
+
}
|
|
373
|
+
})();
|
|
374
|
+
}, pollMs);
|
|
375
|
+
pollTimer.unref?.();
|
|
376
|
+
};
|
|
377
|
+
const connectUpstream = async () => {
|
|
378
|
+
const urlElicitation = server.getClientCapabilities()?.elicitation?.url;
|
|
379
|
+
if (state === "ready" && upstreamHasUrlElicitation === Boolean(urlElicitation))
|
|
380
|
+
return;
|
|
381
|
+
if (connecting) {
|
|
382
|
+
if (state === "connecting")
|
|
383
|
+
return connecting;
|
|
384
|
+
await connecting;
|
|
385
|
+
if (upstream)
|
|
386
|
+
return;
|
|
387
|
+
// A failed startup can race the first recovery tool call by one
|
|
388
|
+
// microtask. Clear that settled attempt before starting the new session.
|
|
389
|
+
connecting = undefined;
|
|
390
|
+
}
|
|
391
|
+
const previous = upstream;
|
|
392
|
+
upstream = undefined;
|
|
393
|
+
state = "connecting";
|
|
394
|
+
connecting = (async () => {
|
|
395
|
+
// URL mode is never claimed on behalf of a client that did not advertise
|
|
396
|
+
// it. The bridge has historically offered no form-elicitation surface,
|
|
397
|
+
// so leaving form mode unadvertised preserves its gateway fallback.
|
|
398
|
+
const candidate = new Client({ name: "passport-bridge", version: VERSION }, {
|
|
399
|
+
capabilities: urlElicitation ? { elicitation: { url: urlElicitation } } : undefined
|
|
400
|
+
});
|
|
401
|
+
if (urlElicitation) {
|
|
402
|
+
candidate.setRequestHandler(ElicitRequestSchema, async (request, extra) => server.elicitInput(request.params, { signal: extra.signal }));
|
|
403
|
+
}
|
|
404
|
+
try {
|
|
405
|
+
await connectCandidate(candidate);
|
|
406
|
+
}
|
|
407
|
+
catch (error) {
|
|
408
|
+
void candidate.close().catch(() => undefined);
|
|
409
|
+
throw error;
|
|
410
|
+
}
|
|
411
|
+
await previous?.close().catch(() => undefined);
|
|
412
|
+
upstream = candidate;
|
|
413
|
+
upstreamHasUrlElicitation = Boolean(urlElicitation);
|
|
414
|
+
state = "ready";
|
|
415
|
+
lastSignature = await toolSignature(candidate);
|
|
416
|
+
log(`connected to ${activeEndpoint}`);
|
|
417
|
+
if (!pollTimer)
|
|
418
|
+
startPolling();
|
|
419
|
+
})()
|
|
420
|
+
.catch(async (error) => {
|
|
421
|
+
if (previous && !isBridgeCredentialError(error)) {
|
|
422
|
+
upstream = previous;
|
|
423
|
+
state = "ready";
|
|
424
|
+
if (!pollTimer)
|
|
425
|
+
startPolling();
|
|
426
|
+
log("URL elicitation negotiation was unavailable; continuing with the existing Passport session.");
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
await enterDegraded(error);
|
|
430
|
+
})
|
|
431
|
+
.finally(() => {
|
|
432
|
+
connecting = undefined;
|
|
433
|
+
});
|
|
434
|
+
return connecting;
|
|
435
|
+
};
|
|
436
|
+
const runUpstream = async (work) => {
|
|
437
|
+
if (state === "connecting")
|
|
438
|
+
await connectUpstream();
|
|
439
|
+
if (!upstream || state !== "ready")
|
|
440
|
+
return undefined;
|
|
441
|
+
try {
|
|
442
|
+
return await work(upstream);
|
|
443
|
+
}
|
|
444
|
+
catch (error) {
|
|
445
|
+
if (isBridgeCredentialError(error)) {
|
|
446
|
+
await enterDegraded(error);
|
|
447
|
+
return undefined;
|
|
448
|
+
}
|
|
449
|
+
throw error;
|
|
450
|
+
}
|
|
451
|
+
};
|
|
452
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
453
|
+
return (await runUpstream((client) => client.listTools())) ?? degradedTools();
|
|
454
|
+
});
|
|
192
455
|
server.setRequestHandler(CallToolRequestSchema, async (req, extra) => {
|
|
456
|
+
if (req.params.name === RECOVERY_TOOL) {
|
|
457
|
+
if (state === "ready")
|
|
458
|
+
return { content: [{ type: "text", text: "Passport is already connected." }] };
|
|
459
|
+
if (!options.recovery) {
|
|
460
|
+
return {
|
|
461
|
+
content: [
|
|
462
|
+
{ type: "text", text: "Passport needs sign-in. Run `passport-bridge login` to replace this credential." }
|
|
463
|
+
],
|
|
464
|
+
isError: true
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
if (recoveryInFlight) {
|
|
468
|
+
return { content: [{ type: "text", text: "Passport sign-in is already waiting for browser approval." }] };
|
|
469
|
+
}
|
|
470
|
+
let flow;
|
|
471
|
+
try {
|
|
472
|
+
flow = await options.recovery.start();
|
|
473
|
+
}
|
|
474
|
+
catch {
|
|
475
|
+
return { content: [{ type: "text", text: "Could not start Passport sign-in. Try again." }], isError: true };
|
|
476
|
+
}
|
|
477
|
+
const abortController = new AbortController();
|
|
478
|
+
recoveryAbort = abortController;
|
|
479
|
+
recoveryInFlight = (async () => {
|
|
480
|
+
await flow.waitForCredential(abortController.signal).then((credential) => {
|
|
481
|
+
tokens.replaceCredential(credential.refreshToken, credential.endpoint);
|
|
482
|
+
activeEndpoint = credential.endpoint;
|
|
483
|
+
});
|
|
484
|
+
await connectUpstream();
|
|
485
|
+
if (!upstream)
|
|
486
|
+
throw new Error("Passport could not reconnect after sign-in.");
|
|
487
|
+
await notifySurfacesChanged().catch(() => undefined);
|
|
488
|
+
log("recovery completed; notified client");
|
|
489
|
+
})()
|
|
490
|
+
.catch(() => {
|
|
491
|
+
if (!abortController.signal.aborted) {
|
|
492
|
+
log("recovery did not complete; remaining in fail-closed recovery mode.");
|
|
493
|
+
}
|
|
494
|
+
})
|
|
495
|
+
.finally(() => {
|
|
496
|
+
if (recoveryAbort === abortController)
|
|
497
|
+
recoveryAbort = undefined;
|
|
498
|
+
recoveryInFlight = undefined;
|
|
499
|
+
});
|
|
500
|
+
return {
|
|
501
|
+
content: [
|
|
502
|
+
{ type: "text", text: `Open Passport and confirm device code: ${flow.userCode}` },
|
|
503
|
+
{
|
|
504
|
+
type: "resource_link",
|
|
505
|
+
name: "Open Passport sign-in",
|
|
506
|
+
uri: flow.verifyUrl,
|
|
507
|
+
description: "Complete Passport device sign-in in your browser."
|
|
508
|
+
}
|
|
509
|
+
]
|
|
510
|
+
};
|
|
511
|
+
}
|
|
193
512
|
const progressToken = req.params._meta?.progressToken;
|
|
194
|
-
|
|
513
|
+
const result = await runUpstream((client) => client.callTool(req.params, undefined, {
|
|
195
514
|
signal: extra.signal,
|
|
196
515
|
onprogress: progressToken
|
|
197
516
|
? (progress) => {
|
|
@@ -202,57 +521,58 @@ export async function runBridge(endpoint, tokens) {
|
|
|
202
521
|
});
|
|
203
522
|
}
|
|
204
523
|
: undefined
|
|
205
|
-
});
|
|
524
|
+
}));
|
|
525
|
+
return result ?? { content: [{ type: "text", text: RECOVERY_MESSAGE }], isError: true };
|
|
206
526
|
});
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
}
|
|
220
|
-
|
|
527
|
+
server.setRequestHandler(ListResourcesRequestSchema, async (req) => (await runUpstream((client) => client.getServerCapabilities()?.resources
|
|
528
|
+
? client.listResources(req.params)
|
|
529
|
+
: Promise.resolve({ resources: [] }))) ?? { resources: [] });
|
|
530
|
+
server.setRequestHandler(ListResourceTemplatesRequestSchema, async (req) => (await runUpstream((client) => client.getServerCapabilities()?.resources
|
|
531
|
+
? client.listResourceTemplates(req.params)
|
|
532
|
+
: Promise.resolve({ resourceTemplates: [] }))) ?? { resourceTemplates: [] });
|
|
533
|
+
server.setRequestHandler(ReadResourceRequestSchema, async (req) => {
|
|
534
|
+
const result = await runUpstream((client) => client.getServerCapabilities()?.resources ? client.readResource(req.params) : Promise.resolve(undefined));
|
|
535
|
+
if (result)
|
|
536
|
+
return result;
|
|
537
|
+
throw new McpError(ErrorCode.InvalidRequest, state === "ready" ? "Passport has no resources available in this session." : RECOVERY_MESSAGE);
|
|
538
|
+
});
|
|
539
|
+
server.setRequestHandler(ListPromptsRequestSchema, async (req) => (await runUpstream((client) => client.getServerCapabilities()?.prompts ? client.listPrompts(req.params) : Promise.resolve({ prompts: [] }))) ?? { prompts: [] });
|
|
540
|
+
server.setRequestHandler(GetPromptRequestSchema, async (req) => {
|
|
541
|
+
const result = await runUpstream((client) => client.getServerCapabilities()?.prompts ? client.getPrompt(req.params) : Promise.resolve(undefined));
|
|
542
|
+
if (result)
|
|
543
|
+
return result;
|
|
544
|
+
throw new McpError(ErrorCode.InvalidRequest, state === "ready" ? "Passport has no prompts available in this session." : RECOVERY_MESSAGE);
|
|
545
|
+
});
|
|
546
|
+
server.oninitialized = () => {
|
|
547
|
+
if (state === "ready")
|
|
548
|
+
void connectUpstream();
|
|
549
|
+
};
|
|
550
|
+
let removeProcessSignalHandlers = () => undefined;
|
|
551
|
+
server.onclose = () => {
|
|
552
|
+
removeProcessSignalHandlers();
|
|
553
|
+
recoveryAbort?.abort();
|
|
554
|
+
if (pollTimer)
|
|
555
|
+
clearInterval(pollTimer);
|
|
556
|
+
pollTimer = undefined;
|
|
557
|
+
void upstream?.close().catch(() => undefined);
|
|
558
|
+
};
|
|
559
|
+
await server.connect(options.downstreamTransport ?? new StdioServerTransport());
|
|
221
560
|
log("ready on stdio");
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
const
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
if (sig !== lastSignature) {
|
|
237
|
-
lastSignature = sig;
|
|
238
|
-
await server.notification({ method: "notifications/tools/list_changed" });
|
|
239
|
-
log("tools changed; notified client");
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
catch {
|
|
243
|
-
/* transient; try again next tick */
|
|
244
|
-
}
|
|
245
|
-
})();
|
|
246
|
-
}, pollMs);
|
|
247
|
-
timer.unref?.();
|
|
248
|
-
const shutdown = () => {
|
|
249
|
-
clearInterval(timer);
|
|
250
|
-
void upstream.close().catch(() => { });
|
|
251
|
-
void server.close().catch(() => { });
|
|
252
|
-
process.exit(0);
|
|
561
|
+
if (upstream)
|
|
562
|
+
startPolling();
|
|
563
|
+
const shutdown = createBoundedBridgeShutdown({
|
|
564
|
+
pollTimer: () => pollTimer,
|
|
565
|
+
upstream: { close: () => upstream?.close() ?? Promise.resolve() },
|
|
566
|
+
server,
|
|
567
|
+
onFailure: () => log("shutdown did not drain cleanly")
|
|
568
|
+
});
|
|
569
|
+
const onSignal = () => void shutdown();
|
|
570
|
+
process.once("SIGINT", onSignal);
|
|
571
|
+
process.once("SIGTERM", onSignal);
|
|
572
|
+
removeProcessSignalHandlers = () => {
|
|
573
|
+
process.off("SIGINT", onSignal);
|
|
574
|
+
process.off("SIGTERM", onSignal);
|
|
253
575
|
};
|
|
254
|
-
process.on("SIGINT", shutdown);
|
|
255
|
-
process.on("SIGTERM", shutdown);
|
|
256
576
|
}
|
|
257
577
|
async function toolSignature(client) {
|
|
258
578
|
const { tools } = await client.listTools();
|