@casys/mcp-server 0.21.1 → 0.22.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 CHANGED
@@ -183,8 +183,16 @@ export {
183
183
  createAuthProviderFromConfig,
184
184
  loadAuthConfig,
185
185
  } from "./src/auth/mod.js";
186
+
186
187
  export type { AuthConfig, AuthProviderName } from "./src/auth/mod.js";
187
188
 
189
+ // Auth - Static Token Provider (opaque pre-shared bearer tokens)
190
+ export {
191
+ createStaticTokenAuthProvider,
192
+ StaticTokenAuthProvider,
193
+ } from "./src/auth/mod.js";
194
+ export type { StaticTokenAuthProviderOptions } from "./src/auth/mod.js";
195
+
188
196
  // Client Auth — OAuth client flow + CIMD
189
197
  export {
190
198
  buildClientIdMetadataDocument,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@casys/mcp-server",
3
- "version": "0.21.1",
3
+ "version": "0.22.0",
4
4
  "description": "Production-ready MCP server framework with concurrency control, auth, and observability",
5
5
  "type": "module",
6
6
  "main": "mod.ts",
package/src/auth/mod.ts CHANGED
@@ -80,3 +80,10 @@ export type {
80
80
  GoogleAuthConfig,
81
81
  OIDCAuthConfig,
82
82
  } from "./config.js";
83
+
84
+ // Static Token Provider (opaque pre-shared bearer tokens; no OIDC/JWT infra)
85
+ export {
86
+ createStaticTokenAuthProvider,
87
+ StaticTokenAuthProvider,
88
+ } from "./static-token-provider.js";
89
+ export type { StaticTokenAuthProviderOptions } from "./static-token-provider.js";
@@ -0,0 +1,197 @@
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
+ }