@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.
Files changed (62) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/LICENSE +21 -0
  3. package/README.md +10 -627
  4. package/esm/mod.d.ts +1 -0
  5. package/esm/mod.js +1 -0
  6. package/package.json +28 -25
  7. package/mod.ts +0 -302
  8. package/src/auth/as-metadata-proxy.ts +0 -288
  9. package/src/auth/config.ts +0 -368
  10. package/src/auth/jwt-provider.ts +0 -327
  11. package/src/auth/middleware.ts +0 -257
  12. package/src/auth/mod.ts +0 -89
  13. package/src/auth/multi-tenant-middleware.ts +0 -236
  14. package/src/auth/presets.ts +0 -351
  15. package/src/auth/provider.ts +0 -49
  16. package/src/auth/scope-middleware.ts +0 -59
  17. package/src/auth/static-token-provider.ts +0 -197
  18. package/src/auth/types.ts +0 -207
  19. package/src/client-auth/callback-server.ts +0 -166
  20. package/src/client-auth/client-id-metadata.ts +0 -260
  21. package/src/client-auth/connect.ts +0 -72
  22. package/src/client-auth/mod.ts +0 -44
  23. package/src/client-auth/provider.ts +0 -300
  24. package/src/client-auth/token-store/file-store.ts +0 -73
  25. package/src/client-auth/token-store/memory-store.ts +0 -32
  26. package/src/client-auth/types.ts +0 -95
  27. package/src/concurrency/rate-limiter.ts +0 -190
  28. package/src/concurrency/request-queue.ts +0 -140
  29. package/src/http/body.ts +0 -72
  30. package/src/http/request-guards.ts +0 -137
  31. package/src/http/wire.ts +0 -41
  32. package/src/inspector/launcher.ts +0 -131
  33. package/src/mcp-app.ts +0 -4595
  34. package/src/middleware/backpressure.ts +0 -36
  35. package/src/middleware/mod.ts +0 -21
  36. package/src/middleware/rate-limit.ts +0 -45
  37. package/src/middleware/runner.ts +0 -63
  38. package/src/middleware/types.ts +0 -104
  39. package/src/middleware/validation.ts +0 -28
  40. package/src/mrtr/capability-check.ts +0 -303
  41. package/src/mrtr/mod.ts +0 -54
  42. package/src/mrtr/replay-store.ts +0 -103
  43. package/src/mrtr/request-state.ts +0 -435
  44. package/src/mrtr/retry-guard.ts +0 -110
  45. package/src/mrtr/types.ts +0 -107
  46. package/src/observability/metrics.ts +0 -336
  47. package/src/observability/mod.ts +0 -21
  48. package/src/observability/otel.ts +0 -330
  49. package/src/runtime/runtime.deno.ts +0 -149
  50. package/src/runtime/runtime.node.ts +0 -324
  51. package/src/runtime/runtime.ts +0 -50
  52. package/src/runtime/types.ts +0 -130
  53. package/src/security/channel-hmac.ts +0 -140
  54. package/src/security/csp.ts +0 -89
  55. package/src/security/message-signer.ts +0 -223
  56. package/src/subscriptions/subscription-registry.ts +0 -558
  57. package/src/tasks/mod.ts +0 -33
  58. package/src/tasks/task-store.ts +0 -1014
  59. package/src/transport/request-headers.ts +0 -661
  60. package/src/types.ts +0 -908
  61. package/src/ui/viewer-utils.ts +0 -117
  62. package/src/validation/schema-validator.ts +0 -307
package/package.json CHANGED
@@ -1,34 +1,37 @@
1
1
  {
2
2
  "name": "@casys/mcp-server",
3
- "version": "0.26.1",
4
- "description": "Production-ready MCP server framework with concurrency control, auth, and observability",
3
+ "version": "0.27.1",
5
4
  "type": "module",
6
- "main": "mod.ts",
7
- "types": "mod.ts",
8
- "scripts": {
9
- "build": "tsc",
10
- "test": "tsx --test src/**/*_test.ts"
11
- },
12
- "dependencies": {
13
- "@modelcontextprotocol/server": "^2.0.0",
14
- "@modelcontextprotocol/sdk": "^1.29.0",
15
- "@modelcontextprotocol/ext-apps": "^1.7.4",
16
- "hono": "^4.0.0",
17
- "ajv": "^8.17.1",
18
- "jose": "^6.0.0",
19
- "yaml": "^2.7.0",
20
- "@opentelemetry/api": "^1.9.0"
21
- },
22
- "devDependencies": {
23
- "typescript": "^5.4.0",
24
- "tsx": "^4.0.0"
5
+ "description": "Deprecated alias — re-exports the @casys/mcp-platform framework",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/Casys-AI/mcp-platform.git"
25
10
  },
11
+ "keywords": [
12
+ "mcp",
13
+ "model-context-protocol",
14
+ "framework"
15
+ ],
26
16
  "engines": {
27
17
  "node": ">=20.0.0"
28
18
  },
29
- "repository": {
30
- "type": "git",
31
- "url": "https://github.com/Casys-AI/mcp-server"
19
+ "dependencies": {
20
+ "@casys/mcp-platform": "^0.28.0"
21
+ },
22
+ "deprecated": "Package renamed to @casys/mcp-platform — same API, please migrate.",
23
+ "main": "./esm/mod.js",
24
+ "types": "./esm/mod.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./esm/mod.d.ts",
28
+ "import": "./esm/mod.js"
29
+ }
32
30
  },
33
- "license": "MIT"
31
+ "files": [
32
+ "esm",
33
+ "README.md",
34
+ "LICENSE",
35
+ "CHANGELOG.md"
36
+ ]
34
37
  }
package/mod.ts DELETED
@@ -1,302 +0,0 @@
1
- /**
2
- * @casys/mcp-server — Hono-style framework for MCP servers
3
- *
4
- * Production-ready MCP server framework with built-in middleware pipeline,
5
- * auth, concurrency control, backpressure, and observability.
6
- *
7
- * Built on top of the official @modelcontextprotocol/sdk.
8
- *
9
- * @example
10
- * ```typescript
11
- * import { McpApp } from "@casys/mcp-server";
12
- *
13
- * const app = new McpApp({
14
- * name: "my-server",
15
- * version: "1.0.0",
16
- * maxConcurrent: 10,
17
- * backpressureStrategy: 'queue'
18
- * });
19
- *
20
- * app.registerTool(
21
- * { name: "greet", description: "Greet someone", inputSchema: { type: "object" } },
22
- * (args) => `Hello, ${args.name}!`,
23
- * );
24
- *
25
- * // STDIO transport
26
- * await app.start();
27
- *
28
- * // — or — HTTP transport with security-first defaults
29
- * const http = await app.startHttp({
30
- * port: 3000,
31
- * maxBodyBytes: 1_048_576, // 1 MB (default)
32
- * corsOrigins: ["https://app.example.com"], // allowlist
33
- * requireAuth: true, // fail-fast without auth
34
- * ipRateLimit: { maxRequests: 60, windowMs: 60_000 },
35
- * });
36
- * ```
37
- *
38
- * @module @casys/mcp-server
39
- */
40
-
41
- // Main server class — canonical name
42
- export { McpApp } from "./src/mcp-app.js";
43
-
44
- /**
45
- * @deprecated Use {@link McpApp} instead. `ConcurrentMCPServer` is kept as
46
- * a re-export for backwards compatibility and will be removed in v1.0.
47
- *
48
- * Both names point to the exact same class — `McpApp === ConcurrentMCPServer`
49
- * is true at runtime, and `instanceof` checks pass in both directions.
50
- * Migration is a one-line import swap.
51
- */
52
- export { McpApp as ConcurrentMCPServer } from "./src/mcp-app.js";
53
-
54
- // Concurrency primitives
55
- export { RequestQueue } from "./src/concurrency/request-queue.js";
56
-
57
- // Rate limiting
58
- export { RateLimiter } from "./src/concurrency/rate-limiter.js";
59
-
60
- // Schema validation
61
- export { SchemaValidator } from "./src/validation/schema-validator.js";
62
- export type {
63
- ValidationError,
64
- ValidationResult,
65
- } from "./src/validation/schema-validator.js";
66
-
67
- // Type exports
68
- export type {
69
- BlobResourceContent,
70
- HttpRateLimitContext,
71
- HttpRateLimitOptions,
72
- HttpServerInstance,
73
- // HTTP Server types
74
- HttpServerOptions,
75
- McpAppOptions,
76
- // MCP Apps types (SEP-1865)
77
- MCPResource,
78
- MCPTool,
79
- MCPToolMeta,
80
- McpUiToolMeta,
81
- QueueMetrics,
82
- RateLimitContext,
83
- RateLimitOptions,
84
- ResourceContent,
85
- ResourceHandler,
86
- SamplingClient,
87
- SamplingParams,
88
- SamplingResult,
89
- StructuredToolResult,
90
- TextResourceContent,
91
- ToolAnnotations,
92
- ToolErrorMapper,
93
- ToolHandler,
94
- ToolHandlerContext,
95
- } from "./src/types.js";
96
-
97
- /**
98
- * @deprecated Use {@link McpAppOptions} instead. `ConcurrentServerOptions`
99
- * is kept as a re-export for backwards compatibility and will be removed
100
- * in v1.0.
101
- */
102
- export type { McpAppOptions as ConcurrentServerOptions } from "./src/types.js";
103
-
104
- // MCP Apps constants & viewer utilities
105
- export {
106
- MCP_APP_MIME_TYPE,
107
- MCP_APPS_EXTENSION_ID,
108
- MCP_APPS_PROTOCOL_VERSION,
109
- } from "./src/types.js";
110
-
111
- // MCP Apps capability negotiation (per ext-apps spec 2026-01-26 + SDK 1.29 extensions)
112
- export { getMcpAppsCapability } from "./src/types.js";
113
- export type { McpAppsClientCapability } from "./src/types.js";
114
-
115
- export type {
116
- RegisterViewersConfig,
117
- RegisterViewersSummary,
118
- } from "./src/mcp-app.js";
119
- export {
120
- discoverViewers,
121
- resolveViewerDistPath,
122
- } from "./src/ui/viewer-utils.js";
123
-
124
- // NOTE: UI composition helpers (`composeEvents`, `uiMeta`, `COMPOSE_EVENT_METHOD`
125
- // and their types) are NOT re-exported here. They live in `@casys/mcp-compose`
126
- // and must be imported from there directly:
127
- // import { composeEvents, uiMeta } from "@casys/mcp-compose/sdk";
128
- // Dropping the convenience re-export removes @casys/mcp-server's dependency on
129
- // @casys/mcp-compose entirely — server stays a lean MCP framework that only
130
- // touches the official protocol packages.
131
-
132
- // Middleware pipeline
133
- export type {
134
- Middleware,
135
- MiddlewareContext,
136
- MiddlewareResult,
137
- NextFunction,
138
- } from "./src/middleware/mod.js";
139
- export { createMiddlewareRunner } from "./src/middleware/mod.js";
140
-
141
- // Auth - Core
142
- export { AuthProvider } from "./src/auth/mod.js";
143
- export {
144
- AuthError,
145
- createAuthMiddleware,
146
- createForbiddenResponse,
147
- createUnauthorizedResponse,
148
- extractBearerToken,
149
- } from "./src/auth/mod.js";
150
- export { createScopeMiddleware } from "./src/auth/mod.js";
151
- export type {
152
- AuthInfo,
153
- AuthOptions,
154
- ProtectedResourceMetadata,
155
- } from "./src/auth/mod.js";
156
-
157
- // Auth - Multi-tenant resolution
158
- export { createMultiTenantMiddleware } from "./src/auth/mod.js";
159
- export type {
160
- MultiTenantMiddlewareOptions,
161
- TenantResolution,
162
- TenantResolver,
163
- } from "./src/auth/mod.js";
164
-
165
- // Auth - JWT Provider + Presets
166
- export { JwtAuthProvider } from "./src/auth/mod.js";
167
- export type { JwtAuthProviderOptions } from "./src/auth/mod.js";
168
- export {
169
- createAuth0AuthProvider,
170
- createGitHubAuthProvider,
171
- createGoogleAuthProvider,
172
- createOIDCAuthProvider,
173
- } from "./src/auth/mod.js";
174
- export type { PresetOptions } from "./src/auth/mod.js";
175
-
176
- // Auth - AS Metadata Proxy (DCR discovery for IdPs without native RFC 7591)
177
- export { createAsMetadataHandler } from "./src/auth/mod.js";
178
- export type { AsMetadataProxyOptions } from "./src/auth/mod.js";
179
-
180
- // Auth - Config (YAML + env)
181
- export {
182
- createAuthProviderFromConfig,
183
- loadAuthConfig,
184
- } from "./src/auth/mod.js";
185
-
186
- export type { AuthConfig, AuthProviderName } from "./src/auth/mod.js";
187
-
188
- // Auth - Static Token Provider (opaque pre-shared bearer tokens)
189
- export {
190
- createStaticTokenAuthProvider,
191
- StaticTokenAuthProvider,
192
- } from "./src/auth/mod.js";
193
- export type { StaticTokenAuthProviderOptions } from "./src/auth/mod.js";
194
-
195
- // Client Auth — OAuth client flow + CIMD
196
- export {
197
- buildClientIdMetadataDocument,
198
- CallbackServer,
199
- CimdConfigError,
200
- FileTokenStore,
201
- isCimdConfig,
202
- MemoryTokenStore,
203
- OAuthClientProviderImpl,
204
- prepareOAuthProvider,
205
- } from "./src/client-auth/mod.js";
206
- export type {
207
- CallbackServerOptions,
208
- CimdClientConfig,
209
- CimdConfigErrorCode,
210
- ClientIdMetadataDocument,
211
- OAuthClientConfig,
212
- OAuthClientConfigBase,
213
- PrepareOAuthResult,
214
- StaticClientConfig,
215
- StoredCredentials,
216
- TokenStore,
217
- } from "./src/client-auth/mod.js";
218
-
219
- // Observability
220
- export {
221
- endToolCallSpan,
222
- getServerTracer,
223
- isOtelEnabled,
224
- recordAuthEvent,
225
- ServerMetrics,
226
- type ServerMetricsSnapshot,
227
- startToolCallSpan,
228
- type ToolCallSpanAttributes,
229
- } from "./src/observability/mod.js";
230
-
231
- // Security - CSP utilities
232
- export { buildCspHeader, injectCspMetaTag } from "./src/security/csp.js";
233
- export type { CspOptions } from "./src/security/csp.js";
234
-
235
- // Security - HMAC channel authentication for PostMessage (MCP Apps)
236
- export { injectChannelAuth } from "./src/security/channel-hmac.js";
237
- export { MessageSigner } from "./src/security/message-signer.js";
238
- export type {
239
- SignedMessage,
240
- VerifyResult,
241
- } from "./src/security/message-signer.js";
242
-
243
- // Runtime port (for advanced consumers who need to inspect the adapter contract)
244
- export type {
245
- FetchHandler,
246
- RuntimePort,
247
- ServeHandle,
248
- ServeOptions,
249
- } from "./src/runtime/types.js";
250
-
251
- // Inspector — launch the MCP Inspector for interactive debugging
252
- export { launchInspector } from "./src/inspector/launcher.js";
253
- export type { InspectorOptions } from "./src/inspector/launcher.js";
254
-
255
- // ── Spec 2026-07-28 features ─────────────────────────────────────────────────
256
-
257
- // Tasks extension (io.modelcontextprotocol/tasks, SEP-2663).
258
- //
259
- // `createTask` is what a tool handler returns to opt into async-task mode, so it
260
- // has to be reachable from the package root — without it the extension is wired
261
- // but unusable by any consumer.
262
- export { createTask } from "./src/tasks/mod.js";
263
- export type {
264
- AsyncTaskDescriptor,
265
- DetailedTask,
266
- Task,
267
- TaskController,
268
- TaskStoreOptions,
269
- } from "./src/tasks/mod.js";
270
-
271
- // MRTR — Multi Round-Trip Requests (SEP-2322).
272
- //
273
- // `InputRequiredSignal` is the shape a handler returns to ask the client for
274
- // input. The seal/verify primitives are exported for consumers implementing their
275
- // own transport; the framework seals automatically on `tools/call`.
276
- export type {
277
- InputRequestEntry,
278
- InputRequestMethod,
279
- InputRequiredSignal,
280
- MemoryMrtrReplayStoreOptions,
281
- MrtrOptions,
282
- MrtrReplayStore,
283
- } from "./src/mrtr/mod.js";
284
- export {
285
- exportStateKey,
286
- generateStateKey,
287
- MemoryMrtrReplayStore,
288
- sealRequestState,
289
- verifyRequestState,
290
- } from "./src/mrtr/mod.js";
291
-
292
- // subscriptions/listen (SEP-2575).
293
- //
294
- // The registry is owned by McpApp; these are exported for consumers driving their
295
- // own streams, and for the filter type used when narrowing what a deployment
296
- // delivers.
297
- export { SubscriptionRegistry } from "./src/subscriptions/subscription-registry.js";
298
- export type {
299
- SubscriptionFilter,
300
- SubscriptionRegistryOptions,
301
- SubscriptionSink,
302
- } from "./src/subscriptions/subscription-registry.js";
@@ -1,288 +0,0 @@
1
- /**
2
- * AS Metadata Proxy for DCR compatibility discovery.
3
- *
4
- * Creates a Web Standard request handler that serves an RFC 8414
5
- * Authorization Server Metadata document enriched with
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`.
13
- *
14
- * **Issuer field note (RFC 8414 §3.2)**:
15
- * The `issuer` field in the served metadata will be the upstream IdP's
16
- * issuer, not the URL where this handler is served. This intentionally
17
- * violates RFC 8414 §3.2 (`issuer` MUST match the AS URL) because
18
- * overriding `issuer` would cause JWT `iss` claim mismatches — the IdP
19
- * still issues tokens with its own `iss`, and clients verify
20
- * `token.iss === metadata.issuer`. The metadata-URL mismatch is the
21
- * lesser evil for this compatibility path and is not needed when clients
22
- * use CIMD or the upstream IdP ships native registration discovery.
23
- *
24
- * @module lib/server/auth/as-metadata-proxy
25
- */
26
-
27
- // ─── Types ───────────────────────────────────────────────────────────
28
-
29
- /**
30
- * Options for {@link createAsMetadataHandler}.
31
- *
32
- * Provide exactly one of:
33
- * - `upstreamMetadataUrl` — full URL of the upstream metadata document
34
- * - `upstreamIssuer` — OIDC issuer (derives `/.well-known/openid-configuration`)
35
- *
36
- * Providing both or neither throws at construction time.
37
- */
38
- export interface AsMetadataProxyOptions {
39
- /**
40
- * Full URL of the upstream AS metadata document to proxy.
41
- *
42
- * IdP-agnostic — pass the appropriate discovery endpoint:
43
- * - OIDC providers: `https://idp.example.com/.well-known/openid-configuration`
44
- * - RFC 8414 AS: `https://as.example.com/.well-known/oauth-authorization-server`
45
- * - Custom paths: any URL that returns a JSON metadata document
46
- *
47
- * Mutually exclusive with `upstreamIssuer`.
48
- */
49
- upstreamMetadataUrl?: string;
50
-
51
- /**
52
- * OIDC issuer URL (e.g., `https://my-tenant.zitadel.cloud`).
53
- * Convenience shorthand — derives `{upstreamIssuer}/.well-known/openid-configuration`.
54
- *
55
- * Mutually exclusive with `upstreamMetadataUrl`.
56
- */
57
- upstreamIssuer?: string;
58
-
59
- /**
60
- * Absolute HTTPS URL of the RFC 7591 DCR endpoint that the MCP server
61
- * exposes (implemented separately by the consumer — outside lib scope).
62
- * Injected as `registration_endpoint` in the enriched metadata.
63
- *
64
- * Must be a valid absolute HTTP(S) URL (validated at construction time).
65
- */
66
- registrationEndpoint: string;
67
-
68
- /**
69
- * TTL for the upstream metadata cache in milliseconds.
70
- * @default 86_400_000 (24 hours)
71
- *
72
- * Uses stale-while-revalidate: serves cached metadata even after
73
- * expiry while refreshing in the background.
74
- */
75
- cacheTtlMs?: number;
76
-
77
- /**
78
- * Additional RFC 8414 fields to inject or override in the metadata
79
- * (beyond `registration_endpoint`). Useful for overriding
80
- * `scopes_supported`, adding `code_challenge_methods_supported`, etc.
81
- *
82
- * **Warning**: avoid overriding `issuer` — see module-level JSDoc
83
- * for why this causes JWT validation failures.
84
- */
85
- extraFields?: Record<string, unknown>;
86
-
87
- /**
88
- * Custom `fetch` implementation. Defaults to `globalThis.fetch`.
89
- *
90
- * Use for dependency injection in tests, or for advanced scenarios
91
- * like mTLS, custom headers, or retry wrappers.
92
- */
93
- fetch?: typeof globalThis.fetch;
94
- }
95
-
96
- // ─── Implementation ──────────────────────────────────────────────────
97
-
98
- function stripTrailingSlash(url: string): string {
99
- return url.endsWith("/") ? url.slice(0, -1) : url;
100
- }
101
-
102
- /**
103
- * Validates that a string is a parseable absolute HTTP(S) URL.
104
- * Throws at construction time for fast failure.
105
- */
106
- function validateUrl(value: string, label: string): void {
107
- try {
108
- const parsed = new URL(value);
109
- if (!parsed.protocol.startsWith("http")) {
110
- throw new Error(`expected http(s) scheme`);
111
- }
112
- } catch (cause) {
113
- throw new Error(
114
- `AsMetadataProxyOptions.${label} is not a valid HTTP(S) URL: "${value}"`,
115
- { cause },
116
- );
117
- }
118
- }
119
-
120
- /**
121
- * Resolves the upstream metadata URL from the flat options.
122
- * Enforces mutual exclusivity: exactly one of upstreamMetadataUrl
123
- * or upstreamIssuer must be provided.
124
- */
125
- function resolveMetadataUrl(options: AsMetadataProxyOptions): string {
126
- const { upstreamMetadataUrl, upstreamIssuer } = options;
127
- const hasUrl = upstreamMetadataUrl !== undefined;
128
- const hasIssuer = upstreamIssuer !== undefined;
129
-
130
- if (hasUrl && hasIssuer) {
131
- throw new Error(
132
- "AsMetadataProxyOptions: provide either upstreamMetadataUrl or upstreamIssuer, not both",
133
- );
134
- }
135
- if (!hasUrl && !hasIssuer) {
136
- throw new Error(
137
- "AsMetadataProxyOptions: one of upstreamMetadataUrl or upstreamIssuer is required",
138
- );
139
- }
140
-
141
- if (hasUrl) {
142
- validateUrl(upstreamMetadataUrl!, "upstreamMetadataUrl");
143
- return upstreamMetadataUrl!;
144
- }
145
-
146
- validateUrl(upstreamIssuer!, "upstreamIssuer");
147
- return `${
148
- stripTrailingSlash(upstreamIssuer!)
149
- }/.well-known/openid-configuration`;
150
- }
151
-
152
- /**
153
- * Creates a Web Standard request handler that serves an RFC 8414
154
- * Authorization Server Metadata document enriched with
155
- * `registration_endpoint`.
156
- *
157
- * The handler is framework-agnostic — mount it in Fresh, Hono, Express
158
- * (via adapter), or any framework that accepts `(Request) => Response`.
159
- *
160
- * @example Explicit metadata URL (any AS)
161
- * ```typescript
162
- * const handler = createAsMetadataHandler({
163
- * upstreamMetadataUrl: "https://as.example.com/.well-known/oauth-authorization-server",
164
- * registrationEndpoint: "https://my-app.example.com/oauth/register",
165
- * });
166
- * ```
167
- *
168
- * @example OIDC issuer shorthand
169
- * ```typescript
170
- * const handler = createAsMetadataHandler({
171
- * upstreamIssuer: "https://my-tenant.zitadel.cloud",
172
- * registrationEndpoint: "https://my-app.example.com/oauth/register",
173
- * });
174
- * ```
175
- */
176
- export function createAsMetadataHandler(
177
- options: AsMetadataProxyOptions,
178
- ): (req: Request) => Promise<Response> {
179
- // ── Fail-fast validation at construction time ──
180
- const metadataUrl = resolveMetadataUrl(options);
181
- validateUrl(options.registrationEndpoint, "registrationEndpoint");
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
- );
189
- }
190
-
191
- const {
192
- registrationEndpoint,
193
- cacheTtlMs = 24 * 60 * 60 * 1000,
194
- extraFields,
195
- fetch: fetchFn = globalThis.fetch,
196
- } = options;
197
-
198
- let cached: { metadata: Record<string, unknown>; fetchedAt: number } | null =
199
- null;
200
- let refreshing = false;
201
-
202
- async function fetchUpstream(): Promise<Record<string, unknown>> {
203
- const res = await fetchFn(metadataUrl, {
204
- signal: AbortSignal.timeout(10_000),
205
- });
206
- if (!res.ok) {
207
- throw new Error(
208
- `AS metadata fetch failed: ${res.status} from ${metadataUrl}`,
209
- );
210
- }
211
- const body = await res.json();
212
- if (body === null || typeof body !== "object" || Array.isArray(body)) {
213
- throw new Error(
214
- `AS metadata from ${metadataUrl} is not a JSON object (got ${
215
- Array.isArray(body) ? "array" : typeof body
216
- })`,
217
- );
218
- }
219
- if (typeof body.issuer !== "string") {
220
- throw new Error(
221
- `AS metadata from ${metadataUrl} is missing required 'issuer' field`,
222
- );
223
- }
224
- return body as Record<string, unknown>;
225
- }
226
-
227
- async function getMetadata(): Promise<Record<string, unknown>> {
228
- const now = Date.now();
229
-
230
- // Fresh cache hit
231
- if (cached && now - cached.fetchedAt < cacheTtlMs) {
232
- return cached.metadata;
233
- }
234
-
235
- // Stale-while-revalidate: serve stale, refresh in background
236
- if (cached) {
237
- if (!refreshing) {
238
- refreshing = true;
239
- fetchUpstream()
240
- .then((m) => {
241
- cached = { metadata: m, fetchedAt: Date.now() };
242
- })
243
- .catch((e) =>
244
- console.error("[as-metadata-proxy] background refresh failed:", e)
245
- )
246
- .finally(() => {
247
- refreshing = false;
248
- });
249
- }
250
- return cached.metadata;
251
- }
252
-
253
- // Cold start: must await
254
- const metadata = await fetchUpstream();
255
- cached = { metadata, fetchedAt: now };
256
- return metadata;
257
- }
258
-
259
- return async (req: Request): Promise<Response> => {
260
- if (req.method !== "GET" && req.method !== "HEAD") {
261
- return new Response(null, {
262
- status: 405,
263
- headers: { "Allow": "GET, HEAD" },
264
- });
265
- }
266
- try {
267
- const upstream = await getMetadata();
268
- const enriched = {
269
- ...upstream,
270
- ...extraFields,
271
- registration_endpoint: registrationEndpoint,
272
- };
273
- return new Response(JSON.stringify(enriched), {
274
- headers: {
275
- "Content-Type": "application/json",
276
- "Cache-Control": "public, max-age=3600",
277
- },
278
- });
279
- } catch (err) {
280
- console.error("[as-metadata-proxy] upstream fetch failed:", err);
281
- const msg = err instanceof Error ? err.message : String(err);
282
- return new Response(
283
- JSON.stringify({ error: "as_metadata_unavailable", message: msg }),
284
- { status: 502, headers: { "Content-Type": "application/json" } },
285
- );
286
- }
287
- };
288
- }