xmcp 0.7.0 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +2 -3
- package/src/auth/api-key.ts +0 -120
- package/src/auth/jwt.ts +0 -52
- package/src/cli/commands/create/__tests__/create.test.ts +0 -99
- package/src/cli/commands/create/index.ts +0 -74
- package/src/cli/commands/create/templates/index.ts +0 -4
- package/src/cli/commands/create/templates/prompt.ts +0 -30
- package/src/cli/commands/create/templates/resource.ts +0 -20
- package/src/cli/commands/create/templates/tool.ts +0 -34
- package/src/cli/commands/create/templates/widget.ts +0 -33
- package/src/cli/utils/naming.ts +0 -39
- package/src/cli.ts +0 -125
- package/src/client/headers.ts +0 -61
- package/src/client/index.ts +0 -180
- package/src/client/types.ts +0 -122
- package/src/client/utils.ts +0 -133
- package/src/cloudflare.ts +0 -6
- package/src/compiler/build-telemetry.ts +0 -88
- package/src/compiler/client/component-compiler.ts +0 -250
- package/src/compiler/client/transpile.ts +0 -21
- package/src/compiler/compiler-context.ts +0 -61
- package/src/compiler/config/__tests__/config.test.ts +0 -459
- package/src/compiler/config/index.ts +0 -62
- package/src/compiler/config/injection.ts +0 -210
- package/src/compiler/config/schemas/bundler.ts +0 -12
- package/src/compiler/config/schemas/experimental/index.ts +0 -22
- package/src/compiler/config/schemas/index.ts +0 -20
- package/src/compiler/config/schemas/paths.ts +0 -35
- package/src/compiler/config/schemas/template.ts +0 -80
- package/src/compiler/config/schemas/transport/http.ts +0 -116
- package/src/compiler/config/schemas/transport/stdio.ts +0 -31
- package/src/compiler/config/schemas/typescript.ts +0 -26
- package/src/compiler/config/utils.ts +0 -168
- package/src/compiler/generate-env-code.ts +0 -5
- package/src/compiler/generate-import-code.ts +0 -187
- package/src/compiler/generate-tools-code.ts +0 -174
- package/src/compiler/get-bundler-config/get-entries.ts +0 -44
- package/src/compiler/get-bundler-config/get-externals.ts +0 -114
- package/src/compiler/get-bundler-config/get-injected-variables.ts +0 -46
- package/src/compiler/get-bundler-config/index.ts +0 -288
- package/src/compiler/get-bundler-config/plugins/index.ts +0 -140
- package/src/compiler/get-bundler-config/plugins/types/express.ts +0 -3
- package/src/compiler/get-bundler-config/plugins/types/fastify.ts +0 -4
- package/src/compiler/get-bundler-config/plugins/types/index.ts +0 -5
- package/src/compiler/get-bundler-config/plugins/types/nest.ts +0 -65
- package/src/compiler/get-bundler-config/plugins/types/next.ts +0 -52
- package/src/compiler/get-bundler-config/resolve-tsconfig-paths.ts +0 -51
- package/src/compiler/index.ts +0 -484
- package/src/compiler/on-first-build.ts +0 -54
- package/src/compiler/parse-xmcp-config.ts +0 -200
- package/src/compiler/start-http-server.ts +0 -42
- package/src/compiler/utils/__tests__/config-detection.test.ts +0 -307
- package/src/compiler/utils/__tests__/path-utils.test.ts +0 -137
- package/src/compiler/utils/config-detection.ts +0 -34
- package/src/compiler/utils/path-utils.ts +0 -22
- package/src/compiler/watcher-recovery.ts +0 -72
- package/src/host-bridge.ts +0 -36
- package/src/index.ts +0 -94
- package/src/platforms/build-cloudflare-output.ts +0 -116
- package/src/platforms/build-vercel-output.ts +0 -131
- package/src/plugins/index.ts +0 -1
- package/src/plugins/x402/index.ts +0 -24
- package/src/runtime/adapters/express/index.ts +0 -75
- package/src/runtime/adapters/fastify/__tests__/fastify.test.ts +0 -115
- package/src/runtime/adapters/fastify/index.ts +0 -78
- package/src/runtime/adapters/nestjs/index.ts +0 -16
- package/src/runtime/adapters/nestjs/xmcp.controller.ts +0 -34
- package/src/runtime/adapters/nestjs/xmcp.guard.ts +0 -101
- package/src/runtime/adapters/nestjs/xmcp.oauth.controller.ts +0 -36
- package/src/runtime/adapters/nestjs/xmcp.oauth.module.ts +0 -21
- package/src/runtime/adapters/nestjs/xmcp.oauth.service.ts +0 -36
- package/src/runtime/adapters/nestjs/xmcp.service.ts +0 -96
- package/src/runtime/adapters/nestjs/xmcp.utils.ts +0 -11
- package/src/runtime/adapters/nextjs/auth.ts +0 -265
- package/src/runtime/adapters/nextjs/handler/error-handler.ts +0 -67
- package/src/runtime/adapters/nextjs/handler/node-to-web-adapter.ts +0 -143
- package/src/runtime/adapters/nextjs/handler/request-converter.ts +0 -74
- package/src/runtime/adapters/nextjs/handler/server-lifecycle.ts +0 -69
- package/src/runtime/adapters/nextjs/index.ts +0 -121
- package/src/runtime/contexts/client-info-context.ts +0 -16
- package/src/runtime/contexts/http-request-context.ts +0 -21
- package/src/runtime/contexts/http-transport-context.ts +0 -18
- package/src/runtime/headers.ts +0 -42
- package/src/runtime/middlewares/utils.ts +0 -72
- package/src/runtime/platforms/cloudflare/cors.ts +0 -44
- package/src/runtime/platforms/cloudflare/middlewares/api-key.ts +0 -102
- package/src/runtime/platforms/cloudflare/middlewares/jwt.ts +0 -127
- package/src/runtime/platforms/cloudflare/types.ts +0 -23
- package/src/runtime/platforms/cloudflare/worker.ts +0 -270
- package/src/runtime/templates/home.ts +0 -746
- package/src/runtime/transports/http/base-streamable-http.ts +0 -46
- package/src/runtime/transports/http/cors/headers.ts +0 -58
- package/src/runtime/transports/http/cors/index.ts +0 -34
- package/src/runtime/transports/http/index.ts +0 -78
- package/src/runtime/transports/http/stateless-streamable-http.ts +0 -353
- package/src/runtime/transports/http/web-stateless-http.ts +0 -288
- package/src/runtime/transports/stdio/index.ts +0 -109
- package/src/runtime/utils/__tests__/client-info.test.ts +0 -146
- package/src/runtime/utils/__tests__/tool-extra.test.ts +0 -239
- package/src/runtime/utils/client-info.ts +0 -114
- package/src/runtime/utils/elicitation.ts +0 -396
- package/src/runtime/utils/ext-apps-registry.ts +0 -151
- package/src/runtime/utils/mcp-app-protocol.ts +0 -16
- package/src/runtime/utils/mcp-app-types.ts +0 -113
- package/src/runtime/utils/mcp-host-bridge.ts +0 -473
- package/src/runtime/utils/path-to-tool-name.ts +0 -69
- package/src/runtime/utils/prompt-loader.ts +0 -151
- package/src/runtime/utils/prompts.ts +0 -69
- package/src/runtime/utils/react/generate-html.ts +0 -69
- package/src/runtime/utils/react/index.ts +0 -6
- package/src/runtime/utils/request-tool-names.ts +0 -48
- package/src/runtime/utils/resource-loader.ts +0 -151
- package/src/runtime/utils/resources.ts +0 -331
- package/src/runtime/utils/server.ts +0 -107
- package/src/runtime/utils/tool-loader.ts +0 -149
- package/src/runtime/utils/tools.ts +0 -183
- package/src/runtime/utils/transformers/prompt.ts +0 -120
- package/src/runtime/utils/transformers/resource.ts +0 -196
- package/src/runtime/utils/transformers/tool.ts +0 -400
- package/src/runtime/utils/ui/__tests__/split-meta.test.ts +0 -803
- package/src/runtime/utils/ui/flatten-meta.ts +0 -44
- package/src/runtime/utils/ui/split-meta.ts +0 -78
- package/src/runtime/utils/utils/resource-uri-composer.ts +0 -204
- package/src/runtime/utils/validators/index.ts +0 -138
- package/src/telemetry/ci-info.ts +0 -6
- package/src/telemetry/debug.ts +0 -8
- package/src/telemetry/events/definitions.ts +0 -52
- package/src/telemetry/events/detached-flush.ts +0 -83
- package/src/telemetry/events/post-payload.ts +0 -141
- package/src/telemetry/events/tracker.ts +0 -281
- package/src/telemetry/index.ts +0 -7
- package/src/telemetry/metadata.ts +0 -49
- package/src/telemetry/project-id.ts +0 -35
- package/src/telemetry/storage.ts +0 -218
- package/src/types/adapter.d.ts +0 -5
- package/src/types/client-info.ts +0 -20
- package/src/types/declarations.ts +0 -37
- package/src/types/injected.d.ts +0 -62
- package/src/types/middleware.ts +0 -19
- package/src/types/prompt.ts +0 -6
- package/src/types/resource.ts +0 -15
- package/src/types/tool.ts +0 -192
- package/src/types/ui-meta.ts +0 -42
- package/src/utils/cli-icons.ts +0 -5
- package/src/utils/constants.ts +0 -31
- package/src/utils/context.ts +0 -105
- package/src/utils/detect-package-manager.ts +0 -46
- package/src/utils/file-watcher.ts +0 -66
- package/src/utils/fs-utils.ts +0 -16
- package/src/utils/path-validation.ts +0 -66
- package/src/utils/port-utils.ts +0 -43
- package/src/utils/spawn-process.ts +0 -49
- package/src/utils/subscribable.ts +0 -62
|
@@ -1,121 +0,0 @@
|
|
|
1
|
-
import type { ServerResponse } from "node:http";
|
|
2
|
-
import { nodeToWebAdapter } from "./handler/node-to-web-adapter";
|
|
3
|
-
import {
|
|
4
|
-
createMethodNotAllowedResponse,
|
|
5
|
-
sendInternalServerError,
|
|
6
|
-
} from "./handler/error-handler";
|
|
7
|
-
import {
|
|
8
|
-
createServerLifecycle,
|
|
9
|
-
setupCleanupHandlers,
|
|
10
|
-
} from "./handler/server-lifecycle";
|
|
11
|
-
import { createIncomingMessage } from "./handler/request-converter";
|
|
12
|
-
import type { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types";
|
|
13
|
-
import { httpRequestContextProvider } from "@/runtime/contexts/http-request-context";
|
|
14
|
-
import { randomUUID } from "node:crypto";
|
|
15
|
-
import {
|
|
16
|
-
setHttpRequestContext,
|
|
17
|
-
} from "@/runtime/contexts/http-request-context";
|
|
18
|
-
import { extractClientInfoFromMessages } from "@/runtime/utils/client-info";
|
|
19
|
-
|
|
20
|
-
const BODY_SIZE_LIMIT = "10mb";
|
|
21
|
-
|
|
22
|
-
/**
|
|
23
|
-
* Main handler for MCP requests in Next.js runtime.
|
|
24
|
-
* Handles POST requests only, validates, parses, and routes to MCP server.
|
|
25
|
-
*/
|
|
26
|
-
export async function xmcpHandler(request: Request): Promise<Response> {
|
|
27
|
-
// Only handle POST requests
|
|
28
|
-
if (request.method !== "POST") {
|
|
29
|
-
return createMethodNotAllowedResponse();
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
const id = randomUUID();
|
|
33
|
-
const requestHeaders = Object.fromEntries(request.headers.entries());
|
|
34
|
-
|
|
35
|
-
return httpRequestContextProvider(
|
|
36
|
-
{ id, headers: requestHeaders, clientInfo: undefined },
|
|
37
|
-
() => {
|
|
38
|
-
return nodeToWebAdapter(request.signal, async (res: ServerResponse) => {
|
|
39
|
-
try {
|
|
40
|
-
// Initialize server and transport
|
|
41
|
-
const lifecycle = await createServerLifecycle(BODY_SIZE_LIMIT);
|
|
42
|
-
|
|
43
|
-
// Setup cleanup handlers
|
|
44
|
-
setupCleanupHandlers(res, lifecycle);
|
|
45
|
-
|
|
46
|
-
// Parse request body
|
|
47
|
-
const bodyContent = await request.json();
|
|
48
|
-
const clientInfo = extractClientInfoFromMessages(bodyContent);
|
|
49
|
-
setHttpRequestContext({ clientInfo });
|
|
50
|
-
|
|
51
|
-
// Convert Web Request to Node.js IncomingMessage
|
|
52
|
-
const incomingRequest = createIncomingMessage({
|
|
53
|
-
method: request.method,
|
|
54
|
-
url: request.url,
|
|
55
|
-
headers: requestHeaders,
|
|
56
|
-
auth: request.auth,
|
|
57
|
-
});
|
|
58
|
-
|
|
59
|
-
// Handle request through transport
|
|
60
|
-
await lifecycle.transport.handleRequest(
|
|
61
|
-
incomingRequest,
|
|
62
|
-
res,
|
|
63
|
-
bodyContent
|
|
64
|
-
);
|
|
65
|
-
} catch (error) {
|
|
66
|
-
console.error("[Next.js MCP] Error handling MCP request:", error);
|
|
67
|
-
sendInternalServerError(res);
|
|
68
|
-
}
|
|
69
|
-
});
|
|
70
|
-
}
|
|
71
|
-
);
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
// Re-export auth types and handlers
|
|
75
|
-
export {
|
|
76
|
-
withAuth,
|
|
77
|
-
resourceMetadataHandler,
|
|
78
|
-
resourceMetadataOptions,
|
|
79
|
-
type VerifyToken,
|
|
80
|
-
type AuthConfig,
|
|
81
|
-
type OAuthProtectedResourceMetadata,
|
|
82
|
-
} from "./auth";
|
|
83
|
-
|
|
84
|
-
/**
|
|
85
|
-
* MCP Server Card handler for Next.js route files (SEP-1649).
|
|
86
|
-
* Serves server identity and transport metadata at `/.well-known/mcp/server-card.json`,
|
|
87
|
-
* enabling agent discovery clients to auto-configure connections.
|
|
88
|
-
*
|
|
89
|
-
* @example
|
|
90
|
-
* // app/.well-known/mcp/server-card.json/route.ts
|
|
91
|
-
* import { serverCardHandler } from "@xmcp/adapter";
|
|
92
|
-
* export { serverCardHandler as GET };
|
|
93
|
-
*/
|
|
94
|
-
export function serverCardHandler(request: Request): Response {
|
|
95
|
-
const url = new URL(request.url);
|
|
96
|
-
const reversedName = url.hostname.split(".").reverse().join(".");
|
|
97
|
-
const card: Record<string, unknown> = {
|
|
98
|
-
$schema:
|
|
99
|
-
"https://static.modelcontextprotocol.io/schemas/v1/server-card.schema.json",
|
|
100
|
-
name: `${reversedName}/mcp`,
|
|
101
|
-
version: SERVER_INFO.version,
|
|
102
|
-
description: TEMPLATE_CONFIG.description,
|
|
103
|
-
title: TEMPLATE_CONFIG.name,
|
|
104
|
-
remotes: [
|
|
105
|
-
{
|
|
106
|
-
type: "streamable-http",
|
|
107
|
-
url: `${url.origin}${HTTP_CONFIG.endpoint}`,
|
|
108
|
-
},
|
|
109
|
-
],
|
|
110
|
-
};
|
|
111
|
-
if (TEMPLATE_CONFIG.icons?.length) {
|
|
112
|
-
card.icons = TEMPLATE_CONFIG.icons;
|
|
113
|
-
}
|
|
114
|
-
return Response.json(card, {
|
|
115
|
-
headers: {
|
|
116
|
-
"Content-Type": "application/mcp-server-card+json",
|
|
117
|
-
"Cache-Control": "public, max-age=3600, must-revalidate",
|
|
118
|
-
"Access-Control-Allow-Origin": "*",
|
|
119
|
-
},
|
|
120
|
-
});
|
|
121
|
-
}
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import type { McpClientInfo } from "@/types/client-info";
|
|
2
|
-
import { createContext } from "../../utils/context";
|
|
3
|
-
|
|
4
|
-
export interface ClientInfoContext {
|
|
5
|
-
clientInfo?: McpClientInfo;
|
|
6
|
-
}
|
|
7
|
-
|
|
8
|
-
export const clientInfoContext = createContext<ClientInfoContext>({
|
|
9
|
-
name: "client-info-context",
|
|
10
|
-
});
|
|
11
|
-
|
|
12
|
-
export const setClientInfoContext = clientInfoContext.setContext;
|
|
13
|
-
|
|
14
|
-
export const getClientInfoContext = clientInfoContext.getContext;
|
|
15
|
-
|
|
16
|
-
export const clientInfoContextProvider = clientInfoContext.provider;
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
import { createContext } from "../../utils/context";
|
|
2
|
-
import type { McpClientInfo } from "@/types/client-info";
|
|
3
|
-
|
|
4
|
-
// Headers type compatible with both Node.js IncomingHttpHeaders and Web API headers
|
|
5
|
-
export type HttpHeaders = Record<string, string | string[] | undefined>;
|
|
6
|
-
|
|
7
|
-
export interface HttpRequestContext {
|
|
8
|
-
id: string;
|
|
9
|
-
headers: HttpHeaders;
|
|
10
|
-
clientInfo?: McpClientInfo;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
export const httpRequestContext = createContext<HttpRequestContext>({
|
|
14
|
-
name: "http-request-context",
|
|
15
|
-
});
|
|
16
|
-
|
|
17
|
-
export const setHttpRequestContext = httpRequestContext.setContext;
|
|
18
|
-
|
|
19
|
-
export const getHttpRequestContext = httpRequestContext.getContext;
|
|
20
|
-
|
|
21
|
-
export const httpRequestContextProvider = httpRequestContext.provider;
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
import { ResolvedHttpConfig } from "@/compiler/config";
|
|
2
|
-
import { createContext } from "../../utils/context";
|
|
3
|
-
|
|
4
|
-
export interface HttpTransportContext {
|
|
5
|
-
config: {
|
|
6
|
-
http?: ResolvedHttpConfig;
|
|
7
|
-
};
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
export const httpTransportContext = createContext<HttpTransportContext>({
|
|
11
|
-
name: "http-transport-context",
|
|
12
|
-
});
|
|
13
|
-
|
|
14
|
-
export const setHttpTransportContext = httpTransportContext.setContext;
|
|
15
|
-
|
|
16
|
-
export const getHttpTransportContext = httpTransportContext.getContext;
|
|
17
|
-
|
|
18
|
-
export const httpTransportContextProvider = httpTransportContext.provider;
|
package/src/runtime/headers.ts
DELETED
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
import { getHttpRequestContext } from "./contexts/http-request-context";
|
|
2
|
-
|
|
3
|
-
export const headers = () => {
|
|
4
|
-
const currentHeaders = getHttpRequestContext().headers;
|
|
5
|
-
const headerLookup = new Map<string, string>();
|
|
6
|
-
|
|
7
|
-
for (const key of Object.keys(currentHeaders)) {
|
|
8
|
-
const normalizedKey = key.toLowerCase();
|
|
9
|
-
|
|
10
|
-
if (!headerLookup.has(normalizedKey)) {
|
|
11
|
-
headerLookup.set(normalizedKey, key);
|
|
12
|
-
}
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
const resolveHeaderKey = (prop: string): string => {
|
|
16
|
-
return headerLookup.get(prop.toLowerCase()) ?? prop;
|
|
17
|
-
};
|
|
18
|
-
|
|
19
|
-
return new Proxy(currentHeaders, {
|
|
20
|
-
get(target, prop, receiver) {
|
|
21
|
-
if (typeof prop !== "string") {
|
|
22
|
-
return Reflect.get(target, prop, receiver);
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
return Reflect.get(target, resolveHeaderKey(prop), receiver);
|
|
26
|
-
},
|
|
27
|
-
has(target, prop) {
|
|
28
|
-
if (typeof prop !== "string") {
|
|
29
|
-
return Reflect.has(target, prop);
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
return Reflect.has(target, resolveHeaderKey(prop));
|
|
33
|
-
},
|
|
34
|
-
getOwnPropertyDescriptor(target, prop) {
|
|
35
|
-
if (typeof prop !== "string") {
|
|
36
|
-
return Reflect.getOwnPropertyDescriptor(target, prop);
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
return Reflect.getOwnPropertyDescriptor(target, resolveHeaderKey(prop));
|
|
40
|
-
},
|
|
41
|
-
});
|
|
42
|
-
};
|
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
import { RequestHandlerAndRouter, Middleware } from "@/types/middleware";
|
|
2
|
-
import { Router, type RequestHandler } from "express";
|
|
3
|
-
|
|
4
|
-
export type Provider = {
|
|
5
|
-
middleware?: RequestHandler;
|
|
6
|
-
router?: Router;
|
|
7
|
-
};
|
|
8
|
-
|
|
9
|
-
export type ProvidersModel = Provider[];
|
|
10
|
-
|
|
11
|
-
// assertion functions to get the type of the middleware and router
|
|
12
|
-
function isRequestHandler(
|
|
13
|
-
middleware: Middleware
|
|
14
|
-
): middleware is RequestHandler {
|
|
15
|
-
return typeof middleware === "function";
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
function isRequestHandlerAndRouter(
|
|
19
|
-
middleware: Middleware
|
|
20
|
-
): middleware is RequestHandlerAndRouter {
|
|
21
|
-
return (
|
|
22
|
-
typeof middleware === "object" &&
|
|
23
|
-
middleware !== null &&
|
|
24
|
-
"middleware" in middleware &&
|
|
25
|
-
"router" in middleware &&
|
|
26
|
-
typeof middleware.middleware === "function" &&
|
|
27
|
-
isExpressRouter(middleware.router)
|
|
28
|
-
);
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
function isExpressRouter(obj: any): obj is Router {
|
|
32
|
-
return (
|
|
33
|
-
typeof obj === "function" &&
|
|
34
|
-
obj !== null &&
|
|
35
|
-
typeof obj.use === "function" &&
|
|
36
|
-
typeof obj.get === "function" &&
|
|
37
|
-
typeof obj.post === "function" &&
|
|
38
|
-
typeof obj.route === "function"
|
|
39
|
-
);
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
// read from the array of providers (middlewares and/or routers) and split them into ordered items preserving sequence
|
|
43
|
-
export function processProviders(
|
|
44
|
-
defaultExport: Middleware | Middleware[]
|
|
45
|
-
): ProvidersModel {
|
|
46
|
-
const providers: ProvidersModel = [];
|
|
47
|
-
|
|
48
|
-
if (Array.isArray(defaultExport)) {
|
|
49
|
-
for (const middleware of defaultExport) {
|
|
50
|
-
if (isRequestHandler(middleware)) {
|
|
51
|
-
providers.push({ middleware });
|
|
52
|
-
} else if (isRequestHandlerAndRouter(middleware)) {
|
|
53
|
-
providers.push({
|
|
54
|
-
middleware: middleware.middleware,
|
|
55
|
-
router: middleware.router,
|
|
56
|
-
});
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
} else {
|
|
60
|
-
// if it's not an array return it as an array anyways
|
|
61
|
-
if (isRequestHandler(defaultExport)) {
|
|
62
|
-
providers.push({ middleware: defaultExport });
|
|
63
|
-
} else if (isRequestHandlerAndRouter(defaultExport)) {
|
|
64
|
-
providers.push({
|
|
65
|
-
middleware: defaultExport.middleware,
|
|
66
|
-
router: defaultExport.router,
|
|
67
|
-
});
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
return providers;
|
|
72
|
-
}
|
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* CORS handling for Cloudflare Workers adapter.
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
import type { CorsConfig } from "@/compiler/config";
|
|
6
|
-
import { buildCorsHeaders } from "@/runtime/transports/http/cors/headers";
|
|
7
|
-
|
|
8
|
-
// CORS config - injected by compiler as combined object
|
|
9
|
-
const corsConfig = HTTP_CORS_CONFIG as CorsConfig;
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* Add CORS headers to a Response
|
|
13
|
-
*/
|
|
14
|
-
export function addCorsHeaders(
|
|
15
|
-
response: Response,
|
|
16
|
-
requestOrigin: string | null
|
|
17
|
-
): Response {
|
|
18
|
-
const headers = new Headers(response.headers);
|
|
19
|
-
|
|
20
|
-
const corsHeaders = buildCorsHeaders(corsConfig, requestOrigin);
|
|
21
|
-
for (const [key, value] of Object.entries(corsHeaders)) {
|
|
22
|
-
headers.set(key, value);
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
return new Response(response.body, {
|
|
26
|
-
status: response.status,
|
|
27
|
-
statusText: response.statusText,
|
|
28
|
-
headers,
|
|
29
|
-
});
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
/**
|
|
33
|
-
* Handle CORS preflight requests
|
|
34
|
-
*/
|
|
35
|
-
export function handleCorsPreflightRequest(
|
|
36
|
-
requestOrigin: string | null
|
|
37
|
-
): Response {
|
|
38
|
-
const headers = new Headers(buildCorsHeaders(corsConfig, requestOrigin));
|
|
39
|
-
|
|
40
|
-
return new Response(null, {
|
|
41
|
-
status: 204,
|
|
42
|
-
headers,
|
|
43
|
-
});
|
|
44
|
-
}
|
|
@@ -1,102 +0,0 @@
|
|
|
1
|
-
import { z } from "zod/v3";
|
|
2
|
-
import type { WebMiddleware } from "@/types/middleware";
|
|
3
|
-
|
|
4
|
-
const apiKeyAuthMiddlewareConfigSchema = z
|
|
5
|
-
.object({
|
|
6
|
-
apiKey: z.string().optional(),
|
|
7
|
-
headerName: z.string().optional(),
|
|
8
|
-
validateApiKey: z
|
|
9
|
-
.function()
|
|
10
|
-
.args(z.string())
|
|
11
|
-
.returns(z.promise(z.boolean()))
|
|
12
|
-
.optional(),
|
|
13
|
-
})
|
|
14
|
-
.strict()
|
|
15
|
-
.refine(
|
|
16
|
-
(config) =>
|
|
17
|
-
config.apiKey !== undefined || config.validateApiKey !== undefined,
|
|
18
|
-
{
|
|
19
|
-
message: "Either 'apiKey' or 'validateApiKey' must be provided",
|
|
20
|
-
}
|
|
21
|
-
)
|
|
22
|
-
.refine(
|
|
23
|
-
(config) =>
|
|
24
|
-
!(config.apiKey !== undefined && config.validateApiKey !== undefined),
|
|
25
|
-
{
|
|
26
|
-
message:
|
|
27
|
-
"'apiKey' and 'validateApiKey' are mutually exclusive - provide only one",
|
|
28
|
-
}
|
|
29
|
-
);
|
|
30
|
-
|
|
31
|
-
const errorMessage = "Unauthorized: Missing or invalid API key";
|
|
32
|
-
|
|
33
|
-
type StaticApiKeyConfig = {
|
|
34
|
-
/** The static API key to validate against */
|
|
35
|
-
apiKey: string;
|
|
36
|
-
/** Optional header name to read the API key from. Defaults to 'x-api-key' */
|
|
37
|
-
headerName?: string;
|
|
38
|
-
};
|
|
39
|
-
|
|
40
|
-
type CustomValidationConfig = {
|
|
41
|
-
/** Optional header name to read the API key from. Defaults to 'x-api-key' */
|
|
42
|
-
headerName?: string;
|
|
43
|
-
/** Custom validation function that receives the API key and returns a Promise<boolean> */
|
|
44
|
-
validateApiKey: (key: string) => Promise<boolean>;
|
|
45
|
-
};
|
|
46
|
-
|
|
47
|
-
export function cloudflareApiKeyAuthMiddleware(
|
|
48
|
-
config: StaticApiKeyConfig
|
|
49
|
-
): WebMiddleware;
|
|
50
|
-
|
|
51
|
-
export function cloudflareApiKeyAuthMiddleware(
|
|
52
|
-
config: CustomValidationConfig
|
|
53
|
-
): WebMiddleware;
|
|
54
|
-
|
|
55
|
-
export function cloudflareApiKeyAuthMiddleware(
|
|
56
|
-
config: StaticApiKeyConfig | CustomValidationConfig
|
|
57
|
-
): WebMiddleware {
|
|
58
|
-
const response = apiKeyAuthMiddlewareConfigSchema.safeParse(config);
|
|
59
|
-
if (!response.success) {
|
|
60
|
-
const hasApiKey = "apiKey" in config;
|
|
61
|
-
const hasValidateApiKey = "validateApiKey" in config;
|
|
62
|
-
|
|
63
|
-
if (hasApiKey && hasValidateApiKey) {
|
|
64
|
-
throw new Error(
|
|
65
|
-
"'apiKey' and 'validateApiKey' are mutually exclusive - provide only one"
|
|
66
|
-
);
|
|
67
|
-
} else if (!hasApiKey && !hasValidateApiKey) {
|
|
68
|
-
throw new Error("Either 'apiKey' or 'validateApiKey' must be provided");
|
|
69
|
-
} else {
|
|
70
|
-
throw new Error(`Invalid configuration: ${response.error.message}`);
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
const headerName = config.headerName ?? "x-api-key";
|
|
75
|
-
const apiKey = "apiKey" in config ? config.apiKey : undefined;
|
|
76
|
-
const validateApiKey =
|
|
77
|
-
"validateApiKey" in config ? config.validateApiKey : undefined;
|
|
78
|
-
|
|
79
|
-
return async (request) => {
|
|
80
|
-
const apiKeyHeader = request.headers.get(headerName);
|
|
81
|
-
if (!apiKeyHeader) {
|
|
82
|
-
return jsonUnauthorized(errorMessage);
|
|
83
|
-
}
|
|
84
|
-
if ("apiKey" in config && apiKeyHeader !== apiKey) {
|
|
85
|
-
return jsonUnauthorized(errorMessage);
|
|
86
|
-
}
|
|
87
|
-
if (validateApiKey) {
|
|
88
|
-
const isValid = await validateApiKey(apiKeyHeader);
|
|
89
|
-
if (!isValid) {
|
|
90
|
-
return jsonUnauthorized(errorMessage);
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
return;
|
|
94
|
-
};
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
function jsonUnauthorized(message: string): Response {
|
|
98
|
-
return new Response(JSON.stringify({ error: message }), {
|
|
99
|
-
status: 401,
|
|
100
|
-
headers: { "Content-Type": "application/json" },
|
|
101
|
-
});
|
|
102
|
-
}
|
|
@@ -1,127 +0,0 @@
|
|
|
1
|
-
import type { JWTPayload, JWTVerifyOptions } from "jose";
|
|
2
|
-
import { decodeProtectedHeader, importJWK, importSPKI, importX509, jwtVerify } from "jose";
|
|
3
|
-
import type { WebMiddleware } from "@/types/middleware";
|
|
4
|
-
|
|
5
|
-
export type CloudflareJWTAuthMiddlewareConfig = {
|
|
6
|
-
secret: string;
|
|
7
|
-
algorithms?: string[];
|
|
8
|
-
audience?: string | string[];
|
|
9
|
-
issuer?: string;
|
|
10
|
-
subject?: string;
|
|
11
|
-
clockTolerance?: number | string;
|
|
12
|
-
maxAge?: string | number;
|
|
13
|
-
};
|
|
14
|
-
|
|
15
|
-
export function cloudflareJwtAuthMiddleware(
|
|
16
|
-
config: CloudflareJWTAuthMiddlewareConfig
|
|
17
|
-
): WebMiddleware {
|
|
18
|
-
return async (request) => {
|
|
19
|
-
const authHeader = request.headers.get("authorization");
|
|
20
|
-
const token = extractBearerToken(authHeader);
|
|
21
|
-
if (!token) {
|
|
22
|
-
return jsonUnauthorized(
|
|
23
|
-
"Unauthorized: Missing or malformed Authorization header"
|
|
24
|
-
);
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
try {
|
|
28
|
-
await verifyJwt(token, config);
|
|
29
|
-
return;
|
|
30
|
-
} catch {
|
|
31
|
-
return jsonUnauthorized("Unauthorized: Invalid or expired token");
|
|
32
|
-
}
|
|
33
|
-
};
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
function extractBearerToken(authHeader: string | null | undefined): string | null {
|
|
37
|
-
if (!authHeader) return null;
|
|
38
|
-
const [scheme, token] = authHeader.split(" ");
|
|
39
|
-
if (!scheme || !token || scheme.toLowerCase() !== "bearer") {
|
|
40
|
-
return null;
|
|
41
|
-
}
|
|
42
|
-
return token.trim() || null;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
function jsonUnauthorized(message: string): Response {
|
|
46
|
-
return new Response(JSON.stringify({ error: message }), {
|
|
47
|
-
status: 401,
|
|
48
|
-
headers: { "Content-Type": "application/json" },
|
|
49
|
-
});
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
async function verifyJwt(
|
|
53
|
-
token: string,
|
|
54
|
-
config: CloudflareJWTAuthMiddlewareConfig
|
|
55
|
-
): Promise<JWTPayload> {
|
|
56
|
-
const { secret, ...verifyOptions } = config;
|
|
57
|
-
const header = decodeProtectedHeader(token);
|
|
58
|
-
const alg =
|
|
59
|
-
verifyOptions.algorithms?.[0] ??
|
|
60
|
-
(typeof header.alg === "string" ? header.alg : undefined);
|
|
61
|
-
|
|
62
|
-
if (!alg) {
|
|
63
|
-
throw new Error("Missing JWT algorithm");
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
const key = await resolveJoseKey(secret, alg);
|
|
67
|
-
const joseOptions = mapJoseVerifyOptions(verifyOptions);
|
|
68
|
-
const { payload } = await jwtVerify(token, key as any, joseOptions);
|
|
69
|
-
return payload;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
async function resolveJoseKey(
|
|
73
|
-
secret: string,
|
|
74
|
-
alg: string
|
|
75
|
-
): Promise<Uint8Array | unknown> {
|
|
76
|
-
const trimmed = secret.trim();
|
|
77
|
-
|
|
78
|
-
if (trimmed.startsWith("{")) {
|
|
79
|
-
try {
|
|
80
|
-
const jwk = JSON.parse(trimmed);
|
|
81
|
-
return await importJWK(jwk, alg);
|
|
82
|
-
} catch {
|
|
83
|
-
return new TextEncoder().encode(secret);
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
if (trimmed.includes("BEGIN CERTIFICATE")) {
|
|
88
|
-
return await importX509(trimmed, alg);
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
if (trimmed.includes("BEGIN PUBLIC KEY")) {
|
|
92
|
-
return await importSPKI(trimmed, alg);
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
return new TextEncoder().encode(secret);
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
function mapJoseVerifyOptions(
|
|
99
|
-
verifyOptions: Omit<CloudflareJWTAuthMiddlewareConfig, "secret">
|
|
100
|
-
): JWTVerifyOptions {
|
|
101
|
-
const joseOptions: JWTVerifyOptions = {};
|
|
102
|
-
|
|
103
|
-
if (verifyOptions.algorithms) {
|
|
104
|
-
joseOptions.algorithms = verifyOptions.algorithms;
|
|
105
|
-
}
|
|
106
|
-
if (verifyOptions.audience) {
|
|
107
|
-
if (typeof verifyOptions.audience === "string") {
|
|
108
|
-
joseOptions.audience = verifyOptions.audience;
|
|
109
|
-
} else if (Array.isArray(verifyOptions.audience)) {
|
|
110
|
-
joseOptions.audience = verifyOptions.audience;
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
if (verifyOptions.issuer) {
|
|
114
|
-
joseOptions.issuer = verifyOptions.issuer;
|
|
115
|
-
}
|
|
116
|
-
if (verifyOptions.subject) {
|
|
117
|
-
joseOptions.subject = verifyOptions.subject;
|
|
118
|
-
}
|
|
119
|
-
if (verifyOptions.clockTolerance !== undefined) {
|
|
120
|
-
joseOptions.clockTolerance = verifyOptions.clockTolerance;
|
|
121
|
-
}
|
|
122
|
-
if (verifyOptions.maxAge !== undefined) {
|
|
123
|
-
joseOptions.maxTokenAge = verifyOptions.maxAge;
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
return joseOptions;
|
|
127
|
-
}
|
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Shared types for Cloudflare Workers adapter.
|
|
3
|
-
* Placed here to avoid circular dependencies.
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* Cloudflare Workers environment bindings.
|
|
8
|
-
* Users can extend this with their own bindings.
|
|
9
|
-
*/
|
|
10
|
-
export interface Env {
|
|
11
|
-
/**
|
|
12
|
-
* Additional user-defined bindings (KV, D1, etc.)
|
|
13
|
-
*/
|
|
14
|
-
[key: string]: unknown;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
/**
|
|
18
|
-
* Cloudflare Workers ExecutionContext type
|
|
19
|
-
*/
|
|
20
|
-
export interface ExecutionContext {
|
|
21
|
-
waitUntil(promise: Promise<unknown>): void;
|
|
22
|
-
passThroughOnException(): void;
|
|
23
|
-
}
|