@osd-project/osd-cli 0.0.0-stage → 0.8.3
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/LICENSE +202 -0
- package/README.md +585 -2
- package/THIRD_PARTY_NOTICES.md +96 -0
- package/dist/auth-store.d.ts +38 -0
- package/dist/auth-store.js +239 -0
- package/dist/brand-catalog.d.ts +65 -0
- package/dist/brand-catalog.js +175 -0
- package/dist/connect-gate.d.ts +31 -0
- package/dist/connect-gate.js +82 -0
- package/dist/contracts.d.ts +61 -0
- package/dist/contracts.js +145 -0
- package/dist/exit-codes.d.ts +32 -0
- package/dist/exit-codes.js +40 -0
- package/dist/format.d.ts +71 -0
- package/dist/format.js +99 -0
- package/dist/generated/schemas.d.ts +2 -0
- package/dist/generated/schemas.js +1781 -0
- package/dist/guarded-fetch.d.ts +28 -0
- package/dist/guarded-fetch.js +252 -0
- package/dist/help.d.ts +27 -0
- package/dist/help.js +32 -0
- package/dist/http-fetch.d.ts +1 -0
- package/dist/http-fetch.js +17 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +821 -0
- package/dist/logout.d.ts +16 -0
- package/dist/logout.js +82 -0
- package/dist/mcp-auth.d.ts +70 -0
- package/dist/mcp-auth.js +603 -0
- package/dist/mcp-card.d.ts +23 -0
- package/dist/mcp-card.js +18 -0
- package/dist/mcp-client.d.ts +77 -0
- package/dist/mcp-client.js +193 -0
- package/dist/net-guard.d.ts +66 -0
- package/dist/net-guard.js +152 -0
- package/dist/proxy-config.d.ts +51 -0
- package/dist/proxy-config.js +147 -0
- package/dist/request.d.ts +32 -0
- package/dist/request.js +62 -0
- package/dist/resolve-endpoint.d.ts +62 -0
- package/dist/resolve-endpoint.js +172 -0
- package/dist/search.d.ts +39 -0
- package/dist/search.js +69 -0
- package/dist/skill.d.ts +155 -0
- package/dist/skill.js +320 -0
- package/dist/updates.d.ts +101 -0
- package/dist/updates.js +541 -0
- package/dist/verify.d.ts +92 -0
- package/dist/verify.js +379 -0
- package/package.json +55 -3
- package/skill/osd/SKILL.md +400 -0
- package/skill/osd/references/connect-mcp.md +48 -0
package/dist/mcp-auth.js
ADDED
|
@@ -0,0 +1,603 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OAuth for the CLI's own MCP client: authorization_code + PKCE with a
|
|
3
|
+
* loopback redirect (RFC 8252), preferring device authorization (RFC 8628)
|
|
4
|
+
* when the server advertises it.
|
|
5
|
+
* Tokens and client registration use the OS vault with a private-file fallback.
|
|
6
|
+
*
|
|
7
|
+
* Browser fallback, when the server does not advertise device authorization:
|
|
8
|
+
* 1. auth() runs discovery, dynamic client registration, and PKCE setup,
|
|
9
|
+
* then calls redirectToAuthorization -- we open the human's browser.
|
|
10
|
+
* 2. The loopback server catches the redirect and validates `state`.
|
|
11
|
+
* 3. auth() again with the code exchanges it and calls saveTokens.
|
|
12
|
+
* 4. The caller retries the MCP connection; the transport now attaches
|
|
13
|
+
* the cached bearer token from provider.tokens().
|
|
14
|
+
*
|
|
15
|
+
* Device authorization displays a URL/code and polls instead of opening a
|
|
16
|
+
* callback listener. Later runs reuse cached credentials; --login explicitly
|
|
17
|
+
* starts a fresh sign-in using the server's advertised capabilities.
|
|
18
|
+
*/
|
|
19
|
+
import { randomUUID } from "node:crypto";
|
|
20
|
+
import { createServer } from "node:http";
|
|
21
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
22
|
+
import open from "open";
|
|
23
|
+
import { auth, discoverOAuthServerInfo, fetchToken, OAuthError, registerClient } from "@modelcontextprotocol/client";
|
|
24
|
+
import { createGuardedFetch } from "./guarded-fetch.js";
|
|
25
|
+
import { AuthStore } from "./auth-store.js";
|
|
26
|
+
const AUTH_TIMEOUT_MS = 10 * 60_000;
|
|
27
|
+
const DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
|
|
28
|
+
/** Fixed port keeps redirect_uri stable across runs; dynamic client registrations are bound to it. */
|
|
29
|
+
const DEFAULT_CALLBACK_PORT = 8976;
|
|
30
|
+
const DEFAULT_CALLBACK_PATH = "/callback";
|
|
31
|
+
/**
|
|
32
|
+
* The loopback redirect this CLI asks for (RFC 8252). Overridable via
|
|
33
|
+
* OSD_MCP_CALLBACK_URL for authorization servers that exact-match
|
|
34
|
+
* redirect_uris against a pre-registered list (no DCR) — point it at one
|
|
35
|
+
* of the registered URIs. The override must stay on the loopback
|
|
36
|
+
* interface; the callback server only ever binds 127.0.0.1.
|
|
37
|
+
*/
|
|
38
|
+
function callbackUrl() {
|
|
39
|
+
const override = process.env.OSD_MCP_CALLBACK_URL;
|
|
40
|
+
if (override === undefined) {
|
|
41
|
+
return new URL(`http://127.0.0.1:${DEFAULT_CALLBACK_PORT}${DEFAULT_CALLBACK_PATH}`);
|
|
42
|
+
}
|
|
43
|
+
let parsed;
|
|
44
|
+
try {
|
|
45
|
+
parsed = new URL(override);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
throw new Error(`OSD_MCP_CALLBACK_URL is not a URL: ${override}`);
|
|
49
|
+
}
|
|
50
|
+
const host = parsed.hostname.replace(/^\[|\]$/g, "");
|
|
51
|
+
if (parsed.protocol !== "http:" || !(host === "127.0.0.1" || host === "::1" || host === "localhost")) {
|
|
52
|
+
throw new Error(`OSD_MCP_CALLBACK_URL must be an http:// loopback URL, got: ${override}`);
|
|
53
|
+
}
|
|
54
|
+
return parsed;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Whether a server-supplied authorization URL may be opened in the browser:
|
|
58
|
+
* https, or http on loopback (OAuth 2.1 §1.5). The SDK only rejects
|
|
59
|
+
* javascript:/data:/vbscript:, so without this a malicious server could make
|
|
60
|
+
* the CLI hand `file://...` or a custom app scheme to the OS URL handler.
|
|
61
|
+
*/
|
|
62
|
+
export function isSafeAuthorizationUrl(url) {
|
|
63
|
+
if (url.protocol === "https:")
|
|
64
|
+
return true;
|
|
65
|
+
const host = url.hostname.replace(/^\[|\]$/g, "");
|
|
66
|
+
return url.protocol === "http:" && (host === "localhost" || host === "::1" || /^127\./.test(host));
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Launches the system browser via the `open` package, which owns the
|
|
70
|
+
* per-platform mess: on Windows it uses PowerShell Start-Process with
|
|
71
|
+
* proper escaping (cmd /c start would re-parse & in the URL's query string
|
|
72
|
+
* as a command separator -- and the URL is server-controlled), on Linux it
|
|
73
|
+
* handles xdg-open detection and WSL. Resolves false when the launch
|
|
74
|
+
* fails; the caller prints the URL as a fallback either way.
|
|
75
|
+
*/
|
|
76
|
+
export async function openInBrowser(url) {
|
|
77
|
+
if (!isSafeAuthorizationUrl(url))
|
|
78
|
+
return false;
|
|
79
|
+
try {
|
|
80
|
+
const child = await open(url.toString(), { wait: false });
|
|
81
|
+
// By the time open() resolves, a successful spawn has already fired its
|
|
82
|
+
// `spawn` event; a live pid means the launcher process exists. Listen
|
|
83
|
+
// for a late `error` so it never becomes an unhandled rejection.
|
|
84
|
+
if (child.pid !== undefined) {
|
|
85
|
+
child.once("error", () => undefined);
|
|
86
|
+
return true;
|
|
87
|
+
}
|
|
88
|
+
return await new Promise((resolve) => {
|
|
89
|
+
child.once("error", () => resolve(false));
|
|
90
|
+
child.once("spawn", () => resolve(true));
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
export class CliOAuthProvider {
|
|
98
|
+
endpoint;
|
|
99
|
+
onAuthorizationUrl;
|
|
100
|
+
store;
|
|
101
|
+
record = {};
|
|
102
|
+
verifier;
|
|
103
|
+
stateValue = randomUUID();
|
|
104
|
+
redirect;
|
|
105
|
+
/** Set only during device polling; the SDK handles token parsing and client authentication. */
|
|
106
|
+
prepareTokenRequest;
|
|
107
|
+
constructor(endpoint, onAuthorizationUrl, store) {
|
|
108
|
+
this.endpoint = endpoint;
|
|
109
|
+
this.onAuthorizationUrl = onAuthorizationUrl;
|
|
110
|
+
this.store = store;
|
|
111
|
+
this.redirect = callbackUrl().toString();
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Provider pre-loaded with whatever is cached for this endpoint.
|
|
115
|
+
* Attach it even for anonymous use: the transport only sends tokens when
|
|
116
|
+
* the cache holds some, and the SDK needs a provider present to attempt
|
|
117
|
+
* refreshes.
|
|
118
|
+
*/
|
|
119
|
+
static async fromStore(endpoint, onAuthorizationUrl, store = new AuthStore()) {
|
|
120
|
+
const provider = new CliOAuthProvider(endpoint, onAuthorizationUrl, store);
|
|
121
|
+
provider.record = await store.read(endpoint);
|
|
122
|
+
return provider;
|
|
123
|
+
}
|
|
124
|
+
/** The loopback server may land on an ephemeral port; keep the redirect in sync. */
|
|
125
|
+
setRedirectUrl(redirect) {
|
|
126
|
+
this.redirect = redirect;
|
|
127
|
+
}
|
|
128
|
+
get redirectUrl() {
|
|
129
|
+
return this.redirect;
|
|
130
|
+
}
|
|
131
|
+
get clientMetadata() {
|
|
132
|
+
return {
|
|
133
|
+
client_name: "osd-cli",
|
|
134
|
+
redirect_uris: [this.redirect],
|
|
135
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
136
|
+
response_types: ["code"],
|
|
137
|
+
token_endpoint_auth_method: "none",
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
state() {
|
|
141
|
+
return this.stateValue;
|
|
142
|
+
}
|
|
143
|
+
clientInformation() {
|
|
144
|
+
return this.record.clientInformation;
|
|
145
|
+
}
|
|
146
|
+
async saveClientInformation(info) {
|
|
147
|
+
this.record.clientInformation = info;
|
|
148
|
+
await this.store.write(this.endpoint, this.record);
|
|
149
|
+
}
|
|
150
|
+
/** Stage a device client in memory; saveTokens commits the new pair after approval. */
|
|
151
|
+
stageClientInformation(info) {
|
|
152
|
+
const previous = this.record;
|
|
153
|
+
this.record = { ...previous, clientInformation: info };
|
|
154
|
+
return () => { this.record = previous; };
|
|
155
|
+
}
|
|
156
|
+
tokens() {
|
|
157
|
+
return this.record.tokens;
|
|
158
|
+
}
|
|
159
|
+
async saveTokens(tokens) {
|
|
160
|
+
this.record.tokens = tokens;
|
|
161
|
+
await this.store.write(this.endpoint, this.record);
|
|
162
|
+
}
|
|
163
|
+
redirectToAuthorization(authorizationUrl) {
|
|
164
|
+
// Throwing fails the SDK's auth() at once, instead of opening the URL or
|
|
165
|
+
// waiting out the callback timeout.
|
|
166
|
+
if (!isSafeAuthorizationUrl(authorizationUrl)) {
|
|
167
|
+
throw new Error(`refusing to open the authorization URL: ${authorizationUrl.protocol}//${authorizationUrl.host} ` +
|
|
168
|
+
"is not https (plain http is only allowed on loopback)");
|
|
169
|
+
}
|
|
170
|
+
this.onAuthorizationUrl(authorizationUrl);
|
|
171
|
+
}
|
|
172
|
+
saveCodeVerifier(codeVerifier) {
|
|
173
|
+
// The verifier never outlives one process run, so memory is the right
|
|
174
|
+
// store -- persisting it would only widen the window to steal it.
|
|
175
|
+
this.verifier = codeVerifier;
|
|
176
|
+
}
|
|
177
|
+
codeVerifier() {
|
|
178
|
+
if (this.verifier === undefined) {
|
|
179
|
+
throw new Error("no PKCE code verifier saved for this authorization attempt");
|
|
180
|
+
}
|
|
181
|
+
return this.verifier;
|
|
182
|
+
}
|
|
183
|
+
async invalidateCredentials(scope) {
|
|
184
|
+
if (scope === "all" || scope === "tokens")
|
|
185
|
+
this.record.tokens = undefined;
|
|
186
|
+
if (scope === "all" || scope === "client")
|
|
187
|
+
this.record.clientInformation = undefined;
|
|
188
|
+
if (scope === "all" || scope === "verifier")
|
|
189
|
+
this.verifier = undefined;
|
|
190
|
+
if (scope !== "verifier")
|
|
191
|
+
await this.store.write(this.endpoint, this.record);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
const CALLBACK_PAGE = (body) => `<!doctype html><html><head><title>osd-cli</title></head><body><p>${body}</p></body></html>`;
|
|
195
|
+
async function startCallbackServer() {
|
|
196
|
+
let expectedState;
|
|
197
|
+
let resolveCode;
|
|
198
|
+
let rejectCode;
|
|
199
|
+
// Buffered outcome for callbacks that land between arm() and waitForCode().
|
|
200
|
+
let buffered = null;
|
|
201
|
+
const deliver = (outcome) => {
|
|
202
|
+
if (resolveCode !== undefined && rejectCode !== undefined) {
|
|
203
|
+
if ("callback" in outcome)
|
|
204
|
+
resolveCode(outcome.callback);
|
|
205
|
+
else
|
|
206
|
+
rejectCode(outcome.error);
|
|
207
|
+
}
|
|
208
|
+
else {
|
|
209
|
+
buffered = outcome;
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
const expectedPath = callbackUrl().pathname;
|
|
213
|
+
const server = createServer((req, res) => {
|
|
214
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
215
|
+
if (url.pathname !== expectedPath) {
|
|
216
|
+
res.writeHead(404).end();
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
const errorParam = url.searchParams.get("error");
|
|
220
|
+
const code = url.searchParams.get("code");
|
|
221
|
+
const state = url.searchParams.get("state");
|
|
222
|
+
// State validation binds the callback to the attempt that opened the
|
|
223
|
+
// browser; it gates EVERYTHING, including error callbacks -- otherwise
|
|
224
|
+
// any local page could cancel a pending sign-in by pushing ?error=...
|
|
225
|
+
// at this port.
|
|
226
|
+
if (state === null || state !== expectedState) {
|
|
227
|
+
res
|
|
228
|
+
.writeHead(400, { "content-type": "text/html" })
|
|
229
|
+
.end(CALLBACK_PAGE("Invalid authorization callback."));
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
if (errorParam !== null) {
|
|
233
|
+
res
|
|
234
|
+
.writeHead(200, { "content-type": "text/html" })
|
|
235
|
+
.end(CALLBACK_PAGE("Authorization failed. You can close this tab."));
|
|
236
|
+
deliver({ error: new Error(`authorization server returned an error: ${errorParam}`) });
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
if (code === null) {
|
|
240
|
+
res
|
|
241
|
+
.writeHead(400, { "content-type": "text/html" })
|
|
242
|
+
.end(CALLBACK_PAGE("Invalid authorization callback."));
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
res
|
|
246
|
+
.writeHead(200, { "content-type": "text/html" })
|
|
247
|
+
.end(CALLBACK_PAGE("Signed in to osd-cli. You can close this tab."));
|
|
248
|
+
// `iss` rides along only after state validation has bound this callback
|
|
249
|
+
// to our attempt -- an unvalidated iss is attacker-controlled text.
|
|
250
|
+
deliver({ callback: { code, iss: url.searchParams.get("iss") ?? undefined } });
|
|
251
|
+
});
|
|
252
|
+
const preferred = callbackUrl();
|
|
253
|
+
const preferredPort = Number(preferred.port) || 80;
|
|
254
|
+
// Bind the host the redirect_uri actually names (127.0.0.1 by default):
|
|
255
|
+
// binding 127.0.0.1 while the AS redirects to [::1] or localhost is a
|
|
256
|
+
// guaranteed connection-refused hang.
|
|
257
|
+
const preferredHost = preferred.hostname.replace(/^\[|\]$/g, "");
|
|
258
|
+
const port = await new Promise((resolve, reject) => {
|
|
259
|
+
server.once("error", (error) => {
|
|
260
|
+
if (error.code !== "EADDRINUSE") {
|
|
261
|
+
reject(error);
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
// An explicit OSD_MCP_CALLBACK_URL is an exact-match contract with the
|
|
265
|
+
// authorization server: falling back to a random port would guarantee a
|
|
266
|
+
// redirect_uri mismatch, so fail loudly instead.
|
|
267
|
+
if (process.env.OSD_MCP_CALLBACK_URL !== undefined) {
|
|
268
|
+
reject(new Error(`callback port ${preferredPort} is already in use (OSD_MCP_CALLBACK_URL is set)`));
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
server.listen(0, preferredHost, () => resolve(server.address().port));
|
|
272
|
+
});
|
|
273
|
+
server.listen(preferredPort, preferredHost, () => resolve(server.address().port));
|
|
274
|
+
});
|
|
275
|
+
return {
|
|
276
|
+
port,
|
|
277
|
+
arm(state) {
|
|
278
|
+
expectedState = state;
|
|
279
|
+
},
|
|
280
|
+
waitForCode() {
|
|
281
|
+
const codePromise = new Promise((resolve, reject) => {
|
|
282
|
+
resolveCode = resolve;
|
|
283
|
+
rejectCode = reject;
|
|
284
|
+
});
|
|
285
|
+
// A rejection after the caller has stopped waiting (e.g. the refresh
|
|
286
|
+
// path returned AUTHORIZED without a browser round-trip) must not be
|
|
287
|
+
// an unhandled rejection.
|
|
288
|
+
codePromise.catch(() => undefined);
|
|
289
|
+
// A callback that landed between arm() and now settles immediately.
|
|
290
|
+
if (buffered !== null) {
|
|
291
|
+
const outcome = buffered;
|
|
292
|
+
buffered = null;
|
|
293
|
+
deliver(outcome);
|
|
294
|
+
}
|
|
295
|
+
let timer;
|
|
296
|
+
const timeout = new Promise((_, reject) => {
|
|
297
|
+
timer = setTimeout(() => reject(new Error("timed out waiting for the browser sign-in to complete")), AUTH_TIMEOUT_MS);
|
|
298
|
+
});
|
|
299
|
+
// Without clearing it, the referenced 10-minute timer keeps the
|
|
300
|
+
// one-shot CLI process alive after a successful (or failed) sign-in.
|
|
301
|
+
return Promise.race([codePromise, timeout]).finally(() => {
|
|
302
|
+
if (timer !== undefined)
|
|
303
|
+
clearTimeout(timer);
|
|
304
|
+
});
|
|
305
|
+
},
|
|
306
|
+
close() {
|
|
307
|
+
server.close();
|
|
308
|
+
},
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* The scopes this CLI asks for, read from what the server itself advertises
|
|
313
|
+
* (RFC 9728 protected-resource metadata first, then RFC 8414 authorization
|
|
314
|
+
* server metadata) -- an explicit, CLI-controlled choice instead of the SDK's
|
|
315
|
+
* silent default. Discovery goes through the SDK's own
|
|
316
|
+
* discoverOAuthServerInfo so this lookup takes literally the same path
|
|
317
|
+
* auth() will (including its origin-root fallback when the protected-resource
|
|
318
|
+
* document omits authorization_servers, which RFC 9728 makes OPTIONAL) --
|
|
319
|
+
* the logged list can never drift from what ends up on the wire.
|
|
320
|
+
* `offline_access` rides along ONLY when the authorization server advertises
|
|
321
|
+
* it (mirroring the SDK's append rule, given we always register the
|
|
322
|
+
* refresh_token grant): the CLI caches and refreshes tokens, so refresh
|
|
323
|
+
* tokens are legitimately needed, but an unadvertised offline_access is
|
|
324
|
+
* never requested. Returns no scopes when the server advertises no
|
|
325
|
+
* scopes_supported anywhere: request no scope rather than inventing one.
|
|
326
|
+
* A discovery FAILURE is reported separately (discoveryError) so the caller
|
|
327
|
+
* never logs "advertises no scopes" for a server it could not read.
|
|
328
|
+
*/
|
|
329
|
+
async function advertisedScopes(endpoint, fetchFn) {
|
|
330
|
+
let info;
|
|
331
|
+
try {
|
|
332
|
+
info = await discoverOAuthServerInfo(endpoint, { fetchFn });
|
|
333
|
+
}
|
|
334
|
+
catch (error) {
|
|
335
|
+
return {
|
|
336
|
+
scopes: undefined,
|
|
337
|
+
discoveryError: error instanceof Error ? error.message : String(error),
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
// When a scope list exists, the resource server's advertisement wins --
|
|
341
|
+
// it's the authority on what it accepts. The authorization server's list
|
|
342
|
+
// is the fallback for resource servers that don't declare scopes at all.
|
|
343
|
+
const scopes = info.resourceMetadata?.scopes_supported ?? info.authorizationServerMetadata?.scopes_supported;
|
|
344
|
+
if (scopes === undefined || scopes.length === 0) {
|
|
345
|
+
return { scopes: undefined, serverInfo: info };
|
|
346
|
+
}
|
|
347
|
+
// Mirror the SDK's offline_access rule (authorization-server metadata +
|
|
348
|
+
// refresh_token in the client's grant_types, which we always register):
|
|
349
|
+
// include offline_access only when the AUTHORIZATION SERVER advertises
|
|
350
|
+
// it. Without this the SDK would append it silently on top of the list
|
|
351
|
+
// we log -- the exact drift this gate exists to prevent.
|
|
352
|
+
const requested = new Set(scopes);
|
|
353
|
+
if (info.authorizationServerMetadata?.scopes_supported?.includes("offline_access") === true) {
|
|
354
|
+
requested.add("offline_access");
|
|
355
|
+
}
|
|
356
|
+
return { scopes: [...requested], serverInfo: info };
|
|
357
|
+
}
|
|
358
|
+
/** RFC 8628 sign-in for a public client, without a browser callback or loopback listener. */
|
|
359
|
+
export async function authorizeDeviceMcpEndpoint(endpoint, provider, hooks, deps) {
|
|
360
|
+
const guarded = createGuardedFetch(undefined, { allowLoopback: deps?.allowLoopback === true });
|
|
361
|
+
let deadline = Date.now() + AUTH_TIMEOUT_MS;
|
|
362
|
+
let restoreClient;
|
|
363
|
+
const fetchFn = async (input, init) => {
|
|
364
|
+
const response = await guarded.fetchFn(input, {
|
|
365
|
+
...init,
|
|
366
|
+
signal: AbortSignal.any([
|
|
367
|
+
AbortSignal.timeout(Math.max(1, Math.min(15_000, deadline - Date.now()))),
|
|
368
|
+
...(init?.signal ? [init.signal] : []),
|
|
369
|
+
]),
|
|
370
|
+
});
|
|
371
|
+
// The SDK checks instanceof global Response when parsing errors; undici has its own class.
|
|
372
|
+
return response.ok ? response : new Response(response.body, {
|
|
373
|
+
status: response.status, statusText: response.statusText, headers: response.headers,
|
|
374
|
+
});
|
|
375
|
+
};
|
|
376
|
+
try {
|
|
377
|
+
const advertised = await advertisedScopes(endpoint, fetchFn);
|
|
378
|
+
if (advertised.discoveryError) {
|
|
379
|
+
throw new Error(`Could not discover OAuth configuration: ${advertised.discoveryError}`);
|
|
380
|
+
}
|
|
381
|
+
const info = advertised.serverInfo;
|
|
382
|
+
const metadata = info?.authorizationServerMetadata;
|
|
383
|
+
const deviceEndpoint = metadata && "device_authorization_endpoint" in metadata
|
|
384
|
+
? metadata.device_authorization_endpoint : undefined;
|
|
385
|
+
if (!info || !metadata || typeof deviceEndpoint !== "string" ||
|
|
386
|
+
!metadata.grant_types_supported?.includes(DEVICE_GRANT)) {
|
|
387
|
+
throw new Error("The server does not advertise OAuth device authorization.");
|
|
388
|
+
}
|
|
389
|
+
const deviceUrl = new URL(deviceEndpoint);
|
|
390
|
+
if (!isSafeAuthorizationUrl(deviceUrl) || deviceUrl.username || deviceUrl.password) {
|
|
391
|
+
throw new Error("The server advertised an unsafe device authorization URL.");
|
|
392
|
+
}
|
|
393
|
+
const scope = advertised.scopes?.join(" ");
|
|
394
|
+
hooks.info(scope ? `Requesting OAuth scopes: ${scope}` : "The server advertises no OAuth scopes; requesting none.");
|
|
395
|
+
let client = provider.clientInformation();
|
|
396
|
+
if (client?.issuer !== metadata.issuer || !("grant_types" in client) ||
|
|
397
|
+
!client.grant_types?.includes(DEVICE_GRANT)) {
|
|
398
|
+
client = await registerClient(info.authorizationServerUrl, {
|
|
399
|
+
metadata,
|
|
400
|
+
clientMetadata: {
|
|
401
|
+
...provider.clientMetadata,
|
|
402
|
+
redirect_uris: [],
|
|
403
|
+
response_types: [],
|
|
404
|
+
grant_types: [
|
|
405
|
+
DEVICE_GRANT,
|
|
406
|
+
...(metadata.grant_types_supported.includes("refresh_token") ? ["refresh_token"] : []),
|
|
407
|
+
],
|
|
408
|
+
},
|
|
409
|
+
scope,
|
|
410
|
+
fetchFn,
|
|
411
|
+
});
|
|
412
|
+
if (!("grant_types" in client) || !client.grant_types?.includes(DEVICE_GRANT)) {
|
|
413
|
+
throw new Error("Client registration did not allow the device grant; check the server's registration response.");
|
|
414
|
+
}
|
|
415
|
+
client = { ...client, issuer: metadata.issuer };
|
|
416
|
+
}
|
|
417
|
+
if (client.client_secret || ("token_endpoint_auth_method" in client &&
|
|
418
|
+
client.token_endpoint_auth_method !== undefined && client.token_endpoint_auth_method !== "none")) {
|
|
419
|
+
throw new Error("Device sign-in requires a public OAuth client (token_endpoint_auth_method: none).");
|
|
420
|
+
}
|
|
421
|
+
restoreClient = provider.stageClientInformation(client);
|
|
422
|
+
const form = new URLSearchParams({ client_id: client.client_id });
|
|
423
|
+
if (scope)
|
|
424
|
+
form.set("scope", scope);
|
|
425
|
+
const started = await fetchFn(deviceUrl, {
|
|
426
|
+
method: "POST",
|
|
427
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
|
|
428
|
+
body: form,
|
|
429
|
+
});
|
|
430
|
+
if (!started.ok) {
|
|
431
|
+
await started.body?.cancel();
|
|
432
|
+
throw new Error(`Device authorization endpoint returned HTTP ${started.status}; check the account flag and OAuth client.`);
|
|
433
|
+
}
|
|
434
|
+
let device;
|
|
435
|
+
try {
|
|
436
|
+
device = await started.json();
|
|
437
|
+
}
|
|
438
|
+
catch {
|
|
439
|
+
throw new Error("The server returned an invalid device authorization response.");
|
|
440
|
+
}
|
|
441
|
+
if (!device || typeof device.device_code !== "string" || !device.device_code ||
|
|
442
|
+
typeof device.user_code !== "string" || !device.user_code ||
|
|
443
|
+
typeof device.verification_uri !== "string" ||
|
|
444
|
+
typeof device.expires_in !== "number" || !Number.isSafeInteger(device.expires_in) || device.expires_in <= 0 ||
|
|
445
|
+
(device.interval !== undefined && (typeof device.interval !== "number" ||
|
|
446
|
+
!Number.isSafeInteger(device.interval) || device.interval <= 0)) ||
|
|
447
|
+
(device.verification_uri_complete !== undefined && typeof device.verification_uri_complete !== "string")) {
|
|
448
|
+
throw new Error("The server returned an invalid device authorization response.");
|
|
449
|
+
}
|
|
450
|
+
for (const value of [device.verification_uri, device.verification_uri_complete]) {
|
|
451
|
+
if (typeof value !== "string")
|
|
452
|
+
continue;
|
|
453
|
+
const url = new URL(value);
|
|
454
|
+
if (!isSafeAuthorizationUrl(url) || url.username || url.password) {
|
|
455
|
+
throw new Error("The server returned an unsafe device verification URL.");
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
deadline = Math.min(deadline, Date.now() + device.expires_in * 1000);
|
|
459
|
+
let interval = (typeof device.interval === "number" ? device.interval : 5) * 1000;
|
|
460
|
+
hooks.info(`Authorize osd-cli by visiting:\n ${device.verification_uri_complete ?? device.verification_uri}\nEnter code: ${device.user_code}`);
|
|
461
|
+
hooks.info("Waiting for approval; keep this command running. Only approve a request you started.");
|
|
462
|
+
provider.prepareTokenRequest = () => new URLSearchParams({
|
|
463
|
+
grant_type: DEVICE_GRANT,
|
|
464
|
+
device_code: device.device_code,
|
|
465
|
+
});
|
|
466
|
+
while (Date.now() < deadline) {
|
|
467
|
+
await delay(Math.min(interval, deadline - Date.now()));
|
|
468
|
+
if (Date.now() >= deadline)
|
|
469
|
+
break;
|
|
470
|
+
let tokens;
|
|
471
|
+
try {
|
|
472
|
+
tokens = await fetchToken(provider, info.authorizationServerUrl, { metadata, resource: endpoint, fetchFn });
|
|
473
|
+
}
|
|
474
|
+
catch (error) {
|
|
475
|
+
if (error instanceof OAuthError) {
|
|
476
|
+
if (error.code === "authorization_pending")
|
|
477
|
+
continue;
|
|
478
|
+
if (error.code === "slow_down") {
|
|
479
|
+
interval += 5000;
|
|
480
|
+
continue;
|
|
481
|
+
}
|
|
482
|
+
throw new Error(error.code === "access_denied" ? "Device authorization was denied." :
|
|
483
|
+
error.code === "expired_token" ? "Device authorization expired; start sign-in again." :
|
|
484
|
+
"The token endpoint rejected device authorization; check the OAuth client and server configuration.");
|
|
485
|
+
}
|
|
486
|
+
if (error instanceof Error && (error.name === "TimeoutError" ||
|
|
487
|
+
["ETIMEDOUT", "UND_ERR_CONNECT_TIMEOUT"].includes(error.cause?.code ?? ""))) {
|
|
488
|
+
interval *= 2;
|
|
489
|
+
continue;
|
|
490
|
+
}
|
|
491
|
+
throw new Error("Device token polling failed; check connectivity and the token endpoint response.");
|
|
492
|
+
}
|
|
493
|
+
await provider.saveTokens({ ...tokens, issuer: metadata.issuer });
|
|
494
|
+
restoreClient = undefined;
|
|
495
|
+
return { kind: "authorized" };
|
|
496
|
+
}
|
|
497
|
+
throw new Error("Device authorization expired; start sign-in again.");
|
|
498
|
+
}
|
|
499
|
+
catch (error) {
|
|
500
|
+
return { kind: "failed", message: error instanceof Error ? error.message : String(error) };
|
|
501
|
+
}
|
|
502
|
+
finally {
|
|
503
|
+
restoreClient?.();
|
|
504
|
+
provider.prepareTokenRequest = undefined;
|
|
505
|
+
await guarded.close().catch(() => undefined);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
/** Prefer the advertised device flow; retain browser authorization for other servers. */
|
|
509
|
+
export async function authorizeMcpEndpoint(endpoint, provider, hooks, deps) {
|
|
510
|
+
const guarded = createGuardedFetch(undefined, { allowLoopback: deps?.allowLoopback === true });
|
|
511
|
+
let useDevice = false;
|
|
512
|
+
try {
|
|
513
|
+
const info = await discoverOAuthServerInfo(endpoint, {
|
|
514
|
+
fetchFn: (input, init) => guarded.fetchFn(input, { ...init, signal: AbortSignal.timeout(15_000) }),
|
|
515
|
+
});
|
|
516
|
+
const metadata = info.authorizationServerMetadata;
|
|
517
|
+
useDevice = metadata?.grant_types_supported?.includes(DEVICE_GRANT) === true &&
|
|
518
|
+
"device_authorization_endpoint" in metadata && typeof metadata.device_authorization_endpoint === "string";
|
|
519
|
+
}
|
|
520
|
+
catch (error) {
|
|
521
|
+
return { kind: "failed", message: `Could not discover OAuth configuration: ${error instanceof Error ? error.message : String(error)}` };
|
|
522
|
+
}
|
|
523
|
+
finally {
|
|
524
|
+
await guarded.close().catch(() => undefined);
|
|
525
|
+
}
|
|
526
|
+
return useDevice
|
|
527
|
+
? authorizeDeviceMcpEndpoint(endpoint, provider, hooks, deps)
|
|
528
|
+
: authorizeBrowserMcpEndpoint(endpoint, provider, hooks, deps);
|
|
529
|
+
}
|
|
530
|
+
/**
|
|
531
|
+
* Runs the full browser-based authorization flow for an endpoint, persisting
|
|
532
|
+
* client registration and tokens in the store. Reuses the caller's provider so
|
|
533
|
+
* the record survives into the retried connection.
|
|
534
|
+
*/
|
|
535
|
+
async function authorizeBrowserMcpEndpoint(endpoint, provider, hooks, deps) {
|
|
536
|
+
// OAuth metadata/registration/token requests go through the same guarded
|
|
537
|
+
// fetch as the MCP transport: a server-controlled protected-resource or
|
|
538
|
+
// authorization URL must not reach private addresses either.
|
|
539
|
+
const guarded = createGuardedFetch(undefined, { allowLoopback: deps?.allowLoopback === true });
|
|
540
|
+
const callback = await startCallbackServer();
|
|
541
|
+
// Preserve the configured host/path (OSD_MCP_CALLBACK_URL or the default);
|
|
542
|
+
// only the actual bound port is substituted, and only the ephemeral
|
|
543
|
+
// fallback ever changes it.
|
|
544
|
+
const actual = callbackUrl();
|
|
545
|
+
actual.port = String(callback.port);
|
|
546
|
+
provider.setRedirectUrl(actual.toString());
|
|
547
|
+
// A cached dynamic client registration is bound to the redirect URI it was
|
|
548
|
+
// registered with. If the bound callback differs now (e.g. the fixed port
|
|
549
|
+
// was occupied and we fell back to an ephemeral one), an exact-matching
|
|
550
|
+
// authorization server would reject the sign-in -- drop the stale
|
|
551
|
+
// registration so DCR re-registers with the current redirect.
|
|
552
|
+
const registered = provider.clientInformation();
|
|
553
|
+
const registeredRedirects = registered !== undefined && "redirect_uris" in registered
|
|
554
|
+
? registered.redirect_uris
|
|
555
|
+
: undefined;
|
|
556
|
+
if (registeredRedirects !== undefined && !registeredRedirects.includes(actual.toString())) {
|
|
557
|
+
await provider.invalidateCredentials("client");
|
|
558
|
+
}
|
|
559
|
+
// Arm BEFORE auth(): the SDK calls redirectToAuthorization before it
|
|
560
|
+
// returns, and a fast authorization server can beat a late-armed waiter
|
|
561
|
+
// (its callback would get a 400 and the flow would hang until timeout).
|
|
562
|
+
callback.arm(provider.state());
|
|
563
|
+
try {
|
|
564
|
+
// Decide the requested scope HERE, visibly, from the server's own
|
|
565
|
+
// advertisement -- when the CLI passes no scope, the SDK silently asks
|
|
566
|
+
// for everything the server lists (a security review finding). Logged so the
|
|
567
|
+
// privilege about to be granted is auditable before the browser opens.
|
|
568
|
+
const advertised = await advertisedScopes(endpoint, guarded.fetchFn);
|
|
569
|
+
hooks.info(advertised.scopes !== undefined
|
|
570
|
+
? `Requesting OAuth scopes: ${advertised.scopes.join(" ")}`
|
|
571
|
+
: advertised.discoveryError !== undefined
|
|
572
|
+
? `Could not read the server's OAuth scope metadata (${advertised.discoveryError}); requesting none.`
|
|
573
|
+
: "The server advertises no OAuth scopes; requesting none.");
|
|
574
|
+
const scope = advertised.scopes?.join(" ");
|
|
575
|
+
// No authorizationCode: discovery, registration, PKCE, then the SDK
|
|
576
|
+
// calls provider.redirectToAuthorization and returns "REDIRECT".
|
|
577
|
+
const phase = await auth(provider, { serverUrl: endpoint, scope, fetchFn: guarded.fetchFn, forceReauthorization: true });
|
|
578
|
+
if (phase === "AUTHORIZED")
|
|
579
|
+
return { kind: "authorized" };
|
|
580
|
+
hooks.info("waiting for the browser sign-in to complete (up to 10 minutes)...");
|
|
581
|
+
const callbackResult = await callback.waitForCode();
|
|
582
|
+
const done = await auth(provider, {
|
|
583
|
+
serverUrl: endpoint,
|
|
584
|
+
scope,
|
|
585
|
+
authorizationCode: callbackResult.code,
|
|
586
|
+
// RFC 9207 §2.4: when the AS advertises iss support the SDK validates
|
|
587
|
+
// this against the discovered issuer BEFORE redeeming the code, and
|
|
588
|
+
// throws IssuerMismatchError when it's missing or wrong. Forward it.
|
|
589
|
+
iss: callbackResult.iss,
|
|
590
|
+
fetchFn: guarded.fetchFn,
|
|
591
|
+
});
|
|
592
|
+
return done === "AUTHORIZED"
|
|
593
|
+
? { kind: "authorized" }
|
|
594
|
+
: { kind: "failed", message: "authorization did not complete" };
|
|
595
|
+
}
|
|
596
|
+
catch (error) {
|
|
597
|
+
return { kind: "failed", message: error instanceof Error ? error.message : String(error) };
|
|
598
|
+
}
|
|
599
|
+
finally {
|
|
600
|
+
callback.close();
|
|
601
|
+
await guarded.close().catch(() => undefined);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal MCP server-card handling: just enough to tell "this JSON document
|
|
3
|
+
* is a server card" apart from "this is an endpoint URL", and to pull the
|
|
4
|
+
* connection endpoint out of a card.
|
|
5
|
+
*
|
|
6
|
+
* The full card schema lives at https://static.modelcontextprotocol.io —
|
|
7
|
+
* this CLI deliberately does not validate against it. Registration needs
|
|
8
|
+
* only the streamable-http remote; strict validation would reject cards
|
|
9
|
+
* from servers whose schema drafts differ slightly from ours.
|
|
10
|
+
*/
|
|
11
|
+
export interface McpServerCard {
|
|
12
|
+
name?: string;
|
|
13
|
+
displayName?: string;
|
|
14
|
+
remotes?: Array<{
|
|
15
|
+
type?: string;
|
|
16
|
+
url?: string;
|
|
17
|
+
}>;
|
|
18
|
+
}
|
|
19
|
+
/** True when the document looks like an MCP server card. */
|
|
20
|
+
export declare function isServerCard(doc: unknown): doc is McpServerCard;
|
|
21
|
+
/** First streamable-http remote URL in the card, if any. */
|
|
22
|
+
export declare function cardEndpoint(card: McpServerCard): string | null;
|
|
23
|
+
export declare function remoteCount(card: McpServerCard): number;
|
package/dist/mcp-card.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** True when the document looks like an MCP server card. */
|
|
2
|
+
export function isServerCard(doc) {
|
|
3
|
+
return (typeof doc === "object" &&
|
|
4
|
+
doc !== null &&
|
|
5
|
+
Array.isArray(doc.remotes));
|
|
6
|
+
}
|
|
7
|
+
/** First streamable-http remote URL in the card, if any. */
|
|
8
|
+
export function cardEndpoint(card) {
|
|
9
|
+
const remote = (card.remotes ?? []).find((r) => r !== null &&
|
|
10
|
+
typeof r === "object" &&
|
|
11
|
+
r.type === "streamable-http" &&
|
|
12
|
+
typeof r.url === "string" &&
|
|
13
|
+
r.url.length > 0);
|
|
14
|
+
return remote?.url ?? null;
|
|
15
|
+
}
|
|
16
|
+
export function remoteCount(card) {
|
|
17
|
+
return card.remotes?.length ?? 0;
|
|
18
|
+
}
|