@dokebi/oauth 0.0.0-stage → 0.1.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.
@@ -0,0 +1,36 @@
1
+ /*
2
+ * Small in-process bookkeeping with hard bounds: a least-recently-used map (never cleared all at
3
+ * once: the oldest entry makes room). Shared by the registration limit and the document fetch
4
+ * limits; the address key of a client is `http.addressKey` of @dokebi/core/libraries.
5
+ */
6
+ /** A Map that keeps at most `max` entries, dropping the least recently used one. */
7
+ export class LruMap {
8
+ #max;
9
+ #entries = new Map();
10
+ constructor(max) {
11
+ this.#max = max;
12
+ }
13
+ get(key) {
14
+ const value = this.#entries.get(key);
15
+ if (value === undefined)
16
+ return undefined;
17
+ this.#entries.delete(key);
18
+ this.#entries.set(key, value);
19
+ return value;
20
+ }
21
+ set(key, value) {
22
+ this.#entries.delete(key);
23
+ if (this.#entries.size >= this.#max) {
24
+ const oldest = this.#entries.keys().next();
25
+ if (!oldest.done)
26
+ this.#entries.delete(oldest.value);
27
+ }
28
+ this.#entries.set(key, value);
29
+ }
30
+ delete(key) {
31
+ this.#entries.delete(key);
32
+ }
33
+ get size() {
34
+ return this.#entries.size;
35
+ }
36
+ }
package/dist/cimd.d.ts ADDED
@@ -0,0 +1,97 @@
1
+ import { type LookupAddress, type LookupAllOptions, type LookupOptions } from 'node:dns';
2
+ import type { ClientRequest, IncomingMessage, RequestOptions } from 'node:http';
3
+ /** Default `cimd.maxBytes`; the other document limits are `cimd` options too (D-0113 §5). */
4
+ export declare const CIMD_MAX_BYTES: number;
5
+ /** How long fetched documents are kept (`cimd.minCacheMs`, `maxCacheMs`, `defaultCacheMs`). */
6
+ export interface CacheLifetimes {
7
+ readonly minCacheMs: number;
8
+ readonly maxCacheMs: number;
9
+ readonly defaultCacheMs: number;
10
+ }
11
+ export type CimdProblem = 'bad-url' | 'not-https' | 'no-path' | 'userinfo' | 'fragment' | 'host-not-allowed' | 'private-address' | 'redirect' | 'status' | 'content-type' | 'too-large' | 'timeout' | 'bad-json' | 'bad-document' | 'client-id-mismatch' | 'network';
12
+ /** A refused document: `problem` for code, `message` for people (no secret in either). */
13
+ export declare class CimdRefusal extends Error {
14
+ readonly problem: CimdProblem;
15
+ constructor(problem: CimdProblem, message: string, cause?: unknown);
16
+ }
17
+ /**
18
+ * True for a public unicast address: false for loopback, private, link-local (the cloud metadata
19
+ * address 169.254.169.254), CGNAT, documentation, benchmarking, multicast, reserved and the IPv6
20
+ * special ranges. An IPv4-mapped or -compatible IPv6 address is judged by its IPv4 address.
21
+ */
22
+ export declare function isPublicAddress(address: string): boolean;
23
+ /** Whether a client_id is shaped like a document URL (`https://host/path`). */
24
+ export declare function looksLikeDocumentUrl(clientId: string): boolean;
25
+ /** The URL rules (1); the parsed URL when they hold. */
26
+ export declare function checkDocumentUrl(raw: string, allowHosts: readonly string[]): URL;
27
+ /** A checked client document (the fields this server uses). */
28
+ export interface ClientDocument {
29
+ readonly clientId: string;
30
+ readonly redirectUris: readonly string[];
31
+ /** The self-declared `client_name`, if any (shown after the host, never alone). */
32
+ readonly name: string | undefined;
33
+ }
34
+ /** The document rules (4), for every fetch. */
35
+ export declare function checkDocument(value: unknown, url: string): ClientDocument;
36
+ /**
37
+ * How long a document is kept: `max-age` within `minCacheMs` and `maxCacheMs` (defaults 5 minutes
38
+ * and 24 hours), `defaultCacheMs` without one (1 hour), `minCacheMs` for no-store.
39
+ */
40
+ export declare function cacheMsOf(cacheControl: string | undefined, lifetimes?: CacheLifetimes): number;
41
+ /** One fetched response, before any check. */
42
+ export interface CimdResponse {
43
+ readonly status: number;
44
+ /** Header names in lower case. */
45
+ readonly headers: Readonly<Record<string, string | undefined>>;
46
+ /** The body: bytes, or a stream read until `maxBytes` (then destroyed). */
47
+ readonly body: Uint8Array | AsyncIterable<Uint8Array>;
48
+ }
49
+ /**
50
+ * Fetches one document URL; never follows a redirect. `signal` aborts at the deadline. An injected
51
+ * fetch (`defineOAuthPlugin({ cimdFetch })`) owns its own address checks; every response check and
52
+ * the document check still run.
53
+ */
54
+ export type CimdFetch = (url: URL, context: {
55
+ readonly signal: AbortSignal;
56
+ readonly maxBytes: number;
57
+ }) => Promise<CimdResponse>;
58
+ type Resolve = (hostname: string, options: LookupAllOptions, callback: (error: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void) => void;
59
+ export interface HttpsFetchSettings {
60
+ /** DNS resolution (default `dns.lookup`); tests give answers here. */
61
+ readonly resolve?: Resolve;
62
+ /** Which resolved addresses may be connected to (default `isPublicAddress`). */
63
+ readonly allowed?: (address: string) => boolean;
64
+ /** The request function (default `https.request`). */
65
+ readonly request?: (options: RequestOptions, callback: (response: IncomingMessage) => void) => ClientRequest;
66
+ /** Largest response head in bytes (`cimd.maxHeaderBytes`, default 8 KiB). */
67
+ readonly maxHeaderBytes?: number;
68
+ }
69
+ /** The lookup hook: the socket only ever gets addresses that passed `allowed` (checked = used). */
70
+ export declare function guardedLookup(resolve: Resolve, allowed: (address: string) => boolean): (hostname: string, options: LookupOptions, callback: (error: NodeJS.ErrnoException | null, address: string | LookupAddress[], family?: number) => void) => void;
71
+ /** The built-in fetch: node:https with the lookup guard, no agent, no redirects. */
72
+ export declare function httpsFetch(settings?: HttpsFetchSettings): CimdFetch;
73
+ /** A fetched and checked document with its cache lifetime. */
74
+ export interface FetchedDocument {
75
+ readonly document: ClientDocument;
76
+ readonly cacheMs: number;
77
+ readonly bytes: number;
78
+ }
79
+ /** Fetches and checks one document within the deadline (2, 3, 4). */
80
+ export declare function fetchDocument(raw: string, settings: {
81
+ readonly fetch: CimdFetch;
82
+ readonly timeoutMs: number;
83
+ readonly allowHosts: readonly string[];
84
+ /** `cimd.maxBytes` (default 16 KiB). */
85
+ readonly maxBytes?: number;
86
+ /** `cimd.minCacheMs`, `maxCacheMs`, `defaultCacheMs` (defaults 5 minutes, 24 hours, 1 hour). */
87
+ readonly lifetimes?: CacheLifetimes;
88
+ }): Promise<FetchedDocument>;
89
+ /** Fetched documents by URL, each for its cache lifetime (at most `cimd.maxCached`, oldest out first). */
90
+ export declare class DocumentCache {
91
+ #private;
92
+ constructor(max?: number);
93
+ get(url: string, now: number): ClientDocument | undefined;
94
+ set(url: string, document: ClientDocument, until: number): void;
95
+ get size(): number;
96
+ }
97
+ export {};
package/dist/cimd.js ADDED
@@ -0,0 +1,384 @@
1
+ import dns, {} from 'node:dns';
2
+ import https from 'node:https';
3
+ import net from 'node:net';
4
+ import { CIMD_LIMITS_DEFAULT } from './options.js';
5
+ import { redirectProblem } from './protocol.js';
6
+ /*
7
+ * Client ID metadata documents (D-0091 §4; draft-ietf-oauth-client-id-metadata-document): a
8
+ * client_id that is an https URL names a JSON document this server fetches. Fetching a URL the
9
+ * client chose is SSRF territory, so:
10
+ *
11
+ * 1. https only, a path, no user information, no fragment; `allowHosts` when set.
12
+ * 2. The address is checked **where the socket gets it**: in the `lookup` hook of node:https
13
+ * (`agent: false`, no pooled socket of an older answer). "Resolve first, then fetch" was
14
+ * broken by DNS rebinding in XF (S7). IP literals do not go through the hook and are checked
15
+ * on their own; an IPv4-mapped IPv6 address is judged by its IPv4 address.
16
+ * 3. No redirect is followed; 16 KB (the declared length and the bytes read); the whole fetch
17
+ * within `timeoutMs` (slow headers and a trickling body alike); JSON content types only.
18
+ * 4. The document: `client_id` equal to the URL, `redirect_uris` (https or loopback http),
19
+ * `grant_types` *containing* authorization_code (claude.ai lists jwt-bearer too), and the
20
+ * authentication methods intersected with ours (`none`): the plural
21
+ * `token_endpoint_auth_methods_supported` decides when present (ChatGPT's singular field says
22
+ * private_key_jwt).
23
+ *
24
+ * The response checks (3) and the document checks (4) run for every fetch, an injected one too
25
+ * (XF w-121: an injected fetch skipped the document checks). Only the address checks (2) belong
26
+ * to the built-in fetch.
27
+ */
28
+ /** Default `cimd.maxBytes`; the other document limits are `cimd` options too (D-0113 §5). */
29
+ export const CIMD_MAX_BYTES = CIMD_LIMITS_DEFAULT.maxBytes;
30
+ /** A refused document: `problem` for code, `message` for people (no secret in either). */
31
+ export class CimdRefusal extends Error {
32
+ problem;
33
+ constructor(problem, message, cause) {
34
+ super(message, cause === undefined ? undefined : { cause });
35
+ this.name = 'CimdRefusal';
36
+ this.problem = problem;
37
+ }
38
+ }
39
+ // ---- Public addresses ---------------------------------------------------------------------------
40
+ const blocked = new net.BlockList();
41
+ for (const [address, prefix] of [
42
+ ['0.0.0.0', 8],
43
+ ['10.0.0.0', 8],
44
+ ['100.64.0.0', 10],
45
+ ['127.0.0.0', 8],
46
+ ['169.254.0.0', 16],
47
+ ['172.16.0.0', 12],
48
+ ['192.0.0.0', 24],
49
+ ['192.0.2.0', 24],
50
+ ['192.88.99.0', 24],
51
+ ['192.168.0.0', 16],
52
+ ['198.18.0.0', 15],
53
+ ['198.51.100.0', 24],
54
+ ['203.0.113.0', 24],
55
+ ['224.0.0.0', 4],
56
+ ['240.0.0.0', 4],
57
+ ])
58
+ blocked.addSubnet(address, prefix, 'ipv4');
59
+ for (const [address, prefix] of [
60
+ ['::', 128],
61
+ // IPv4-compatible addresses (::a.b.c.d, deprecated): never a public destination.
62
+ ['::', 96],
63
+ ['::1', 128],
64
+ ['64:ff9b::', 96],
65
+ ['64:ff9b:1::', 48],
66
+ ['100::', 64],
67
+ ['2001::', 23],
68
+ ['2001:db8::', 32],
69
+ ['2002::', 16],
70
+ ['fc00::', 7],
71
+ ['fe80::', 10],
72
+ ['fec0::', 10],
73
+ ['ff00::', 8],
74
+ ])
75
+ blocked.addSubnet(address, prefix, 'ipv6');
76
+ /**
77
+ * True for a public unicast address: false for loopback, private, link-local (the cloud metadata
78
+ * address 169.254.169.254), CGNAT, documentation, benchmarking, multicast, reserved and the IPv6
79
+ * special ranges. An IPv4-mapped or -compatible IPv6 address is judged by its IPv4 address.
80
+ */
81
+ export function isPublicAddress(address) {
82
+ const family = net.isIP(address);
83
+ if (family === 0)
84
+ return false;
85
+ if (family === 4)
86
+ return !blocked.check(address, 'ipv4');
87
+ const dotted = /^::ffff:(?:0:)?(\d+\.\d+\.\d+\.\d+)$/i.exec(address) ??
88
+ /^::(\d+\.\d+\.\d+\.\d+)$/.exec(address);
89
+ if (dotted?.[1] !== undefined)
90
+ return isPublicAddress(dotted[1]);
91
+ const hex = /^::ffff:(?:0:)?([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i.exec(address);
92
+ if (hex?.[1] !== undefined && hex[2] !== undefined) {
93
+ const high = Number.parseInt(hex[1], 16);
94
+ const low = Number.parseInt(hex[2], 16);
95
+ return isPublicAddress(`${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`);
96
+ }
97
+ return !blocked.check(address, 'ipv6');
98
+ }
99
+ // ---- The URL and the document -------------------------------------------------------------------
100
+ /** Whether a client_id is shaped like a document URL (`https://host/path`). */
101
+ export function looksLikeDocumentUrl(clientId) {
102
+ if (!clientId.startsWith('https://'))
103
+ return false;
104
+ try {
105
+ const url = new URL(clientId);
106
+ return url.pathname !== '/' && url.pathname !== '';
107
+ }
108
+ catch (error) {
109
+ if (!(error instanceof TypeError))
110
+ throw error;
111
+ return false;
112
+ }
113
+ }
114
+ /** The URL rules (1); the parsed URL when they hold. */
115
+ export function checkDocumentUrl(raw, allowHosts) {
116
+ let url;
117
+ try {
118
+ url = new URL(raw);
119
+ }
120
+ catch (error) {
121
+ if (!(error instanceof TypeError))
122
+ throw error;
123
+ throw new CimdRefusal('bad-url', 'The client_id is not a URL');
124
+ }
125
+ if (url.protocol !== 'https:')
126
+ throw new CimdRefusal('not-https', 'A client document must use https');
127
+ if (url.pathname === '/' || url.pathname === '')
128
+ throw new CimdRefusal('no-path', 'A client document URL needs a path (https://host/path)');
129
+ if (url.username || url.password)
130
+ throw new CimdRefusal('userinfo', 'A client document URL must not carry user information');
131
+ if (raw.includes('#'))
132
+ throw new CimdRefusal('fragment', 'A client document URL must not have a fragment');
133
+ if (allowHosts.length > 0 && !allowHosts.includes(url.hostname))
134
+ throw new CimdRefusal('host-not-allowed', `This server does not accept client documents from ${url.hostname}`);
135
+ const host = url.hostname.replace(/^\[|\]$/g, '');
136
+ if (net.isIP(host) !== 0 && !isPublicAddress(host))
137
+ throw new CimdRefusal('private-address', 'The client document address is not a public address');
138
+ return url;
139
+ }
140
+ const strings = (value) => Array.isArray(value) && value.every((item) => typeof item === 'string');
141
+ /** The document rules (4), for every fetch. */
142
+ export function checkDocument(value, url) {
143
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
144
+ throw new CimdRefusal('bad-document', 'The client document is not a JSON object');
145
+ const document = value;
146
+ if (document.client_id !== url)
147
+ throw new CimdRefusal('client-id-mismatch', 'The client_id of the document is not its URL');
148
+ const redirects = document.redirect_uris;
149
+ if (!strings(redirects) || redirects.length === 0 || redirects.length > 32)
150
+ throw new CimdRefusal('bad-document', 'The client document needs redirect_uris (1 to 32 strings)');
151
+ for (const uri of redirects) {
152
+ const problem = redirectProblem(uri);
153
+ if (problem)
154
+ throw new CimdRefusal('bad-document', `The client document's redirect_uris: ${problem}`);
155
+ }
156
+ const methods = document.token_endpoint_auth_methods_supported;
157
+ const method = document.token_endpoint_auth_method;
158
+ if (methods !== undefined) {
159
+ if (!strings(methods))
160
+ throw new CimdRefusal('bad-document', 'token_endpoint_auth_methods_supported of the client document is not a list of strings');
161
+ if (!methods.includes('none'))
162
+ throw new CimdRefusal('bad-document', 'The client document lists no authentication method this server supports for documents (none)');
163
+ }
164
+ else if (method !== undefined && method !== 'none')
165
+ throw new CimdRefusal('bad-document', 'The client document asks for an authentication method this server does not support for documents (only none)');
166
+ const grants = document.grant_types;
167
+ if (grants !== undefined && (!strings(grants) || !grants.includes('authorization_code')))
168
+ throw new CimdRefusal('bad-document', 'The grant_types of the client document lack authorization_code');
169
+ const responses = document.response_types;
170
+ if (responses !== undefined && (!strings(responses) || !responses.includes('code')))
171
+ throw new CimdRefusal('bad-document', 'The response_types of the client document lack code');
172
+ const name = document.client_name;
173
+ if (name !== undefined && (typeof name !== 'string' || name.length > 255))
174
+ throw new CimdRefusal('bad-document', 'client_name must be a string of at most 255 characters');
175
+ return Object.freeze({
176
+ clientId: url,
177
+ redirectUris: Object.freeze([...redirects]),
178
+ name: typeof name === 'string' && name.trim() !== '' ? name.trim() : undefined,
179
+ });
180
+ }
181
+ /**
182
+ * How long a document is kept: `max-age` within `minCacheMs` and `maxCacheMs` (defaults 5 minutes
183
+ * and 24 hours), `defaultCacheMs` without one (1 hour), `minCacheMs` for no-store.
184
+ */
185
+ export function cacheMsOf(cacheControl, lifetimes = CIMD_LIMITS_DEFAULT) {
186
+ if (cacheControl === undefined)
187
+ return lifetimes.defaultCacheMs;
188
+ const directives = cacheControl.toLowerCase();
189
+ if (/\b(?:no-store|no-cache)\b/.test(directives))
190
+ return lifetimes.minCacheMs;
191
+ const match = /\bmax-age\s*=\s*"?(\d+)"?/.exec(directives);
192
+ if (!match?.[1])
193
+ return lifetimes.defaultCacheMs;
194
+ return Math.min(lifetimes.maxCacheMs, Math.max(lifetimes.minCacheMs, Number(match[1]) * 1000));
195
+ }
196
+ const defaultResolve = (hostname, options, callback) => dns.lookup(hostname, options, callback);
197
+ /** The lookup hook: the socket only ever gets addresses that passed `allowed` (checked = used). */
198
+ export function guardedLookup(resolve, allowed) {
199
+ return (hostname, options, callback) => {
200
+ resolve(hostname, { ...options, all: true }, (error, addresses) => {
201
+ if (error) {
202
+ callback(error, []);
203
+ return;
204
+ }
205
+ if (addresses.length === 0) {
206
+ callback(new CimdRefusal('network', 'The client document host has no address'), []);
207
+ return;
208
+ }
209
+ if (addresses.some((entry) => !allowed(entry.address))) {
210
+ callback(new CimdRefusal('private-address', 'The client document host resolves to a non-public address'), []);
211
+ return;
212
+ }
213
+ if (options.all === true)
214
+ callback(null, addresses);
215
+ else {
216
+ const first = addresses[0];
217
+ callback(null, first.address, first.family);
218
+ }
219
+ });
220
+ };
221
+ }
222
+ /** The built-in fetch: node:https with the lookup guard, no agent, no redirects. */
223
+ export function httpsFetch(settings = {}) {
224
+ const lookup = guardedLookup(settings.resolve ?? defaultResolve, settings.allowed ?? isPublicAddress);
225
+ const send = settings.request ?? https.request;
226
+ return (url, context) => new Promise((resolve, reject) => {
227
+ const request = send({
228
+ protocol: url.protocol === 'https:' && settings.request ? undefined : url.protocol,
229
+ hostname: url.hostname.replace(/^\[|\]$/g, ''),
230
+ port: url.port || 443,
231
+ path: `${url.pathname}${url.search}`,
232
+ method: 'GET',
233
+ // No pooled socket: every fetch gets its own checked resolution.
234
+ agent: false,
235
+ lookup: lookup,
236
+ headers: { accept: 'application/json', 'user-agent': 'dokebi-oauth-cimd' },
237
+ maxHeaderSize: settings.maxHeaderBytes ?? CIMD_LIMITS_DEFAULT.maxHeaderBytes,
238
+ signal: context.signal,
239
+ }, (response) => {
240
+ const headers = {};
241
+ for (const [name, value] of Object.entries(response.headers))
242
+ headers[name] = Array.isArray(value) ? value.join(', ') : value;
243
+ resolve({ status: response.statusCode ?? 0, headers, body: response });
244
+ });
245
+ request.on('error', reject);
246
+ request.end();
247
+ });
248
+ }
249
+ /** Reads a body up to `maxBytes`; a larger one is refused (and its stream destroyed). */
250
+ async function readBody(body, maxBytes) {
251
+ if (body instanceof Uint8Array) {
252
+ if (body.byteLength > maxBytes)
253
+ throw tooLarge(maxBytes);
254
+ return Buffer.from(body);
255
+ }
256
+ const chunks = [];
257
+ let total = 0;
258
+ for await (const chunk of body) {
259
+ total += chunk.byteLength;
260
+ if (total > maxBytes) {
261
+ body.destroy?.();
262
+ throw tooLarge(maxBytes);
263
+ }
264
+ chunks.push(Buffer.from(chunk));
265
+ }
266
+ return Buffer.concat(chunks);
267
+ }
268
+ function tooLarge(maxBytes) {
269
+ return new CimdRefusal('too-large', `The client document is larger than ${maxBytes} bytes`);
270
+ }
271
+ /** Fetches and checks one document within the deadline (2, 3, 4). */
272
+ export async function fetchDocument(raw, settings) {
273
+ const url = checkDocumentUrl(raw, settings.allowHosts);
274
+ const limits = {
275
+ maxBytes: settings.maxBytes ?? CIMD_MAX_BYTES,
276
+ lifetimes: settings.lifetimes ?? CIMD_LIMITS_DEFAULT,
277
+ };
278
+ const controller = new AbortController();
279
+ let timer;
280
+ const deadline = new Promise((_resolve, reject) => {
281
+ timer = setTimeout(() => {
282
+ controller.abort();
283
+ reject(new CimdRefusal('timeout', `The client document did not arrive within ${settings.timeoutMs} ms`));
284
+ }, settings.timeoutMs);
285
+ });
286
+ // When the work ends first the timer is cleared below, so `deadline` never settles.
287
+ try {
288
+ return await Promise.race([
289
+ deadline,
290
+ read(raw, url, settings.fetch, controller.signal, limits),
291
+ ]);
292
+ }
293
+ finally {
294
+ clearTimeout(timer);
295
+ controller.abort();
296
+ }
297
+ }
298
+ async function read(raw, url, fetch, signal, limits) {
299
+ const maxBytes = limits.maxBytes;
300
+ let response;
301
+ try {
302
+ response = await fetch(url, { signal, maxBytes });
303
+ }
304
+ catch (error) {
305
+ if (error instanceof CimdRefusal)
306
+ throw error;
307
+ if (signal.aborted)
308
+ throw new CimdRefusal('timeout', 'The client document did not arrive in time', error);
309
+ const code = error?.code;
310
+ throw new CimdRefusal('network', `The client document could not be fetched${typeof code === 'string' ? ` (${code})` : ''}`, error);
311
+ }
312
+ const discard = () => response.body.destroy?.();
313
+ if (response.status >= 300 && response.status < 400) {
314
+ discard();
315
+ throw new CimdRefusal('redirect', `The client document answered a redirect (${response.status}); redirects are not followed`);
316
+ }
317
+ if (response.status !== 200) {
318
+ discard();
319
+ throw new CimdRefusal('status', `The client document answered HTTP ${response.status}`);
320
+ }
321
+ const type = response.headers['content-type'] ?? '';
322
+ if (!/^application\/(?:[\w.+-]+\+)?json\s*(?:;|$)/i.test(type)) {
323
+ discard();
324
+ throw new CimdRefusal('content-type', 'The client document is not JSON (content-type)');
325
+ }
326
+ const declared = Number(response.headers['content-length'] ?? Number.NaN);
327
+ if (Number.isFinite(declared) && declared > maxBytes) {
328
+ discard();
329
+ throw tooLarge(maxBytes);
330
+ }
331
+ let bytes;
332
+ try {
333
+ bytes = await readBody(response.body, maxBytes);
334
+ }
335
+ catch (error) {
336
+ if (error instanceof CimdRefusal)
337
+ throw error;
338
+ if (signal.aborted)
339
+ throw new CimdRefusal('timeout', 'The client document did not arrive in time', error);
340
+ throw new CimdRefusal('network', 'The client document body could not be read', error);
341
+ }
342
+ let parsed;
343
+ try {
344
+ parsed = JSON.parse(bytes.toString('utf8'));
345
+ }
346
+ catch (error) {
347
+ throw new CimdRefusal('bad-json', 'The client document is not valid JSON', error);
348
+ }
349
+ return Object.freeze({
350
+ document: checkDocument(parsed, raw),
351
+ cacheMs: cacheMsOf(response.headers['cache-control'], limits.lifetimes),
352
+ bytes: bytes.byteLength,
353
+ });
354
+ }
355
+ /** Fetched documents by URL, each for its cache lifetime (at most `cimd.maxCached`, oldest out first). */
356
+ export class DocumentCache {
357
+ #entries = new Map();
358
+ #max;
359
+ constructor(max = CIMD_LIMITS_DEFAULT.maxCached) {
360
+ this.#max = max;
361
+ }
362
+ get(url, now) {
363
+ const entry = this.#entries.get(url);
364
+ if (!entry)
365
+ return undefined;
366
+ if (entry.until <= now) {
367
+ this.#entries.delete(url);
368
+ return undefined;
369
+ }
370
+ return entry.document;
371
+ }
372
+ set(url, document, until) {
373
+ this.#entries.delete(url);
374
+ if (this.#entries.size >= this.#max) {
375
+ const oldest = this.#entries.keys().next();
376
+ if (!oldest.done)
377
+ this.#entries.delete(oldest.value);
378
+ }
379
+ this.#entries.set(url, { document, until });
380
+ }
381
+ get size() {
382
+ return this.#entries.size;
383
+ }
384
+ }
@@ -0,0 +1,85 @@
1
+ import { type CimdFetch, CimdRefusal } from './cimd.js';
2
+ import type { OAuthClientInfo, OAuthClientKind } from './extension.js';
3
+ import { type OAuthCimdOptions, type OAuthClientOptions } from './options.js';
4
+ import type { ClientRow } from './store.js';
5
+ /** A client the plugin knows, with what the checks need. */
6
+ export interface KnownClient {
7
+ readonly id: string;
8
+ readonly kind: OAuthClientKind;
9
+ readonly redirectUris: readonly string[];
10
+ /** The configured name of a pre-registered client (trusted), else undefined. */
11
+ readonly configuredName: string | undefined;
12
+ /** The self-declared name (a document's or a registration's), unverified. */
13
+ readonly declaredName: string | undefined;
14
+ /** sha256 hex of the secret of a confidential pre-registered client. */
15
+ readonly secretSha256: string | undefined;
16
+ }
17
+ export type ClientLookup = {
18
+ readonly ok: true;
19
+ readonly client: KnownClient;
20
+ readonly cached?: boolean;
21
+ readonly bytes?: number;
22
+ } | {
23
+ readonly ok: false;
24
+ /** `busy`: too many document fetches at once (globally or from this address). */
25
+ readonly reason: 'unknown' | 'document' | 'busy';
26
+ /** A fixed sentence for the page: never an errno or a part of the document. */
27
+ readonly message: string;
28
+ readonly problem?: string;
29
+ /** The refusal with its cause, for the log only. */
30
+ readonly error?: CimdRefusal;
31
+ /** True when the refusal came from the refusal cache (no fetch). */
32
+ readonly remembered?: boolean;
33
+ };
34
+ /** The dynamic registration ids this server makes: `dcr_` and 22 base64url characters. */
35
+ export declare const DYNAMIC_ID: RegExp;
36
+ export declare function newDynamicId(): string;
37
+ /** The host a client is known by: the document URL's, else the first redirect URI's. */
38
+ export declare function clientHost(client: KnownClient): string;
39
+ /** The default display name (D-0091 §4): host first, the self-declared name after it. */
40
+ export declare function displayName(client: KnownClient, hookName: string | undefined): string;
41
+ export declare function clientInfo(client: KnownClient, hookName: string | undefined): OAuthClientInfo;
42
+ export interface ClientDirectorySettings {
43
+ readonly registered: Readonly<Record<string, OAuthClientOptions>>;
44
+ readonly cimd: OAuthCimdOptions;
45
+ readonly fetch: CimdFetch;
46
+ /** The store lookup of a registered (dynamic) client. */
47
+ readonly findDynamic: (id: string) => Promise<ClientRow | undefined>;
48
+ /** `maxTrackedAddresses`: client addresses whose fetches are counted (default 10000). */
49
+ readonly maxTrackedAddresses?: number;
50
+ }
51
+ /** Defaults of `cimd.refusalCacheMs`, `cimd.maxFetches` and `cimd.maxFetchesPerAddress`. */
52
+ export declare const REFUSAL_CACHE_MS: 300000;
53
+ export declare const MAX_FETCHES: 16;
54
+ export declare const MAX_FETCHES_PER_ADDRESS: 2;
55
+ export declare class ClientDirectory {
56
+ #private;
57
+ constructor(settings: ClientDirectorySettings);
58
+ /** Whether a client_id is a document URL this server would accept the shape of. */
59
+ isDocument(clientId: string): boolean;
60
+ /**
61
+ * The client of an authorization request, with its redirect URIs: a document is fetched (or
62
+ * taken from the cache) and checked here. `address` (the requesting client's) bounds the
63
+ * fetches one address may start at once.
64
+ */
65
+ resolve(clientId: string, address?: string): Promise<ClientLookup>;
66
+ /**
67
+ * A client known without fetching anything (a document client by its URL shape, a dynamic one
68
+ * from the store), for checks after the consent; undefined when unknown.
69
+ */
70
+ known(clientId: string): Promise<KnownClient | undefined>;
71
+ /**
72
+ * Client authentication at /oauth/token and /oauth/revoke (RFC 6749 §2.3): Basic or the body,
73
+ * never both; a confidential client must prove its secret, a public client must not send one.
74
+ * A document client is public and is not fetched here (the code and the grant bind it).
75
+ */
76
+ authenticate(params: Readonly<Record<string, string>>, authorization: string | undefined): Promise<KnownClient>;
77
+ }
78
+ /** A dynamic registration request, checked (RFC 7591; public clients only). */
79
+ export interface Registration {
80
+ /** The declared `client_name`, or '' without one. */
81
+ readonly name: string;
82
+ readonly redirectUris: readonly string[];
83
+ }
84
+ /** Checks a registration body; an RFC 7591 error otherwise. */
85
+ export declare function checkRegistration(body: unknown): Registration;