@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
@@ -1,351 +0,0 @@
1
- /**
2
- * OIDC auth provider presets.
3
- *
4
- * Factory functions for common OIDC providers. Each preset pre-configures
5
- * the issuer, JWKS URI, and authorization server for the provider.
6
- *
7
- * Bridge layer (0.16.0): presets accept raw `string` fields for `resource`,
8
- * `resourceMetadataUrl`, and `authorizationServers`, then wrap them through
9
- * {@link httpsUrl} before passing to the branded {@link JwtAuthProviderOptions}
10
- * constructor. This keeps the YAML/env config pipeline (`createAuthProviderFromConfig`)
11
- * working with raw strings while the core `JwtAuthProvider` API enforces the
12
- * `HttpsUrl` brand at the type level.
13
- *
14
- * @module lib/server/auth/presets
15
- */
16
-
17
- import { JwtAuthProvider } from "./jwt-provider.js";
18
- import { type HttpsUrl, httpsUrl, tryHttpsUrl } from "./types.js";
19
-
20
- /**
21
- * Base options shared by all presets.
22
- */
23
- export interface PresetOptions {
24
- /** JWT audience (aud claim) */
25
- audience: string;
26
- /**
27
- * RFC 9728 § 2 resource identifier, as a raw string. Presets detect
28
- * whether this is an HTTP(S) URL or an opaque URI and pick the correct
29
- * {@link JwtAuthProviderOptions} branch internally. When opaque, you
30
- * MUST also supply {@link resourceMetadataUrl}.
31
- */
32
- resource: string;
33
- /** Scopes supported by this server */
34
- scopesSupported?: string[];
35
- /**
36
- * Absolute HTTP(S) URL where the `/.well-known/oauth-protected-resource`
37
- * metadata document is served publicly (RFC 9728 § 3). Required when
38
- * `resource` is an opaque URI; optional when `resource` is itself an
39
- * HTTP(S) URL (in which case the preset auto-derives). Empty and
40
- * whitespace-only values are treated as absent.
41
- */
42
- resourceMetadataUrl?: string;
43
- }
44
-
45
- /**
46
- * Options for {@link createOIDCAuthProvider}. Unlike 0.15.x where this
47
- * function accepted `JwtAuthProviderOptions` directly, 0.16.0 exposes a
48
- * preset-style interface with raw string fields — the preset wraps them
49
- * through {@link httpsUrl} internally.
50
- *
51
- * BREAKING: callers that previously passed a pre-built
52
- * `JwtAuthProviderOptions` to `createOIDCAuthProvider` must now pass
53
- * raw strings. Migration: just drop the `httpsUrl()` wrappers you'd
54
- * otherwise need at the call site.
55
- */
56
- export interface OIDCPresetOptions extends PresetOptions {
57
- /** OIDC issuer (typically an HTTPS URL) */
58
- issuer: string;
59
- /**
60
- * JWKS URI for signature validation. Defaults to
61
- * `{issuer}/.well-known/jwks.json`.
62
- */
63
- jwksUri?: string;
64
- /**
65
- * Authorization servers, as raw strings. Defaults to `[issuer]` when
66
- * omitted. Each entry must be a valid absolute HTTP(S) URL — the preset
67
- * validates via {@link httpsUrl}.
68
- */
69
- authorizationServers?: string[];
70
- }
71
-
72
- /**
73
- * GitHub Actions OIDC provider.
74
- *
75
- * Validates tokens issued by GitHub Actions workflows.
76
- * Issuer: https://token.actions.githubusercontent.com
77
- *
78
- * @example
79
- * ```typescript
80
- * const provider = createGitHubAuthProvider({
81
- * audience: "https://my-mcp.example.com",
82
- * resource: "https://my-mcp.example.com",
83
- * });
84
- * ```
85
- */
86
- export function createGitHubAuthProvider(
87
- options: PresetOptions,
88
- ): JwtAuthProvider {
89
- return buildJwtAuthProvider({
90
- issuer: "https://token.actions.githubusercontent.com",
91
- audience: options.audience,
92
- authorizationServers: ["https://token.actions.githubusercontent.com"],
93
- scopesSupported: options.scopesSupported,
94
- resource: options.resource,
95
- resourceMetadataUrl: options.resourceMetadataUrl,
96
- }, "createGitHubAuthProvider");
97
- }
98
-
99
- /**
100
- * Google OIDC provider.
101
- *
102
- * Validates tokens issued by Google accounts.
103
- * Issuer: https://accounts.google.com
104
- *
105
- * @example
106
- * ```typescript
107
- * const provider = createGoogleAuthProvider({
108
- * audience: "https://my-mcp.example.com",
109
- * resource: "https://my-mcp.example.com",
110
- * });
111
- * ```
112
- */
113
- export function createGoogleAuthProvider(
114
- options: PresetOptions,
115
- ): JwtAuthProvider {
116
- return buildJwtAuthProvider({
117
- issuer: "https://accounts.google.com",
118
- audience: options.audience,
119
- authorizationServers: ["https://accounts.google.com"],
120
- jwksUri: "https://www.googleapis.com/oauth2/v3/certs",
121
- scopesSupported: options.scopesSupported,
122
- resource: options.resource,
123
- resourceMetadataUrl: options.resourceMetadataUrl,
124
- }, "createGoogleAuthProvider");
125
- }
126
-
127
- /**
128
- * Auth0 OIDC provider.
129
- *
130
- * Validates tokens issued by an Auth0 tenant.
131
- * Issuer: https://{domain}/
132
- *
133
- * @example
134
- * ```typescript
135
- * const provider = createAuth0AuthProvider({
136
- * domain: "my-tenant.auth0.com",
137
- * audience: "https://my-mcp.example.com",
138
- * resource: "https://my-mcp.example.com",
139
- * });
140
- * ```
141
- */
142
- export function createAuth0AuthProvider(
143
- options: PresetOptions & { domain: string },
144
- ): JwtAuthProvider {
145
- const issuer = `https://${options.domain}/`;
146
- return buildJwtAuthProvider({
147
- issuer,
148
- audience: options.audience,
149
- authorizationServers: [issuer],
150
- jwksUri: `${issuer}.well-known/jwks.json`,
151
- scopesSupported: options.scopesSupported,
152
- resource: options.resource,
153
- resourceMetadataUrl: options.resourceMetadataUrl,
154
- }, "createAuth0AuthProvider");
155
- }
156
-
157
- /**
158
- * Generic OIDC provider.
159
- *
160
- * For any OIDC-compliant provider not covered by presets.
161
- *
162
- * @example
163
- * ```typescript
164
- * const provider = createOIDCAuthProvider({
165
- * issuer: "https://my-idp.example.com",
166
- * audience: "https://my-mcp.example.com",
167
- * resource: "https://my-mcp.example.com",
168
- * authorizationServers: ["https://my-idp.example.com"],
169
- * });
170
- * ```
171
- */
172
- export function createOIDCAuthProvider(
173
- options: OIDCPresetOptions,
174
- ): JwtAuthProvider {
175
- return buildJwtAuthProvider({
176
- issuer: options.issuer,
177
- audience: options.audience,
178
- jwksUri: options.jwksUri,
179
- authorizationServers: options.authorizationServers ?? [options.issuer],
180
- scopesSupported: options.scopesSupported,
181
- resource: options.resource,
182
- resourceMetadataUrl: options.resourceMetadataUrl,
183
- }, "createOIDCAuthProvider");
184
- }
185
-
186
- // ============================================================================
187
- // Public bridge: raw strings → branded JwtAuthProviderOptions
188
- // ============================================================================
189
-
190
- /**
191
- * Raw-string options accepted by {@link buildJwtAuthProvider}. Mirrors
192
- * {@link JwtAuthProviderOptions} but with all URL fields as plain `string`
193
- * instead of {@link HttpsUrl}, and without the `kind` discriminant tag
194
- * (the bridge auto-detects).
195
- *
196
- * Exported for 3rd-party OIDC provider implementations that want to accept
197
- * YAML/env-style raw string config and delegate URL validation to the
198
- * bridge instead of reimplementing it. See `createGitHubAuthProvider`,
199
- * `createGoogleAuthProvider`, `createAuth0AuthProvider`, and
200
- * `createOIDCAuthProvider` for built-in consumers.
201
- */
202
- export interface BuildJwtAuthProviderOptions {
203
- /** JWT issuer (iss claim) */
204
- issuer: string;
205
- /** JWT audience (aud claim) */
206
- audience: string;
207
- /**
208
- * JWKS URI for signature validation. Defaults to
209
- * `{issuer}/.well-known/jwks.json` when omitted.
210
- */
211
- jwksUri?: string;
212
- /**
213
- * Authorization servers that issue valid tokens, as raw strings. Each
214
- * entry must be a valid absolute HTTP(S) URL — the bridge validates
215
- * via {@link httpsUrl} and throws with a preset-named error if invalid.
216
- */
217
- authorizationServers: string[];
218
- /** Scopes supported by this server */
219
- scopesSupported?: string[];
220
- /**
221
- * RFC 9728 § 2 resource identifier, as a raw string. The bridge detects
222
- * whether this is an HTTP(S) URL or an opaque URI and picks the correct
223
- * {@link JwtAuthProviderOptions} branch internally. When opaque, you
224
- * MUST also supply {@link resourceMetadataUrl}.
225
- */
226
- resource: string;
227
- /**
228
- * Absolute HTTP(S) URL where the `/.well-known/oauth-protected-resource`
229
- * metadata document is served publicly (RFC 9728 § 3). Required when
230
- * `resource` is an opaque URI; optional when `resource` is itself an
231
- * HTTP(S) URL. Empty and whitespace-only values are treated as absent.
232
- */
233
- resourceMetadataUrl?: string;
234
- }
235
-
236
- /**
237
- * Bridge raw-string options to a fully-constructed `JwtAuthProvider`.
238
- *
239
- * This is the shared validation + DU-branch-selection pathway used by all
240
- * four built-in preset factories (`createGitHubAuthProvider` et al). 0.17.0
241
- * exports it as public API so 3rd-party OIDC provider implementations
242
- * (Keycloak, Zitadel custom, Okta, ...) can reuse the same pathway instead
243
- * of reimplementing URL-vs-opaque detection, `HttpsUrl` wrapping, and
244
- * empty-metadata fall-through.
245
- *
246
- * Rules:
247
- * - `authorizationServers[]`: every entry must be a valid absolute HTTP(S)
248
- * URL. Invalid entries throw with a `[${label}] authorizationServers[i]`
249
- * prefix for pinpointing.
250
- * - `resource`: if parseable as HTTP(S) URL → `UrlResource` branch (metadata
251
- * URL derivable per RFC 9728 § 3.1). Otherwise → `OpaqueResource` branch
252
- * requiring explicit `resourceMetadataUrl`.
253
- * - `resourceMetadataUrl`: empty or whitespace-only strings are treated as
254
- * absent (matches YAML-key-with-no-value semantics from 0.15.1).
255
- *
256
- * @param opts Raw-string options, as from YAML/env config.
257
- * @param label Identifier used in error messages — REQUIRED. Pass your
258
- * factory name so error prefixes point at the actual caller rather than
259
- * the anonymous bridge layer. E.g., `"createKeycloakAuthProvider"`.
260
- * (0.17.0: required, was optional with a misleading default in the
261
- * draft — type-design review recommendation Q4.)
262
- *
263
- * @example Custom OIDC provider factory
264
- * ```typescript
265
- * import { buildJwtAuthProvider, type JwtAuthProvider } from "@casys/mcp-server";
266
- *
267
- * export interface KeycloakPresetOptions {
268
- * keycloakHost: string;
269
- * realm: string;
270
- * audience: string;
271
- * resource: string;
272
- * resourceMetadataUrl?: string;
273
- * }
274
- *
275
- * export function createKeycloakAuthProvider(
276
- * options: KeycloakPresetOptions,
277
- * ): JwtAuthProvider {
278
- * const issuer = `https://${options.keycloakHost}/realms/${options.realm}`;
279
- * return buildJwtAuthProvider({
280
- * issuer,
281
- * audience: options.audience,
282
- * authorizationServers: [issuer],
283
- * jwksUri: `${issuer}/protocol/openid-connect/certs`,
284
- * resource: options.resource,
285
- * resourceMetadataUrl: options.resourceMetadataUrl,
286
- * }, "createKeycloakAuthProvider");
287
- * }
288
- * ```
289
- */
290
- export function buildJwtAuthProvider(
291
- opts: BuildJwtAuthProviderOptions,
292
- label: string,
293
- ): JwtAuthProvider {
294
- const wrappedAuthServers: HttpsUrl[] = opts.authorizationServers.map(
295
- (raw, i) => {
296
- try {
297
- return httpsUrl(raw);
298
- } catch (err) {
299
- throw new Error(
300
- `[${label}] authorizationServers[${i}] is not a valid ` +
301
- `HTTP(S) URL: ${(err as Error).message}`,
302
- );
303
- }
304
- },
305
- );
306
-
307
- const explicitMetadata: HttpsUrl | undefined = opts.resourceMetadataUrl &&
308
- opts.resourceMetadataUrl.trim().length > 0
309
- ? httpsUrl(opts.resourceMetadataUrl)
310
- : undefined;
311
-
312
- const base = {
313
- issuer: opts.issuer,
314
- audience: opts.audience,
315
- jwksUri: opts.jwksUri,
316
- authorizationServers: wrappedAuthServers,
317
- scopesSupported: opts.scopesSupported,
318
- };
319
-
320
- const resourceUrl = tryHttpsUrl(opts.resource);
321
- if (resourceUrl !== null) {
322
- // URL resource branch — metadata URL optional (derivable). 0.17.0 sets
323
- // the explicit `kind: "url"` tag so the DU narrowing in the constructor
324
- // body is structurally sound.
325
- return new JwtAuthProvider({
326
- ...base,
327
- kind: "url",
328
- resource: resourceUrl,
329
- resourceMetadataUrl: explicitMetadata,
330
- });
331
- }
332
-
333
- // Opaque resource branch — metadata URL required
334
- if (!explicitMetadata) {
335
- throw new Error(
336
- `[${label}] resourceMetadataUrl is required when 'resource' is ` +
337
- `not an HTTP(S) URL (got resource=${JSON.stringify(opts.resource)}). ` +
338
- `Per RFC 9728 § 2, 'resource' can be an opaque URI (e.g., an OIDC ` +
339
- `project ID used as JWT audience); in that case the metadata ` +
340
- `document URL is a separate concept and must be provided explicitly. ` +
341
- `Set 'resourceMetadataUrl' to the HTTPS URL where your ` +
342
- `/.well-known/oauth-protected-resource endpoint is served publicly.`,
343
- );
344
- }
345
- return new JwtAuthProvider({
346
- ...base,
347
- kind: "opaque",
348
- resource: opts.resource,
349
- resourceMetadataUrl: explicitMetadata,
350
- });
351
- }
@@ -1,49 +0,0 @@
1
- /**
2
- * AuthProvider abstract class.
3
- *
4
- * Abstract class (not interface) for DI compatibility with diod tokens.
5
- * Implement this to provide custom token validation (API keys, opaque tokens, etc.)
6
- *
7
- * @module lib/server/auth/provider
8
- */
9
-
10
- import type { AuthInfo, ProtectedResourceMetadata } from "./types.js";
11
-
12
- /**
13
- * Base class for authentication providers.
14
- *
15
- * @example
16
- * ```typescript
17
- * class ApiKeyProvider extends AuthProvider {
18
- * async verifyToken(token: string): Promise<AuthInfo | null> {
19
- * const user = await db.findByApiKey(token);
20
- * if (!user) return null;
21
- * return { subject: user.id, scopes: user.scopes };
22
- * }
23
- *
24
- * getResourceMetadata(): ProtectedResourceMetadata {
25
- * return {
26
- * resource: "https://my-mcp.example.com",
27
- * resource_metadata_url:
28
- * "https://my-mcp.example.com/.well-known/oauth-protected-resource",
29
- * authorization_servers: ["https://auth.example.com"],
30
- * bearer_methods_supported: ["header"],
31
- * };
32
- * }
33
- * }
34
- * ```
35
- */
36
- export abstract class AuthProvider {
37
- /**
38
- * Validate a token and extract auth information.
39
- *
40
- * @param token - The raw Bearer token string
41
- * @returns AuthInfo if valid, null if invalid/expired
42
- */
43
- abstract verifyToken(token: string): Promise<AuthInfo | null>;
44
-
45
- /**
46
- * Return RFC 9728 Protected Resource Metadata for this provider.
47
- */
48
- abstract getResourceMetadata(): ProtectedResourceMetadata;
49
- }
@@ -1,59 +0,0 @@
1
- /**
2
- * Scope enforcement middleware.
3
- *
4
- * Verifies that the authenticated user has the required scopes
5
- * for the tool being called. Placed after the auth middleware.
6
- *
7
- * @module lib/server/auth/scope-middleware
8
- */
9
-
10
- import type { AuthInfo } from "./types.js";
11
- import { AuthError } from "./middleware.js";
12
- import type { Middleware } from "../middleware/types.js";
13
-
14
- /**
15
- * Create a scope enforcement middleware.
16
- *
17
- * Checks `requiredScopes` for the called tool against `ctx.authInfo.scopes`.
18
- * If auth is not configured (no authInfo), the middleware passes through.
19
- * If the tool has no requiredScopes, the middleware passes through.
20
- *
21
- * @param toolScopes - Map of tool name to required scopes
22
- */
23
- export function createScopeMiddleware(
24
- toolScopes: Map<string, string[]>,
25
- ): Middleware {
26
- // deno-lint-ignore require-await
27
- return async (ctx, next) => {
28
- const requiredScopes = toolScopes.get(ctx.toolName);
29
-
30
- // No scopes required for this tool
31
- if (!requiredScopes?.length) return next();
32
-
33
- // No auth configured: STDIO (no request) is fine, HTTP without authInfo is a misconfiguration
34
- const authInfo = ctx.authInfo as AuthInfo | undefined;
35
- if (!authInfo) {
36
- if (!ctx.request) return next(); // STDIO: local transport, no auth needed
37
- // HTTP request with required scopes but no authInfo = auth middleware is missing
38
- throw new Error(
39
- `[ScopeMiddleware] Tool "${ctx.toolName}" requires scopes [${
40
- requiredScopes.join(", ")
41
- }] ` +
42
- "but no authInfo found on HTTP request. Ensure auth middleware is configured in the pipeline.",
43
- );
44
- }
45
-
46
- const hasAll = requiredScopes.every((s) => authInfo.scopes.includes(s));
47
- if (!hasAll) {
48
- const missingScopes = requiredScopes.filter((s) =>
49
- !authInfo.scopes.includes(s)
50
- );
51
- // Used by 403 responses to advertise protected resource metadata in
52
- // WWW-Authenticate; auth middleware populates it for HTTP requests.
53
- const metadataUrl = (ctx.resourceMetadataUrl as string | undefined) ?? "";
54
- throw new AuthError("insufficient_scope", metadataUrl, missingScopes);
55
- }
56
-
57
- return next();
58
- };
59
- }
@@ -1,197 +0,0 @@
1
- // deno-lint-ignore-file require-await
2
- /**
3
- * Static (opaque) bearer-token auth provider.
4
- *
5
- * Validates a fixed set of pre-shared bearer tokens with no OIDC/JWT
6
- * infrastructure — no issuer, no JWKS endpoint, no key management. Suited to
7
- * same-network deployments (Docker, VPN, LAN), server-to-server integrations,
8
- * and CI pipelines where a full OAuth flow is disproportionate.
9
- *
10
- * All valid tokens map to the same {@link AuthInfo}: this is authentication
11
- * ("is this an allowed caller?"), not per-user identity. For per-user identity,
12
- * expiry, or scopes issued by an IdP, use {@link JwtAuthProvider} / the OIDC
13
- * presets instead.
14
- *
15
- * Per RFC 9728 the emitted {@link ProtectedResourceMetadata} carries an empty
16
- * `authorization_servers` array: there is no authorization server in a static
17
- * token scheme — tokens are provisioned out of band — which is the correct
18
- * signal for clients not to attempt AS discovery.
19
- *
20
- * @module lib/server/auth/static-token-provider
21
- */
22
-
23
- import { AuthProvider } from "./provider.js";
24
- import {
25
- type AuthInfo,
26
- type HttpsUrl,
27
- httpsUrl,
28
- type ProtectedResourceMetadata,
29
- } from "./types.js";
30
-
31
- /**
32
- * Options for {@link createStaticTokenAuthProvider} /
33
- * {@link StaticTokenAuthProvider}.
34
- */
35
- export interface StaticTokenAuthProviderOptions {
36
- /**
37
- * RFC 9728 § 2 resource identifier — an absolute HTTP(S) URL identifying
38
- * this server, validated via {@link httpsUrl} at construction. Required: the
39
- * {@link AuthProvider} contract must emit Protected Resource Metadata, which
40
- * needs a resource URL.
41
- */
42
- resource: string;
43
- /**
44
- * `subject` reported in {@link AuthInfo} for every valid token.
45
- * Default `"static-token-user"`.
46
- */
47
- subject?: string;
48
- /**
49
- * `scopes` granted to every valid token. Default `[]` — a pure gate with no
50
- * scopes, which is the common same-network case.
51
- */
52
- scopes?: string[];
53
- /**
54
- * `scopes_supported` advertised in the metadata document (what the resource
55
- * accepts). Defaults to `scopes` when omitted.
56
- */
57
- scopesSupported?: string[];
58
- /**
59
- * Explicit Protected Resource Metadata URL. When omitted it is auto-derived
60
- * from `resource` per RFC 9728 § 3.1, identically to {@link JwtAuthProvider}.
61
- * Empty / whitespace-only values are treated as absent.
62
- */
63
- resourceMetadataUrl?: string;
64
- }
65
-
66
- /**
67
- * {@link AuthProvider} that accepts a fixed set of opaque bearer tokens.
68
- *
69
- * Token lookup is O(1) via a pre-built `Set`; the shared {@link AuthInfo} (and
70
- * its `scopes` array) is frozen at construction. Tokens are stored trimmed to
71
- * match the bearer value the HTTP middleware extracts. Note that `Set.has()` is
72
- * not constant-time — prefer long, high-entropy tokens (>= 32 random bytes) and
73
- * rotate them regularly.
74
- *
75
- * @example
76
- * ```typescript
77
- * const provider = new StaticTokenAuthProvider(
78
- * [Deno.env.get("MCP_AUTH_TOKEN")!],
79
- * { resource: "https://my-mcp.example.com", scopes: ["tools:invoke"] },
80
- * );
81
- * ```
82
- */
83
- export class StaticTokenAuthProvider extends AuthProvider {
84
- private readonly tokens: Set<string>;
85
- private readonly authInfo: AuthInfo;
86
- private readonly resource: string;
87
- private readonly resourceMetadataUrl: HttpsUrl;
88
- private readonly scopesSupported: string[] | undefined;
89
-
90
- constructor(tokens: string[], options: StaticTokenAuthProviderOptions) {
91
- super();
92
-
93
- if (tokens.length === 0) {
94
- throw new Error(
95
- "[StaticTokenAuthProvider] `tokens` must contain at least one token",
96
- );
97
- }
98
- if (tokens.some((t) => t.trim().length === 0)) {
99
- throw new Error(
100
- "[StaticTokenAuthProvider] `tokens` must not contain empty entries",
101
- );
102
- }
103
- if (!options.resource?.trim()) {
104
- throw new Error("[StaticTokenAuthProvider] `resource` is required");
105
- }
106
-
107
- // Validate `resource` as an absolute HTTP(S) URL unconditionally, so the
108
- // documented guarantee holds even when `resourceMetadataUrl` is supplied.
109
- const resourceUrl = httpsUrl(options.resource);
110
-
111
- // Store tokens trimmed: the HTTP middleware trims the extracted bearer
112
- // value (`extractBearerToken`), so a padded entry would otherwise be stored
113
- // in a form that can never match an incoming request.
114
- this.tokens = new Set(tokens.map((t) => t.trim()));
115
-
116
- // Clone + freeze the scopes array: verifyToken returns this same AuthInfo
117
- // reference for every valid token, so a shared mutable array would let one
118
- // caller escalate scopes for all callers.
119
- const scopes = Object.freeze([...(options.scopes ?? [])]) as string[];
120
- this.authInfo = Object.freeze({
121
- subject: options.subject ?? "static-token-user",
122
- scopes,
123
- }) as AuthInfo;
124
-
125
- // Store the caller's raw resource string (RFC 9728 allows opaque URIs, and
126
- // JwtAuthProvider does the same); `resourceUrl` above is used only for
127
- // validation and metadata-URL derivation.
128
- this.resource = options.resource;
129
- this.scopesSupported = options.scopesSupported
130
- ? (Object.freeze([...options.scopesSupported]) as string[])
131
- : (scopes.length > 0 ? scopes : undefined);
132
-
133
- // RFC 9728 § 3.1: when `resourceMetadataUrl` is omitted, insert the
134
- // well-known suffix between the resource's origin and its path/query
135
- // (identical derivation to JwtAuthProvider).
136
- if (options.resourceMetadataUrl?.trim()) {
137
- this.resourceMetadataUrl = httpsUrl(options.resourceMetadataUrl);
138
- } else {
139
- const parsed = new URL(resourceUrl);
140
- const pathPart = parsed.pathname === "/" ? "" : parsed.pathname;
141
- this.resourceMetadataUrl = httpsUrl(
142
- `${parsed.origin}/.well-known/oauth-protected-resource${pathPart}${parsed.search}`,
143
- );
144
- }
145
- }
146
-
147
- async verifyToken(token: string): Promise<AuthInfo | null> {
148
- // Trim to match how tokens are stored (and how the HTTP middleware extracts
149
- // the bearer), so direct callers and the middleware path behave identically.
150
- return this.tokens.has(token.trim()) ? this.authInfo : null;
151
- }
152
-
153
- getResourceMetadata(): ProtectedResourceMetadata {
154
- // Fresh object per call (matching JwtAuthProvider) so a caller cannot
155
- // mutate shared metadata — e.g. the `authorization_servers` array.
156
- return {
157
- resource: this.resource,
158
- resource_metadata_url: this.resourceMetadataUrl,
159
- // No authorization server: static tokens are provisioned out of band.
160
- authorization_servers: [],
161
- scopes_supported: this.scopesSupported,
162
- bearer_methods_supported: ["header"],
163
- };
164
- }
165
- }
166
-
167
- /**
168
- * Create a static (opaque) bearer-token {@link AuthProvider}.
169
- *
170
- * @param tokens Non-empty list of valid bearer tokens (deduplicated, stored
171
- * trimmed). Load them from env / a secrets manager — never hard-code tokens
172
- * in source.
173
- * @param options Provider configuration; `options.resource` is required.
174
- *
175
- * @example
176
- * ```typescript
177
- * import { createStaticTokenAuthProvider, McpApp } from "@casys/mcp-server";
178
- *
179
- * const app = new McpApp({
180
- * name: "my-server",
181
- * version: "1.0.0",
182
- * auth: {
183
- * provider: createStaticTokenAuthProvider(
184
- * (Deno.env.get("MCP_AUTH_TOKENS") ?? "").split(",").filter(Boolean),
185
- * { resource: "https://my-mcp.example.com" },
186
- * ),
187
- * },
188
- * });
189
- * await app.startHttp({ port: 7654, requireAuth: true });
190
- * ```
191
- */
192
- export function createStaticTokenAuthProvider(
193
- tokens: string[],
194
- options: StaticTokenAuthProviderOptions,
195
- ): StaticTokenAuthProvider {
196
- return new StaticTokenAuthProvider(tokens, options);
197
- }