@casys/mcp-server 0.17.7 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/mod.ts +31 -16
- package/package.json +1 -2
- package/src/auth/as-metadata-proxy.ts +27 -11
- package/src/client-auth/callback-server.ts +79 -43
- package/src/client-auth/client-id-metadata.ts +256 -0
- package/src/client-auth/connect.ts +26 -2
- package/src/client-auth/mod.ts +44 -0
- package/src/client-auth/provider.ts +44 -8
- package/src/client-auth/token-store/file-store.ts +23 -32
- package/src/client-auth/types.ts +33 -4
- package/src/runtime/runtime.ts +111 -7
- package/src/runtime/types.ts +41 -1
package/mod.ts
CHANGED
|
@@ -122,22 +122,13 @@ export {
|
|
|
122
122
|
resolveViewerDistPath,
|
|
123
123
|
} from "./src/ui/viewer-utils.js";
|
|
124
124
|
|
|
125
|
-
//
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
ComposeEventHandler,
|
|
133
|
-
ComposeEventPayload,
|
|
134
|
-
ComposeEvents,
|
|
135
|
-
ComposeSource,
|
|
136
|
-
ComposeTarget,
|
|
137
|
-
UiMetaOptions,
|
|
138
|
-
UiMetaResult,
|
|
139
|
-
UiMetaUi,
|
|
140
|
-
} from "@casys/mcp-compose/sdk";
|
|
125
|
+
// NOTE: UI composition helpers (`composeEvents`, `uiMeta`, `COMPOSE_EVENT_METHOD`
|
|
126
|
+
// and their types) are NOT re-exported here. They live in `@casys/mcp-compose`
|
|
127
|
+
// and must be imported from there directly:
|
|
128
|
+
// import { composeEvents, uiMeta } from "@casys/mcp-compose/sdk";
|
|
129
|
+
// Dropping the convenience re-export removes @casys/mcp-server's dependency on
|
|
130
|
+
// @casys/mcp-compose entirely — server stays a lean MCP framework that only
|
|
131
|
+
// touches the official protocol packages.
|
|
141
132
|
|
|
142
133
|
// Middleware pipeline
|
|
143
134
|
export type {
|
|
@@ -194,6 +185,30 @@ export {
|
|
|
194
185
|
} from "./src/auth/mod.js";
|
|
195
186
|
export type { AuthConfig, AuthProviderName } from "./src/auth/mod.js";
|
|
196
187
|
|
|
188
|
+
// Client Auth — OAuth client flow + CIMD
|
|
189
|
+
export {
|
|
190
|
+
buildClientIdMetadataDocument,
|
|
191
|
+
CallbackServer,
|
|
192
|
+
CimdConfigError,
|
|
193
|
+
FileTokenStore,
|
|
194
|
+
isCimdConfig,
|
|
195
|
+
MemoryTokenStore,
|
|
196
|
+
OAuthClientProviderImpl,
|
|
197
|
+
prepareOAuthProvider,
|
|
198
|
+
} from "./src/client-auth/mod.js";
|
|
199
|
+
export type {
|
|
200
|
+
CallbackServerOptions,
|
|
201
|
+
CimdClientConfig,
|
|
202
|
+
CimdConfigErrorCode,
|
|
203
|
+
ClientIdMetadataDocument,
|
|
204
|
+
OAuthClientConfig,
|
|
205
|
+
OAuthClientConfigBase,
|
|
206
|
+
PrepareOAuthResult,
|
|
207
|
+
StaticClientConfig,
|
|
208
|
+
StoredCredentials,
|
|
209
|
+
TokenStore,
|
|
210
|
+
} from "./src/client-auth/mod.js";
|
|
211
|
+
|
|
197
212
|
// Observability
|
|
198
213
|
export {
|
|
199
214
|
endToolCallSpan,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@casys/mcp-server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.19.0",
|
|
4
4
|
"description": "Production-ready MCP server framework with concurrency control, auth, and observability",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "mod.ts",
|
|
@@ -12,7 +12,6 @@
|
|
|
12
12
|
"dependencies": {
|
|
13
13
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
14
14
|
"@modelcontextprotocol/ext-apps": "^1.7.1",
|
|
15
|
-
"@casys/mcp-compose": "^0.5.2",
|
|
16
15
|
"hono": "^4.0.0",
|
|
17
16
|
"ajv": "^8.17.1",
|
|
18
17
|
"jose": "^6.0.0",
|
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* AS Metadata Proxy for DCR
|
|
2
|
+
* AS Metadata Proxy for DCR compatibility discovery.
|
|
3
3
|
*
|
|
4
4
|
* Creates a Web Standard request handler that serves an RFC 8414
|
|
5
5
|
* Authorization Server Metadata document enriched with
|
|
6
|
-
* `registration_endpoint` (RFC 7591).
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
6
|
+
* `registration_endpoint` (RFC 7591). This is a compatibility path for
|
|
7
|
+
* MCP clients and IdPs that still rely on Dynamic Client Registration
|
|
8
|
+
* (DCR), which is now optional (`MAY`) in the 2025-11-25 MCP spec.
|
|
9
|
+
*
|
|
10
|
+
* For new OAuth client integrations, prefer the spec-preferred Client ID
|
|
11
|
+
* Metadata Documents (CIMD) on the client side. See
|
|
12
|
+
* `src/client-auth/client-id-metadata.ts`.
|
|
10
13
|
*
|
|
11
14
|
* **Issuer field note (RFC 8414 §3.2)**:
|
|
12
15
|
* The `issuer` field in the served metadata will be the upstream IdP's
|
|
@@ -15,7 +18,8 @@
|
|
|
15
18
|
* overriding `issuer` would cause JWT `iss` claim mismatches — the IdP
|
|
16
19
|
* still issues tokens with its own `iss`, and clients verify
|
|
17
20
|
* `token.iss === metadata.issuer`. The metadata-URL mismatch is the
|
|
18
|
-
* lesser evil
|
|
21
|
+
* lesser evil for this compatibility path and is not needed when clients
|
|
22
|
+
* use CIMD or the upstream IdP ships native registration discovery.
|
|
19
23
|
*
|
|
20
24
|
* @module lib/server/auth/as-metadata-proxy
|
|
21
25
|
*/
|
|
@@ -140,7 +144,9 @@ function resolveMetadataUrl(options: AsMetadataProxyOptions): string {
|
|
|
140
144
|
}
|
|
141
145
|
|
|
142
146
|
validateUrl(upstreamIssuer!, "upstreamIssuer");
|
|
143
|
-
return `${
|
|
147
|
+
return `${
|
|
148
|
+
stripTrailingSlash(upstreamIssuer!)
|
|
149
|
+
}/.well-known/openid-configuration`;
|
|
144
150
|
}
|
|
145
151
|
|
|
146
152
|
/**
|
|
@@ -173,8 +179,13 @@ export function createAsMetadataHandler(
|
|
|
173
179
|
// ── Fail-fast validation at construction time ──
|
|
174
180
|
const metadataUrl = resolveMetadataUrl(options);
|
|
175
181
|
validateUrl(options.registrationEndpoint, "registrationEndpoint");
|
|
176
|
-
if (
|
|
177
|
-
|
|
182
|
+
if (
|
|
183
|
+
options.cacheTtlMs !== undefined &&
|
|
184
|
+
(options.cacheTtlMs < 0 || !Number.isFinite(options.cacheTtlMs))
|
|
185
|
+
) {
|
|
186
|
+
throw new Error(
|
|
187
|
+
"AsMetadataProxyOptions.cacheTtlMs must be a non-negative finite number",
|
|
188
|
+
);
|
|
178
189
|
}
|
|
179
190
|
|
|
180
191
|
const {
|
|
@@ -200,7 +211,9 @@ export function createAsMetadataHandler(
|
|
|
200
211
|
const body = await res.json();
|
|
201
212
|
if (body === null || typeof body !== "object" || Array.isArray(body)) {
|
|
202
213
|
throw new Error(
|
|
203
|
-
`AS metadata from ${metadataUrl} is not a JSON object (got ${
|
|
214
|
+
`AS metadata from ${metadataUrl} is not a JSON object (got ${
|
|
215
|
+
Array.isArray(body) ? "array" : typeof body
|
|
216
|
+
})`,
|
|
204
217
|
);
|
|
205
218
|
}
|
|
206
219
|
if (typeof body.issuer !== "string") {
|
|
@@ -245,7 +258,10 @@ export function createAsMetadataHandler(
|
|
|
245
258
|
|
|
246
259
|
return async (req: Request): Promise<Response> => {
|
|
247
260
|
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
248
|
-
return new Response(null, {
|
|
261
|
+
return new Response(null, {
|
|
262
|
+
status: 405,
|
|
263
|
+
headers: { "Allow": "GET, HEAD" },
|
|
264
|
+
});
|
|
249
265
|
}
|
|
250
266
|
try {
|
|
251
267
|
const upstream = await getMetadata();
|
|
@@ -8,9 +8,13 @@
|
|
|
8
8
|
* @module lib/server/client-auth/callback-server
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
+
import { serve, type ServeHandle } from "../runtime/runtime.js";
|
|
12
|
+
|
|
11
13
|
export interface CallbackServerOptions {
|
|
12
14
|
/** Port to listen on (0 = auto-assign, default: 0) */
|
|
13
15
|
port?: number;
|
|
16
|
+
/** Hostname to bind (default: 127.0.0.1) */
|
|
17
|
+
hostname?: string;
|
|
14
18
|
/** Timeout in ms (default: 120_000) */
|
|
15
19
|
timeout?: number;
|
|
16
20
|
}
|
|
@@ -35,26 +39,33 @@ body{font-family:system-ui;display:flex;justify-content:center;align-items:cente
|
|
|
35
39
|
|
|
36
40
|
export class CallbackServer {
|
|
37
41
|
private port: number;
|
|
42
|
+
private hostname: string;
|
|
38
43
|
private timeout: number;
|
|
39
|
-
private
|
|
40
|
-
private server: Deno.HttpServer | null = null;
|
|
44
|
+
private server: ServeHandle | null = null;
|
|
41
45
|
private timerId: ReturnType<typeof setTimeout> | null = null;
|
|
42
46
|
private closeTimerId: ReturnType<typeof setTimeout> | null = null;
|
|
43
47
|
|
|
44
48
|
constructor(options?: CallbackServerOptions) {
|
|
45
49
|
this.port = options?.port ?? 0;
|
|
50
|
+
this.hostname = options?.hostname ?? "127.0.0.1";
|
|
46
51
|
this.timeout = options?.timeout ?? 120_000;
|
|
47
52
|
}
|
|
48
53
|
|
|
49
54
|
async start(): Promise<{ port: number; codePromise: Promise<string> }> {
|
|
50
|
-
this.abortController = new AbortController();
|
|
51
|
-
|
|
52
55
|
let resolveCode!: (code: string) => void;
|
|
53
56
|
let rejectCode!: (err: Error) => void;
|
|
54
57
|
const codePromise = new Promise<string>((resolve, reject) => {
|
|
55
58
|
resolveCode = resolve;
|
|
56
59
|
rejectCode = reject;
|
|
57
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
|
+
});
|
|
58
69
|
|
|
59
70
|
this.timerId = setTimeout(() => {
|
|
60
71
|
this.timerId = null;
|
|
@@ -66,46 +77,71 @@ export class CallbackServer {
|
|
|
66
77
|
this.close();
|
|
67
78
|
}, this.timeout);
|
|
68
79
|
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
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,
|
|
82
115
|
headers: { "Content-Type": "text/html" },
|
|
83
116
|
});
|
|
84
117
|
}
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
this.closeTimerId = null;
|
|
93
|
-
this.close();
|
|
94
|
-
}, 100);
|
|
95
|
-
return new Response(SUCCESS_HTML, {
|
|
96
|
-
status: 200,
|
|
97
|
-
headers: { "Content-Type": "text/html" },
|
|
98
|
-
});
|
|
99
|
-
}
|
|
100
|
-
return new Response("Not Found", { status: 404 });
|
|
101
|
-
},
|
|
102
|
-
);
|
|
118
|
+
return new Response("Not Found", { status: 404 });
|
|
119
|
+
},
|
|
120
|
+
);
|
|
121
|
+
} catch (err) {
|
|
122
|
+
await this.cleanupAfterStartFailure();
|
|
123
|
+
throw err;
|
|
124
|
+
}
|
|
103
125
|
|
|
104
|
-
|
|
105
|
-
|
|
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 };
|
|
106
134
|
}
|
|
107
135
|
|
|
108
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 {
|
|
109
145
|
if (this.timerId) {
|
|
110
146
|
clearTimeout(this.timerId);
|
|
111
147
|
this.timerId = null;
|
|
@@ -114,15 +150,15 @@ export class CallbackServer {
|
|
|
114
150
|
clearTimeout(this.closeTimerId);
|
|
115
151
|
this.closeTimerId = null;
|
|
116
152
|
}
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
private async cleanupAfterStartFailure(): Promise<void> {
|
|
156
|
+
this.clearTimers();
|
|
121
157
|
if (this.server) {
|
|
122
158
|
try {
|
|
123
|
-
await this.server.
|
|
159
|
+
await this.server.shutdown();
|
|
124
160
|
} catch {
|
|
125
|
-
//
|
|
161
|
+
// Ignore shutdown failures after a failed bind.
|
|
126
162
|
}
|
|
127
163
|
this.server = null;
|
|
128
164
|
}
|
|
@@ -0,0 +1,256 @@
|
|
|
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"];
|
|
33
|
+
response_types: ["code"];
|
|
34
|
+
token_endpoint_auth_method: "none";
|
|
35
|
+
scope?: string;
|
|
36
|
+
client_uri?: string;
|
|
37
|
+
logo_uri?: string;
|
|
38
|
+
contacts?: string[];
|
|
39
|
+
[key: string]: unknown;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function isCimdConfig(
|
|
43
|
+
config: OAuthClientConfig,
|
|
44
|
+
): config is CimdClientConfig {
|
|
45
|
+
return config.clientRegistration?.method === "client_id_metadata";
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function resolveClientMode(config: OAuthClientConfig): OAuthClientMode {
|
|
49
|
+
const raw = config as unknown as Record<string, unknown>;
|
|
50
|
+
const hasClientId = raw.clientId !== undefined;
|
|
51
|
+
const hasClientRegistration = raw.clientRegistration !== undefined;
|
|
52
|
+
|
|
53
|
+
if (hasClientId && hasClientRegistration) {
|
|
54
|
+
throw new CimdConfigError(
|
|
55
|
+
"cimd_config_conflict",
|
|
56
|
+
"OAuth client config cannot include both clientId and clientRegistration",
|
|
57
|
+
{ hasClientId: true, hasClientRegistration: true },
|
|
58
|
+
"Choose either static clientId mode or client_id_metadata mode.",
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
if (hasClientRegistration) {
|
|
63
|
+
const registration = raw.clientRegistration;
|
|
64
|
+
if (
|
|
65
|
+
registration === null || typeof registration !== "object" ||
|
|
66
|
+
Array.isArray(registration)
|
|
67
|
+
) {
|
|
68
|
+
throw new CimdConfigError(
|
|
69
|
+
"cimd_registration_missing",
|
|
70
|
+
"clientRegistration must be an object with a registration method",
|
|
71
|
+
{ clientRegistration: registration },
|
|
72
|
+
'Provide clientRegistration.method = "client_id_metadata".',
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
const method = (registration as Record<string, unknown>).method;
|
|
76
|
+
if (method === undefined) {
|
|
77
|
+
throw new CimdConfigError(
|
|
78
|
+
"cimd_registration_missing",
|
|
79
|
+
"clientRegistration.method is required",
|
|
80
|
+
{ method },
|
|
81
|
+
'Provide clientRegistration.method = "client_id_metadata".',
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
if (method !== "client_id_metadata") {
|
|
85
|
+
throw new CimdConfigError(
|
|
86
|
+
"cimd_method_invalid",
|
|
87
|
+
'Unsupported clientRegistration.method; expected "client_id_metadata"',
|
|
88
|
+
{ method },
|
|
89
|
+
'Set clientRegistration.method to "client_id_metadata".',
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
return "client_id_metadata";
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
if (typeof raw.clientId !== "string") {
|
|
96
|
+
throw new CimdConfigError(
|
|
97
|
+
"cimd_registration_missing",
|
|
98
|
+
"OAuth client config requires either clientId or clientRegistration",
|
|
99
|
+
{ hasClientId: false, hasClientRegistration: false },
|
|
100
|
+
"Provide clientId for static mode or clientRegistration for CIMD mode.",
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return "static";
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function buildClientIdMetadataDocument(
|
|
108
|
+
config: CimdClientConfig,
|
|
109
|
+
): ClientIdMetadataDocument {
|
|
110
|
+
validateCimdClientConfig(config);
|
|
111
|
+
|
|
112
|
+
const { clientRegistration } = config;
|
|
113
|
+
const document = {
|
|
114
|
+
...clientRegistration.metadata?.extra,
|
|
115
|
+
client_uri: clientRegistration.metadata?.client_uri,
|
|
116
|
+
logo_uri: clientRegistration.metadata?.logo_uri,
|
|
117
|
+
contacts: clientRegistration.metadata?.contacts,
|
|
118
|
+
client_id: clientRegistration.clientIdMetadataUrl,
|
|
119
|
+
client_name: config.clientName!,
|
|
120
|
+
redirect_uris: [clientRegistration.redirectUri],
|
|
121
|
+
grant_types: ["authorization_code"],
|
|
122
|
+
response_types: ["code"],
|
|
123
|
+
token_endpoint_auth_method: "none",
|
|
124
|
+
} as ClientIdMetadataDocument;
|
|
125
|
+
|
|
126
|
+
if (config.scopes?.length) {
|
|
127
|
+
document.scope = config.scopes.join(" ");
|
|
128
|
+
}
|
|
129
|
+
for (const key of ["client_uri", "logo_uri", "contacts"] as const) {
|
|
130
|
+
if (document[key] === undefined) {
|
|
131
|
+
delete document[key];
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
return document;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function validateCimdClientConfig(
|
|
139
|
+
config: OAuthClientConfig,
|
|
140
|
+
): asserts config is CimdClientConfig {
|
|
141
|
+
const mode = resolveClientMode(config);
|
|
142
|
+
if (mode !== "client_id_metadata") {
|
|
143
|
+
throw new CimdConfigError(
|
|
144
|
+
"cimd_registration_missing",
|
|
145
|
+
"CIMD config requires clientRegistration",
|
|
146
|
+
{ mode },
|
|
147
|
+
'Provide clientRegistration.method = "client_id_metadata".',
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const raw = config as unknown as Record<string, unknown>;
|
|
152
|
+
const registration = raw.clientRegistration as Record<string, unknown>;
|
|
153
|
+
const metadataUrl = registration.clientIdMetadataUrl;
|
|
154
|
+
try {
|
|
155
|
+
if (typeof metadataUrl !== "string") {
|
|
156
|
+
throw new Error("expected string");
|
|
157
|
+
}
|
|
158
|
+
const parsed = new URL(metadataUrl);
|
|
159
|
+
if (parsed.protocol !== "https:") {
|
|
160
|
+
throw new Error("expected https scheme");
|
|
161
|
+
}
|
|
162
|
+
} catch (cause) {
|
|
163
|
+
throw new CimdConfigError(
|
|
164
|
+
"cimd_url_invalid",
|
|
165
|
+
"clientIdMetadataUrl must be an absolute HTTPS URL",
|
|
166
|
+
{ clientIdMetadataUrl: metadataUrl },
|
|
167
|
+
"Provide an absolute https:// URL for clientRegistration.clientIdMetadataUrl.",
|
|
168
|
+
{ cause },
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
if (
|
|
172
|
+
typeof raw.callbackPort !== "number" || raw.callbackPort === 0 ||
|
|
173
|
+
!Number.isFinite(raw.callbackPort)
|
|
174
|
+
) {
|
|
175
|
+
throw new CimdConfigError(
|
|
176
|
+
"cimd_port_unfixed",
|
|
177
|
+
"CIMD mode requires a fixed callbackPort",
|
|
178
|
+
{ callbackPort: raw.callbackPort },
|
|
179
|
+
"Set callbackPort to a fixed non-zero port and publish the same port in redirectUri.",
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
if (
|
|
183
|
+
typeof raw.clientName !== "string" || raw.clientName.trim().length === 0
|
|
184
|
+
) {
|
|
185
|
+
throw new CimdConfigError(
|
|
186
|
+
"cimd_name_missing",
|
|
187
|
+
"CIMD mode requires an explicit clientName",
|
|
188
|
+
{ clientName: raw.clientName },
|
|
189
|
+
"Set clientName to the user-facing application name for the metadata document.",
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
const redirectUri = registration.redirectUri;
|
|
193
|
+
try {
|
|
194
|
+
if (typeof redirectUri !== "string") {
|
|
195
|
+
throw new Error("expected string");
|
|
196
|
+
}
|
|
197
|
+
const parsedRedirect = new URL(redirectUri);
|
|
198
|
+
if (parsedRedirect.protocol !== "http:") {
|
|
199
|
+
throw new Error("redirect scheme must be http");
|
|
200
|
+
}
|
|
201
|
+
if (parsedRedirect.hostname !== "127.0.0.1") {
|
|
202
|
+
throw new Error("redirect host must be 127.0.0.1");
|
|
203
|
+
}
|
|
204
|
+
if (parsedRedirect.pathname !== "/callback") {
|
|
205
|
+
throw new Error("redirect path must be /callback");
|
|
206
|
+
}
|
|
207
|
+
if (parsedRedirect.port !== String(raw.callbackPort)) {
|
|
208
|
+
throw new Error("redirect port differs from callbackPort");
|
|
209
|
+
}
|
|
210
|
+
} catch (cause) {
|
|
211
|
+
throw new CimdConfigError(
|
|
212
|
+
"cimd_redirect_mismatch",
|
|
213
|
+
"redirectUri must match the fixed callbackPort",
|
|
214
|
+
{ redirectUri, callbackPort: raw.callbackPort },
|
|
215
|
+
"Set clientRegistration.redirectUri to the exact loopback callback URL that will be used at runtime.",
|
|
216
|
+
{ cause },
|
|
217
|
+
);
|
|
218
|
+
}
|
|
219
|
+
validateExtraMetadataKeys(registration.metadata);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const RESERVED_METADATA_KEYS = new Set([
|
|
223
|
+
"scope",
|
|
224
|
+
"client_id",
|
|
225
|
+
"client_name",
|
|
226
|
+
"client_uri",
|
|
227
|
+
"logo_uri",
|
|
228
|
+
"contacts",
|
|
229
|
+
"redirect_uris",
|
|
230
|
+
"grant_types",
|
|
231
|
+
"response_types",
|
|
232
|
+
"token_endpoint_auth_method",
|
|
233
|
+
]);
|
|
234
|
+
|
|
235
|
+
function validateExtraMetadataKeys(metadata: unknown): void {
|
|
236
|
+
if (metadata === null || typeof metadata !== "object") {
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
const extra = (metadata as { extra?: unknown }).extra;
|
|
240
|
+
if (extra === undefined) {
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
if (extra === null || typeof extra !== "object" || Array.isArray(extra)) {
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
for (const key of Object.keys(extra)) {
|
|
247
|
+
if (RESERVED_METADATA_KEYS.has(key)) {
|
|
248
|
+
throw new CimdConfigError(
|
|
249
|
+
"cimd_reserved_metadata_key",
|
|
250
|
+
"clientRegistration.metadata.extra cannot contain reserved metadata keys",
|
|
251
|
+
{ key },
|
|
252
|
+
"Move reserved OAuth client metadata fields to their dedicated config fields.",
|
|
253
|
+
);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
}
|
|
@@ -11,6 +11,11 @@
|
|
|
11
11
|
import { OAuthClientProviderImpl } from "./provider.js";
|
|
12
12
|
import type { OAuthClientConfig } from "./types.js";
|
|
13
13
|
import { CallbackServer } from "./callback-server.js";
|
|
14
|
+
import {
|
|
15
|
+
CimdConfigError,
|
|
16
|
+
isCimdConfig,
|
|
17
|
+
resolveClientMode,
|
|
18
|
+
} from "./client-id-metadata.js";
|
|
14
19
|
|
|
15
20
|
export interface PrepareOAuthResult {
|
|
16
21
|
/** The configured provider — pass as authProvider to StreamableHTTPClientTransport */
|
|
@@ -35,14 +40,33 @@ export async function prepareOAuthProvider(
|
|
|
35
40
|
serverUrl: string,
|
|
36
41
|
config: OAuthClientConfig,
|
|
37
42
|
): Promise<PrepareOAuthResult> {
|
|
43
|
+
const mode = resolveClientMode(config);
|
|
44
|
+
const provider = new OAuthClientProviderImpl(serverUrl, config);
|
|
38
45
|
const callbackServer = new CallbackServer({
|
|
39
46
|
port: config.callbackPort ?? 0,
|
|
47
|
+
hostname: mode === "client_id_metadata" ? "127.0.0.1" : "localhost",
|
|
40
48
|
timeout: config.authTimeout ?? 120_000,
|
|
41
49
|
});
|
|
42
50
|
const { port } = await callbackServer.start();
|
|
43
51
|
|
|
44
|
-
|
|
45
|
-
|
|
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
|
+
}
|
|
46
70
|
|
|
47
71
|
return { provider, callbackServer, callbackPort: port };
|
|
48
72
|
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OAuth client-auth helpers for MCP clients.
|
|
3
|
+
*
|
|
4
|
+
* Includes the local callback server, OAuth client provider wiring, token
|
|
5
|
+
* stores, and Client ID Metadata Document (CIMD) helpers.
|
|
6
|
+
*
|
|
7
|
+
* @module lib/server/client-auth
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
// OAuth provider wiring
|
|
11
|
+
export { prepareOAuthProvider } from "./connect.js";
|
|
12
|
+
export type { PrepareOAuthResult } from "./connect.js";
|
|
13
|
+
|
|
14
|
+
// OAuthClientProvider implementation
|
|
15
|
+
export { OAuthClientProviderImpl } from "./provider.js";
|
|
16
|
+
|
|
17
|
+
// Local callback server
|
|
18
|
+
export { CallbackServer } from "./callback-server.js";
|
|
19
|
+
export type { CallbackServerOptions } from "./callback-server.js";
|
|
20
|
+
|
|
21
|
+
// Types
|
|
22
|
+
export type {
|
|
23
|
+
CimdClientConfig,
|
|
24
|
+
OAuthClientConfig,
|
|
25
|
+
OAuthClientConfigBase,
|
|
26
|
+
StaticClientConfig,
|
|
27
|
+
StoredCredentials,
|
|
28
|
+
TokenStore,
|
|
29
|
+
} from "./types.js";
|
|
30
|
+
|
|
31
|
+
// Token stores
|
|
32
|
+
export { MemoryTokenStore } from "./token-store/memory-store.js";
|
|
33
|
+
export { FileTokenStore } from "./token-store/file-store.js";
|
|
34
|
+
|
|
35
|
+
// Client ID Metadata Documents (CIMD)
|
|
36
|
+
export {
|
|
37
|
+
buildClientIdMetadataDocument,
|
|
38
|
+
CimdConfigError,
|
|
39
|
+
isCimdConfig,
|
|
40
|
+
} from "./client-id-metadata.js";
|
|
41
|
+
export type {
|
|
42
|
+
CimdConfigErrorCode,
|
|
43
|
+
ClientIdMetadataDocument,
|
|
44
|
+
} from "./client-id-metadata.js";
|
|
@@ -15,6 +15,12 @@ import type {
|
|
|
15
15
|
} from "@modelcontextprotocol/sdk/shared/auth.js";
|
|
16
16
|
import type { OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.js";
|
|
17
17
|
import type { OAuthClientConfig } from "./types.js";
|
|
18
|
+
import {
|
|
19
|
+
CimdConfigError,
|
|
20
|
+
isCimdConfig,
|
|
21
|
+
resolveClientMode,
|
|
22
|
+
validateCimdClientConfig,
|
|
23
|
+
} from "./client-id-metadata.js";
|
|
18
24
|
|
|
19
25
|
export class OAuthClientProviderImpl implements OAuthClientProvider {
|
|
20
26
|
private serverUrl: string;
|
|
@@ -24,16 +30,37 @@ export class OAuthClientProviderImpl implements OAuthClientProvider {
|
|
|
24
30
|
private _redirectUrl: string | undefined;
|
|
25
31
|
|
|
26
32
|
constructor(serverUrl: string, config: OAuthClientConfig) {
|
|
33
|
+
const mode = resolveClientMode(config);
|
|
34
|
+
if (mode === "client_id_metadata") {
|
|
35
|
+
validateCimdClientConfig(config);
|
|
36
|
+
}
|
|
27
37
|
this.serverUrl = serverUrl;
|
|
28
38
|
this.config = config;
|
|
29
39
|
}
|
|
30
40
|
|
|
31
41
|
get redirectUrl(): string | URL {
|
|
42
|
+
if (isCimdConfig(this.config)) {
|
|
43
|
+
return this.config.clientRegistration.redirectUri;
|
|
44
|
+
}
|
|
32
45
|
return this._redirectUrl ?? "http://localhost:0/callback";
|
|
33
46
|
}
|
|
34
47
|
|
|
35
48
|
/** Set the redirect URL (called after CallbackServer binds to a port). */
|
|
36
49
|
setRedirectUrl(url: string): void {
|
|
50
|
+
if (isCimdConfig(this.config)) {
|
|
51
|
+
if (url !== this.config.clientRegistration.redirectUri) {
|
|
52
|
+
throw new CimdConfigError(
|
|
53
|
+
"cimd_redirect_mismatch",
|
|
54
|
+
"CIMD redirectUrl cannot differ from configured redirectUri",
|
|
55
|
+
{
|
|
56
|
+
redirectUrl: url,
|
|
57
|
+
configuredRedirectUri: this.config.clientRegistration.redirectUri,
|
|
58
|
+
},
|
|
59
|
+
"Use clientRegistration.redirectUri as the runtime redirect URL.",
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
37
64
|
this._redirectUrl = url;
|
|
38
65
|
}
|
|
39
66
|
|
|
@@ -47,16 +74,24 @@ export class OAuthClientProviderImpl implements OAuthClientProvider {
|
|
|
47
74
|
};
|
|
48
75
|
}
|
|
49
76
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
77
|
+
clientInformation(): Promise<OAuthClientInformationMixed | undefined> {
|
|
78
|
+
if (isCimdConfig(this.config)) {
|
|
79
|
+
return Promise.resolve({
|
|
80
|
+
client_id: this.config.clientRegistration.clientIdMetadataUrl,
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
return Promise.resolve(
|
|
84
|
+
this._clientInfo ?? {
|
|
85
|
+
client_id: this.config.clientId,
|
|
86
|
+
},
|
|
87
|
+
);
|
|
54
88
|
}
|
|
55
89
|
|
|
56
|
-
|
|
90
|
+
saveClientInformation(
|
|
57
91
|
info: OAuthClientInformationMixed,
|
|
58
92
|
): Promise<void> {
|
|
59
93
|
this._clientInfo = info;
|
|
94
|
+
return Promise.resolve();
|
|
60
95
|
}
|
|
61
96
|
|
|
62
97
|
async tokens(): Promise<OAuthTokens | undefined> {
|
|
@@ -76,12 +111,13 @@ export class OAuthClientProviderImpl implements OAuthClientProvider {
|
|
|
76
111
|
await this.config.openBrowser(authorizationUrl.toString());
|
|
77
112
|
}
|
|
78
113
|
|
|
79
|
-
|
|
114
|
+
saveCodeVerifier(codeVerifier: string): Promise<void> {
|
|
80
115
|
this._codeVerifier = codeVerifier;
|
|
116
|
+
return Promise.resolve();
|
|
81
117
|
}
|
|
82
118
|
|
|
83
|
-
|
|
84
|
-
return this._codeVerifier;
|
|
119
|
+
codeVerifier(): Promise<string> {
|
|
120
|
+
return Promise.resolve(this._codeVerifier);
|
|
85
121
|
}
|
|
86
122
|
|
|
87
123
|
async invalidateCredentials(
|
|
@@ -8,6 +8,13 @@
|
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
import type { StoredCredentials, TokenStore } from "../types.js";
|
|
11
|
+
import {
|
|
12
|
+
mkdir,
|
|
13
|
+
readDir,
|
|
14
|
+
readTextFile,
|
|
15
|
+
remove,
|
|
16
|
+
writeTextFile,
|
|
17
|
+
} from "../../runtime/runtime.js";
|
|
11
18
|
|
|
12
19
|
async function sha256hex(input: string): Promise<string> {
|
|
13
20
|
const data = new TextEncoder().encode(input);
|
|
@@ -26,57 +33,41 @@ export class FileTokenStore implements TokenStore {
|
|
|
26
33
|
}
|
|
27
34
|
|
|
28
35
|
private async ensureDir(): Promise<void> {
|
|
29
|
-
await
|
|
36
|
+
await mkdir(this.baseDir, { recursive: true, mode: 0o700 });
|
|
30
37
|
}
|
|
31
38
|
|
|
32
39
|
async get(serverUrl: string): Promise<StoredCredentials | null> {
|
|
33
40
|
const path = await this.filePath(serverUrl);
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
return JSON.parse(content) as StoredCredentials;
|
|
37
|
-
} catch (e) {
|
|
38
|
-
if (e instanceof Deno.errors.NotFound) return null;
|
|
39
|
-
throw e;
|
|
40
|
-
}
|
|
41
|
+
const content = await readTextFile(path);
|
|
42
|
+
return content === null ? null : JSON.parse(content) as StoredCredentials;
|
|
41
43
|
}
|
|
42
44
|
|
|
43
45
|
async set(serverUrl: string, credentials: StoredCredentials): Promise<void> {
|
|
44
46
|
await this.ensureDir();
|
|
45
47
|
const path = await this.filePath(serverUrl);
|
|
46
48
|
const content = JSON.stringify(credentials, null, 2);
|
|
47
|
-
await
|
|
49
|
+
await writeTextFile(path, content, { mode: 0o600 });
|
|
48
50
|
}
|
|
49
51
|
|
|
50
52
|
async delete(serverUrl: string): Promise<void> {
|
|
51
53
|
const path = await this.filePath(serverUrl);
|
|
52
|
-
|
|
53
|
-
await Deno.remove(path);
|
|
54
|
-
} catch (e) {
|
|
55
|
-
if (e instanceof Deno.errors.NotFound) return;
|
|
56
|
-
throw e;
|
|
57
|
-
}
|
|
54
|
+
await remove(path);
|
|
58
55
|
}
|
|
59
56
|
|
|
60
57
|
async list(): Promise<string[]> {
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
} catch {
|
|
72
|
-
// Corrupted file, skip
|
|
73
|
-
}
|
|
58
|
+
const urls: string[] = [];
|
|
59
|
+
for (const name of await readDir(this.baseDir)) {
|
|
60
|
+
if (name.endsWith(".json")) {
|
|
61
|
+
try {
|
|
62
|
+
const content = await readTextFile(`${this.baseDir}/${name}`);
|
|
63
|
+
if (content === null) continue;
|
|
64
|
+
const creds = JSON.parse(content) as StoredCredentials;
|
|
65
|
+
urls.push(creds.serverUrl);
|
|
66
|
+
} catch {
|
|
67
|
+
// Corrupted file, skip
|
|
74
68
|
}
|
|
75
69
|
}
|
|
76
|
-
return urls;
|
|
77
|
-
} catch (e) {
|
|
78
|
-
if (e instanceof Deno.errors.NotFound) return [];
|
|
79
|
-
throw e;
|
|
80
70
|
}
|
|
71
|
+
return urls;
|
|
81
72
|
}
|
|
82
73
|
}
|
package/src/client-auth/types.ts
CHANGED
|
@@ -34,10 +34,8 @@ export interface TokenStore {
|
|
|
34
34
|
list(): Promise<string[]>;
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
-
/**
|
|
38
|
-
export interface
|
|
39
|
-
/** OAuth Client ID (public — embedded in consumer binary) */
|
|
40
|
-
clientId: string;
|
|
37
|
+
/** Fields shared by all OAuth client registration modes. */
|
|
38
|
+
export interface OAuthClientConfigBase {
|
|
41
39
|
/** Client name shown in consent screen */
|
|
42
40
|
clientName?: string;
|
|
43
41
|
/** Scopes to request (space-separated in OAuth, array here) */
|
|
@@ -51,3 +49,34 @@ export interface OAuthClientConfig {
|
|
|
51
49
|
/** Timeout for user to complete OAuth flow (ms, default: 120_000) */
|
|
52
50
|
authTimeout?: number;
|
|
53
51
|
}
|
|
52
|
+
|
|
53
|
+
/** Static OAuth client registration (default, backwards-compatible mode). */
|
|
54
|
+
export interface StaticClientConfig extends OAuthClientConfigBase {
|
|
55
|
+
/** OAuth Client ID (public — embedded in consumer binary) */
|
|
56
|
+
clientId: string;
|
|
57
|
+
/** Absence of clientRegistration selects static client-id behavior. */
|
|
58
|
+
clientRegistration?: undefined;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** CIMD client registration (explicit opt-in). */
|
|
62
|
+
export interface CimdClientConfig extends OAuthClientConfigBase {
|
|
63
|
+
/** In CIMD mode, client_id is derived from clientIdMetadataUrl. */
|
|
64
|
+
clientId?: never;
|
|
65
|
+
clientRegistration: {
|
|
66
|
+
method: "client_id_metadata";
|
|
67
|
+
/** HTTPS URL of the hosted Client ID Metadata Document; also the client_id. */
|
|
68
|
+
clientIdMetadataUrl: string;
|
|
69
|
+
/** Runtime redirect URI published in the metadata document. */
|
|
70
|
+
redirectUri: string;
|
|
71
|
+
/** Optional display and extension metadata for the hosted document. */
|
|
72
|
+
metadata?: {
|
|
73
|
+
client_uri?: string;
|
|
74
|
+
logo_uri?: string;
|
|
75
|
+
contacts?: string[];
|
|
76
|
+
extra?: Record<string, unknown>;
|
|
77
|
+
};
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Configuration for creating an OAuthClientProvider */
|
|
82
|
+
export type OAuthClientConfig = StaticClientConfig | CimdClientConfig;
|
package/src/runtime/runtime.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// deno-lint-ignore-file no-process-global
|
|
1
|
+
// deno-lint-ignore-file no-process-global
|
|
2
2
|
/**
|
|
3
3
|
* Runtime adapter — Node.js implementation
|
|
4
4
|
*
|
|
@@ -9,7 +9,14 @@
|
|
|
9
9
|
* @module lib/server/runtime.node
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
-
import {
|
|
12
|
+
import { Buffer } from "node:buffer";
|
|
13
|
+
import {
|
|
14
|
+
mkdir as nodeMkdir,
|
|
15
|
+
readdir,
|
|
16
|
+
readFile,
|
|
17
|
+
rm,
|
|
18
|
+
writeFile,
|
|
19
|
+
} from "node:fs/promises";
|
|
13
20
|
import { createServer } from "node:http";
|
|
14
21
|
import type {
|
|
15
22
|
FetchHandler,
|
|
@@ -52,6 +59,55 @@ export async function readTextFile(path: string): Promise<string | null> {
|
|
|
52
59
|
}
|
|
53
60
|
}
|
|
54
61
|
|
|
62
|
+
/**
|
|
63
|
+
* Write a UTF-8 text file.
|
|
64
|
+
*/
|
|
65
|
+
export async function writeTextFile(
|
|
66
|
+
path: string,
|
|
67
|
+
content: string,
|
|
68
|
+
opts?: { mode?: number },
|
|
69
|
+
): Promise<void> {
|
|
70
|
+
await writeFile(path, content, { mode: opts?.mode });
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Create a directory.
|
|
75
|
+
*/
|
|
76
|
+
export async function mkdir(
|
|
77
|
+
path: string,
|
|
78
|
+
opts?: { recursive?: boolean; mode?: number },
|
|
79
|
+
): Promise<void> {
|
|
80
|
+
await nodeMkdir(path, { recursive: opts?.recursive, mode: opts?.mode });
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Remove a file or empty directory. No-op if absent.
|
|
85
|
+
*/
|
|
86
|
+
export async function remove(path: string): Promise<void> {
|
|
87
|
+
try {
|
|
88
|
+
await rm(path);
|
|
89
|
+
} catch (err: unknown) {
|
|
90
|
+
if (isNodeNotFound(err)) {
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
throw err;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Read directory entry names. Returns [] if absent.
|
|
99
|
+
*/
|
|
100
|
+
export async function readDir(path: string): Promise<string[]> {
|
|
101
|
+
try {
|
|
102
|
+
return await readdir(path);
|
|
103
|
+
} catch (err: unknown) {
|
|
104
|
+
if (isNodeNotFound(err)) {
|
|
105
|
+
return [];
|
|
106
|
+
}
|
|
107
|
+
throw err;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
55
111
|
/**
|
|
56
112
|
* Start an HTTP server with a fetch-style handler.
|
|
57
113
|
* Uses node:http with a Request/Response adapter (compatible with Hono).
|
|
@@ -149,16 +205,36 @@ export function serve(
|
|
|
149
205
|
}
|
|
150
206
|
});
|
|
151
207
|
|
|
208
|
+
server.on("error", (err) => {
|
|
209
|
+
if (options.onError) {
|
|
210
|
+
options.onError(err);
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
setTimeout(() => {
|
|
214
|
+
throw err;
|
|
215
|
+
}, 0);
|
|
216
|
+
});
|
|
217
|
+
|
|
152
218
|
server.listen(options.port, hostname, () => {
|
|
153
219
|
if (options.onListen) {
|
|
154
|
-
|
|
220
|
+
const address = server.address();
|
|
221
|
+
const port = typeof address === "object" && address !== null
|
|
222
|
+
? address.port
|
|
223
|
+
: options.port;
|
|
224
|
+
options.onListen({ hostname, port });
|
|
155
225
|
}
|
|
156
226
|
});
|
|
157
227
|
|
|
158
228
|
return {
|
|
159
229
|
shutdown: () =>
|
|
160
230
|
new Promise<void>((resolve, reject) => {
|
|
161
|
-
server.close((err) =>
|
|
231
|
+
server.close((err) => {
|
|
232
|
+
if (err && !isNodeServerNotRunning(err)) {
|
|
233
|
+
reject(err);
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
resolve();
|
|
237
|
+
});
|
|
162
238
|
}),
|
|
163
239
|
};
|
|
164
240
|
}
|
|
@@ -182,7 +258,16 @@ export function unrefTimer(id: number): void {
|
|
|
182
258
|
}
|
|
183
259
|
|
|
184
260
|
/** Compile-time contract check — ensures this module satisfies RuntimePort */
|
|
185
|
-
void ({
|
|
261
|
+
void ({
|
|
262
|
+
env,
|
|
263
|
+
readTextFile,
|
|
264
|
+
writeTextFile,
|
|
265
|
+
mkdir,
|
|
266
|
+
remove,
|
|
267
|
+
readDir,
|
|
268
|
+
serve,
|
|
269
|
+
unrefTimer,
|
|
270
|
+
} satisfies RuntimePort);
|
|
186
271
|
|
|
187
272
|
// ─── Internal helpers ────────────────────────────────────
|
|
188
273
|
|
|
@@ -190,7 +275,7 @@ void ({ env, readTextFile, serve, unrefTimer } satisfies RuntimePort);
|
|
|
190
275
|
function collectBody(
|
|
191
276
|
req: import("node:http").IncomingMessage,
|
|
192
277
|
maxBytes: number | null,
|
|
193
|
-
): Promise<
|
|
278
|
+
): Promise<ArrayBuffer> {
|
|
194
279
|
return new Promise((resolve, reject) => {
|
|
195
280
|
const chunks: Buffer[] = [];
|
|
196
281
|
let total = 0;
|
|
@@ -208,7 +293,13 @@ function collectBody(
|
|
|
208
293
|
});
|
|
209
294
|
req.on("end", () => {
|
|
210
295
|
if (!rejected) {
|
|
211
|
-
|
|
296
|
+
const body = Buffer.concat(chunks);
|
|
297
|
+
resolve(
|
|
298
|
+
body.buffer.slice(
|
|
299
|
+
body.byteOffset,
|
|
300
|
+
body.byteOffset + body.byteLength,
|
|
301
|
+
),
|
|
302
|
+
);
|
|
212
303
|
}
|
|
213
304
|
});
|
|
214
305
|
req.on("error", (err) => {
|
|
@@ -218,3 +309,16 @@ function collectBody(
|
|
|
218
309
|
});
|
|
219
310
|
});
|
|
220
311
|
}
|
|
312
|
+
|
|
313
|
+
function isNodeNotFound(err: unknown): boolean {
|
|
314
|
+
return Boolean(
|
|
315
|
+
err && typeof err === "object" && "code" in err && err.code === "ENOENT",
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function isNodeServerNotRunning(err: unknown): boolean {
|
|
320
|
+
return Boolean(
|
|
321
|
+
err && typeof err === "object" && "code" in err &&
|
|
322
|
+
err.code === "ERR_SERVER_NOT_RUNNING",
|
|
323
|
+
);
|
|
324
|
+
}
|
package/src/runtime/types.ts
CHANGED
|
@@ -27,6 +27,31 @@ export type EnvFn = (key: string) => string | undefined;
|
|
|
27
27
|
*/
|
|
28
28
|
export type ReadTextFileFn = (path: string) => Promise<string | null>;
|
|
29
29
|
|
|
30
|
+
/** Write a UTF-8 text file. */
|
|
31
|
+
export type WriteTextFileFn = (
|
|
32
|
+
path: string,
|
|
33
|
+
content: string,
|
|
34
|
+
opts?: { mode?: number },
|
|
35
|
+
) => Promise<void>;
|
|
36
|
+
|
|
37
|
+
/** Create a directory. */
|
|
38
|
+
export type MkdirFn = (
|
|
39
|
+
path: string,
|
|
40
|
+
opts?: { recursive?: boolean; mode?: number },
|
|
41
|
+
) => Promise<void>;
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Remove a file or empty directory.
|
|
45
|
+
* Does nothing if the path does not exist.
|
|
46
|
+
*/
|
|
47
|
+
export type RemoveFn = (path: string) => Promise<void>;
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Read directory entry names.
|
|
51
|
+
* Returns [] if the directory does not exist.
|
|
52
|
+
*/
|
|
53
|
+
export type ReadDirFn = (path: string) => Promise<string[]>;
|
|
54
|
+
|
|
30
55
|
// ─── HTTP Server ─────────────────────────────────────────
|
|
31
56
|
|
|
32
57
|
/** Fetch-style request handler (Web standard) */
|
|
@@ -37,6 +62,8 @@ export interface ServeOptions {
|
|
|
37
62
|
port: number;
|
|
38
63
|
hostname?: string;
|
|
39
64
|
onListen?: (info: { hostname: string; port: number }) => void;
|
|
65
|
+
/** Optional bind/startup error channel. */
|
|
66
|
+
onError?: (err: Error) => void;
|
|
40
67
|
/** Maximum request body size in bytes (optional, adapter-specific). */
|
|
41
68
|
maxBodyBytes?: number | null;
|
|
42
69
|
}
|
|
@@ -79,12 +106,25 @@ export type UnrefTimerFn = (id: number) => void;
|
|
|
79
106
|
* @example
|
|
80
107
|
* ```typescript
|
|
81
108
|
* // At the bottom of runtime.ts / runtime.node.ts:
|
|
82
|
-
* export const _port = {
|
|
109
|
+
* export const _port = {
|
|
110
|
+
* env,
|
|
111
|
+
* readTextFile,
|
|
112
|
+
* writeTextFile,
|
|
113
|
+
* mkdir,
|
|
114
|
+
* remove,
|
|
115
|
+
* readDir,
|
|
116
|
+
* serve,
|
|
117
|
+
* unrefTimer,
|
|
118
|
+
* } satisfies RuntimePort;
|
|
83
119
|
* ```
|
|
84
120
|
*/
|
|
85
121
|
export interface RuntimePort {
|
|
86
122
|
env: EnvFn;
|
|
87
123
|
readTextFile: ReadTextFileFn;
|
|
124
|
+
writeTextFile: WriteTextFileFn;
|
|
125
|
+
mkdir: MkdirFn;
|
|
126
|
+
remove: RemoveFn;
|
|
127
|
+
readDir: ReadDirFn;
|
|
88
128
|
serve: ServeFn;
|
|
89
129
|
unrefTimer: UnrefTimerFn;
|
|
90
130
|
}
|