@casys/mcp-server 0.26.1 → 0.27.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/CHANGELOG.md +15 -0
- package/LICENSE +21 -0
- package/README.md +10 -627
- package/esm/mod.d.ts +1 -0
- package/esm/mod.js +1 -0
- package/package.json +28 -25
- package/mod.ts +0 -302
- package/src/auth/as-metadata-proxy.ts +0 -288
- package/src/auth/config.ts +0 -368
- package/src/auth/jwt-provider.ts +0 -327
- package/src/auth/middleware.ts +0 -257
- package/src/auth/mod.ts +0 -89
- package/src/auth/multi-tenant-middleware.ts +0 -236
- package/src/auth/presets.ts +0 -351
- package/src/auth/provider.ts +0 -49
- package/src/auth/scope-middleware.ts +0 -59
- package/src/auth/static-token-provider.ts +0 -197
- package/src/auth/types.ts +0 -207
- package/src/client-auth/callback-server.ts +0 -166
- package/src/client-auth/client-id-metadata.ts +0 -260
- package/src/client-auth/connect.ts +0 -72
- package/src/client-auth/mod.ts +0 -44
- package/src/client-auth/provider.ts +0 -300
- package/src/client-auth/token-store/file-store.ts +0 -73
- package/src/client-auth/token-store/memory-store.ts +0 -32
- package/src/client-auth/types.ts +0 -95
- package/src/concurrency/rate-limiter.ts +0 -190
- package/src/concurrency/request-queue.ts +0 -140
- package/src/http/body.ts +0 -72
- package/src/http/request-guards.ts +0 -137
- package/src/http/wire.ts +0 -41
- package/src/inspector/launcher.ts +0 -131
- package/src/mcp-app.ts +0 -4595
- package/src/middleware/backpressure.ts +0 -36
- package/src/middleware/mod.ts +0 -21
- package/src/middleware/rate-limit.ts +0 -45
- package/src/middleware/runner.ts +0 -63
- package/src/middleware/types.ts +0 -104
- package/src/middleware/validation.ts +0 -28
- package/src/mrtr/capability-check.ts +0 -303
- package/src/mrtr/mod.ts +0 -54
- package/src/mrtr/replay-store.ts +0 -103
- package/src/mrtr/request-state.ts +0 -435
- package/src/mrtr/retry-guard.ts +0 -110
- package/src/mrtr/types.ts +0 -107
- package/src/observability/metrics.ts +0 -336
- package/src/observability/mod.ts +0 -21
- package/src/observability/otel.ts +0 -330
- package/src/runtime/runtime.deno.ts +0 -149
- package/src/runtime/runtime.node.ts +0 -324
- package/src/runtime/runtime.ts +0 -50
- package/src/runtime/types.ts +0 -130
- package/src/security/channel-hmac.ts +0 -140
- package/src/security/csp.ts +0 -89
- package/src/security/message-signer.ts +0 -223
- package/src/subscriptions/subscription-registry.ts +0 -558
- package/src/tasks/mod.ts +0 -33
- package/src/tasks/task-store.ts +0 -1014
- package/src/transport/request-headers.ts +0 -661
- package/src/types.ts +0 -908
- package/src/ui/viewer-utils.ts +0 -117
- package/src/validation/schema-validator.ts +0 -307
package/src/auth/types.ts
DELETED
|
@@ -1,207 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Authentication types for McpApp.
|
|
3
|
-
*
|
|
4
|
-
* Types follow RFC 9728 (OAuth Protected Resource Metadata)
|
|
5
|
-
* and MCP Auth spec (draft 2025-11-25).
|
|
6
|
-
*
|
|
7
|
-
* @module lib/server/auth/types
|
|
8
|
-
*/
|
|
9
|
-
|
|
10
|
-
// ============================================================================
|
|
11
|
-
// HttpsUrl brand — 0.16.0
|
|
12
|
-
// ============================================================================
|
|
13
|
-
|
|
14
|
-
declare const httpsUrlBrand: unique symbol;
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* A string that has been validated as a syntactically valid absolute HTTP(S)
|
|
18
|
-
* URL. Cannot be constructed by type assertion — callers MUST go through
|
|
19
|
-
* {@link httpsUrl} (which parses, normalizes, and throws on invalid input) so
|
|
20
|
-
* the invariant is enforced at both the type level and runtime.
|
|
21
|
-
*
|
|
22
|
-
* Added in 0.16.0 to lift `resource_metadata_url`, `authorization_servers`,
|
|
23
|
-
* and the URL-resource branch of {@link JwtAuthProviderOptions} from raw
|
|
24
|
-
* `string` into a type that structurally encodes the invariant. The motivating
|
|
25
|
-
* incident was 0.14.x silently producing `"://host/.well-known/..."` in
|
|
26
|
-
* `WWW-Authenticate` headers when callers mis-set `resource` — a class of bug
|
|
27
|
-
* that 0.15.x closed with runtime guards and 0.16.0 closes at the type level.
|
|
28
|
-
*/
|
|
29
|
-
export type HttpsUrl = string & { readonly [httpsUrlBrand]: never };
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* Parse, validate, and normalize a string as an absolute HTTP(S) URL.
|
|
33
|
-
*
|
|
34
|
-
* Trims leading/trailing whitespace before parsing so YAML keys with trailing
|
|
35
|
-
* spaces don't produce unparseable URLs. Delegates parsing to `new URL()`,
|
|
36
|
-
* which lowercases the scheme — so `HTTPS://foo.com` is accepted and returned
|
|
37
|
-
* as `https://foo.com/`.
|
|
38
|
-
*
|
|
39
|
-
* @throws if the string is empty/whitespace-only, unparseable as a URL, or
|
|
40
|
-
* uses a non-HTTP(S) scheme (RFC 9728 § 3 requires HTTPS for metadata
|
|
41
|
-
* documents; http is permitted here for local dev only).
|
|
42
|
-
*
|
|
43
|
-
* @example
|
|
44
|
-
* ```typescript
|
|
45
|
-
* const url = httpsUrl("https://my-mcp.example.com");
|
|
46
|
-
* // url is of type HttpsUrl and can be passed wherever HttpsUrl is required.
|
|
47
|
-
* ```
|
|
48
|
-
*/
|
|
49
|
-
export function httpsUrl(raw: string): HttpsUrl {
|
|
50
|
-
const trimmed = raw.trim();
|
|
51
|
-
if (trimmed.length === 0) {
|
|
52
|
-
throw new Error(
|
|
53
|
-
`[httpsUrl] empty or whitespace-only string is not a valid URL. ` +
|
|
54
|
-
`Expected an absolute HTTP(S) URL like ` +
|
|
55
|
-
`"https://my-mcp.example.com/.well-known/oauth-protected-resource".`,
|
|
56
|
-
);
|
|
57
|
-
}
|
|
58
|
-
let parsed: URL;
|
|
59
|
-
try {
|
|
60
|
-
parsed = new URL(trimmed);
|
|
61
|
-
} catch {
|
|
62
|
-
throw new Error(
|
|
63
|
-
`[httpsUrl] not a parseable URL: ${JSON.stringify(raw)}. ` +
|
|
64
|
-
`Expected an absolute HTTP(S) URL like ` +
|
|
65
|
-
`"https://my-mcp.example.com/.well-known/oauth-protected-resource".`,
|
|
66
|
-
);
|
|
67
|
-
}
|
|
68
|
-
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
|
|
69
|
-
throw new Error(
|
|
70
|
-
`[httpsUrl] must use http:// or https:// scheme, got ${
|
|
71
|
-
JSON.stringify(parsed.protocol)
|
|
72
|
-
} in ${JSON.stringify(raw)}. Per RFC 9728 § 3, the protected resource ` +
|
|
73
|
-
`metadata document must be served over HTTP(S).`,
|
|
74
|
-
);
|
|
75
|
-
}
|
|
76
|
-
return parsed.toString() as HttpsUrl;
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
/**
|
|
80
|
-
* Non-throwing variant of {@link httpsUrl}. Returns the normalized `HttpsUrl`
|
|
81
|
-
* on success, `null` on any validation failure. Use this when you need to
|
|
82
|
-
* branch on validity without catching exceptions — typically to detect whether
|
|
83
|
-
* an RFC 9728 § 2 `resource` identifier is an HTTP(S) URL (the URL-resource
|
|
84
|
-
* branch) or an opaque URI (the opaque-resource branch that requires an
|
|
85
|
-
* explicit metadata URL).
|
|
86
|
-
*/
|
|
87
|
-
export function tryHttpsUrl(raw: string): HttpsUrl | null {
|
|
88
|
-
try {
|
|
89
|
-
return httpsUrl(raw);
|
|
90
|
-
} catch {
|
|
91
|
-
return null;
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
// ============================================================================
|
|
96
|
-
// Runtime auth types
|
|
97
|
-
// ============================================================================
|
|
98
|
-
|
|
99
|
-
/**
|
|
100
|
-
* Information extracted from a validated token.
|
|
101
|
-
* Frozen (Object.freeze) before being passed to tool handlers.
|
|
102
|
-
*/
|
|
103
|
-
export interface AuthInfo {
|
|
104
|
-
/** User ID (sub claim from JWT) */
|
|
105
|
-
subject: string;
|
|
106
|
-
|
|
107
|
-
/** OAuth client ID (optional - azp or client_id claim) */
|
|
108
|
-
clientId?: string;
|
|
109
|
-
|
|
110
|
-
/** Granted scopes */
|
|
111
|
-
scopes: string[];
|
|
112
|
-
|
|
113
|
-
/** Additional JWT claims */
|
|
114
|
-
claims?: Record<string, unknown>;
|
|
115
|
-
|
|
116
|
-
/** Token expiration timestamp (Unix epoch seconds) */
|
|
117
|
-
expiresAt?: number;
|
|
118
|
-
|
|
119
|
-
/**
|
|
120
|
-
* Tenant identifier for multi-tenant servers.
|
|
121
|
-
*
|
|
122
|
-
* Populated by `createMultiTenantMiddleware` when a `TenantResolver`
|
|
123
|
-
* is configured. Undefined on single-tenant servers.
|
|
124
|
-
*
|
|
125
|
-
* Tool handlers in multi-tenant servers should read this (never trust
|
|
126
|
-
* raw JWT claims directly) to scope data access to the current tenant.
|
|
127
|
-
*/
|
|
128
|
-
tenantId?: string;
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
/**
|
|
132
|
-
* Auth configuration slot for {@link McpAppOptions.auth}.
|
|
133
|
-
*
|
|
134
|
-
* 0.17.0: slimmed to a single `provider` field. Previously exposed
|
|
135
|
-
* `authorizationServers`, `resource`, and `scopesSupported` fields that
|
|
136
|
-
* were NEVER read by `McpApp` at runtime (only `provider` was consumed at
|
|
137
|
-
* `mcp-app.ts:1061`). Those fields were vestigial from a pre-0.15 design
|
|
138
|
-
* where `McpApp` could auto-construct a `JwtAuthProvider` from its own
|
|
139
|
-
* `auth:` option; that auto-construction path was removed when
|
|
140
|
-
* `createAuthProviderFromConfig` took over YAML/env provider construction,
|
|
141
|
-
* but the dead fields stayed in the interface. 0.17.0 deletes them as part
|
|
142
|
-
* of the auth-module cleanup (Casys-AI/mcp-server#13).
|
|
143
|
-
*
|
|
144
|
-
* The interface is kept (rather than reducing `McpAppOptions.auth` to a
|
|
145
|
-
* bare `AuthProvider`) so that future additions like pipeline-level auth
|
|
146
|
-
* hooks have a named extension point without another BC break.
|
|
147
|
-
*/
|
|
148
|
-
export interface AuthOptions {
|
|
149
|
-
/**
|
|
150
|
-
* The `AuthProvider` that validates bearer tokens and produces RFC 9728
|
|
151
|
-
* metadata. Construct via {@link JwtAuthProvider}, any of the preset
|
|
152
|
-
* factories (`createGitHubAuthProvider`, `createGoogleAuthProvider`,
|
|
153
|
-
* `createAuth0AuthProvider`, `createOIDCAuthProvider`), or a custom
|
|
154
|
-
* `AuthProvider` subclass for non-JWT token schemes.
|
|
155
|
-
*/
|
|
156
|
-
provider: AuthProvider;
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
// Forward reference - actual class is in provider.ts
|
|
160
|
-
import type { AuthProvider } from "./provider.js";
|
|
161
|
-
|
|
162
|
-
/**
|
|
163
|
-
* RFC 9728 Protected Resource Metadata.
|
|
164
|
-
* Returned by /.well-known/oauth-protected-resource
|
|
165
|
-
*
|
|
166
|
-
* @see https://datatracker.ietf.org/doc/html/rfc9728
|
|
167
|
-
*/
|
|
168
|
-
export interface ProtectedResourceMetadata {
|
|
169
|
-
/**
|
|
170
|
-
* RFC 9728 § 2 resource identifier. URI that identifies the protected
|
|
171
|
-
* resource — used as the JWT `aud` claim. Can be an HTTP(S) URL OR an
|
|
172
|
-
* opaque URI (e.g., an OIDC project ID). Stays `string` because RFC 9728
|
|
173
|
-
* explicitly allows opaque URIs; callers must NOT assume it parses as
|
|
174
|
-
* an URL.
|
|
175
|
-
*/
|
|
176
|
-
resource: string;
|
|
177
|
-
|
|
178
|
-
/**
|
|
179
|
-
* Absolute HTTP(S) URL where this metadata document is served publicly.
|
|
180
|
-
* Per RFC 9728 § 3, this is the URL a client discovers via the
|
|
181
|
-
* WWW-Authenticate challenge. Always an HTTP(S) URL, regardless of
|
|
182
|
-
* whether `resource` itself is an URL or an opaque URI.
|
|
183
|
-
*
|
|
184
|
-
* 0.16.0: typed as {@link HttpsUrl} (branded). The invariant is now
|
|
185
|
-
* structurally enforced — producers must construct the value via
|
|
186
|
-
* {@link httpsUrl}, which validates at runtime AND returns the brand.
|
|
187
|
-
* Prior to 0.16.0 this was a raw `string` guarded only by a runtime
|
|
188
|
-
* validator in the `JwtAuthProvider` constructor (0.15.1).
|
|
189
|
-
*/
|
|
190
|
-
resource_metadata_url: HttpsUrl;
|
|
191
|
-
|
|
192
|
-
/**
|
|
193
|
-
* Authorization servers that can issue valid tokens.
|
|
194
|
-
*
|
|
195
|
-
* 0.16.0: each element is branded as {@link HttpsUrl} so downstream
|
|
196
|
-
* consumers (e.g., MCP clients building discovery URLs) can rely on
|
|
197
|
-
* them being parseable absolute URLs without re-validation. Construct
|
|
198
|
-
* via {@link httpsUrl}.
|
|
199
|
-
*/
|
|
200
|
-
authorization_servers: HttpsUrl[];
|
|
201
|
-
|
|
202
|
-
/** Scopes this resource supports */
|
|
203
|
-
scopes_supported?: string[];
|
|
204
|
-
|
|
205
|
-
/** How bearer tokens can be presented (always ["header"]) */
|
|
206
|
-
bearer_methods_supported: string[];
|
|
207
|
-
}
|
|
@@ -1,166 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Localhost callback server for OAuth PKCE redirect capture.
|
|
3
|
-
*
|
|
4
|
-
* Starts a temporary HTTP server on localhost to receive the
|
|
5
|
-
* authorization code from the OAuth redirect. Shuts down
|
|
6
|
-
* after receiving the code or on timeout.
|
|
7
|
-
*
|
|
8
|
-
* @module lib/server/client-auth/callback-server
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
import { serve, type ServeHandle } from "../runtime/runtime.js";
|
|
12
|
-
|
|
13
|
-
export interface CallbackServerOptions {
|
|
14
|
-
/** Port to listen on (0 = auto-assign, default: 0) */
|
|
15
|
-
port?: number;
|
|
16
|
-
/** Hostname to bind (default: 127.0.0.1) */
|
|
17
|
-
hostname?: string;
|
|
18
|
-
/** Timeout in ms (default: 120_000) */
|
|
19
|
-
timeout?: number;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
const SUCCESS_HTML = `<!DOCTYPE html>
|
|
23
|
-
<html><head><title>PML Auth</title><style>
|
|
24
|
-
body{font-family:system-ui;display:flex;justify-content:center;align-items:center;height:100vh;margin:0;background:#08080a;color:#fff}
|
|
25
|
-
.card{text-align:center;padding:2rem}h1{color:#FFB86F}
|
|
26
|
-
</style></head><body><div class="card">
|
|
27
|
-
<h1>Authentication successful</h1>
|
|
28
|
-
<p>You can close this tab and return to the terminal.</p>
|
|
29
|
-
</div></body></html>`;
|
|
30
|
-
|
|
31
|
-
const ERROR_HTML = `<!DOCTYPE html>
|
|
32
|
-
<html><head><title>PML Auth Error</title><style>
|
|
33
|
-
body{font-family:system-ui;display:flex;justify-content:center;align-items:center;height:100vh;margin:0;background:#08080a;color:#fff}
|
|
34
|
-
.card{text-align:center;padding:2rem}h1{color:#ff6b6b}
|
|
35
|
-
</style></head><body><div class="card">
|
|
36
|
-
<h1>Authentication failed</h1>
|
|
37
|
-
<p>Missing authorization code. Please try again.</p>
|
|
38
|
-
</div></body></html>`;
|
|
39
|
-
|
|
40
|
-
export class CallbackServer {
|
|
41
|
-
private port: number;
|
|
42
|
-
private hostname: string;
|
|
43
|
-
private timeout: number;
|
|
44
|
-
private server: ServeHandle | null = null;
|
|
45
|
-
private timerId: ReturnType<typeof setTimeout> | null = null;
|
|
46
|
-
private closeTimerId: ReturnType<typeof setTimeout> | null = null;
|
|
47
|
-
|
|
48
|
-
constructor(options?: CallbackServerOptions) {
|
|
49
|
-
this.port = options?.port ?? 0;
|
|
50
|
-
this.hostname = options?.hostname ?? "127.0.0.1";
|
|
51
|
-
this.timeout = options?.timeout ?? 120_000;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
async start(): Promise<{ port: number; codePromise: Promise<string> }> {
|
|
55
|
-
let resolveCode!: (code: string) => void;
|
|
56
|
-
let rejectCode!: (err: Error) => void;
|
|
57
|
-
const codePromise = new Promise<string>((resolve, reject) => {
|
|
58
|
-
resolveCode = resolve;
|
|
59
|
-
rejectCode = reject;
|
|
60
|
-
});
|
|
61
|
-
let resolveListen!: (port: number) => void;
|
|
62
|
-
let rejectListen!: (err: Error) => void;
|
|
63
|
-
const listenPromise = new Promise<number>((resolve) => {
|
|
64
|
-
resolveListen = resolve;
|
|
65
|
-
});
|
|
66
|
-
const bindPromise = new Promise<never>((_, reject) => {
|
|
67
|
-
rejectListen = reject;
|
|
68
|
-
});
|
|
69
|
-
|
|
70
|
-
this.timerId = setTimeout(() => {
|
|
71
|
-
this.timerId = null;
|
|
72
|
-
rejectCode(
|
|
73
|
-
new Error(
|
|
74
|
-
"OAuth callback timeout — no authorization code received",
|
|
75
|
-
),
|
|
76
|
-
);
|
|
77
|
-
this.close();
|
|
78
|
-
}, this.timeout);
|
|
79
|
-
|
|
80
|
-
try {
|
|
81
|
-
this.server = serve(
|
|
82
|
-
{
|
|
83
|
-
port: this.port,
|
|
84
|
-
hostname: this.hostname,
|
|
85
|
-
onListen: ({ port }) => {
|
|
86
|
-
this.port = port;
|
|
87
|
-
resolveListen(port);
|
|
88
|
-
},
|
|
89
|
-
onError: (err) => {
|
|
90
|
-
rejectListen(err);
|
|
91
|
-
},
|
|
92
|
-
},
|
|
93
|
-
(req) => {
|
|
94
|
-
const url = new URL(req.url);
|
|
95
|
-
if (url.pathname === "/callback") {
|
|
96
|
-
const code = url.searchParams.get("code");
|
|
97
|
-
if (!code) {
|
|
98
|
-
return new Response(ERROR_HTML, {
|
|
99
|
-
status: 400,
|
|
100
|
-
headers: { "Content-Type": "text/html" },
|
|
101
|
-
});
|
|
102
|
-
}
|
|
103
|
-
if (this.timerId) {
|
|
104
|
-
clearTimeout(this.timerId);
|
|
105
|
-
this.timerId = null;
|
|
106
|
-
}
|
|
107
|
-
resolveCode(code);
|
|
108
|
-
// Schedule close after response is sent
|
|
109
|
-
this.closeTimerId = setTimeout(() => {
|
|
110
|
-
this.closeTimerId = null;
|
|
111
|
-
this.close();
|
|
112
|
-
}, 100);
|
|
113
|
-
return new Response(SUCCESS_HTML, {
|
|
114
|
-
status: 200,
|
|
115
|
-
headers: { "Content-Type": "text/html" },
|
|
116
|
-
});
|
|
117
|
-
}
|
|
118
|
-
return new Response("Not Found", { status: 404 });
|
|
119
|
-
},
|
|
120
|
-
);
|
|
121
|
-
} catch (err) {
|
|
122
|
-
await this.cleanupAfterStartFailure();
|
|
123
|
-
throw err;
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
let port: number;
|
|
127
|
-
try {
|
|
128
|
-
port = await Promise.race([listenPromise, bindPromise]);
|
|
129
|
-
} catch (err) {
|
|
130
|
-
await this.cleanupAfterStartFailure();
|
|
131
|
-
throw err;
|
|
132
|
-
}
|
|
133
|
-
return { port, codePromise };
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
async close(): Promise<void> {
|
|
137
|
-
this.clearTimers();
|
|
138
|
-
if (this.server) {
|
|
139
|
-
await this.server.shutdown();
|
|
140
|
-
this.server = null;
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
private clearTimers(): void {
|
|
145
|
-
if (this.timerId) {
|
|
146
|
-
clearTimeout(this.timerId);
|
|
147
|
-
this.timerId = null;
|
|
148
|
-
}
|
|
149
|
-
if (this.closeTimerId) {
|
|
150
|
-
clearTimeout(this.closeTimerId);
|
|
151
|
-
this.closeTimerId = null;
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
private async cleanupAfterStartFailure(): Promise<void> {
|
|
156
|
-
this.clearTimers();
|
|
157
|
-
if (this.server) {
|
|
158
|
-
try {
|
|
159
|
-
await this.server.shutdown();
|
|
160
|
-
} catch {
|
|
161
|
-
// Ignore shutdown failures after a failed bind.
|
|
162
|
-
}
|
|
163
|
-
this.server = null;
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
}
|
|
@@ -1,260 +0,0 @@
|
|
|
1
|
-
import type { CimdClientConfig, OAuthClientConfig } from "./types.js";
|
|
2
|
-
|
|
3
|
-
export type CimdConfigErrorCode =
|
|
4
|
-
| "cimd_config_conflict"
|
|
5
|
-
| "cimd_registration_missing"
|
|
6
|
-
| "cimd_method_invalid"
|
|
7
|
-
| "cimd_url_invalid"
|
|
8
|
-
| "cimd_port_unfixed"
|
|
9
|
-
| "cimd_redirect_mismatch"
|
|
10
|
-
| "cimd_name_missing"
|
|
11
|
-
| "cimd_reserved_metadata_key";
|
|
12
|
-
|
|
13
|
-
export type OAuthClientMode = "static" | "client_id_metadata";
|
|
14
|
-
|
|
15
|
-
export class CimdConfigError extends Error {
|
|
16
|
-
constructor(
|
|
17
|
-
public readonly code: CimdConfigErrorCode,
|
|
18
|
-
message: string,
|
|
19
|
-
public readonly context: Record<string, unknown>,
|
|
20
|
-
public readonly recovery: string,
|
|
21
|
-
options?: ErrorOptions,
|
|
22
|
-
) {
|
|
23
|
-
super(message, options);
|
|
24
|
-
this.name = "CimdConfigError";
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
export interface ClientIdMetadataDocument {
|
|
29
|
-
client_id: string;
|
|
30
|
-
client_name: string;
|
|
31
|
-
redirect_uris: string[];
|
|
32
|
-
grant_types: ["authorization_code", "refresh_token"];
|
|
33
|
-
response_types: ["code"];
|
|
34
|
-
token_endpoint_auth_method: "none";
|
|
35
|
-
/** RFC 7591 application type. Always "native" for loopback CLI/desktop clients. */
|
|
36
|
-
application_type: "native" | "web";
|
|
37
|
-
scope?: string;
|
|
38
|
-
client_uri?: string;
|
|
39
|
-
logo_uri?: string;
|
|
40
|
-
contacts?: string[];
|
|
41
|
-
[key: string]: unknown;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
export function isCimdConfig(
|
|
45
|
-
config: OAuthClientConfig,
|
|
46
|
-
): config is CimdClientConfig {
|
|
47
|
-
return config.clientRegistration?.method === "client_id_metadata";
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
export function resolveClientMode(config: OAuthClientConfig): OAuthClientMode {
|
|
51
|
-
const raw = config as unknown as Record<string, unknown>;
|
|
52
|
-
const hasClientId = raw.clientId !== undefined;
|
|
53
|
-
const hasClientRegistration = raw.clientRegistration !== undefined;
|
|
54
|
-
|
|
55
|
-
if (hasClientId && hasClientRegistration) {
|
|
56
|
-
throw new CimdConfigError(
|
|
57
|
-
"cimd_config_conflict",
|
|
58
|
-
"OAuth client config cannot include both clientId and clientRegistration",
|
|
59
|
-
{ hasClientId: true, hasClientRegistration: true },
|
|
60
|
-
"Choose either static clientId mode or client_id_metadata mode.",
|
|
61
|
-
);
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
if (hasClientRegistration) {
|
|
65
|
-
const registration = raw.clientRegistration;
|
|
66
|
-
if (
|
|
67
|
-
registration === null || typeof registration !== "object" ||
|
|
68
|
-
Array.isArray(registration)
|
|
69
|
-
) {
|
|
70
|
-
throw new CimdConfigError(
|
|
71
|
-
"cimd_registration_missing",
|
|
72
|
-
"clientRegistration must be an object with a registration method",
|
|
73
|
-
{ clientRegistration: registration },
|
|
74
|
-
'Provide clientRegistration.method = "client_id_metadata".',
|
|
75
|
-
);
|
|
76
|
-
}
|
|
77
|
-
const method = (registration as Record<string, unknown>).method;
|
|
78
|
-
if (method === undefined) {
|
|
79
|
-
throw new CimdConfigError(
|
|
80
|
-
"cimd_registration_missing",
|
|
81
|
-
"clientRegistration.method is required",
|
|
82
|
-
{ method },
|
|
83
|
-
'Provide clientRegistration.method = "client_id_metadata".',
|
|
84
|
-
);
|
|
85
|
-
}
|
|
86
|
-
if (method !== "client_id_metadata") {
|
|
87
|
-
throw new CimdConfigError(
|
|
88
|
-
"cimd_method_invalid",
|
|
89
|
-
'Unsupported clientRegistration.method; expected "client_id_metadata"',
|
|
90
|
-
{ method },
|
|
91
|
-
'Set clientRegistration.method to "client_id_metadata".',
|
|
92
|
-
);
|
|
93
|
-
}
|
|
94
|
-
return "client_id_metadata";
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
if (typeof raw.clientId !== "string") {
|
|
98
|
-
throw new CimdConfigError(
|
|
99
|
-
"cimd_registration_missing",
|
|
100
|
-
"OAuth client config requires either clientId or clientRegistration",
|
|
101
|
-
{ hasClientId: false, hasClientRegistration: false },
|
|
102
|
-
"Provide clientId for static mode or clientRegistration for CIMD mode.",
|
|
103
|
-
);
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
return "static";
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
export function buildClientIdMetadataDocument(
|
|
110
|
-
config: CimdClientConfig,
|
|
111
|
-
): ClientIdMetadataDocument {
|
|
112
|
-
validateCimdClientConfig(config);
|
|
113
|
-
|
|
114
|
-
const { clientRegistration } = config;
|
|
115
|
-
const document = {
|
|
116
|
-
...clientRegistration.metadata?.extra,
|
|
117
|
-
client_uri: clientRegistration.metadata?.client_uri,
|
|
118
|
-
logo_uri: clientRegistration.metadata?.logo_uri,
|
|
119
|
-
contacts: clientRegistration.metadata?.contacts,
|
|
120
|
-
client_id: clientRegistration.clientIdMetadataUrl,
|
|
121
|
-
client_name: config.clientName!,
|
|
122
|
-
redirect_uris: [clientRegistration.redirectUri],
|
|
123
|
-
grant_types: ["authorization_code", "refresh_token"],
|
|
124
|
-
response_types: ["code"],
|
|
125
|
-
token_endpoint_auth_method: "none",
|
|
126
|
-
application_type: "native",
|
|
127
|
-
} as ClientIdMetadataDocument;
|
|
128
|
-
|
|
129
|
-
if (config.scopes?.length) {
|
|
130
|
-
document.scope = config.scopes.join(" ");
|
|
131
|
-
}
|
|
132
|
-
for (const key of ["client_uri", "logo_uri", "contacts"] as const) {
|
|
133
|
-
if (document[key] === undefined) {
|
|
134
|
-
delete document[key];
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
return document;
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
export function validateCimdClientConfig(
|
|
142
|
-
config: OAuthClientConfig,
|
|
143
|
-
): asserts config is CimdClientConfig {
|
|
144
|
-
const mode = resolveClientMode(config);
|
|
145
|
-
if (mode !== "client_id_metadata") {
|
|
146
|
-
throw new CimdConfigError(
|
|
147
|
-
"cimd_registration_missing",
|
|
148
|
-
"CIMD config requires clientRegistration",
|
|
149
|
-
{ mode },
|
|
150
|
-
'Provide clientRegistration.method = "client_id_metadata".',
|
|
151
|
-
);
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
const raw = config as unknown as Record<string, unknown>;
|
|
155
|
-
const registration = raw.clientRegistration as Record<string, unknown>;
|
|
156
|
-
const metadataUrl = registration.clientIdMetadataUrl;
|
|
157
|
-
try {
|
|
158
|
-
if (typeof metadataUrl !== "string") {
|
|
159
|
-
throw new Error("expected string");
|
|
160
|
-
}
|
|
161
|
-
const parsed = new URL(metadataUrl);
|
|
162
|
-
if (parsed.protocol !== "https:") {
|
|
163
|
-
throw new Error("expected https scheme");
|
|
164
|
-
}
|
|
165
|
-
} catch (cause) {
|
|
166
|
-
throw new CimdConfigError(
|
|
167
|
-
"cimd_url_invalid",
|
|
168
|
-
"clientIdMetadataUrl must be an absolute HTTPS URL",
|
|
169
|
-
{ clientIdMetadataUrl: metadataUrl },
|
|
170
|
-
"Provide an absolute https:// URL for clientRegistration.clientIdMetadataUrl.",
|
|
171
|
-
{ cause },
|
|
172
|
-
);
|
|
173
|
-
}
|
|
174
|
-
if (
|
|
175
|
-
typeof raw.callbackPort !== "number" || raw.callbackPort === 0 ||
|
|
176
|
-
!Number.isFinite(raw.callbackPort)
|
|
177
|
-
) {
|
|
178
|
-
throw new CimdConfigError(
|
|
179
|
-
"cimd_port_unfixed",
|
|
180
|
-
"CIMD mode requires a fixed callbackPort",
|
|
181
|
-
{ callbackPort: raw.callbackPort },
|
|
182
|
-
"Set callbackPort to a fixed non-zero port and publish the same port in redirectUri.",
|
|
183
|
-
);
|
|
184
|
-
}
|
|
185
|
-
if (
|
|
186
|
-
typeof raw.clientName !== "string" || raw.clientName.trim().length === 0
|
|
187
|
-
) {
|
|
188
|
-
throw new CimdConfigError(
|
|
189
|
-
"cimd_name_missing",
|
|
190
|
-
"CIMD mode requires an explicit clientName",
|
|
191
|
-
{ clientName: raw.clientName },
|
|
192
|
-
"Set clientName to the user-facing application name for the metadata document.",
|
|
193
|
-
);
|
|
194
|
-
}
|
|
195
|
-
const redirectUri = registration.redirectUri;
|
|
196
|
-
try {
|
|
197
|
-
if (typeof redirectUri !== "string") {
|
|
198
|
-
throw new Error("expected string");
|
|
199
|
-
}
|
|
200
|
-
const parsedRedirect = new URL(redirectUri);
|
|
201
|
-
if (parsedRedirect.protocol !== "http:") {
|
|
202
|
-
throw new Error("redirect scheme must be http");
|
|
203
|
-
}
|
|
204
|
-
if (parsedRedirect.hostname !== "127.0.0.1") {
|
|
205
|
-
throw new Error("redirect host must be 127.0.0.1");
|
|
206
|
-
}
|
|
207
|
-
if (parsedRedirect.pathname !== "/callback") {
|
|
208
|
-
throw new Error("redirect path must be /callback");
|
|
209
|
-
}
|
|
210
|
-
if (parsedRedirect.port !== String(raw.callbackPort)) {
|
|
211
|
-
throw new Error("redirect port differs from callbackPort");
|
|
212
|
-
}
|
|
213
|
-
} catch (cause) {
|
|
214
|
-
throw new CimdConfigError(
|
|
215
|
-
"cimd_redirect_mismatch",
|
|
216
|
-
"redirectUri must match the fixed callbackPort",
|
|
217
|
-
{ redirectUri, callbackPort: raw.callbackPort },
|
|
218
|
-
"Set clientRegistration.redirectUri to the exact loopback callback URL that will be used at runtime.",
|
|
219
|
-
{ cause },
|
|
220
|
-
);
|
|
221
|
-
}
|
|
222
|
-
validateExtraMetadataKeys(registration.metadata);
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
const RESERVED_METADATA_KEYS = new Set([
|
|
226
|
-
"scope",
|
|
227
|
-
"client_id",
|
|
228
|
-
"client_name",
|
|
229
|
-
"client_uri",
|
|
230
|
-
"logo_uri",
|
|
231
|
-
"contacts",
|
|
232
|
-
"redirect_uris",
|
|
233
|
-
"grant_types",
|
|
234
|
-
"response_types",
|
|
235
|
-
"token_endpoint_auth_method",
|
|
236
|
-
"application_type",
|
|
237
|
-
]);
|
|
238
|
-
|
|
239
|
-
function validateExtraMetadataKeys(metadata: unknown): void {
|
|
240
|
-
if (metadata === null || typeof metadata !== "object") {
|
|
241
|
-
return;
|
|
242
|
-
}
|
|
243
|
-
const extra = (metadata as { extra?: unknown }).extra;
|
|
244
|
-
if (extra === undefined) {
|
|
245
|
-
return;
|
|
246
|
-
}
|
|
247
|
-
if (extra === null || typeof extra !== "object" || Array.isArray(extra)) {
|
|
248
|
-
return;
|
|
249
|
-
}
|
|
250
|
-
for (const key of Object.keys(extra)) {
|
|
251
|
-
if (RESERVED_METADATA_KEYS.has(key)) {
|
|
252
|
-
throw new CimdConfigError(
|
|
253
|
-
"cimd_reserved_metadata_key",
|
|
254
|
-
"clientRegistration.metadata.extra cannot contain reserved metadata keys",
|
|
255
|
-
{ key },
|
|
256
|
-
"Move reserved OAuth client metadata fields to their dedicated config fields.",
|
|
257
|
-
);
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
}
|
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Sugar helper for preparing an authenticated MCP transport.
|
|
3
|
-
*
|
|
4
|
-
* Wires together OAuthClientProviderImpl with a CallbackServer.
|
|
5
|
-
* The consumer is responsible for creating the StreamableHTTPClientTransport
|
|
6
|
-
* and passing `result.provider` as the `authProvider` option.
|
|
7
|
-
*
|
|
8
|
-
* @module lib/server/client-auth/connect
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
import { OAuthClientProviderImpl } from "./provider.js";
|
|
12
|
-
import type { OAuthClientConfig } from "./types.js";
|
|
13
|
-
import { CallbackServer } from "./callback-server.js";
|
|
14
|
-
import {
|
|
15
|
-
CimdConfigError,
|
|
16
|
-
isCimdConfig,
|
|
17
|
-
resolveClientMode,
|
|
18
|
-
} from "./client-id-metadata.js";
|
|
19
|
-
|
|
20
|
-
export interface PrepareOAuthResult {
|
|
21
|
-
/** The configured provider — pass as authProvider to StreamableHTTPClientTransport */
|
|
22
|
-
provider: OAuthClientProviderImpl;
|
|
23
|
-
/** The callback server instance (caller must close on error paths) */
|
|
24
|
-
callbackServer: CallbackServer;
|
|
25
|
-
/** The actual port the callback server is listening on */
|
|
26
|
-
callbackPort: number;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* Prepare an OAuth client provider with a running callback server.
|
|
31
|
-
*
|
|
32
|
-
* Usage:
|
|
33
|
-
* ```typescript
|
|
34
|
-
* const { provider, callbackServer } = await prepareOAuthProvider(serverUrl, config);
|
|
35
|
-
* const transport = new StreamableHTTPClientTransport(new URL(serverUrl), { authProvider: provider });
|
|
36
|
-
* await client.connect(transport);
|
|
37
|
-
* ```
|
|
38
|
-
*/
|
|
39
|
-
export async function prepareOAuthProvider(
|
|
40
|
-
serverUrl: string,
|
|
41
|
-
config: OAuthClientConfig,
|
|
42
|
-
): Promise<PrepareOAuthResult> {
|
|
43
|
-
const mode = resolveClientMode(config);
|
|
44
|
-
const provider = new OAuthClientProviderImpl(serverUrl, config);
|
|
45
|
-
const callbackServer = new CallbackServer({
|
|
46
|
-
port: config.callbackPort ?? 0,
|
|
47
|
-
hostname: mode === "client_id_metadata" ? "127.0.0.1" : "localhost",
|
|
48
|
-
timeout: config.authTimeout ?? 120_000,
|
|
49
|
-
});
|
|
50
|
-
const { port } = await callbackServer.start();
|
|
51
|
-
|
|
52
|
-
if (isCimdConfig(config)) {
|
|
53
|
-
if (port !== config.callbackPort) {
|
|
54
|
-
await callbackServer.close();
|
|
55
|
-
throw new CimdConfigError(
|
|
56
|
-
"cimd_redirect_mismatch",
|
|
57
|
-
"CIMD callback server bound to a different port than callbackPort",
|
|
58
|
-
{
|
|
59
|
-
callbackPort: config.callbackPort,
|
|
60
|
-
boundPort: port,
|
|
61
|
-
redirectUri: config.clientRegistration.redirectUri,
|
|
62
|
-
},
|
|
63
|
-
"Set callbackPort to the fixed port used by the callback server and publish the same port in redirectUri.",
|
|
64
|
-
);
|
|
65
|
-
}
|
|
66
|
-
provider.setRedirectUrl(config.clientRegistration.redirectUri);
|
|
67
|
-
} else {
|
|
68
|
-
provider.setRedirectUrl(`http://localhost:${port}/callback`);
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
return { provider, callbackServer, callbackPort: port };
|
|
72
|
-
}
|