@entro314labs/entro-auth-cimd 0.0.0-stage → 1.8.0-beta.12

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/LICENSE.md ADDED
@@ -0,0 +1,20 @@
1
+ The MIT License (MIT)
2
+ Copyright (c) 2024 - present, Bereket Engida
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
5
+ this software and associated documentation files (the “Software”), to deal in
6
+ the Software without restriction, including without limitation the rights to
7
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
8
+ the Software, and to permit persons to whom the Software is furnished to do so,
9
+ subject to the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in all
12
+ copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
16
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20
+ DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,17 @@
1
- # Temporary Holding Version
1
+ # Entro Auth CIMD Plugin
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Client ID Metadata Document draft-02 plugin for [Entro Auth](https://www.better-auth.com): unauthenticated client discovery over HTTPS. An explicit metadata profile applies the draft-00 requirements pinned by [MCP 2026-07-28](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization/client-registration#client-id-metadata-documents).
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @entro314labs/entro-auth-cimd
9
+ ```
10
+
11
+ ## Documentation
12
+
13
+ For full documentation, visit [better-auth.com/docs/plugins/cimd](https://www.better-auth.com/docs/plugins/cimd).
14
+
15
+ ## License
16
+
17
+ MIT
@@ -0,0 +1,379 @@
1
+ import { ClientDiscovery, ClientMetadataResourceFetch, OAuthClientMetadata, SchemaClient, Scope } from "@entro314labs/entro-auth-oauth-provider";
2
+ import { GenericEndpointContext } from "@entro314labs/entro-auth-core";
3
+ type CimdMetadataProfile = "mcp-2026-07-28";
4
+ /** A validated Client ID Metadata Document, ready to be persisted. */
5
+ interface CimdMetadataResolution {
6
+ /** Validated document. A copy: changing it does not change the cache. */
7
+ metadata: OAuthClientMetadata;
8
+ /**
9
+ * Whether an unexpired cache entry answered at once, so the request neither
10
+ * fetched nor waited for a fetch. It is `false` when the request fetched the
11
+ * document, joined a fetch, or found a document another request cached while
12
+ * the URL policy ran.
13
+ */
14
+ fromCache: boolean;
15
+ }
16
+ /**
17
+ * Fetches, validates, and caches Client ID Metadata Documents without touching
18
+ * the database. Create one with {@link createCimdMetadataResolver} and pass it
19
+ * to `cimd({ metadataResolver })`.
20
+ *
21
+ * Calling it returns `null` when `clientId` is not a Client ID Metadata
22
+ * Document URL. The context is the request's own: it reaches
23
+ * `isMetadataDocumentUrlAllowed` and supplies the OAuth provider's extension
24
+ * fields, and nothing is written through it.
25
+ */
26
+ interface CimdMetadataResolver {
27
+ (context: GenericEndpointContext, clientId: string): Promise<CimdMetadataResolution | null>;
28
+ /**
29
+ * The transport the resolver fetches documents with. A discovery that uses
30
+ * the resolver also fetches its other metadata resources, such as
31
+ * `jwks_uri`, with it.
32
+ */
33
+ readonly fetchClientMetadataResource: ClientMetadataResourceFetch;
34
+ }
35
+ interface CimdClientCreatedEvent {
36
+ /** Newly persisted discovery-owned OAuth client. */
37
+ client: SchemaClient<Scope[]>;
38
+ /** Validated Client ID Metadata Document that produced the client. */
39
+ clientMetadataDocument: OAuthClientMetadata;
40
+ /** Entro Auth endpoint context for the discovery request. */
41
+ context: GenericEndpointContext;
42
+ }
43
+ interface CimdClientRefreshedEvent {
44
+ /** Discovery-owned OAuth client after metadata reconciliation. */
45
+ client: SchemaClient<Scope[]>;
46
+ /** Client state captured before metadata reconciliation. */
47
+ previousClient: SchemaClient<Scope[]>;
48
+ /** Validated Client ID Metadata Document used for reconciliation. */
49
+ clientMetadataDocument: OAuthClientMetadata;
50
+ /** Entro Auth endpoint context for the discovery request. */
51
+ context: GenericEndpointContext;
52
+ }
53
+ interface CimdMetadataFetchPolicy {
54
+ /**
55
+ * Minimum time before retrying a failed metadata fetch for one exact client
56
+ * ID. Successful fetches are governed by HTTP freshness and the origin/global
57
+ * fetch budgets. Numeric values are seconds. Set to `0` to disable failed-fetch
58
+ * pacing.
59
+ *
60
+ * @default 1
61
+ */
62
+ minimumFetchInterval?: number | string;
63
+ /**
64
+ * Maximum metadata fetches in flight across the plugin instance.
65
+ *
66
+ * @default 16
67
+ */
68
+ maximumConcurrentFetches?: number;
69
+ /**
70
+ * Maximum metadata fetches in flight for one URL origin.
71
+ *
72
+ * @default 4
73
+ */
74
+ maximumConcurrentFetchesPerOrigin?: number;
75
+ /**
76
+ * Maximum fetch starts in a rolling 60-second window across the
77
+ * plugin instance.
78
+ *
79
+ * @default 120
80
+ */
81
+ maximumFetchesPerMinute?: number;
82
+ /**
83
+ * Maximum fetch starts in a rolling 60-second window for one URL
84
+ * origin.
85
+ *
86
+ * @default 30
87
+ */
88
+ maximumFetchesPerOriginPerMinute?: number;
89
+ }
90
+ /**
91
+ * Options that govern how metadata documents are fetched, validated, and
92
+ * cached. Pass them to `cimd()`, or to {@link createCimdMetadataResolver} when
93
+ * several plugin instances share one resolver.
94
+ */
95
+ interface CimdMetadataResolverOptions {
96
+ /**
97
+ * Fetch transport for metadata documents and discovery-owned metadata
98
+ * resources such as `jwks_uri`.
99
+ *
100
+ * The transport MUST resolve the hostname exactly once, reject RFC 6890
101
+ * special-use addresses, pin the approved address for the connection, and
102
+ * refuse redirects. Those guarantees cannot be implemented by wrapping the
103
+ * standard Fetch API after DNS resolution, so the application must provide
104
+ * them at its runtime-specific network boundary.
105
+ */
106
+ fetchClientMetadataResource: ClientMetadataResourceFetch;
107
+ /**
108
+ * Apply an additional protocol profile to otherwise generic draft-02
109
+ * metadata validation.
110
+ *
111
+ * The MCP 2026-07-28 profile requires `client_name` and `redirect_uris`
112
+ * because that MCP revision normatively pins CIMD draft-00.
113
+ */
114
+ metadataProfile?: CimdMetadataProfile;
115
+ /**
116
+ * Maximum and fallback cache freshness lifetime for a client's metadata
117
+ * document. An expired entry is revalidated on the next client resolution;
118
+ * the plugin does not perform periodic or background fetches.
119
+ *
120
+ * Accepts a number of seconds or a duration string (e.g. `"60m"`,
121
+ * `"1d"`).
122
+ *
123
+ * @default "60m"
124
+ */
125
+ metadataRevalidationInterval?: number | string;
126
+ /**
127
+ * Keep serving a stored client for up to this long after it was last
128
+ * validated (its `updatedAt`) when refreshing its metadata document fails
129
+ * transiently: the fetch times out after its host name resolved, the
130
+ * connection fails with a known error code, or the server answers with
131
+ * HTTP 500, 502, 503, or 504. Other failures still reject the request.
132
+ * Cached `jwks_uri` keys follow the same rules.
133
+ *
134
+ * Accepts a number of seconds or a duration string (e.g. `"6h"`), at most
135
+ * 24 hours.
136
+ *
137
+ * @see https://www.better-auth.com/docs/plugins/cimd#transient-refresh-failures
138
+ * @see https://datatracker.ietf.org/doc/html/draft-ietf-oauth-client-id-metadata-document-03#section-6.1
139
+ */
140
+ metadataStaleIfError?: number | string;
141
+ /**
142
+ * Bounded request-amplification policy for metadata document fetches.
143
+ *
144
+ * A permitted fetch consumes its concurrency and rolling-window budget when
145
+ * it starts. Same-client concurrent resolutions coalesce, while fresh-cache
146
+ * hits consume no budget. Limits reject immediately rather than queueing.
147
+ */
148
+ metadataFetchPolicy?: CimdMetadataFetchPolicy;
149
+ /**
150
+ * Maximum number of validated metadata documents retained by this plugin
151
+ * instance. The least-recently-used entry is evicted when the bound is
152
+ * reached.
153
+ *
154
+ * @default 1000
155
+ */
156
+ maxCacheEntries?: number;
157
+ /**
158
+ * Metadata fields whose URL values must share the same origin as the
159
+ * `client_id` URL. Prevents a client from claiming URIs on a different
160
+ * domain.
161
+ *
162
+ * Pass an empty array to disable origin binding (not recommended for
163
+ * production).
164
+ *
165
+ * Only `post_logout_redirect_uris` is origin-bound by default.
166
+ * `redirect_uris` is excluded because exact redirect URI matching remains
167
+ * mandatory at authorization time. The informative URIs `client_uri`,
168
+ * `logo_uri`, `tos_uri`, and `policy_uri` are never origin-bound by
169
+ * default; they must still be credential-free HTTP(S) URLs on a public
170
+ * host. CIMD draft-03 §4.4 forbids requiring `client_uri` to share an
171
+ * origin with `client_id` or `redirect_uris`, so listing `client_uri` here
172
+ * is the operator's own policy and contradicts the draft.
173
+ *
174
+ * @default ["post_logout_redirect_uris"]
175
+ */
176
+ originBoundFields?: readonly string[];
177
+ /**
178
+ * Pre-fetch gate called before a metadata document is requested. Return
179
+ * `false` to reject the `client_id` URL.
180
+ *
181
+ * Use this for origin allowlists, per-host rate limiting, or integrating
182
+ * with an external trust service. It is application policy, not a
183
+ * substitute for the required transport's resolve-once and connection-
184
+ * pinning guarantees; resolving here would introduce a TOCTOU boundary.
185
+ *
186
+ * It runs for each request that needs the document fetched, including
187
+ * requests that would join another request's in-flight fetch, before any
188
+ * fetch budget is consumed. Fresh cache hits skip it. Keep it cheap, or cache
189
+ * its decisions, if it consults an external service.
190
+ *
191
+ * @default always allow
192
+ */
193
+ isMetadataDocumentUrlAllowed?: (clientIdUrl: string, context: GenericEndpointContext) => boolean | Promise<boolean>;
194
+ }
195
+ interface CimdDiscoveryOptions {
196
+ /**
197
+ * Allows a client's `jwks_uri` on an origin that is neither a trusted
198
+ * origin nor the `client_id` URL's origin. Return `true` to allow it.
199
+ *
200
+ * By default such a `jwks_uri` is rejected. This is consulted only for
201
+ * that case, when the document is registered or refreshed and before each
202
+ * client assertion is verified. `false`, a throw, or a rejection keeps the
203
+ * rejection. HTTPS, public-host, credential, and fragment checks still
204
+ * apply first, and the keys are fetched through
205
+ * `fetchClientMetadataResource`.
206
+ *
207
+ * `jwks_uri` fetches are not gated by `isMetadataDocumentUrlAllowed` or
208
+ * `metadataFetchPolicy`, so the origin rule is what bounds where a
209
+ * document can make the server send requests. Match the client and key
210
+ * origins together rather than allowing a key origin for every client.
211
+ *
212
+ * @default always reject
213
+ */
214
+ isCrossOriginJwksUriAllowed?: (input: {
215
+ clientId: string;
216
+ jwksUri: string;
217
+ }, context: GenericEndpointContext) => boolean | Promise<boolean>;
218
+ /**
219
+ * Called after a client is created from a metadata document for the
220
+ * first time. Use this to assign local trust, emit an audit event, or
221
+ * perform other post-creation processing. Entro Auth does not fetch or
222
+ * render metadata-owned remote assets such as `logo_uri`.
223
+ *
224
+ * This is a best-effort notification. A rejected callback is logged and
225
+ * does not roll back an otherwise valid registration.
226
+ */
227
+ onClientCreated?: (event: CimdClientCreatedEvent) => void | Promise<void>;
228
+ /**
229
+ * Called after a client is refreshed from a re-fetched metadata
230
+ * document. Use this for change-detection logging or updating derived
231
+ * fields.
232
+ *
233
+ * This is a best-effort notification. A rejected callback is logged and
234
+ * does not roll back an otherwise valid refresh.
235
+ */
236
+ onClientRefreshed?: (event: CimdClientRefreshedEvent) => void | Promise<void>;
237
+ }
238
+ /**
239
+ * Options for a plugin instance that owns its metadata resolver. This is the
240
+ * half of {@link CimdOptions} that sets the transport and the fetch and
241
+ * validation options directly.
242
+ */
243
+ interface CimdOwnedResolverOptions extends CimdMetadataResolverOptions, CimdDiscoveryOptions {
244
+ /**
245
+ * Share one metadata resolver across several plugin instances instead. See
246
+ * {@link createCimdMetadataResolver}.
247
+ *
248
+ * @default a resolver owned by this plugin instance
249
+ */
250
+ metadataResolver?: undefined;
251
+ }
252
+ type ResolverOwnedOptions = { [Option in keyof CimdMetadataResolverOptions]?: never; };
253
+ /**
254
+ * Options for a plugin instance that uses a shared metadata resolver. This is
255
+ * the half of {@link CimdOptions} that takes the transport and every fetch and
256
+ * validation option from the resolver.
257
+ */
258
+ interface CimdSharedResolverOptions extends CimdDiscoveryOptions, ResolverOwnedOptions {
259
+ /**
260
+ * Share one metadata cache, set of fetch budgets, and in-flight fetch map
261
+ * across several plugin instances, by passing the result of
262
+ * {@link createCimdMetadataResolver}. Each request still saves the client
263
+ * with its own context.
264
+ *
265
+ * The resolver owns the transport and every option that governs fetching
266
+ * and validation, so those options are set on it and cannot be set here.
267
+ * The plugin fetches discovery-owned resources such as `jwks_uri` with the
268
+ * resolver's `fetchClientMetadataResource`.
269
+ */
270
+ metadataResolver: CimdMetadataResolver;
271
+ }
272
+ /**
273
+ * Options for the Client ID Metadata Document plugin: the fetch and validation
274
+ * options of {@link CimdMetadataResolverOptions}, or a shared
275
+ * `metadataResolver` that carries them.
276
+ *
277
+ * @see https://datatracker.ietf.org/doc/html/draft-ietf-oauth-client-id-metadata-document-02
278
+ */
279
+ type CimdOptions = CimdOwnedResolverOptions | CimdSharedResolverOptions;
280
+ /**
281
+ * Build a resolver that fetches, validates, and caches Client ID Metadata
282
+ * Documents, and saves nothing.
283
+ *
284
+ * The cache, fetch budgets, and in-flight fetches live in this closure. Pass
285
+ * the result to `cimd({ metadataResolver })` to share them between discoveries
286
+ * that are created per request, as a runtime whose database handle belongs to
287
+ * one request needs. Without it, each plugin instance owns its own resolver, so
288
+ * separate `cimd()` instances never share trust state or conditional validators.
289
+ *
290
+ * Concurrent requests for one client share a single fetch. The document each
291
+ * request receives is its own copy, and the caller saves it with that
292
+ * request's context. A request waits at most 10 seconds for each fetch it
293
+ * joins and then fetches for itself, so a request that the runtime ended
294
+ * cannot stall the others.
295
+ *
296
+ * The resolver carries `fetchClientMetadataResource`, and a discovery that uses
297
+ * it fetches discovery-owned resources such as `jwks_uri` with that transport.
298
+ */
299
+ export declare function createCimdMetadataResolver(options: CimdMetadataResolverOptions): CimdMetadataResolver;
300
+ type CimdMetadataValidationResult = {
301
+ valid: true;
302
+ metadata: OAuthClientMetadata;
303
+ error?: never;
304
+ warnings?: string[];
305
+ } | {
306
+ valid: false;
307
+ error: string;
308
+ metadata?: never;
309
+ warnings?: string[];
310
+ };
311
+ interface CimdMetadataValidationOptions {
312
+ originBoundFields?: readonly string[];
313
+ metadataProfile?: CimdMetadataProfile;
314
+ /**
315
+ * Registration fields that OAuth provider extensions declare, such as
316
+ * CIBA's `backchannel_token_delivery_mode`. They are kept in the validated
317
+ * metadata instead of being ignored as unknown members; the provider
318
+ * validates them when it registers the client.
319
+ */
320
+ extensionFields?: ReadonlySet<string>;
321
+ }
322
+ /**
323
+ * Detect a URL-formatted client_id (Client ID Metadata Document pattern).
324
+ *
325
+ * HTTPS URLs match. This is a routing predicate, not a security gate: it
326
+ * performs no DNS resolution, so callers MUST also run
327
+ * {@link validateClientIdUrl} (and a fetch-time policy) before fetching.
328
+ */
329
+ export declare function isCimdClientIdUrlCandidate(clientId: string): boolean;
330
+ /**
331
+ * Validate a client_id URL per Client ID Metadata Document draft-02 §3.
332
+ * Returns null on success, an error string on failure.
333
+ *
334
+ * Loopback and every other non-public host (private, link-local,
335
+ * cloud-metadata, IPv6 tunnels) are rejected.
336
+ */
337
+ export declare function validateClientIdUrl(url: string): string | null;
338
+ /**
339
+ * Validate a fetched Client ID Metadata Document per §4.1.
340
+ *
341
+ * @param clientIdUrl - The URL the document was fetched from.
342
+ * @param raw - The parsed JSON body of the response.
343
+ * @param options - Generic draft-02 validation options and an optional protocol profile.
344
+ */
345
+ export declare function validateCimdMetadata(clientIdUrl: string, raw: unknown, options?: CimdMetadataValidationOptions): CimdMetadataValidationResult;
346
+ declare module "@entro314labs/entro-auth-core" {
347
+ interface EntroAuthPluginRegistry<AuthOptions, Options> {
348
+ cimd: {
349
+ creator: typeof cimd;
350
+ };
351
+ }
352
+ }
353
+ /**
354
+ * Build a {@link ClientDiscovery} for Client ID Metadata Documents.
355
+ *
356
+ * Users who prefer explicit composition can contribute the result through
357
+ * `oauthProvider({ extensions: [{ clientDiscovery }] })`; most users should
358
+ * install the {@link cimd} plugin instead, which contributes this discovery
359
+ * alongside whatever else is configured.
360
+ */
361
+ export declare function createCimdClientDiscovery(options: CimdOptions): ClientDiscovery;
362
+ /**
363
+ * Client ID Metadata Document plugin.
364
+ *
365
+ * Adds unauthenticated dynamic client discovery over HTTPS to an
366
+ * `oauth-provider` instance. Clients identify themselves by providing
367
+ * an HTTPS URL as their `client_id`; the plugin fetches and validates
368
+ * the document at that URL, then creates a client record whose authentication
369
+ * behavior is determined by `token_endpoint_auth_method`.
370
+ *
371
+ * See {@link https://datatracker.ietf.org/doc/html/draft-ietf-oauth-client-id-metadata-document-02 | Client ID Metadata Document draft-02}
372
+ * and {@link https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization/client-registration#client-id-metadata-documents | the MCP authorization spec}.
373
+ */
374
+ export declare const cimd: (options: CimdOptions) => {
375
+ id: "cimd";
376
+ version: string;
377
+ init(ctx: import("@entro314labs/entro-auth-core").AuthContext): void;
378
+ };
379
+ export type { CimdClientCreatedEvent, CimdClientRefreshedEvent, CimdMetadataFetchPolicy, CimdMetadataProfile, CimdMetadataResolution, CimdMetadataResolver, CimdMetadataResolverOptions, CimdMetadataValidationOptions, CimdMetadataValidationResult, CimdOptions, CimdOwnedResolverOptions, CimdSharedResolverOptions };