@dokebi/oauth 0.0.0-stage → 0.1.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/dist/server.js ADDED
@@ -0,0 +1,1516 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { DokebiError } from '@dokebi/core';
3
+ import { diagnostics, http } from '@dokebi/core/libraries';
4
+ import { LruMap } from './bounded.js';
5
+ import { checkRegistration, clientInfo, newDynamicId, } from './clients.js';
6
+ import { OAuthError, OAuthProtocolError, RETRY_AFTER_MS, } from './errors.js';
7
+ import { grantView, newGrantId } from './grants.js';
8
+ import { GrantLease } from './live.js';
9
+ import { LIMITS_DEFAULT, LIVE_DEFAULT } from './options.js';
10
+ import { CHALLENGE, formatScope, hostOf, isLoopbackUri, paramList, paramsProblem, parseScope, queryOf, redirectMatches, resourceKey, sameResource, sha256, strictParams, verifyPkce, withQuery, } from './protocol.js';
11
+ import { authTimeMark, authTimeOf, marksOf, PENDING_MARK, parseMaxAge, parsePrompt, withoutMarks, } from './signin.js';
12
+ /** The map of pending requests that versions before R4X saved (read and cleaned, never written). */
13
+ const PENDING_KEY = 'oauth:pending';
14
+ /** One session key per pending request (`oauth:pending:<id>`): concurrent saves keep both. */
15
+ const PENDING_PREFIX = 'oauth:pending:';
16
+ /** A pending request id (16 random bytes, base64url). */
17
+ const PENDING_ID = /^[A-Za-z0-9_-]{22}$/;
18
+ /** The one-use decision ticket of a consent request (`<prefix><id>`, @dokebi/session setOnce). */
19
+ const TICKET_KEY = 'oauth:decide:';
20
+ /** The shortest ttlMs @dokebi/session setOnce takes. */
21
+ const TICKET_MIN_MS = 1_000;
22
+ /** Default of `pendingMs` (D-0113 §5). */
23
+ export const PENDING_MS = LIMITS_DEFAULT.pendingMs;
24
+ /** Hook result shapes (a decision's kind and binding): contracts, not capacity. */
25
+ const MAX_KIND = 64;
26
+ const MAX_BINDING_BYTES = 4_096;
27
+ const KIND = /^[\x20-\x7e]{1,64}$/;
28
+ /** The shortest lifetimes dokebi-auth `tokens.pair` takes (the pending pair lives `codeMs`, capped by notAfter). */
29
+ const PENDING_ACCESS_MIN_MS = 10_000;
30
+ const PENDING_REFRESH_MIN_MS = 60_000;
31
+ const CHALLENGES = new WeakMap();
32
+ const LOOPBACK_WARNING = 'This request sends its answer to this computer (a loopback address): allow it only if you started the connection from an application on this device.';
33
+ /** The `WWW-Authenticate` an error of a protected route carries (the onError hook writes it). */
34
+ export function challengeOf(error) {
35
+ return error !== null && typeof error === 'object' ? CHALLENGES.get(error) : undefined;
36
+ }
37
+ /** A 400 page of /oauth/authorize that is never redirected. */
38
+ function refused(message, hint) {
39
+ return new OAuthError('AUTHORIZE_REFUSED', message, {
40
+ status: 400,
41
+ hint,
42
+ });
43
+ }
44
+ const CLIENT_HINT = 'Connect again from the application that sent you here; this page does not send you back to an address that was not verified.';
45
+ const SERVER_LIMITS_DEFAULT = Object.freeze({
46
+ pendingMs: LIMITS_DEFAULT.pendingMs,
47
+ maxPending: LIMITS_DEFAULT.maxPending,
48
+ registrationLimit: LIMITS_DEFAULT.registrationLimit,
49
+ registrationWindowMs: LIMITS_DEFAULT.registrationWindowMs,
50
+ maxTrackedAddresses: LIMITS_DEFAULT.maxTrackedAddresses,
51
+ maxCachedGrants: LIMITS_DEFAULT.maxCachedGrants,
52
+ });
53
+ /** The abilities of a scope-less token (a resource without scopes): no ability at all. */
54
+ export const NO_SCOPE = 'dokebi-oauth:none';
55
+ /** OAuth scopes as dokebi-auth token abilities (the option grammar makes them fit). */
56
+ export function abilitiesOf(scopes) {
57
+ return scopes.length ? [...scopes] : [NO_SCOPE];
58
+ }
59
+ /** The Retry-After of a coded store error: its own `data.retryAfterMs`, or the default. */
60
+ function retryAfterOf(error) {
61
+ const own = error.data?.retryAfterMs;
62
+ if (typeof own === 'number' && Number.isFinite(own) && own > 0)
63
+ return own;
64
+ return error.code === 'STORE_FULL' ? RETRY_AFTER_MS.STORE_FULL : RETRY_AFTER_MS.STORE_FAILED;
65
+ }
66
+ /**
67
+ * A backend that failed or is full for now, behind the token, revocation and registration
68
+ * endpoints: this plugin's grant store (STORE_FAILED, STORE_FULL), dokebi-auth's token store behind
69
+ * `tokens.pair`, `peek` and `refresh` (its 503 STORE_FAILED), and the @dokebi/rate-limit policy of
70
+ * `rateLimit` (its 503 UNAVAILABLE, CAPACITY or CLOSED when its Redis is down, full or the app
71
+ * stops). Every coded 503 is the transient `temporarily_unavailable` of RFC 6749 §5.2, never a
72
+ * D-0074 body a client cannot read.
73
+ */
74
+ function transientStoreError(error) {
75
+ if (!(error instanceof DokebiError))
76
+ return false;
77
+ if (error instanceof OAuthError)
78
+ return error.code === 'STORE_FAILED' || error.code === 'STORE_FULL';
79
+ return error.status === 503;
80
+ }
81
+ export class OAuthServer {
82
+ #s;
83
+ #logger;
84
+ #limits;
85
+ /** Registrations per client address (IPv6 by /64), least recently used out first. */
86
+ #registrations;
87
+ #byKey = new Map();
88
+ /** Grants whose user `canDelegate` allowed recently (until when). */
89
+ #delegation;
90
+ /** Consent requests whose decision is running in this process (each is decided once). */
91
+ #deciding = new Set();
92
+ /** The session store answered NOT_SUPPORTED to setOnce (warned once). */
93
+ #ticketsUnsupported = false;
94
+ constructor(settings) {
95
+ this.#s = settings;
96
+ this.#logger = settings.logger;
97
+ this.#limits = { ...SERVER_LIMITS_DEFAULT, ...settings.limits };
98
+ this.#registrations = new LruMap(this.#limits.maxTrackedAddresses);
99
+ this.#delegation = new LruMap(this.#limits.maxCachedGrants);
100
+ for (const resource of settings.resources.values())
101
+ this.#byKey.set(resource.key, resource);
102
+ }
103
+ /**
104
+ * D-0113: hooks run per request, so one failure of a burst (the app's database) is logged in
105
+ * full once per hook, error code and `logRepeatWindowMs`; the rest are counted into a summary.
106
+ */
107
+ #hookFailed(hook, error) {
108
+ const name = error instanceof Error ? error.name : typeof error;
109
+ this.#s.grants.repeats.log('error', 'OAuth extension hook failed', 'OAUTH_HOOK_FAILED', error, { hook }, `${hook}\u0000${diagnostics.errorCode(error, name)}`);
110
+ }
111
+ #debug(message, fields) {
112
+ diagnostics.logDebug(this.#logger, message, fields);
113
+ }
114
+ /** A refusal (debug), with the id of the route that refused (D-0142: `oauth.token`, …). */
115
+ #refused(request, message, fields) {
116
+ diagnostics.logDebug(this.#logger, message, () => {
117
+ // A request made by hand (tests, a caller outside a route) may have no route options.
118
+ const id = request.routeOptions?.config?.id;
119
+ return { ...fields(), routeId: typeof id === 'string' ? id : null };
120
+ });
121
+ }
122
+ /** The one lookup of a resource by a URI a client sent (`resourceKey`). */
123
+ resourceByUri(uri) {
124
+ const key = resourceKey(uri);
125
+ return key === undefined ? undefined : this.#byKey.get(key);
126
+ }
127
+ // ---- hooks ----------------------------------------------------------------------------------
128
+ async #hook(hook, work) {
129
+ try {
130
+ return await work();
131
+ }
132
+ catch (error) {
133
+ if (error instanceof OAuthError && error.code !== 'EXTENSION_REQUIRED')
134
+ throw error;
135
+ this.#hookFailed(hook, error);
136
+ throw new OAuthError('HOOK_FAILED', `The ${hook}() hook failed`, {
137
+ cause: error,
138
+ data: { hook },
139
+ });
140
+ }
141
+ }
142
+ async #clientName(client) {
143
+ const hooks = this.#s.hooks;
144
+ if (!hooks || !this.#s.overridden.has('clientName'))
145
+ return undefined;
146
+ const name = await this.#hook('clientName', () => hooks.clientName(client.id, this.#s.hookContext));
147
+ if (name === undefined)
148
+ return undefined;
149
+ if (typeof name !== 'string' || name.trim() === '' || name.length > 200)
150
+ throw new OAuthError('INVALID_HOOK_RESULT', 'clientName() must return a name or undefined', {
151
+ fix: 'Return a string of 1 to 200 characters, or undefined for the default name, from clientName() in src/infra/oauth/extension.ts.',
152
+ data: { hook: 'clientName' },
153
+ });
154
+ return name.trim();
155
+ }
156
+ async #canDelegate(user, client) {
157
+ const hooks = this.#s.hooks;
158
+ if (!hooks || !this.#s.overridden.has('canDelegate'))
159
+ return true;
160
+ const info = clientInfo(client, await this.#clientName(client));
161
+ const allowed = await this.#hook('canDelegate', () => hooks.canDelegate(user, info, this.#s.hookContext));
162
+ if (typeof allowed !== 'boolean')
163
+ throw new OAuthError('INVALID_HOOK_RESULT', 'canDelegate() must return a boolean', {
164
+ fix: 'Return true or false from canDelegate() in src/infra/oauth/extension.ts.',
165
+ data: { hook: 'canDelegate' },
166
+ });
167
+ return allowed;
168
+ }
169
+ /**
170
+ * The kind and binding a decision may store. They are what the browser posted, so without the
171
+ * `checkDecision` hook a decision that carries either is refused (fail closed); with it, what
172
+ * the hook returns (checked again here) is stored, and `false` refuses the decision.
173
+ */
174
+ async #checkDecision(user, client, scopes, kind, binding) {
175
+ const hooks = this.#s.hooks;
176
+ if (!hooks || !this.#s.overridden.has('checkDecision')) {
177
+ if (kind !== null || binding !== null)
178
+ throw new OAuthError('INVALID_CONSENT', 'The decision carries a kind or binding this app does not accept', { status: 400, hint: 'Allow or deny the connection without extra fields.' });
179
+ return { kind: null, binding: null };
180
+ }
181
+ const info = clientInfo(client, await this.#clientName(client));
182
+ const decision = Object.freeze({
183
+ scopes: Object.freeze([...scopes]),
184
+ kind,
185
+ binding: binding === null ? null : JSON.parse(binding),
186
+ });
187
+ const result = await this.#hook('checkDecision', () => hooks.checkDecision(user, info, decision, this.#s.hookContext));
188
+ if (result === false)
189
+ throw new OAuthError('INVALID_CONSENT', 'The decision was refused', {
190
+ status: 400,
191
+ hint: 'Change the choices on the page, or deny the connection.',
192
+ });
193
+ const value = result;
194
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
195
+ throw new OAuthError('INVALID_HOOK_RESULT', 'checkDecision() must return { kind?, binding? } or false', {
196
+ fix: 'Return the accepted { kind, binding } (null for none), or false to refuse, from checkDecision() in src/infra/oauth/extension.ts.',
197
+ data: { hook: 'checkDecision' },
198
+ });
199
+ const acceptedKind = value.kind ?? null;
200
+ if (acceptedKind !== null && (typeof acceptedKind !== 'string' || !KIND.test(acceptedKind)))
201
+ throw new OAuthError('INVALID_HOOK_RESULT', `checkDecision() returned a kind that is not 1 to ${MAX_KIND} printable characters`, {
202
+ data: { hook: 'checkDecision' },
203
+ });
204
+ let acceptedBinding = null;
205
+ if (value.binding !== undefined && value.binding !== null) {
206
+ acceptedBinding = JSON.stringify(value.binding);
207
+ if (acceptedBinding === undefined ||
208
+ Buffer.byteLength(acceptedBinding, 'utf8') > MAX_BINDING_BYTES)
209
+ throw new OAuthError('INVALID_HOOK_RESULT', `checkDecision() returned a binding that is not JSON of at most ${MAX_BINDING_BYTES} bytes`, {
210
+ data: { hook: 'checkDecision' },
211
+ });
212
+ }
213
+ return { kind: acceptedKind, binding: acceptedBinding };
214
+ }
215
+ #scopeLabel(resource, scope, request) {
216
+ const hooks = this.#s.hooks;
217
+ if (hooks && this.#s.overridden.has('scopeLabel')) {
218
+ let label;
219
+ try {
220
+ label = hooks.scopeLabel(scope, request, this.#s.hookContext);
221
+ }
222
+ catch (error) {
223
+ this.#hookFailed('scopeLabel', error);
224
+ throw new OAuthError('HOOK_FAILED', 'The scopeLabel() hook failed', {
225
+ cause: error,
226
+ data: { hook: 'scopeLabel' },
227
+ });
228
+ }
229
+ if (typeof label === 'string' && label !== '')
230
+ return label;
231
+ if (label !== undefined)
232
+ throw new OAuthError('INVALID_HOOK_RESULT', 'scopeLabel() must return a label or undefined', {
233
+ fix: 'Return a non-empty string, or undefined for the label in options, from scopeLabel() in src/infra/oauth/extension.ts.',
234
+ data: { hook: 'scopeLabel' },
235
+ });
236
+ }
237
+ return Object.hasOwn(resource.scopes, scope) ? resource.scopes[scope] : scope;
238
+ }
239
+ // ---- the session ----------------------------------------------------------------------------
240
+ /** A pending request read back from the session, or undefined for anything else. */
241
+ #pendingOf(value) {
242
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
243
+ return undefined;
244
+ const pending = value;
245
+ return typeof pending.id === 'string' &&
246
+ typeof pending.createdAt === 'number' &&
247
+ typeof pending.expiresAt === 'number'
248
+ ? pending
249
+ : undefined;
250
+ }
251
+ /**
252
+ * Every pending request of the session: one key each (`oauth:pending:<id>`), so two requests
253
+ * saved at once (two tabs, two clients connecting) both stay — a merged save keeps different
254
+ * keys, and the later save wins a key both changed (@dokebi/session, D-0160 §2). Requests saved
255
+ * before (one map under `oauth:pending`) are read too.
256
+ */
257
+ async #pendingAll(session) {
258
+ const list = [];
259
+ for (const key of await session.keys()) {
260
+ if (!key.startsWith(PENDING_PREFIX))
261
+ continue;
262
+ const pending = this.#pendingOf(await session.get(key));
263
+ if (pending)
264
+ list.push(pending);
265
+ }
266
+ const legacy = await session.get(PENDING_KEY);
267
+ if (legacy !== null && typeof legacy === 'object' && !Array.isArray(legacy))
268
+ for (const value of Object.values(legacy)) {
269
+ const pending = this.#pendingOf(value);
270
+ if (pending && !list.some((item) => item.id === pending.id))
271
+ list.push(pending);
272
+ }
273
+ return list;
274
+ }
275
+ /** Removes pending requests by id: their keys, and their entries of the map saved before. */
276
+ async #dropPending(session, ids) {
277
+ if (!ids.length)
278
+ return;
279
+ for (const id of ids)
280
+ await session.delete(`${PENDING_PREFIX}${id}`);
281
+ const legacy = await session.get(PENDING_KEY);
282
+ if (legacy === null || typeof legacy !== 'object' || Array.isArray(legacy))
283
+ return;
284
+ const next = { ...legacy };
285
+ let changed = false;
286
+ for (const id of ids)
287
+ if (Object.hasOwn(next, id)) {
288
+ delete next[id];
289
+ changed = true;
290
+ }
291
+ if (!changed)
292
+ return;
293
+ if (Object.keys(next).length)
294
+ await session.set(PENDING_KEY, next);
295
+ else
296
+ await session.delete(PENDING_KEY);
297
+ }
298
+ async #savePending(session, pending) {
299
+ const now = Date.now();
300
+ const all = await this.#pendingAll(session);
301
+ // The newest maxPending - 1 others stay (`slice(-0)` would keep them all: maxPending 1); the
302
+ // rest and the expired ones go.
303
+ const others = this.#limits.maxPending - 1;
304
+ const sorted = all
305
+ .filter((item) => item.expiresAt > now && item.id !== pending.id)
306
+ .sort((a, b) => a.createdAt - b.createdAt);
307
+ const kept = new Set((others > 0 ? sorted.slice(-others) : []).map((item) => item.id));
308
+ await this.#dropPending(session, all.filter((item) => item.id !== pending.id && !kept.has(item.id)).map((item) => item.id));
309
+ await session.set(`${PENDING_PREFIX}${pending.id}`, pending);
310
+ }
311
+ async #takePending(session, id, remove) {
312
+ const pending = typeof id === 'string' && PENDING_ID.test(id)
313
+ ? (await this.#pendingAll(session)).find((item) => item.id === id)
314
+ : undefined;
315
+ if (remove && pending)
316
+ await this.#dropPending(session, [id]);
317
+ if (!pending || pending.expiresAt <= Date.now())
318
+ throw new OAuthError('CONSENT_EXPIRED', 'This connection request is unknown or expired', {
319
+ status: 400,
320
+ hint: 'Start the connection again from the application; a request lasts 10 minutes and is decided once.',
321
+ });
322
+ return pending;
323
+ }
324
+ /**
325
+ * Sets the decision ticket of a request shown on the consent page (OAUTH-5 across workers):
326
+ * true when the session store keeps one-use values, false when it does not (NOT_SUPPORTED: warn
327
+ * OAUTH_DECIDE_NOT_ATOMIC once, the decision is then guarded in this process only).
328
+ */
329
+ async #setTicket(session, pending) {
330
+ if (this.#ticketsUnsupported || typeof session.setOnce !== 'function')
331
+ return this.#noTickets();
332
+ try {
333
+ await session.setOnce(`${TICKET_KEY}${pending.id}`, true, {
334
+ ttlMs: Math.max(TICKET_MIN_MS, pending.expiresAt - Date.now()),
335
+ });
336
+ return true;
337
+ }
338
+ catch (error) {
339
+ if (error?.code !== 'NOT_SUPPORTED')
340
+ throw error;
341
+ return this.#noTickets(error);
342
+ }
343
+ }
344
+ #noTickets(cause) {
345
+ if (!this.#ticketsUnsupported) {
346
+ this.#ticketsUnsupported = true;
347
+ this.#logger.log('warn', 'The session store keeps no one-use values: a consent decision posted to two workers at once may decide twice', {
348
+ code: 'OAUTH_DECIDE_NOT_ATOMIC',
349
+ ...(cause === undefined ? {} : { error: diagnostics.describeError(cause) }),
350
+ fix: 'Use a @dokebi/session store with setOnce and takeOnce (memory, redis, or an app store that implements them).',
351
+ });
352
+ }
353
+ return false;
354
+ }
355
+ /** Takes the decision ticket; CONSENT_EXPIRED when another request (any worker) took it. */
356
+ async #takeTicket(session, pending) {
357
+ if (pending.ticket !== true || typeof session.takeOnce !== 'function')
358
+ return;
359
+ if ((await session.takeOnce(`${TICKET_KEY}${pending.id}`)) === undefined)
360
+ throw new OAuthError('CONSENT_EXPIRED', 'This connection request was decided already', {
361
+ status: 400,
362
+ hint: 'A request is decided once; start the connection again from the application if needed.',
363
+ });
364
+ }
365
+ #session(request) {
366
+ return this.#s.session(request);
367
+ }
368
+ // ---- answers --------------------------------------------------------------------------------
369
+ /** Sends a browser to another origin; an Inertia request gets 409 + X-Inertia-Location. */
370
+ #redirectOut(request, reply, url) {
371
+ reply.header('cache-control', 'no-store');
372
+ if (request.headers['x-inertia'] !== undefined)
373
+ return reply.code(409).header('x-inertia-location', url).send('');
374
+ return reply.redirect(url, 302);
375
+ }
376
+ #errorRedirect(pending, error, description) {
377
+ return withQuery(pending.redirectUri, {
378
+ error,
379
+ error_description: description,
380
+ state: pending.state ?? undefined,
381
+ iss: this.#s.issuer,
382
+ });
383
+ }
384
+ #sendError(reply, error) {
385
+ reply.header('cache-control', 'no-store').header('pragma', 'no-cache');
386
+ if (error.basic)
387
+ reply.header('www-authenticate', `Basic realm="${this.#s.issuer}"`);
388
+ if (error.retryAfterMs !== undefined)
389
+ reply.header('retry-after', String(Math.max(1, Math.ceil(error.retryAfterMs / 1000))));
390
+ return reply.code(error.status).send({ error: error.error, error_description: error.message });
391
+ }
392
+ // ---- GET /oauth/authorize -------------------------------------------------------------------
393
+ async authorize(request, reply) {
394
+ reply.header('cache-control', 'no-store');
395
+ const parsed = strictParams(paramList(queryOf(request.url)));
396
+ if (!parsed.ok) {
397
+ this.#refused(request, 'OAuth authorize refused', () => ({
398
+ reason: parsed.reason,
399
+ parameter: parsed.name,
400
+ }));
401
+ throw refused(paramsProblem(parsed), CLIENT_HINT);
402
+ }
403
+ const params = parsed.params;
404
+ const names = Object.keys(params);
405
+ let decided;
406
+ if (names.length === 1 && names[0] === 'request')
407
+ decided = await this.#resume(request, params.request);
408
+ else
409
+ decided = await this.#check(request, params);
410
+ if (decided.kind === 'redirect')
411
+ return this.#redirectOut(request, reply, decided.url);
412
+ return this.#consent(request, reply, decided.pending, decided.client);
413
+ }
414
+ async #lookup(clientId, request) {
415
+ const lookup = await this.#s.clients.resolve(clientId, request.ip);
416
+ if (!lookup.ok) {
417
+ // D-0047: the refusal with its cause (an errno, a parse error) goes to the log only.
418
+ if (lookup.reason === 'document' && !lookup.remembered)
419
+ this.#s.grants.repeats.log('warn', 'OAuth client document refused', 'OAUTH_CIMD_REFUSED', lookup.error, { host: hostOf(clientId), problem: lookup.problem }, `${hostOf(clientId)}\u0000${lookup.problem ?? ''}`);
420
+ if (lookup.reason === 'busy')
421
+ this.#s.grants.repeats.log('warn', 'OAuth client document fetches at their limit', 'OAUTH_CIMD_BUSY', undefined, { host: hostOf(clientId) }, 'busy');
422
+ this.#refused(request, 'OAuth authorize refused', () => ({
423
+ reason: lookup.reason,
424
+ problem: lookup.problem,
425
+ client: hostOf(clientId) || undefined,
426
+ }));
427
+ throw refused(`The connection cannot start: ${lookup.message}`, CLIENT_HINT);
428
+ }
429
+ if (lookup.cached === false)
430
+ this.#debug('OAuth client document fetched', () => ({
431
+ host: hostOf(clientId),
432
+ bytes: lookup.bytes,
433
+ }));
434
+ return lookup.client;
435
+ }
436
+ async #check(request, params) {
437
+ // 1. The client. 2. The exact redirect URI. Neither failure redirects.
438
+ const client = await this.#lookup(params.client_id ?? '', request);
439
+ const redirectUri = params.redirect_uri ?? '';
440
+ if (redirectUri === '' ||
441
+ !client.redirectUris.some((uri) => redirectMatches(uri, redirectUri))) {
442
+ this.#refused(request, 'OAuth authorize refused', () => ({
443
+ reason: 'redirect_uri',
444
+ client: client.id,
445
+ }));
446
+ throw refused(redirectUri === ''
447
+ ? 'The request has no redirect_uri'
448
+ : 'The redirect address is not registered for this client', CLIENT_HINT);
449
+ }
450
+ const state = params.state ?? null;
451
+ // Only a pre-registered client gets its errors redirected before the user decided: anybody
452
+ // can publish a client document or register a client, and an error redirect to its URI
453
+ // would make this server an open redirector. The others get the page. The descriptions are
454
+ // fixed sentences: nothing of the request is echoed.
455
+ const redirects = client.kind === 'registered';
456
+ const back = (error, description) => {
457
+ this.#refused(request, 'OAuth authorize refused', () => ({
458
+ reason: error,
459
+ client: client.id,
460
+ redirected: redirects,
461
+ }));
462
+ if (!redirects)
463
+ throw refused(`The authorization request is not valid: ${description}`, CLIENT_HINT);
464
+ return {
465
+ kind: 'redirect',
466
+ url: this.#errorRedirect({ redirectUri, state }, error, description),
467
+ };
468
+ };
469
+ // 3. response_type, PKCE.
470
+ if (params.response_type !== 'code')
471
+ return back('unsupported_response_type', "response_type must be 'code'");
472
+ const challenge = params.code_challenge;
473
+ if (challenge === undefined)
474
+ return back('invalid_request', 'code_challenge is required (PKCE S256)');
475
+ if (params.code_challenge_method !== 'S256')
476
+ return back('invalid_request', "code_challenge_method must be 'S256' (plain is not accepted)");
477
+ if (!CHALLENGE.test(challenge))
478
+ return back('invalid_request', 'code_challenge must be 43 base64url characters (S256)');
479
+ // 4. resource: required, one of ours (the one comparison function).
480
+ if (params.resource === undefined)
481
+ return back('invalid_target', 'resource is required (RFC 8707): name the resource the token is for');
482
+ const resource = this.resourceByUri(params.resource);
483
+ if (!resource)
484
+ return back('invalid_target', 'This server does not know the resource');
485
+ // 5. scope: declared ones only; none asked: the resource's defaults.
486
+ const asked = parseScope(params.scope);
487
+ let scopes;
488
+ if (asked.length === 0) {
489
+ if (Object.keys(resource.scopes).length > 0 && resource.defaultScopes.length === 0)
490
+ return back('invalid_scope', 'scope is required: this resource has no default scopes');
491
+ scopes = [...resource.defaultScopes];
492
+ }
493
+ else {
494
+ const unknown = asked.filter((scope) => !Object.hasOwn(resource.scopes, scope));
495
+ if (unknown.length)
496
+ return back('invalid_scope', 'The request asks for a scope this resource does not declare');
497
+ scopes = asked;
498
+ }
499
+ // 6. prompt and max_age (D-0122): a fresh authentication before the consent when asked.
500
+ const prompt = parsePrompt(params.prompt);
501
+ if (!prompt.ok)
502
+ return back('invalid_request', prompt.description);
503
+ const maxAge = parseMaxAge(params.max_age);
504
+ if (!maxAge.ok)
505
+ return back('invalid_request', maxAge.description);
506
+ const now = Date.now();
507
+ const pending = {
508
+ id: randomBytes(16).toString('base64url'),
509
+ clientId: client.id,
510
+ redirectUri,
511
+ state,
512
+ challenge,
513
+ resource: resource.id,
514
+ scopes,
515
+ createdAt: now,
516
+ expiresAt: now + this.#limits.pendingMs,
517
+ userId: null,
518
+ fresh: prompt.values.has('login'),
519
+ maxAge: maxAge.seconds,
520
+ requestedAt: null,
521
+ authTime: null,
522
+ };
523
+ await this.#savePending(this.#session(request), pending);
524
+ return { kind: 'page', pending, client };
525
+ }
526
+ /** After the login: the pending request again (the client checked again, from the cache). */
527
+ async #resume(request, id) {
528
+ const pending = await this.#takePending(this.#session(request), id, false);
529
+ const client = await this.#lookup(pending.clientId, request);
530
+ if (!client.redirectUris.some((uri) => redirectMatches(uri, pending.redirectUri)))
531
+ throw refused('The redirect address is not registered for this client any more', CLIENT_HINT);
532
+ return { kind: 'page', pending, client };
533
+ }
534
+ /**
535
+ * D-0122, D-0124: asks for a fresh authentication; the pending request remembers when, so the
536
+ * authentication that brings it back is known to be newer. A signed-in browser goes to the
537
+ * application's re-authentication page (dokebi-auth `reauthenticatePath`: the password again,
538
+ * or a social re-confirmation) and stays signed in; without that page, or signed out, it is
539
+ * signed out of the realm and goes to the login page (the D-0122 way).
540
+ */
541
+ async #authenticateAgain(reply, session, auth, pending, client, reason) {
542
+ const back = `${this.#s.paths.authorize}?request=${pending.id}`;
543
+ const page = auth.reauthenticatePath;
544
+ if (page !== undefined && (await auth.user()) !== undefined) {
545
+ const requestedAt = Date.now();
546
+ await this.#savePending(session, { ...pending, fresh: true, requestedAt, authTime: null });
547
+ const target = await auth.reauthenticate(back);
548
+ this.#debug('OAuth authorize: re-authentication first', () => ({
549
+ client: client.id,
550
+ reason,
551
+ }));
552
+ return reply.redirect(target, 303);
553
+ }
554
+ await auth.logout();
555
+ const requestedAt = Date.now();
556
+ await this.#savePending(session, { ...pending, fresh: true, requestedAt, authTime: null });
557
+ await auth.rememberReturnPath(back);
558
+ this.#debug('OAuth authorize: fresh sign-in first', () => ({ client: client.id, reason }));
559
+ return reply.redirect(auth.loginPath, 303);
560
+ }
561
+ #requestAuth(request) {
562
+ return this.#s.auth.of(request).forRealm(this.#s.realm);
563
+ }
564
+ async #consent(request, reply, opened, client) {
565
+ let pending = opened;
566
+ const session = this.#session(request);
567
+ const auth = this.#requestAuth(request);
568
+ // 7. prompt=login (D-0122): a fresh authentication is asked for before anything else, so the
569
+ // one that follows is newer than this request.
570
+ const requestedAt = pending.requestedAt ?? pending.signedOutAt ?? null;
571
+ if (pending.fresh === true && requestedAt === null)
572
+ return this.#authenticateAgain(reply, session, auth, pending, client, 'prompt');
573
+ // 8. The login (the way back is in the session, never in the query).
574
+ const user = await auth.user();
575
+ if (user === undefined) {
576
+ // Reading the login may have ended the whole session (a changed account stamp destroys
577
+ // it): the request is written again, or the sign-in would come back to nothing.
578
+ await this.#savePending(session, pending);
579
+ await auth.rememberReturnPath(`${this.#s.paths.authorize}?request=${pending.id}`);
580
+ this.#debug('OAuth authorize: sign-in first', () => ({ client: client.id }));
581
+ return reply.redirect(auth.loginPath, 303);
582
+ }
583
+ const userId = this.#s.realmApi.idOf(user);
584
+ if (pending.userId !== null && pending.userId !== userId)
585
+ throw new OAuthError('FORBIDDEN', 'This connection request was opened by another account', {
586
+ status: 403,
587
+ hint: 'Sign in with the account that started it, or start the connection again.',
588
+ });
589
+ // 9. The authentication time (D-0124): exactly when this user last authenticated
590
+ // (dokebi-auth `authenticatedAt()`: the sign-in, the one behind a remember cookie, or a later
591
+ // re-authentication), never a guess.
592
+ const at = (await auth.authenticatedAt())?.getTime() ?? null;
593
+ if (pending.fresh === true) {
594
+ // Asked at `requestedAt`: only a newer authentication counts (to the second, the precision
595
+ // of a provider's auth_time). Anything else, a restore from a remember-me cookie included,
596
+ // goes round once more.
597
+ if (at === null || at < Math.floor(requestedAt / 1000) * 1000)
598
+ return this.#authenticateAgain(reply, session, auth, pending, client, 'again');
599
+ pending = { ...pending, fresh: false, authTime: at };
600
+ this.#debug('OAuth authorize: fresh authentication seen', () => ({ client: client.id }));
601
+ }
602
+ else {
603
+ const maxAge = pending.maxAge ?? null;
604
+ if (maxAge !== null && (at === null || Date.now() - at > maxAge * 1000))
605
+ return this.#authenticateAgain(reply, session, auth, pending, client, 'max_age');
606
+ pending = { ...pending, authTime: at };
607
+ }
608
+ // 10. May this account delegate at all?
609
+ if (!(await this.#canDelegate(user, client))) {
610
+ await this.#takePending(session, pending.id, true);
611
+ this.#refused(request, 'OAuth authorize refused', () => ({
612
+ reason: 'canDelegate',
613
+ client: client.id,
614
+ }));
615
+ // The user has not decided anything yet: a client that is not pre-registered gets no
616
+ // redirect (the page says it), as for every error before the decision.
617
+ if (client.kind !== 'registered')
618
+ throw new OAuthError('FORBIDDEN', 'This account cannot connect applications now', {
619
+ status: 403,
620
+ hint: 'Ask the operator of this service about your account.',
621
+ });
622
+ return this.#redirectOut(request, reply, this.#errorRedirect(pending, 'access_denied', 'This account cannot connect applications now'));
623
+ }
624
+ // 11. The pending request, bound to this user, then the application's page.
625
+ const bound = { ...pending, userId, ticket: await this.#setTicket(session, pending) };
626
+ await this.#savePending(session, bound);
627
+ const resource = this.#s.resources.get(pending.resource);
628
+ // D-0124: what this user allowed this client for this resource before (a new grant follows).
629
+ const live = await this.#s.grants.remembered(userId, client.id, resource.id, Date.now());
630
+ // The redirect of this request decides (another registered URI may be remote).
631
+ const loopback = isLoopbackUri(pending.redirectUri);
632
+ const consent = Object.freeze({
633
+ id: pending.id,
634
+ action: this.#s.paths.authorize,
635
+ client: clientInfo(client, await this.#clientName(client)),
636
+ redirectUri: pending.redirectUri,
637
+ redirectHost: hostOf(pending.redirectUri),
638
+ loopback,
639
+ warning: loopback ? LOOPBACK_WARNING : undefined,
640
+ resource: Object.freeze({ id: resource.id, uri: resource.uri, name: resource.name }),
641
+ scopes: Object.freeze(pending.scopes.map((name) => Object.freeze({ name, label: this.#scopeLabel(resource, name, request) }))),
642
+ userId,
643
+ grant: live
644
+ ? Object.freeze({
645
+ id: live.id,
646
+ scopes: Object.freeze([...live.scopes]),
647
+ kind: live.kind,
648
+ binding: grantView(live).binding,
649
+ expiresAt: new Date(live.expiresAt),
650
+ })
651
+ : undefined,
652
+ expiresAt: new Date(pending.expiresAt),
653
+ fields: Object.freeze({
654
+ request: 'request',
655
+ decision: 'decision',
656
+ scope: 'scope',
657
+ kind: 'kind',
658
+ binding: 'binding',
659
+ }),
660
+ });
661
+ reply
662
+ .header('cache-control', 'no-store')
663
+ .header('x-frame-options', 'DENY')
664
+ .header('content-security-policy', "frame-ancestors 'none'")
665
+ .header('referrer-policy', 'no-referrer');
666
+ this.#debug('OAuth consent shown', () => ({
667
+ client: client.id,
668
+ resource: resource.id,
669
+ scopes: pending.scopes,
670
+ grant: live?.id,
671
+ }));
672
+ const hooks = this.#s.hooks;
673
+ const result = await this.#hook('renderConsent', () => hooks.renderConsent(request, reply, consent, this.#s.hookContext));
674
+ if (reply.sent)
675
+ return reply;
676
+ if (result === undefined)
677
+ throw new OAuthError('INVALID_HOOK_RESULT', 'renderConsent() sent nothing', {
678
+ fix: 'Send the page in renderConsent() (reply.type(…).send(html), a view renderer) or return what the route answers, in src/infra/oauth/extension.ts.',
679
+ data: { hook: 'renderConsent' },
680
+ });
681
+ return result;
682
+ }
683
+ /** The grant lifetime of a client: its own `grant.maxDays` (pre-registered only), else the global one. */
684
+ #grantMs(client) {
685
+ if (client.kind !== 'registered')
686
+ return this.#s.grantMs;
687
+ return this.#s.clientGrantMs?.get(client.id) ?? this.#s.grantMs;
688
+ }
689
+ // ---- POST /oauth/authorize (the decision) ---------------------------------------------------
690
+ async decide(request, reply) {
691
+ reply.header('cache-control', 'no-store');
692
+ const body = decisionBody(request.body);
693
+ const session = this.#session(request);
694
+ const pending = await this.#takePending(session, body.request, false);
695
+ const auth = this.#requestAuth(request);
696
+ const user = await auth.user();
697
+ const userId = user === undefined ? undefined : this.#s.realmApi.idOf(user);
698
+ if (user === undefined || pending.userId === null || userId !== pending.userId)
699
+ throw new OAuthError('FORBIDDEN', 'This connection request belongs to another sign-in', {
700
+ status: 403,
701
+ hint: 'Sign in with the account that opened the consent page, or start the connection again.',
702
+ });
703
+ // Decided once: a double-submitted form must not make a grant and a code per submission while
704
+ // the first one awaits the hooks (the session holds the request until it is decided).
705
+ if (this.#deciding.has(pending.id))
706
+ throw new OAuthError('CONSENT_EXPIRED', 'This connection request is being decided already', {
707
+ status: 400,
708
+ hint: 'Wait for the first answer; a request is decided once.',
709
+ });
710
+ this.#deciding.add(pending.id);
711
+ try {
712
+ return await this.#decided(request, reply, session, body, pending, user, userId);
713
+ }
714
+ finally {
715
+ this.#deciding.delete(pending.id);
716
+ }
717
+ }
718
+ async #decided(request, reply, session, body, pending, user, userId) {
719
+ if (body.decision === 'deny') {
720
+ await this.#takeTicket(session, pending);
721
+ await this.#takePending(session, pending.id, true);
722
+ this.#logger.log('info', 'OAuth connection denied', {
723
+ code: 'OAUTH_DENIED',
724
+ realm: this.#s.realm,
725
+ userId,
726
+ clientId: pending.clientId,
727
+ resource: pending.resource,
728
+ });
729
+ return this.#redirectOut(request, reply, this.#errorRedirect(pending, 'access_denied', 'The user denied the connection'));
730
+ }
731
+ const scopes = body.scopes ?? pending.scopes;
732
+ const wider = scopes.filter((scope) => !pending.scopes.includes(scope));
733
+ if (wider.length)
734
+ throw new OAuthError('INVALID_CONSENT', 'The decision allows scopes that were not requested', {
735
+ status: 400,
736
+ hint: 'Allow only scopes of the request.',
737
+ details: { scopes: wider },
738
+ });
739
+ if (scopes.length === 0 && pending.scopes.length > 0)
740
+ throw new OAuthError('INVALID_CONSENT', 'The decision allows no scope', {
741
+ status: 400,
742
+ hint: 'Allow at least one scope, or deny the connection.',
743
+ });
744
+ const client = await this.#lookup(pending.clientId, request);
745
+ // kind and binding come from the browser: only checkDecision may accept them.
746
+ const accepted = await this.#checkDecision(user, client, scopes, body.kind, body.binding);
747
+ // Decided once, on any worker: the ticket is taken in one store step (a refused decision
748
+ // above keeps it, so the page can be posted again correctly).
749
+ await this.#takeTicket(session, pending);
750
+ await this.#takePending(session, pending.id, true);
751
+ if (!(await this.#canDelegate(user, client)))
752
+ return this.#redirectOut(request, reply, this.#errorRedirect(pending, 'access_denied', 'This account cannot connect applications now'));
753
+ const name = clientInfo(client, await this.#clientName(client)).name;
754
+ const now = Date.now();
755
+ const grants = this.#s.grants;
756
+ // D-0124: every authorization is its own grant (and its exchange its own token family), so
757
+ // a second device never shares the first one's tokens; the bound per user and client makes
758
+ // room first.
759
+ await grants.makeRoom(user, userId, client.id, now, this.#s.codeMs);
760
+ const grant = {
761
+ id: newGrantId(),
762
+ realm: this.#s.realm,
763
+ userId,
764
+ clientId: client.id,
765
+ resource: pending.resource,
766
+ createdAt: now,
767
+ expiresAt: now + this.#grantMs(client),
768
+ lastUsedAt: null,
769
+ revokedAt: null,
770
+ clientName: name,
771
+ scopes,
772
+ ...accepted,
773
+ };
774
+ await grants.call('insertGrant', () => grants.store.insertGrant(grant));
775
+ // The pending pair: the grant's token family has a live token from the consent until its code
776
+ // expires, so the grant is listed (and can be revoked) before the client exchanged the code,
777
+ // and an account-wide invalidation in that window (a new stamp, tokens.revokeAll, an inactive
778
+ // account) ends the code as it ends tokens. Its values never leave this function.
779
+ await this.#s.realmApi.tokens.pair(user, {
780
+ family: grant.id,
781
+ audience: pending.resource,
782
+ accessMs: Math.max(PENDING_ACCESS_MIN_MS, this.#s.codeMs),
783
+ refreshMs: Math.max(PENDING_REFRESH_MIN_MS, this.#s.codeMs),
784
+ notAfter: now + this.#s.codeMs,
785
+ abilities: [PENDING_MARK],
786
+ });
787
+ const code = randomBytes(32).toString('base64url');
788
+ const row = {
789
+ hash: sha256(code),
790
+ grantId: grant.id,
791
+ realm: this.#s.realm,
792
+ userId,
793
+ clientId: client.id,
794
+ redirectUri: pending.redirectUri,
795
+ challenge: pending.challenge,
796
+ resource: pending.resource,
797
+ // D-0122, D-0124: the authentication time rides with the code to the tokens (signin.ts).
798
+ scopes: [
799
+ ...scopes,
800
+ ...((pending.authTime ?? null) === null ? [] : [authTimeMark(pending.authTime)]),
801
+ PENDING_MARK,
802
+ ],
803
+ createdAt: now,
804
+ expiresAt: now + this.#s.codeMs,
805
+ usedAt: null,
806
+ };
807
+ await grants.call('insertCode', () => grants.store.insertCode(row));
808
+ this.#logger.log('info', 'OAuth connection allowed', {
809
+ code: 'OAUTH_GRANTED',
810
+ realm: this.#s.realm,
811
+ userId,
812
+ clientId: client.id,
813
+ grant: grant.id,
814
+ resource: pending.resource,
815
+ scopes,
816
+ });
817
+ return this.#redirectOut(request, reply, withQuery(pending.redirectUri, {
818
+ code,
819
+ state: pending.state ?? undefined,
820
+ iss: this.#s.issuer,
821
+ }));
822
+ }
823
+ // ---- POST /oauth/token ----------------------------------------------------------------------
824
+ #form(request) {
825
+ const type = String(request.headers['content-type'] ?? '').toLowerCase();
826
+ const list = formList(request.body);
827
+ if (!type.startsWith('application/x-www-form-urlencoded') || list === undefined)
828
+ throw new OAuthProtocolError('invalid_request', 'The body must be application/x-www-form-urlencoded');
829
+ const parsed = strictParams(list);
830
+ if (!parsed.ok)
831
+ throw new OAuthProtocolError('invalid_request', paramsProblem(parsed));
832
+ return parsed.params;
833
+ }
834
+ async token(request, reply) {
835
+ reply.header('cache-control', 'no-store').header('pragma', 'no-cache');
836
+ let grantType;
837
+ try {
838
+ const params = this.#form(request);
839
+ grantType = params.grant_type;
840
+ const client = await this.#s.clients.authenticate(params, request.headers.authorization);
841
+ if (this.#s.limiter) {
842
+ const credential = params.code ?? params.refresh_token ?? '';
843
+ const decision = await this.#s.limiter.consume(`${client.id}\u0000${sha256(credential).slice(0, 22)}`);
844
+ if (!decision.allowed) {
845
+ reply.header('retry-after', String(Math.max(1, Math.ceil(decision.retryAfterMs / 1000))));
846
+ throw new OAuthProtocolError('invalid_request', 'Too many token requests; try again later', {
847
+ status: 429,
848
+ });
849
+ }
850
+ }
851
+ let body;
852
+ if (grantType === 'authorization_code')
853
+ body = await this.#exchangeCode(params, client);
854
+ else if (grantType === 'refresh_token')
855
+ body = await this.#exchangeRefresh(params, client);
856
+ else
857
+ throw new OAuthProtocolError('unsupported_grant_type', 'grant_type must be authorization_code or refresh_token');
858
+ if (client.kind === 'dynamic')
859
+ this.#touchClient(client.id);
860
+ return reply.code(200).send(body);
861
+ }
862
+ catch (error) {
863
+ const transient = this.#transient(reply, error);
864
+ if (transient)
865
+ return transient;
866
+ if (!(error instanceof OAuthProtocolError))
867
+ throw error;
868
+ this.#refused(request, 'OAuth token refused', () => ({
869
+ grantType: grantType ?? null,
870
+ error: error.error,
871
+ reason: error.message,
872
+ }));
873
+ return this.#sendError(reply, error);
874
+ }
875
+ }
876
+ /**
877
+ * A store that failed or is full for now, at an endpoint whose errors are RFC bodies (token,
878
+ * revocation, registration): RFC 6749 §5.2 `temporarily_unavailable` with the Retry-After of the
879
+ * coded error (D-0109 §7), its cause kept. dokebi-auth's token store and the rate limiter count
880
+ * too: their outage is as transient as ours. Undefined for any other error.
881
+ */
882
+ #transient(reply, error) {
883
+ if (!transientStoreError(error))
884
+ return undefined;
885
+ return this.#sendError(reply, new OAuthProtocolError('temporarily_unavailable', 'The server cannot answer now; try again', {
886
+ status: 503,
887
+ retryAfterMs: retryAfterOf(error),
888
+ cause: error,
889
+ }));
890
+ }
891
+ #touchClient(id) {
892
+ const store = this.#s.grants.store;
893
+ store.touchClient(id, Date.now()).then(undefined, (error) => this.#s.grants.repeats.log('error', 'OAuth client last use not written', 'OAUTH_TOUCH_FAILED', error, {
894
+ store: store.name,
895
+ }));
896
+ }
897
+ #tokenBody(pair, scopes) {
898
+ return {
899
+ access_token: pair.accessToken,
900
+ token_type: 'Bearer',
901
+ expires_in: pair.expiresIn,
902
+ refresh_token: pair.refreshToken,
903
+ ...(scopes.length ? { scope: formatScope(scopes) } : {}),
904
+ };
905
+ }
906
+ async #exchangeCode(params, client) {
907
+ const { code, code_verifier: verifier, redirect_uri: redirectUri } = params;
908
+ if (code === undefined || verifier === undefined || redirectUri === undefined)
909
+ throw new OAuthProtocolError('invalid_request', 'code, code_verifier and redirect_uri are required');
910
+ const grants = this.#s.grants;
911
+ const now = Date.now();
912
+ const hash = sha256(code);
913
+ // Read first: an attempt whose client, redirect URI, verifier or resource does not match is
914
+ // refused without using the code (a stranger must not burn it); only a matching second use
915
+ // is a replay.
916
+ const found = await grants.call('findCode', () => grants.store.findCode(hash));
917
+ if (!found)
918
+ throw new OAuthProtocolError('invalid_grant', 'The authorization code is unknown');
919
+ if (found.clientId !== client.id)
920
+ throw new OAuthProtocolError('invalid_grant', 'The authorization code belongs to another client');
921
+ if (found.redirectUri !== redirectUri)
922
+ throw new OAuthProtocolError('invalid_grant', 'redirect_uri differs from the authorization request');
923
+ if (!verifyPkce(verifier, found.challenge))
924
+ throw new OAuthProtocolError('invalid_grant', 'code_verifier does not match (PKCE S256)');
925
+ const resource = this.#s.resources.get(found.resource);
926
+ if (!resource)
927
+ throw new OAuthProtocolError('invalid_grant', 'The resource of the code is gone');
928
+ if (params.resource !== undefined && !sameResource(params.resource, resource.uri))
929
+ throw new OAuthProtocolError('invalid_target', 'resource differs from the authorization request');
930
+ const consumed = found.usedAt === null
931
+ ? await grants.call('consumeCode', () => grants.store.consumeCode(hash, now))
932
+ : { row: found, first: false };
933
+ if (!consumed)
934
+ throw new OAuthProtocolError('invalid_grant', 'The authorization code is unknown');
935
+ const row = consumed.row;
936
+ if (!consumed.first) {
937
+ // A matching second use of a code is the one sign that it leaked: what its first use
938
+ // issued goes.
939
+ const grant = await grants.find(row.grantId);
940
+ if (grant)
941
+ await grants.revokeRow(grant, 'code-reused');
942
+ else
943
+ await this.#s.realmApi.tokens.revokeFamily(row.grantId);
944
+ grants.repeats.log('warn', 'OAuth authorization code used twice: its grant is revoked', 'OAUTH_CODE_REUSED', undefined, { realm: row.realm, userId: row.userId, clientId: row.clientId, grant: row.grantId }, row.grantId);
945
+ throw new OAuthProtocolError('invalid_grant', 'The authorization code was used already; the connection it made is revoked');
946
+ }
947
+ if (row.expiresAt <= now)
948
+ throw new OAuthProtocolError('invalid_grant', 'The authorization code expired');
949
+ const grant = await grants.find(row.grantId);
950
+ if (!grant || grant.revokedAt !== null || grant.expiresAt <= now)
951
+ throw new OAuthProtocolError('invalid_grant', 'The connection was revoked or expired');
952
+ // The user is read again: an account suspended since the consent gets no token.
953
+ const user = await this.#s.realmApi.findById(row.userId);
954
+ if (user === undefined)
955
+ throw new OAuthProtocolError('invalid_grant', 'The account is gone');
956
+ if (!(await this.#canDelegate(user, client)))
957
+ throw new OAuthProtocolError('invalid_grant', 'This account cannot connect applications now');
958
+ // The pending pair of the consent must still be live for this user: a revoked grant, a new
959
+ // stamp (a password change, "log out other devices"), tokens.revokeAll or an inactive account
960
+ // since the consent ends the code here, not only the tokens it would give.
961
+ if (row.scopes.includes(PENDING_MARK) &&
962
+ !(await this.#s.realmApi.tokens.list(user)).some((one) => one.family === grant.id))
963
+ throw new OAuthProtocolError('invalid_grant', 'The connection was revoked, or the account changed, since the consent');
964
+ const scopes = withoutMarks(row.scopes);
965
+ const pair = await this.#s.realmApi.tokens.pair(user, {
966
+ family: grant.id,
967
+ audience: resource.id,
968
+ accessMs: this.#s.accessMs,
969
+ refreshMs: this.#s.refreshMs,
970
+ notAfter: grant.expiresAt,
971
+ abilities: [...abilitiesOf(scopes), ...marksOf(row.scopes)],
972
+ });
973
+ // A replay of the code between the consumption and the insert revoked the grant meanwhile:
974
+ // the new tokens go too.
975
+ const after = await grants.find(grant.id);
976
+ if (!after || after.revokedAt !== null) {
977
+ await this.#s.realmApi.tokens.revokeFamily(grant.id);
978
+ throw new OAuthProtocolError('invalid_grant', 'The connection was revoked');
979
+ }
980
+ grants.forget(grant.id);
981
+ grants.touch(after, now);
982
+ this.#debug('OAuth tokens issued', () => ({
983
+ grantType: 'authorization_code',
984
+ grant: grant.id,
985
+ clientId: client.id,
986
+ }));
987
+ return this.#tokenBody(pair, scopes);
988
+ }
989
+ async #exchangeRefresh(params, client) {
990
+ const presented = params.refresh_token;
991
+ if (presented === undefined)
992
+ throw new OAuthProtocolError('invalid_request', 'refresh_token is required');
993
+ const tokens = this.#s.realmApi.tokens;
994
+ const grants = this.#s.grants;
995
+ // Looked at before it is used: a token of another client is refused and keeps its family.
996
+ const peeked = await tokens.peek(presented);
997
+ if (peeked?.kind !== 'refresh' || peeked.audience === null || peeked.family === null)
998
+ throw new OAuthProtocolError('invalid_grant', 'The refresh token is not valid');
999
+ const resource = this.#s.resources.get(peeked.audience);
1000
+ const grant = await grants.find(peeked.family);
1001
+ if (!resource || !grant || grant.realm !== this.#s.realm)
1002
+ throw new OAuthProtocolError('invalid_grant', 'The refresh token is not valid');
1003
+ if (grant.clientId !== client.id)
1004
+ throw new OAuthProtocolError('invalid_grant', 'The refresh token belongs to another client');
1005
+ const now = Date.now();
1006
+ if (grant.revokedAt !== null || grant.expiresAt <= now)
1007
+ throw new OAuthProtocolError('invalid_grant', 'The connection was revoked or expired; connect again');
1008
+ if (params.resource !== undefined && !sameResource(params.resource, resource.uri))
1009
+ throw new OAuthProtocolError('invalid_target', 'resource differs from the token');
1010
+ // Narrowing (RFC 6749 §6): the new access token gets the asked subset (default: the grant's
1011
+ // scopes the refresh token holds); the new refresh token keeps the refresh token's.
1012
+ const held = peeked.abilities ?? [];
1013
+ const asked = parseScope(params.scope);
1014
+ if (asked.some((scope) => !grant.scopes.includes(scope) || !held.includes(scope)))
1015
+ throw new OAuthProtocolError('invalid_scope', 'scope asks for more than was granted');
1016
+ const scopes = asked.length ? asked : grant.scopes.filter((scope) => held.includes(scope));
1017
+ // The account is read again: one that may not delegate any more loses the grant.
1018
+ const user = await this.#s.realmApi.findById(grant.userId);
1019
+ if (user === undefined || !(await this.#canDelegate(user, client))) {
1020
+ await grants.revokeRow(grant, user === undefined ? 'user-gone' : 'cannot-delegate');
1021
+ throw new OAuthProtocolError('invalid_grant', 'This account cannot connect applications now');
1022
+ }
1023
+ let pair;
1024
+ try {
1025
+ pair = await tokens.refresh(presented, {
1026
+ audience: resource.id,
1027
+ accessMs: this.#s.accessMs,
1028
+ refreshMs: this.#s.refreshMs,
1029
+ // The sign-in time of the chain stays with every token of it (D-0122).
1030
+ accessAbilities: [...abilitiesOf(scopes), ...marksOf(held)],
1031
+ });
1032
+ }
1033
+ catch (error) {
1034
+ const code = error?.code;
1035
+ if (code === 'INVALID_ARGUMENT')
1036
+ throw new OAuthProtocolError('invalid_scope', 'scope asks for more than was granted');
1037
+ if (code !== 'UNAUTHENTICATED')
1038
+ throw error;
1039
+ if (peeked.used) {
1040
+ // dokebi-auth revoked the family (TOKEN_REUSED); the grant goes with it.
1041
+ await grants.revokeRow(grant, 'refresh-reused');
1042
+ grants.repeats.log('warn', 'OAuth refresh token used twice: its grant is revoked', 'OAUTH_REFRESH_REUSED', undefined, { realm: grant.realm, userId: grant.userId, clientId: client.id, grant: grant.id }, grant.id);
1043
+ }
1044
+ throw new OAuthProtocolError('invalid_grant', 'The refresh token cannot be used; connect again');
1045
+ }
1046
+ grants.touch(grant, now);
1047
+ this.#debug('OAuth tokens issued', () => ({
1048
+ grantType: 'refresh_token',
1049
+ grant: grant.id,
1050
+ clientId: client.id,
1051
+ }));
1052
+ return this.#tokenBody(pair, scopes);
1053
+ }
1054
+ // ---- POST /oauth/revoke (RFC 7009) ----------------------------------------------------------
1055
+ async revoke(request, reply) {
1056
+ reply.header('cache-control', 'no-store').header('pragma', 'no-cache');
1057
+ try {
1058
+ const params = this.#form(request);
1059
+ const client = await this.#s.clients.authenticate(params, request.headers.authorization);
1060
+ const token = params.token;
1061
+ if (token === undefined)
1062
+ throw new OAuthProtocolError('invalid_request', 'token is required');
1063
+ const peeked = await this.#s.realmApi.tokens.peek(token);
1064
+ let revoked = false;
1065
+ if (peeked && peeked.audience !== null && peeked.family !== null) {
1066
+ const grant = await this.#s.grants.find(peeked.family);
1067
+ // Another client's token, or a token of nobody: the same 200, nothing revoked (§2.2).
1068
+ if (grant && grant.clientId === client.id && grant.realm === this.#s.realm) {
1069
+ await this.#s.grants.revokeRow(grant, 'client');
1070
+ revoked = true;
1071
+ }
1072
+ }
1073
+ this.#debug('OAuth revocation', () => ({ clientId: client.id, revoked }));
1074
+ return reply.code(200).send();
1075
+ }
1076
+ catch (error) {
1077
+ // RFC 7009 §2.2.1: a revocation the server cannot do now is a 503 the client retries.
1078
+ const transient = this.#transient(reply, error);
1079
+ if (transient)
1080
+ return transient;
1081
+ if (!(error instanceof OAuthProtocolError))
1082
+ throw error;
1083
+ this.#refused(request, 'OAuth revocation refused', () => ({
1084
+ error: error.error,
1085
+ reason: error.message,
1086
+ }));
1087
+ return this.#sendError(reply, error);
1088
+ }
1089
+ }
1090
+ // ---- POST /oauth/register (RFC 7591) --------------------------------------------------------
1091
+ async register(request, reply) {
1092
+ reply.header('cache-control', 'no-store').header('pragma', 'no-cache');
1093
+ if (this.#s.registration !== 'open')
1094
+ return reply.code(404).send({
1095
+ error: 'invalid_request',
1096
+ error_description: 'Dynamic client registration is closed on this server',
1097
+ });
1098
+ try {
1099
+ const type = String(request.headers['content-type'] ?? '').toLowerCase();
1100
+ if (!type.startsWith('application/json'))
1101
+ throw new OAuthProtocolError('invalid_client_metadata', 'The body must be application/json');
1102
+ if (request.body === BAD_JSON)
1103
+ throw new OAuthProtocolError('invalid_client_metadata', 'The body is not valid JSON');
1104
+ const now = Date.now();
1105
+ const address = http.addressKey(request.ip);
1106
+ const bucket = this.#registrations.get(address);
1107
+ if (bucket && bucket.until > now && bucket.count >= this.#limits.registrationLimit) {
1108
+ reply.header('retry-after', String(Math.ceil((bucket.until - now) / 1000)));
1109
+ throw new OAuthProtocolError('invalid_request', 'Too many registrations from this address; try again later', {
1110
+ status: 429,
1111
+ });
1112
+ }
1113
+ const registration = checkRegistration(request.body);
1114
+ if (!bucket || bucket.until <= now)
1115
+ this.#registrations.set(address, {
1116
+ count: 1,
1117
+ until: now + this.#limits.registrationWindowMs,
1118
+ });
1119
+ else
1120
+ bucket.count++;
1121
+ const row = {
1122
+ id: newDynamicId(),
1123
+ name: registration.name,
1124
+ redirectUris: registration.redirectUris,
1125
+ createdAt: now,
1126
+ lastUsedAt: now,
1127
+ };
1128
+ await this.#s.grants.call('insertClient', () => this.#s.grants.store.insertClient(row));
1129
+ this.#logger.log('info', 'OAuth client registered', {
1130
+ code: 'OAUTH_CLIENT_REGISTERED',
1131
+ clientId: row.id,
1132
+ redirectHosts: [...new Set(row.redirectUris.map(hostOf))],
1133
+ });
1134
+ return reply.code(201).send({
1135
+ client_id: row.id,
1136
+ client_id_issued_at: Math.floor(now / 1000),
1137
+ ...(row.name ? { client_name: row.name } : {}),
1138
+ redirect_uris: [...row.redirectUris],
1139
+ grant_types: ['authorization_code', 'refresh_token'],
1140
+ response_types: ['code'],
1141
+ token_endpoint_auth_method: 'none',
1142
+ });
1143
+ }
1144
+ catch (error) {
1145
+ const transient = this.#transient(reply, error);
1146
+ if (transient)
1147
+ return transient;
1148
+ if (!(error instanceof OAuthProtocolError))
1149
+ throw error;
1150
+ this.#refused(request, 'OAuth registration refused', () => ({
1151
+ error: error.error,
1152
+ reason: error.message,
1153
+ }));
1154
+ return this.#sendError(reply, error);
1155
+ }
1156
+ }
1157
+ // ---- metadata -------------------------------------------------------------------------------
1158
+ /** RFC 8414, derived from the options only. */
1159
+ serverMetadata() {
1160
+ const issuer = this.#s.issuer;
1161
+ const paths = this.#s.paths;
1162
+ const scopes = new Set();
1163
+ for (const resource of this.#s.resources.values())
1164
+ for (const scope of Object.keys(resource.scopes))
1165
+ scopes.add(scope);
1166
+ const methods = ['none', 'client_secret_basic', 'client_secret_post'];
1167
+ return {
1168
+ issuer,
1169
+ authorization_endpoint: `${issuer}${paths.authorize}`,
1170
+ token_endpoint: `${issuer}${paths.token}`,
1171
+ revocation_endpoint: `${issuer}${paths.revoke}`,
1172
+ ...(this.#s.registration === 'open'
1173
+ ? { registration_endpoint: `${issuer}${paths.register}` }
1174
+ : {}),
1175
+ response_types_supported: ['code'],
1176
+ response_modes_supported: ['query'],
1177
+ grant_types_supported: ['authorization_code', 'refresh_token'],
1178
+ code_challenge_methods_supported: ['S256'],
1179
+ token_endpoint_auth_methods_supported: methods,
1180
+ revocation_endpoint_auth_methods_supported: methods,
1181
+ ...(scopes.size ? { scopes_supported: [...scopes].sort() } : {}),
1182
+ ...(this.#s.cimd ? { client_id_metadata_document_supported: true } : {}),
1183
+ authorization_response_iss_parameter_supported: true,
1184
+ };
1185
+ }
1186
+ /** RFC 9728 for one resource: `resource` exactly as configured. */
1187
+ resourceMetadata(resource) {
1188
+ return {
1189
+ resource: resource.uri,
1190
+ authorization_servers: [this.#s.issuer],
1191
+ ...(Object.keys(resource.scopes).length
1192
+ ? { scopes_supported: Object.keys(resource.scopes) }
1193
+ : {}),
1194
+ bearer_methods_supported: ['header'],
1195
+ resource_name: resource.name,
1196
+ };
1197
+ }
1198
+ /** The resource whose metadata lives at a path, or undefined. */
1199
+ resourceAtPath(path) {
1200
+ for (const resource of this.#s.resources.values())
1201
+ if (resource.metadataPath === path)
1202
+ return resource;
1203
+ return undefined;
1204
+ }
1205
+ /** The informative 404 of an unknown metadata path: where this app's metadata is. */
1206
+ metadataNotFound() {
1207
+ return {
1208
+ error: 'not_found',
1209
+ error_description: 'No protected resource of this server has its metadata at this path',
1210
+ resource_metadata: [...this.#s.resources.values()].map((resource) => resource.metadataUrl),
1211
+ };
1212
+ }
1213
+ // ---- protected routes -----------------------------------------------------------------------
1214
+ #challenge(resource, settings) {
1215
+ const parts = [`resource_metadata="${resource.metadataUrl}"`];
1216
+ if (settings.description)
1217
+ parts.unshift(`error_description="${settings.description}"`);
1218
+ if (settings.error)
1219
+ parts.unshift(`error="${settings.error}"`);
1220
+ if (settings.scopes.length)
1221
+ parts.push(`scope="${formatScope(settings.scopes)}"`);
1222
+ if (settings.maxAge !== undefined)
1223
+ parts.push(`max_age="${settings.maxAge}"`);
1224
+ return `Bearer ${parts.join(', ')}`;
1225
+ }
1226
+ #unauthenticated(resource, presented, scopes) {
1227
+ const error = new OAuthError('UNAUTHENTICATED', 'The access token is missing or not valid for this resource', {
1228
+ status: 401,
1229
+ hint: 'Connect again to get a token for this resource.',
1230
+ });
1231
+ CHALLENGES.set(error, this.#challenge(resource, { ...(presented ? { error: 'invalid_token' } : {}), scopes }));
1232
+ return error;
1233
+ }
1234
+ /**
1235
+ * The check of a protected route: a Bearer token of this resource's audience (dokebi-auth),
1236
+ * its user still valid (stamp, active), its grant live (not revoked, not expired; read per
1237
+ * request with the short `grantCacheMs` cache) and holding `scopes`.
1238
+ */
1239
+ async authenticate(request, resourceId, needed, maxAge = null) {
1240
+ const resource = this.#s.resources.get(resourceId);
1241
+ if (!resource)
1242
+ throw new OAuthError('INVALID_ARGUMENT', `There is no resource ${resourceId}`, {
1243
+ fix: `Use one of the resources of options.dokebi-oauth.resources: ${[...this.#s.resources.keys()].join(', ')}.`,
1244
+ });
1245
+ const challengeScopes = needed.length ? needed : resource.defaultScopes;
1246
+ const auth = this.#s.auth.of(request, { audience: resource.id, realm: this.#s.realm });
1247
+ const user = await auth.user();
1248
+ if (user === undefined) {
1249
+ this.#refused(request, 'OAuth protected route refused', () => ({
1250
+ resource: resource.id,
1251
+ reason: auth.bearer === 'invalid' ? 'token' : 'missing',
1252
+ }));
1253
+ throw this.#unauthenticated(resource, auth.bearer === 'invalid', challengeScopes);
1254
+ }
1255
+ const family = auth.token?.family ?? null;
1256
+ const now = Date.now();
1257
+ const row = family === null ? undefined : await this.#s.grants.cached(family, now);
1258
+ const reason = row === undefined
1259
+ ? 'grant-missing'
1260
+ : row.realm !== this.#s.realm || row.resource !== resource.id
1261
+ ? 'grant-resource'
1262
+ : row.revokedAt !== null
1263
+ ? 'grant-revoked'
1264
+ : row.expiresAt <= now
1265
+ ? 'grant-expired'
1266
+ : undefined;
1267
+ if (reason !== undefined || row === undefined) {
1268
+ this.#refused(request, 'OAuth protected route refused', () => ({
1269
+ resource: resource.id,
1270
+ reason,
1271
+ }));
1272
+ throw this.#unauthenticated(resource, true, challengeScopes);
1273
+ }
1274
+ if (!(await this.#delegates(row, user, now))) {
1275
+ this.#refused(request, 'OAuth protected route refused', () => ({
1276
+ resource: resource.id,
1277
+ reason: 'cannot-delegate',
1278
+ }));
1279
+ throw this.#unauthenticated(resource, true, challengeScopes);
1280
+ }
1281
+ // A scope must be in the grant and in this access token (a refresh may have narrowed it).
1282
+ const abilities = auth.token?.abilities ?? [];
1283
+ const scopes = row.scopes.filter((scope) => abilities.includes(scope));
1284
+ const missing = needed.filter((scope) => !scopes.includes(scope));
1285
+ if (missing.length) {
1286
+ this.#refused(request, 'OAuth protected route refused', () => ({
1287
+ resource: resource.id,
1288
+ reason: 'scope',
1289
+ missing,
1290
+ }));
1291
+ const error = new OAuthError('INSUFFICIENT_SCOPE', 'The grant does not allow this', {
1292
+ status: 403,
1293
+ hint: 'Connect again and allow the needed scopes.',
1294
+ details: { scopes: missing },
1295
+ });
1296
+ CHALLENGES.set(error, this.#challenge(resource, { error: 'insufficient_scope', scopes: needed }));
1297
+ throw error;
1298
+ }
1299
+ // RFC 9470: a route that needs a recent sign-in (D-0122).
1300
+ const authTime = authTimeOf(abilities);
1301
+ if (maxAge !== null && (authTime === null || now - authTime > maxAge * 1000)) {
1302
+ this.#refused(request, 'OAuth protected route refused', () => ({
1303
+ resource: resource.id,
1304
+ reason: authTime === null ? 'auth-time-unknown' : 'auth-time-old',
1305
+ maxAge,
1306
+ }));
1307
+ const error = new OAuthError('INSUFFICIENT_USER_AUTHENTICATION', 'A more recent sign-in is required', {
1308
+ status: 401,
1309
+ hint: 'Sign in again in the browser (authorize with max_age or prompt=login).',
1310
+ details: { maxAge },
1311
+ });
1312
+ CHALLENGES.set(error, this.#challenge(resource, {
1313
+ error: 'insufficient_user_authentication',
1314
+ description: 'A more recent sign-in is required',
1315
+ scopes: challengeScopes,
1316
+ maxAge,
1317
+ }));
1318
+ throw error;
1319
+ }
1320
+ this.#s.grants.touch(row, now);
1321
+ return Object.freeze({
1322
+ grant: grantView(row),
1323
+ resource: resource.id,
1324
+ scopes: Object.freeze(scopes),
1325
+ authTime: authTime === null ? null : new Date(authTime),
1326
+ });
1327
+ }
1328
+ /**
1329
+ * D-0122, D-0124: the live authorization of a connection this request opens with its access
1330
+ * token (the request passed `authenticate` first). dokebi-auth's lease of the Bearer request
1331
+ * (the token row, its user and the stamp) with the grant and `canDelegate` in the same check:
1332
+ * the token's expiry ends it at that instant, a revocation in this process at once, anything
1333
+ * else (an account change too) within `live.maxAgeMs`.
1334
+ */
1335
+ async live(request, slot) {
1336
+ const resource = slot === undefined ? undefined : this.#s.resources.get(slot.resource);
1337
+ const auth = resource === undefined
1338
+ ? undefined
1339
+ : this.#s.auth.of(request, { audience: resource.id, realm: this.#s.realm });
1340
+ const token = auth?.token;
1341
+ if (!slot || !auth || !resource || !token || token.family !== slot.grant.id)
1342
+ throw new OAuthError('INVALID_ARGUMENT', 'live() needs a request that passed the OAuth check with a Bearer access token', {
1343
+ fix: 'Call await oauth.authenticate(request, { resource }) first (or use a config.oauth route), then oauth.live(request), in the SSE or WebSocket authenticate hook.',
1344
+ });
1345
+ const started = Date.now();
1346
+ const grantId = slot.grant.id;
1347
+ const userId = slot.grant.userId;
1348
+ const grants = this.#s.grants;
1349
+ const timing = this.#s.liveTiming ?? LIVE_DEFAULT;
1350
+ const inner = await auth.live({
1351
+ maxAgeMs: timing.maxAgeMs,
1352
+ renewBeforeMs: timing.renewBeforeMs,
1353
+ // In the same check as the token and the user (one read of each, D-0124).
1354
+ check: async (user) => {
1355
+ const now = Date.now();
1356
+ try {
1357
+ const row = await grants.find(grantId);
1358
+ if (!row || row.revokedAt !== null || row.expiresAt <= now || row.userId !== userId)
1359
+ return false;
1360
+ return await this.#delegates(row, user, now);
1361
+ }
1362
+ catch (error) {
1363
+ // The lease ends (fail closed); the cause is logged once in a while.
1364
+ grants.repeats.log('error', 'OAuth live authorization check failed', 'OAUTH_LIVE_CHECK_FAILED', error, { resource: slot.resource }, 'live');
1365
+ return false;
1366
+ }
1367
+ },
1368
+ });
1369
+ if (!inner) {
1370
+ // Revoked or changed between the route check and now.
1371
+ this.#refused(request, 'OAuth live authorization refused', () => ({
1372
+ resource: slot.resource,
1373
+ grant: grantId,
1374
+ }));
1375
+ throw this.#unauthenticated(resource, true, resource.defaultScopes);
1376
+ }
1377
+ const endsAt = Math.min(token.expiresAt === null ? Number.POSITIVE_INFINITY : token.expiresAt.getTime(), slot.grant.expiresAt.getTime());
1378
+ const lease = new GrantLease({
1379
+ grant: grantId,
1380
+ inner,
1381
+ endsAt,
1382
+ logger: this.#logger,
1383
+ registry: grants.connections,
1384
+ });
1385
+ this.#debug('OAuth live authorization opened', () => ({
1386
+ resource: slot.resource,
1387
+ grant: grantId,
1388
+ endsInMs: endsAt - started,
1389
+ }));
1390
+ return lease;
1391
+ }
1392
+ /**
1393
+ * `canDelegate` for a protected request, at most once per `grantCacheMs` per grant (the user
1394
+ * is the one the Bearer check loaded anyway); always true without the hook.
1395
+ */
1396
+ async #delegates(row, user, now) {
1397
+ if (!this.#s.hooks || !this.#s.overridden.has('canDelegate'))
1398
+ return true;
1399
+ const until = this.#delegation.get(row.id);
1400
+ if (until !== undefined && until > now)
1401
+ return true;
1402
+ const client = await this.#s.clients.known(row.clientId);
1403
+ if (!client)
1404
+ return false;
1405
+ const allowed = await this.#canDelegate(user, client);
1406
+ if (allowed && this.#s.grantCacheMs > 0)
1407
+ this.#delegation.set(row.id, now + this.#s.grantCacheMs);
1408
+ else
1409
+ this.#delegation.delete(row.id);
1410
+ return allowed;
1411
+ }
1412
+ }
1413
+ /** What a JSON body that did not parse becomes (the handlers answer it in their own format). */
1414
+ export const BAD_JSON = Symbol('dokebi.oauth.badJson');
1415
+ /**
1416
+ * Where a form body parsed by this plugin keeps its raw parameter list (every value of every
1417
+ * name): the object itself is what other plugins read (`_csrf` of @dokebi/csrf), the list is what
1418
+ * the strict checks read.
1419
+ */
1420
+ export const FORM_PARAMS = Symbol('dokebi.oauth.formParams');
1421
+ /** The body of this plugin's urlencoded parser: fields like node:querystring, the list beside. */
1422
+ export function formBody(text) {
1423
+ const list = paramList(text);
1424
+ const body = Object.create(null);
1425
+ if (list instanceof Map)
1426
+ for (const [name, values] of list)
1427
+ body[name] = values.length === 1 ? values[0] : [...values];
1428
+ Object.defineProperty(body, FORM_PARAMS, { value: list, enumerable: false });
1429
+ return body;
1430
+ }
1431
+ function formList(body) {
1432
+ if (body === null || typeof body !== 'object')
1433
+ return undefined;
1434
+ return body[FORM_PARAMS];
1435
+ }
1436
+ /** The fields of a consent decision, from a form (ParamList) or a JSON body. */
1437
+ function decisionBody(body) {
1438
+ let read;
1439
+ let scopeValue;
1440
+ const raw = formList(body);
1441
+ const form = raw !== undefined;
1442
+ if (raw !== undefined) {
1443
+ if (!(raw instanceof Map))
1444
+ throw new OAuthError('INVALID_CONSENT', 'The decision has a broken percent-encoding', {
1445
+ status: 400,
1446
+ });
1447
+ const list = raw;
1448
+ for (const name of ['request', 'decision', 'kind', 'binding'])
1449
+ if ((list.get(name)?.length ?? 0) > 1)
1450
+ throw new OAuthError('INVALID_CONSENT', `The field ${name} is given more than once`, {
1451
+ status: 400,
1452
+ });
1453
+ read = (name) => list.get(name)?.[0];
1454
+ const scopes = list.get('scope');
1455
+ scopeValue = scopes === undefined ? undefined : scopes.flatMap((value) => parseScope(value));
1456
+ }
1457
+ else if (body !== null && typeof body === 'object' && !Array.isArray(body)) {
1458
+ const object = body;
1459
+ read = (name) => (Object.hasOwn(object, name) ? object[name] : undefined);
1460
+ scopeValue = read('scope');
1461
+ if (typeof scopeValue === 'string')
1462
+ scopeValue = parseScope(scopeValue);
1463
+ }
1464
+ else
1465
+ throw new OAuthError('INVALID_CONSENT', 'The decision has no body', { status: 400 });
1466
+ const request = read('request');
1467
+ const decision = read('decision');
1468
+ if (typeof request !== 'string' || request === '')
1469
+ throw new OAuthError('CONSENT_EXPIRED', 'This connection request is unknown or expired', {
1470
+ status: 400,
1471
+ hint: 'Start the connection again from the application.',
1472
+ });
1473
+ if (decision !== 'allow' && decision !== 'deny')
1474
+ throw new OAuthError('INVALID_CONSENT', "decision must be 'allow' or 'deny'", { status: 400 });
1475
+ if (scopeValue !== undefined &&
1476
+ (!Array.isArray(scopeValue) || scopeValue.some((item) => typeof item !== 'string')))
1477
+ throw new OAuthError('INVALID_CONSENT', 'scope must be scope names', { status: 400 });
1478
+ const kind = read('kind');
1479
+ if (kind !== undefined &&
1480
+ kind !== '' &&
1481
+ (typeof kind !== 'string' || kind.length > MAX_KIND || !KIND.test(kind)))
1482
+ throw new OAuthError('INVALID_CONSENT', `kind must be 1 to ${MAX_KIND} printable characters`, {
1483
+ status: 400,
1484
+ });
1485
+ const given = read('binding');
1486
+ let binding = null;
1487
+ if (given !== undefined && given !== '' && given !== null) {
1488
+ let text;
1489
+ if (typeof given === 'string' && form) {
1490
+ try {
1491
+ JSON.parse(given);
1492
+ }
1493
+ catch (error) {
1494
+ throw new OAuthError('INVALID_CONSENT', 'binding must be JSON text', {
1495
+ status: 400,
1496
+ cause: error,
1497
+ });
1498
+ }
1499
+ text = given;
1500
+ }
1501
+ else
1502
+ text = JSON.stringify(given);
1503
+ if (Buffer.byteLength(text, 'utf8') > MAX_BINDING_BYTES)
1504
+ throw new OAuthError('INVALID_CONSENT', `binding must be at most ${MAX_BINDING_BYTES} bytes of JSON`, {
1505
+ status: 400,
1506
+ });
1507
+ binding = text;
1508
+ }
1509
+ return {
1510
+ request,
1511
+ decision,
1512
+ scopes: scopeValue === undefined ? undefined : [...new Set(scopeValue)],
1513
+ kind: typeof kind === 'string' && kind !== '' ? kind : null,
1514
+ binding,
1515
+ };
1516
+ }