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