@authfn/oauth-provider 0.2.0 → 0.3.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.
Files changed (45) hide show
  1. package/README.md +37 -2
  2. package/dist/device/index.d.ts +39 -0
  3. package/dist/device/index.d.ts.map +1 -0
  4. package/dist/device/index.js +409 -0
  5. package/dist/device/index.js.map +1 -0
  6. package/dist/device/store.d.ts +129 -0
  7. package/dist/device/store.d.ts.map +1 -0
  8. package/dist/device/store.js +325 -0
  9. package/dist/device/store.js.map +1 -0
  10. package/dist/device/types.d.ts +87 -0
  11. package/dist/device/types.d.ts.map +1 -0
  12. package/dist/device/types.js +3 -0
  13. package/dist/device/types.js.map +1 -0
  14. package/dist/http.d.ts +1 -1
  15. package/dist/http.d.ts.map +1 -1
  16. package/dist/http.js.map +1 -1
  17. package/dist/index.d.ts +3 -1
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +14 -6
  20. package/dist/index.js.map +1 -1
  21. package/dist/metadata/index.d.ts.map +1 -1
  22. package/dist/metadata/index.js +4 -1
  23. package/dist/metadata/index.js.map +1 -1
  24. package/dist/registration/document.d.ts +8 -4
  25. package/dist/registration/document.d.ts.map +1 -1
  26. package/dist/registration/document.js +13 -7
  27. package/dist/registration/document.js.map +1 -1
  28. package/dist/registration/store.d.ts +5 -1
  29. package/dist/registration/store.d.ts.map +1 -1
  30. package/dist/registration/store.js.map +1 -1
  31. package/dist/runtime.d.ts +3 -0
  32. package/dist/runtime.d.ts.map +1 -1
  33. package/dist/runtime.js +3 -1
  34. package/dist/runtime.js.map +1 -1
  35. package/dist/store.d.ts +34 -5
  36. package/dist/store.d.ts.map +1 -1
  37. package/dist/store.js +35 -14
  38. package/dist/store.js.map +1 -1
  39. package/dist/token/index.d.ts.map +1 -1
  40. package/dist/token/index.js +5 -1
  41. package/dist/token/index.js.map +1 -1
  42. package/dist/types.d.ts +4 -1
  43. package/dist/types.d.ts.map +1 -1
  44. package/dist/types.js.map +1 -1
  45. package/package.json +2 -2
package/README.md CHANGED
@@ -5,10 +5,11 @@ OAuth 2.1 authorization server for AuthFn. It serves:
5
5
  - `GET {basePath}/.well-known/oauth-authorization-server`: metadata (RFC 8414)
6
6
  - `GET {basePath}/oauth/authorize`: authorization code with PKCE `S256` only
7
7
  - `POST {basePath}/oauth/authorize`: the consent decision
8
- - `POST {basePath}/oauth/token`: code exchange; refresh with rotation and reuse detection
8
+ - `POST {basePath}/oauth/token`: code exchange; refresh with rotation and reuse detection; the device code grant (RFC 8628) when `deviceAuthorization` is configured
9
9
  - `POST {basePath}/oauth/revoke`: revocation (RFC 7009)
10
10
  - `POST {basePath}/oauth/introspect`: introspection (RFC 7662)
11
11
  - `POST {basePath}/oauth/register`: dynamic client registration (RFC 7591), when `registration.dynamic` is on
12
+ - `POST {basePath}/oauth/device_authorization`, `GET`/`POST {basePath}/oauth/device`: the device authorization grant (RFC 8628) for CLIs, when `deviceAuthorization` is configured
12
13
 
13
14
  Every token is bound to one resource (RFC 8707) and carries the scopes the user granted, using the AuthFn scope registry.
14
15
 
@@ -50,7 +51,7 @@ const auth = app.createServer({
50
51
  - Client authentication failures are `invalid_client`: 401 with a `Basic` challenge when the client sent an `Authorization` header, otherwise 400. A public or `client_secret_post` client that sends any `Authorization` header fails.
51
52
  - A `trusted` client asks for consent once per resource; later requests within the consented scopes skip the page. Any other client asks every time.
52
53
  - Tokens stop working when their grant is revoked or their user is deleted or disabled (`metadata.disabled`).
53
- - A code or refresh token is spent by a conditional write that also stores a claim ID, and the request that reads its own claim ID back wins; adapter row counts are not used. The new access and refresh tokens are stored first, each recording that claim ID, and a token is valid only while the code or refresh token it was issued for stores the same claim ID. So the claim is the single commit point and nothing is ever undone: a failure before it leaves the credential unspent and the stored tokens inert, and the loser of a concurrent exchange gets nothing usable. If the claim write fails, its read-back still decides, since the write may have committed. After the claim commits, the exchange checks the grant and user again: a disconnect, a revocation or a disabled or deleted user that took effect before the commit gets `invalid_grant`, never tokens; one that takes effect later revokes the tokens delivered. Only when the response is lost after the claim commits (including a lost write acknowledgement whose read-back also fails) is the credential spent without the client holding the tokens; presenting it again is a replay that revokes the grant, so the user authorizes again. Because validity reads the code or parent refresh token row, keep code rows and rotated refresh token rows while a token issued from them can still be valid (up to 30 days after their own refresh token was issued); deleting them makes those tokens inactive.
54
+ - A code, device code or refresh token is spent by a conditional write that also stores a claim ID, and the request that reads its own claim ID back wins; adapter row counts are not used. The new access and refresh tokens are stored first, each recording that claim ID, and a token is valid only while the code or refresh token it was issued for stores the same claim ID. So the claim is the single commit point and nothing is ever undone: a failure before it leaves the credential unspent and the stored tokens inert, and the loser of a concurrent exchange gets nothing usable. If the claim write fails, its read-back still decides, since the write may have committed. After the claim commits, the exchange checks the grant and user again: a disconnect, a revocation or a disabled or deleted user that took effect before the commit gets `invalid_grant`, never tokens; one that takes effect later revokes the tokens delivered. Only when the response is lost after the claim commits (including a lost write acknowledgement whose read-back also fails) is the credential spent without the client holding the tokens; presenting it again is a replay that revokes the grant, so the user authorizes again. Because validity reads the code, device code or parent refresh token row, keep code rows, exchanged device code rows and rotated refresh token rows while a token issued from them can still be valid (up to 30 days after their own refresh token was issued); deleting them makes those tokens inactive. The provider itself deletes a device code row only once no token issued for it can be valid (see Device authorization).
54
55
 
55
56
  ## Client registration
56
57
 
@@ -76,6 +77,40 @@ registration: {
76
77
  - **Rate limit.** Registrations and first fetches of unknown metadata document clients are limited separately, per client IP and overall, in fixed windows stored in the database, so every instance shares them. Over the limit the answer is `429` `temporarily_unavailable` with `Retry-After`. Without `resolveClientIp` (or AuthFn's `rateLimit.resolveClientIp`) only the overall limit applies. Concurrent requests never exceed a limit; at its edge they may all be refused, and refused requests do not use it up. A registration body must arrive complete within 5 seconds and be at most 64 KB, so a slow upload cannot hold a request open before it is counted.
77
78
  - **Storage.** Registration uses the tables `oauth_provider_clients`, `oauth_provider_document_clients` and `oauth_provider_registration_events`. A custom plugin `schema` that leaves them out gets them added (one it defines itself is kept), so migrate them even while registration is off.
78
79
 
80
+ ## Device authorization (CLI login)
81
+
82
+ A CLI or other device without a browser signs in with the device authorization grant (RFC 8628). It is off until `pluginRuntime.oauthProvider.deviceAuthorization` turns it on:
83
+
84
+ ```ts
85
+ deviceAuthorization: {
86
+ verification: (input) => renderDevicePage(input),
87
+ rateLimit: { perUser: 10, global: 1000, windowSeconds: 600 }, // user code lookups; the defaults
88
+ authorizationRateLimit: { perIp: 20, global: 1000, windowSeconds: 600 }, // device authorization requests; the defaults
89
+ resolveClientIp: (request) => request.headers.get('cf-connecting-ip') // only behind Cloudflare; see Client registration
90
+ }
91
+ ```
92
+
93
+ 1. The CLI POSTs `client_id`, `resource` and optionally `scope` (form-encoded) to `{basePath}/oauth/device_authorization`. It gets `device_code`, `user_code`, `verification_uri`, `verification_uri_complete`, `expires_in: 600` and `interval: 5`, and shows the user the code and the URI. Over `authorizationRateLimit` it gets `429` `temporarily_unavailable` with `Retry-After`, and nothing is stored. A body over 8 KB, declared or sent, or one that has not arrived within 5 seconds is an `invalid_request`, before the client is authenticated or the request counted.
94
+ 2. The user opens `verification_uri` (`{basePath}/oauth/device`). Without a session the page answers through `loginRequired`, with the page URL as `returnTo`. `verification` renders the page. Without a `user_code` query parameter it asks for the code; its form submits `user_code` with GET to `verificationUrl`. With one, `verification` receives the `authorization` it names (client, resource, scopes), or an `error`: `invalid_user_code` (unknown, malformed, already decided, or for a client that is no longer configured), `expired_user_code` or `too_many_attempts` with `retryAfterSeconds`. The page POSTs `{ user_code, decision: 'approve' | 'deny' }` as JSON to `decisionUrl` with the session cookie and the `x-authfn-csrf` header; the response's `data.decision` is `approved` or `denied`. A code that cannot be decided answers `invalid_grant`, and over the rate limit `429` `temporarily_unavailable` with `Retry-After`.
95
+ 3. Meanwhile the CLI polls the token endpoint with `grant_type=urn:ietf:params:oauth:grant-type:device_code`, `device_code` and its client authentication, and optionally `resource`. After an approval it gets the same response as an authorization code exchange: an access token for the approved scopes and resource and a refresh token that rotates. Otherwise the answer is a `400` with one of:
96
+ - `authorization_pending`: the user has not decided yet.
97
+ - `slow_down`: the poll came within the interval (below).
98
+ - `access_denied`: the user denied the request, or the approved grant was revoked before the exchange (the app was disconnected, also during the approval, or the user was disabled or deleted).
99
+ - `expired_token`: the code is 10 minutes old, decided or not.
100
+ - `invalid_target`: `resource` is not the one requested in step 1; the code is not spent.
101
+ - `invalid_grant`: the code is unknown or was issued to another client, or it was already exchanged (which revokes the grant, below), or the grant was revoked while the exchange ran.
102
+
103
+ A poll that loses 16 rounds to concurrent polls of one code, or that cannot tell whether it was stored because 16 or more polls of the code were stored meanwhile, gets `429` `temporarily_unavailable`, never tokens or `slow_down`; in the second case it may already count as the last poll and have added its 5 seconds. Its `Retry-After` is the time left until the last stored poll time plus the code's interval as stored after the concurrent polls (0 once that has passed), plus those 5 seconds when they may count, so a poll after it is not too fast.
104
+
105
+ - User codes are 8 letters from `BCDFGHJKLMNPQRSTVWXZ` (no vowels, nothing that looks like a digit), shown as `XXXX-XXXX`; the page accepts them in any case, with or without the dash and spaces. They and device codes are valid for 10 minutes and stored only as hashes.
106
+ - A poll less than `interval` seconds after the previous one gets `slow_down` and adds 5 seconds to that device code's interval, and counts as the previous poll, so a client that keeps polling early keeps being slowed. Each poll gets one answer and is stored once: of concurrent polls of one code at most one is admitted, the others get `slow_down` and each adds its 5 seconds, so the stored interval is 5 plus 5 for each `slow_down` answered (plus 5 for each early poll answered `429` because it could not tell whether it was stored, above). A poll that arrives with an earlier clock reading than the last one is too fast and does not move the last poll time back.
107
+ - Every user code lookup by the page or the decision endpoint counts toward the rate limit, found or not: per signed-in user and overall, in fixed windows shared by every instance through the registration event table. 20^8 codes and at most `global` guesses per window keep the chance of hitting someone's pending code small.
108
+ - Each code is decided once; of concurrent decisions exactly one is recorded. An approval creates its own grant (so disconnecting the app or revoking the grant ends it like any other) and follows the same disconnect rule as an authorization code approval: it checks the disconnect generation after creating the grant and only then records the decision, so the device cannot exchange the code before that check. An app disconnected while the approval runs gets no usable grant: the decision answers `access_denied` and the request is recorded as denied. Expiry is checked just before and again after the decision is recorded; an approval that crosses it revokes its grant and answers `invalid_grant`, and the device gets `expired_token`. One that crosses it before the write records nothing; one that crosses it after the write spends the code, unless the device already exchanged it. An exchange judges expiry with a clock read after it read the approval, so one that wins shows the approval was recorded in time: the approval stands and the tokens stay valid. An approval interrupted before it records the decision leaves the request pending. The user always sees the approval page, even for a `trusted` client, and the approval is not remembered as consent.
109
+ - The device code works once. Presenting it again after the exchange revokes the grant and every token issued under it, as a replayed authorization code does. It is bound to the client it was issued to.
110
+ - Only configured clients may use the grant; a self-registered client gets `unauthorized_client`. When the grant is off, its endpoints do not exist and the token endpoint answers `unsupported_grant_type` for it.
111
+ - Every device authorization request counts toward `authorizationRateLimit`, per client IP and overall, in the same shared windows as the user code lookups; refused requests store no code and do not use the limit up. The client IP comes from `resolveClientIp`, or AuthFn's `rateLimit.resolveClientIp`; without either only the overall limit applies, and the same rule as for registration applies to where it reads the address.
112
+ - **Storage.** The grant uses the table `oauth_provider_device_codes`, which a custom plugin `schema` gets added like the registration tables, so migrate it even while the grant is off. Each admitted device authorization request deletes codes never exchanged 10 minutes after they expired. An exchanged code is kept while tokens issued for it can be valid (30 days after the exchange), since they stay valid only while its row exists, as for authorization code rows; after that it is kept while its grant is unrevoked and holds an unexpired refresh token that was not rotated or revoked, so that replaying it still revokes the grant and the tokens refreshed under it, and deleted once neither holds. Its user code lookups and requests are counted in `oauth_provider_registration_events`.
113
+
79
114
  ## Host responsibilities
80
115
 
81
116
  **Metadata path.** RFC 8414 clients look for `/.well-known/oauth-authorization-server` at the issuer's origin, followed by the issuer's path when it has one (RFC 8414 3.1): for the issuer `https://auth.example.com/tenant` that is `https://auth.example.com/.well-known/oauth-authorization-server/tenant`. Route that path to `{basePath}/.well-known/oauth-authorization-server`. The issuer is the AuthFn environment's `issuer` (the request origin by default).
@@ -0,0 +1,39 @@
1
+ import type { Route } from '@superfunctions/http';
2
+ import { type OAuthProviderRuntime } from '../runtime.js';
3
+ import { type IssuedTokens } from '../store.js';
4
+ import type { OAuthProviderClient } from '../types.js';
5
+ export { createDeviceSchema, OAUTH_DEVICE_CODE_TTL_SECONDS, OAUTH_DEVICE_POLL_INTERVAL_SECONDS } from './store.js';
6
+ export * from './types.js';
7
+ export declare const OAUTH_DEVICE_AUTHORIZATION_PATH = "/oauth/device_authorization";
8
+ export declare const OAUTH_DEVICE_VERIFICATION_PATH = "/oauth/device";
9
+ /** Rejects a malformed `pluginRuntime.oauthProvider.deviceAuthorization` at startup. */
10
+ export declare function validateDeviceConfig(device: unknown): void;
11
+ /**
12
+ * The device authorization endpoint (RFC 8628 3.1, 3.2), the verification
13
+ * page with its decision endpoint (3.3), when `deviceAuthorization` is
14
+ * configured. The token endpoint accepts the device code grant through
15
+ * `exchangeDeviceCode`.
16
+ */
17
+ export declare function createDeviceRoutes(runtime: OAuthProviderRuntime): Route[];
18
+ /**
19
+ * Device access token request (RFC 8628 3.4, 3.5). The device polls with its
20
+ * device code: `authorization_pending` until the user decides, `slow_down`
21
+ * for a poll within the interval of the previous one (which adds 5 seconds
22
+ * to it), `access_denied` after a denial or once the approved grant was
23
+ * revoked (the app was disconnected, or the user disabled) and
24
+ * `expired_token` after 10 minutes. A `resource` other than the requested
25
+ * one is `invalid_target` and leaves the code as it was. A poll that loses to
26
+ * 16 concurrent polls, or cannot tell whether it was stored, is a 429
27
+ * `temporarily_unavailable` whose `Retry-After` is the time left until the
28
+ * stored last poll time plus the stored interval (none once that has passed),
29
+ * plus 5 seconds when its own `slow_down` may count.
30
+ * An approval yields the same tokens as an authorization code: an
31
+ * access token for the approved scopes and a refresh token under the grant.
32
+ * The exchange is judged unexpired with a clock read after the row read that
33
+ * showed the approval, and its tokens are issued at that time; tokens whose
34
+ * exchange was judged in time stay valid even when the claim commits later.
35
+ * The device code works once; when its client presents it again after the
36
+ * exchange, the grant is revoked, as for a replayed authorization code.
37
+ */
38
+ export declare function exchangeDeviceCode(runtime: OAuthProviderRuntime, client: OAuthProviderClient, params: Map<string, string>): Promise<IssuedTokens>;
39
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/device/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAiBlD,OAAO,EAIL,KAAK,oBAAoB,EAC1B,MAAM,eAAe,CAAC;AACvB,OAAO,EAML,KAAK,YAAY,EAClB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,mBAAmB,EAAqB,MAAM,aAAa,CAAC;AAkB1E,OAAO,EAAE,kBAAkB,EAAE,6BAA6B,EAAE,kCAAkC,EAAE,MAAM,YAAY,CAAC;AACnH,cAAc,YAAY,CAAC;AAE3B,eAAO,MAAM,+BAA+B,gCAAgC,CAAC;AAC7E,eAAO,MAAM,8BAA8B,kBAAkB,CAAC;AAiB9D,wFAAwF;AACxF,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,OAAO,GAAG,IAAI,CAkB1D;AAwKD;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,oBAAoB,GAAG,KAAK,EAAE,CAgIzE;AAMD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,kBAAkB,CACtC,OAAO,EAAE,oBAAoB,EAC7B,MAAM,EAAE,mBAAmB,EAC3B,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,GAC1B,OAAO,CAAC,YAAY,CAAC,CA8DvB"}
@@ -0,0 +1,409 @@
1
+ import { AuthFnConfigError, AuthFnValidationError } from 'authfn/core/errors';
2
+ import { assertValidCsrf, getCookieSessionState, requireCookieSession } from 'authfn/core/sessions';
3
+ import { jsonSuccess } from 'authfn/http/envelopes';
4
+ import { createAuthFnRouteMeta, readOptionalJson } from 'authfn/http/router';
5
+ import { authenticateClient, handleOAuth, OAuthError, oauthJson, readSingleParams, requireParam } from '../http.js';
6
+ import { BodyTimeoutError, declaresMoreThan, readCappedBody } from '../registration/document.js';
7
+ import { REGISTRATION_BODY_TIMEOUT_MS } from '../registration/index.js';
8
+ import { isPlainObject } from '../registration/metadata.js';
9
+ import { admitRegistrationEvent } from '../registration/store.js';
10
+ import { requireResource, resolveEndpoints, resolveRequestedScopes } from '../runtime.js';
11
+ import { createGrant, findLiveGrant, readGeneration, revokeGrant, stageTokens } from '../store.js';
12
+ import { admitPoll, claimDecision, claimDeviceCode, closeExpiredDeviceCode, createDeviceCode, EXPIRED_CLAIM_PREFIX, findByUserCode, findDeviceCode, normalizeUserCode, pruneDeviceCodes, OAUTH_DEVICE_CODE_TTL_SECONDS, OAUTH_DEVICE_POLL_INTERVAL_SECONDS } from './store.js';
13
+ export { createDeviceSchema, OAUTH_DEVICE_CODE_TTL_SECONDS, OAUTH_DEVICE_POLL_INTERVAL_SECONDS } from './store.js';
14
+ export * from './types.js';
15
+ export const OAUTH_DEVICE_AUTHORIZATION_PATH = '/oauth/device_authorization';
16
+ export const OAUTH_DEVICE_VERIFICATION_PATH = '/oauth/device';
17
+ const DEFAULT_RATE_LIMIT = { perUser: 10, global: 1000, windowSeconds: 600 };
18
+ const DEFAULT_AUTHORIZATION_RATE_LIMIT = { perIp: 20, global: 1000, windowSeconds: 600 };
19
+ /** True when `limits` is absent or an object of positive integers named in `names`. */
20
+ function validLimits(limits, names) {
21
+ return limits === undefined || (isPlainObject(limits) && Object.entries(limits).every(([name, value]) => names.includes(name) &&
22
+ (value === undefined || (typeof value === 'number' && Number.isSafeInteger(value) && value > 0))));
23
+ }
24
+ /** The configured limits over the defaults; an `undefined` value keeps the default. */
25
+ function limitsWithDefaults(defaults, configured) {
26
+ return { ...defaults, ...Object.fromEntries(Object.entries(configured ?? {}).filter(([, value]) => value !== undefined)) };
27
+ }
28
+ /** Rejects a malformed `pluginRuntime.oauthProvider.deviceAuthorization` at startup. */
29
+ export function validateDeviceConfig(device) {
30
+ if (device === undefined) {
31
+ return;
32
+ }
33
+ const invalid = (message) => new AuthFnConfigError(`pluginRuntime.oauthProvider.deviceAuthorization ${message}`);
34
+ if (!isPlainObject(device) || typeof device.verification !== 'function') {
35
+ throw invalid('needs a verification hook');
36
+ }
37
+ const { rateLimit, authorizationRateLimit, resolveClientIp } = device;
38
+ if (!validLimits(rateLimit, ['perUser', 'global', 'windowSeconds'])) {
39
+ throw invalid('rateLimit takes positive integers perUser, global and windowSeconds');
40
+ }
41
+ if (!validLimits(authorizationRateLimit, ['perIp', 'global', 'windowSeconds'])) {
42
+ throw invalid('authorizationRateLimit takes positive integers perIp, global and windowSeconds');
43
+ }
44
+ if (resolveClientIp !== undefined && typeof resolveClientIp !== 'function') {
45
+ throw invalid('resolveClientIp must be a function');
46
+ }
47
+ }
48
+ /** The largest device authorization request body; its parameters are a few short strings. */
49
+ const MAX_DEVICE_AUTHORIZATION_BODY_BYTES = 8 * 1024;
50
+ /**
51
+ * Reads the form body of an anonymous device authorization request, bounded
52
+ * before anything else runs: a declared or streamed body over 8 KB, or one
53
+ * that has not arrived within 5 seconds, is an `invalid_request` and the
54
+ * stream is cancelled.
55
+ */
56
+ async function readCappedFormBody(request) {
57
+ const contentType = request.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase();
58
+ if (contentType !== 'application/x-www-form-urlencoded') {
59
+ throw new OAuthError('invalid_request', 'Request body must be application/x-www-form-urlencoded');
60
+ }
61
+ const tooLarge = new OAuthError('invalid_request', 'Request body must be at most 8 KB');
62
+ if (declaresMoreThan(request.headers, MAX_DEVICE_AUTHORIZATION_BODY_BYTES)) {
63
+ await request.body?.cancel().catch(() => undefined);
64
+ throw tooLarge;
65
+ }
66
+ let bytes = new Uint8Array();
67
+ try {
68
+ if (request.body) {
69
+ bytes = await readCappedBody(request.body.getReader(), MAX_DEVICE_AUTHORIZATION_BODY_BYTES, REGISTRATION_BODY_TIMEOUT_MS);
70
+ }
71
+ }
72
+ catch (error) {
73
+ if (error instanceof BodyTimeoutError) {
74
+ throw new OAuthError('invalid_request', 'Request body must arrive within 5 seconds');
75
+ }
76
+ throw error;
77
+ }
78
+ if (!bytes) {
79
+ throw tooLarge;
80
+ }
81
+ return readSingleParams(new URLSearchParams(new TextDecoder().decode(bytes)));
82
+ }
83
+ /**
84
+ * Counts one device authorization request per client IP and overall, or
85
+ * throws a 429 `temporarily_unavailable` before anything is stored.
86
+ */
87
+ async function admitDeviceAuthorization(runtime, device, request) {
88
+ const resolve = device.resolveClientIp ?? runtime.ctx.config.rateLimit?.resolveClientIp;
89
+ const ip = (await resolve?.(request))?.trim() || undefined;
90
+ const { perIp, global, windowSeconds } = limitsWithDefaults(DEFAULT_AUTHORIZATION_RATE_LIMIT, device.authorizationRateLimit);
91
+ const result = await admitRegistrationEvent(runtime.store, {
92
+ kind: 'device_code',
93
+ ip,
94
+ now: runtime.now(),
95
+ limits: { perIp, global, windowSeconds }
96
+ });
97
+ if (!result.admitted) {
98
+ throw new OAuthError('temporarily_unavailable', 'Too many device authorization requests; try again later', 429, {
99
+ 'retry-after': String(result.retryAfterSeconds)
100
+ });
101
+ }
102
+ }
103
+ /**
104
+ * Counts one user code lookup by `user`, or reports the seconds until the
105
+ * window ends. Lookups share the windowed event store of client registration.
106
+ */
107
+ async function admitUserCodeLookup(runtime, device, user) {
108
+ const { perUser, global, windowSeconds } = limitsWithDefaults(DEFAULT_RATE_LIMIT, device.rateLimit);
109
+ const result = await admitRegistrationEvent(runtime.store, {
110
+ kind: 'user_code',
111
+ ip: `user:${user.id}`,
112
+ now: runtime.now(),
113
+ limits: { perIp: perUser, global, windowSeconds }
114
+ });
115
+ return result.admitted ? null : result.retryAfterSeconds;
116
+ }
117
+ /**
118
+ * Finds the pending device authorization a user code names, after counting
119
+ * the lookup. A code that is decided, unknown or whose client is no longer
120
+ * configured is `invalid_user_code`.
121
+ */
122
+ async function lookUpUserCode(runtime, device, user, userCode) {
123
+ const retryAfterSeconds = await admitUserCodeLookup(runtime, device, user);
124
+ if (retryAfterSeconds !== null) {
125
+ return { ok: false, error: 'too_many_attempts', retryAfterSeconds };
126
+ }
127
+ const record = userCode ? await findByUserCode(runtime.store, userCode) : null;
128
+ const client = record ? runtime.findClient(record.clientId) : undefined;
129
+ if (!record || !client || record.decidedAt) {
130
+ return { ok: false, error: 'invalid_user_code' };
131
+ }
132
+ if (record.expiresAt.getTime() <= runtime.now().getTime()) {
133
+ return { ok: false, error: 'expired_user_code' };
134
+ }
135
+ return { ok: true, record, client };
136
+ }
137
+ /**
138
+ * Approves a pending device authorization for `user`: creates its grant,
139
+ * checks the disconnect generation, and only then records the decision,
140
+ * which makes the code exchangeable and which only one decision wins. As for
141
+ * an authorization code, the generation is read before the grant is created
142
+ * and again after: a disconnect in between revokes the new grant and records
143
+ * the request as denied, so the device gets `access_denied`. A disconnect
144
+ * after the second read finds the grant, which already exists, and revokes
145
+ * it; the device then also gets `access_denied` (see `exchangeDeviceCode`).
146
+ * Expiry is checked before the decision is recorded and again after: an
147
+ * approval that crosses it revokes its grant and throws `invalid_grant`. One
148
+ * that crossed before the write records nothing. One that crossed after it
149
+ * spends the code with an expiry claim, unless an exchange claimed it first:
150
+ * an exchange judges expiry with a clock read after it read the approval, so
151
+ * its winning claim proves the approval was published before expiry, and the
152
+ * approval stands. An approval interrupted anywhere before the decision
153
+ * leaves the request pending.
154
+ * Returns whether the device will receive tokens.
155
+ */
156
+ async function approve(runtime, record, user) {
157
+ const { store } = runtime;
158
+ const triple = { userId: user.id, clientId: record.clientId, resource: record.resource };
159
+ const generation = await readGeneration(store, triple);
160
+ const grant = await createGrant(store, { ...triple, scopes: record.scopes, now: runtime.now() });
161
+ if (await readGeneration(store, triple) !== generation) {
162
+ await revokeGrant(store, grant.id, 'consent_withdrawn', runtime.now());
163
+ await claimDecision(store, record.id, { decision: 'denied', userId: user.id, now: runtime.now() });
164
+ return 'withdrawn';
165
+ }
166
+ const now = runtime.now();
167
+ if (record.expiresAt.getTime() <= now.getTime()) {
168
+ await revokeGrant(store, grant.id, 'device_code_expired', now);
169
+ throw new OAuthError('invalid_grant', 'The user code has expired');
170
+ }
171
+ if (!(await claimDecision(store, record.id, { decision: 'approved', userId: user.id, grantId: grant.id, now }))) {
172
+ await revokeGrant(store, grant.id, 'device_decided', runtime.now());
173
+ return 'decided';
174
+ }
175
+ // Expired by the time the decision was written: spend the code so nothing
176
+ // can exchange it, unless an exchange that found it unexpired already did.
177
+ if (record.expiresAt.getTime() <= runtime.now().getTime() && await closeExpiredDeviceCode(store, record.id, runtime.now())) {
178
+ await revokeGrant(store, grant.id, 'device_code_expired', runtime.now());
179
+ throw new OAuthError('invalid_grant', 'The user code has expired');
180
+ }
181
+ return 'approved';
182
+ }
183
+ function deviceConfig(runtime) {
184
+ return runtime.config.deviceAuthorization;
185
+ }
186
+ /**
187
+ * The device authorization endpoint (RFC 8628 3.1, 3.2), the verification
188
+ * page with its decision endpoint (3.3), when `deviceAuthorization` is
189
+ * configured. The token endpoint accepts the device code grant through
190
+ * `exchangeDeviceCode`.
191
+ */
192
+ export function createDeviceRoutes(runtime) {
193
+ const device = deviceConfig(runtime);
194
+ if (!device) {
195
+ return [];
196
+ }
197
+ return [
198
+ {
199
+ method: 'POST',
200
+ path: OAUTH_DEVICE_AUTHORIZATION_PATH,
201
+ meta: createAuthFnRouteMeta('oauthDeviceAuthorization', 'OAuth 2.0 device authorization endpoint', { mode: 'none' }),
202
+ handler: (request) => handleOAuth(async () => {
203
+ const params = await readCappedFormBody(request);
204
+ const client = await authenticateClient(runtime, request, params);
205
+ if (!runtime.findClient(client.clientId)) {
206
+ throw new OAuthError('unauthorized_client', 'This client may not use the device authorization grant');
207
+ }
208
+ const resource = requireResource(runtime, params.get('resource'));
209
+ const scopes = resolveRequestedScopes(resource, params.get('scope'));
210
+ await admitDeviceAuthorization(runtime, device, request);
211
+ await pruneDeviceCodes(runtime.store, runtime.now());
212
+ const { deviceCode, userCode } = await createDeviceCode(runtime.store, {
213
+ clientId: client.clientId,
214
+ resource: resource.resource,
215
+ scopes,
216
+ now: runtime.now()
217
+ });
218
+ const verificationUri = (await resolveEndpoints(runtime, request)).deviceVerification;
219
+ return oauthJson({
220
+ device_code: deviceCode,
221
+ user_code: userCode,
222
+ verification_uri: verificationUri,
223
+ verification_uri_complete: `${verificationUri}?${new URLSearchParams({ user_code: userCode })}`,
224
+ expires_in: OAUTH_DEVICE_CODE_TTL_SECONDS,
225
+ interval: OAUTH_DEVICE_POLL_INTERVAL_SECONDS
226
+ });
227
+ })
228
+ },
229
+ {
230
+ method: 'GET',
231
+ path: OAUTH_DEVICE_VERIFICATION_PATH,
232
+ meta: createAuthFnRouteMeta('oauthDeviceVerification', 'OAuth 2.0 device verification page', { mode: 'hybrid' }),
233
+ handler: async (request) => {
234
+ const state = await getCookieSessionState(runtime.ctx.config, request);
235
+ if (!state.session || !state.user) {
236
+ return runtime.config.loginRequired({ request, returnTo: request.url });
237
+ }
238
+ const user = { id: state.user.id, primaryEmail: state.user.primaryEmail };
239
+ const endpoints = await resolveEndpoints(runtime, request);
240
+ const input = {
241
+ request,
242
+ user,
243
+ verificationUrl: endpoints.deviceVerification,
244
+ decisionUrl: endpoints.deviceVerification
245
+ };
246
+ const entered = new URL(request.url).searchParams.getAll('user_code');
247
+ if (entered.length === 0) {
248
+ return device.verification(input);
249
+ }
250
+ const userCode = entered.length === 1 ? normalizeUserCode(entered[0]) : null;
251
+ const lookup = await lookUpUserCode(runtime, device, user, userCode);
252
+ input.userCode = userCode ?? undefined;
253
+ if (lookup.ok) {
254
+ input.authorization = {
255
+ client: { clientId: lookup.client.clientId, name: lookup.client.name, trusted: lookup.client.trusted === true },
256
+ resource: lookup.record.resource,
257
+ scopes: [...lookup.record.scopes]
258
+ };
259
+ }
260
+ else {
261
+ input.error = lookup.error;
262
+ if (lookup.error === 'too_many_attempts') {
263
+ input.retryAfterSeconds = lookup.retryAfterSeconds;
264
+ }
265
+ }
266
+ return device.verification(input);
267
+ }
268
+ },
269
+ {
270
+ method: 'POST',
271
+ path: OAUTH_DEVICE_VERIFICATION_PATH,
272
+ meta: createAuthFnRouteMeta('oauthDeviceDecision', 'Record the decision for an OAuth device authorization', {
273
+ mode: 'cookie-session',
274
+ csrf: true
275
+ }),
276
+ handler: (request) => handleOAuth(async () => {
277
+ const session = await requireCookieSession(runtime.ctx.config, request);
278
+ assertValidCsrf(request, session);
279
+ let body;
280
+ try {
281
+ body = await readOptionalJson(request);
282
+ }
283
+ catch (error) {
284
+ if (error instanceof AuthFnValidationError) {
285
+ throw new OAuthError('invalid_request', 'The decision body must be valid JSON');
286
+ }
287
+ throw error;
288
+ }
289
+ if (!isPlainObject(body) || typeof body.user_code !== 'string' ||
290
+ (body.decision !== 'approve' && body.decision !== 'deny')) {
291
+ throw new OAuthError('invalid_request', 'The decision body must be { user_code, decision: approve | deny }');
292
+ }
293
+ const user = { id: session.user.id, primaryEmail: session.user.primaryEmail };
294
+ const lookup = await lookUpUserCode(runtime, device, user, normalizeUserCode(body.user_code));
295
+ if (!lookup.ok) {
296
+ if (lookup.error === 'too_many_attempts') {
297
+ throw new OAuthError('temporarily_unavailable', 'Too many user code attempts; try again later', 429, {
298
+ 'retry-after': String(lookup.retryAfterSeconds)
299
+ });
300
+ }
301
+ throw new OAuthError('invalid_grant', lookup.error === 'expired_user_code'
302
+ ? 'The user code has expired'
303
+ : 'The user code is invalid or was already used');
304
+ }
305
+ let outcome;
306
+ if (body.decision === 'approve') {
307
+ outcome = await approve(runtime, lookup.record, user);
308
+ }
309
+ else {
310
+ const denied = await claimDecision(runtime.store, lookup.record.id, { decision: 'denied', userId: user.id, now: runtime.now() });
311
+ outcome = denied ? 'denied' : 'decided';
312
+ }
313
+ if (outcome === 'decided') {
314
+ throw new OAuthError('invalid_grant', 'The user code is invalid or was already used');
315
+ }
316
+ if (outcome === 'withdrawn') {
317
+ throw new OAuthError('access_denied', 'The authorization was withdrawn while it was being approved');
318
+ }
319
+ return jsonSuccess(request, { decision: outcome }, { headers: { 'cache-control': 'no-store' } });
320
+ })
321
+ }
322
+ ];
323
+ }
324
+ function deviceError(error, description) {
325
+ return new OAuthError(error, description);
326
+ }
327
+ /**
328
+ * Device access token request (RFC 8628 3.4, 3.5). The device polls with its
329
+ * device code: `authorization_pending` until the user decides, `slow_down`
330
+ * for a poll within the interval of the previous one (which adds 5 seconds
331
+ * to it), `access_denied` after a denial or once the approved grant was
332
+ * revoked (the app was disconnected, or the user disabled) and
333
+ * `expired_token` after 10 minutes. A `resource` other than the requested
334
+ * one is `invalid_target` and leaves the code as it was. A poll that loses to
335
+ * 16 concurrent polls, or cannot tell whether it was stored, is a 429
336
+ * `temporarily_unavailable` whose `Retry-After` is the time left until the
337
+ * stored last poll time plus the stored interval (none once that has passed),
338
+ * plus 5 seconds when its own `slow_down` may count.
339
+ * An approval yields the same tokens as an authorization code: an
340
+ * access token for the approved scopes and a refresh token under the grant.
341
+ * The exchange is judged unexpired with a clock read after the row read that
342
+ * showed the approval, and its tokens are issued at that time; tokens whose
343
+ * exchange was judged in time stay valid even when the claim commits later.
344
+ * The device code works once; when its client presents it again after the
345
+ * exchange, the grant is revoked, as for a replayed authorization code.
346
+ */
347
+ export async function exchangeDeviceCode(runtime, client, params) {
348
+ const deviceCode = requireParam(params, 'device_code');
349
+ const now = runtime.now();
350
+ const record = await findDeviceCode(runtime.store, deviceCode);
351
+ if (record?.clientId !== client.clientId) {
352
+ throw deviceError('invalid_grant', 'Device code is invalid');
353
+ }
354
+ if (record.consumedAt) {
355
+ if (record.claimId?.startsWith(`${EXPIRED_CLAIM_PREFIX}_`)) {
356
+ throw deviceError('expired_token', 'Device code has expired');
357
+ }
358
+ if (record.grantId) {
359
+ await revokeGrant(runtime.store, record.grantId, 'code_replay', now);
360
+ }
361
+ throw deviceError('invalid_grant', 'Device code has already been used');
362
+ }
363
+ if (record.expiresAt.getTime() <= now.getTime()) {
364
+ throw deviceError('expired_token', 'Device code has expired');
365
+ }
366
+ const resource = params.get('resource');
367
+ if (resource !== undefined && resource !== record.resource) {
368
+ throw new OAuthError('invalid_target', 'resource does not match the device authorization request');
369
+ }
370
+ const poll = await admitPoll(runtime.store, record, now);
371
+ if (poll.outcome === 'busy' || poll.outcome === 'unknown') {
372
+ throw new OAuthError('temporarily_unavailable', 'Too many concurrent polls of this device code; try again later', 429, {
373
+ 'retry-after': String(poll.retryAfterSeconds)
374
+ });
375
+ }
376
+ if (poll.outcome === 'slow_down') {
377
+ throw deviceError('slow_down', 'Polling too fast; wait longer between requests');
378
+ }
379
+ if (!record.decidedAt) {
380
+ throw deviceError('authorization_pending', 'The user has not yet completed the authorization');
381
+ }
382
+ if (record.decision !== 'approved' || !record.grantId) {
383
+ throw deviceError('access_denied', 'The user denied the authorization request');
384
+ }
385
+ const grant = await findLiveGrant(runtime.store, record.grantId);
386
+ if (!grant) {
387
+ throw deviceError('access_denied', 'The authorization was withdrawn');
388
+ }
389
+ // `now` was read before the row, so the approval may have been published
390
+ // after it. Expiry is judged again with a clock read after the row showed
391
+ // the approval: only then does a committed exchange prove the approval was
392
+ // published in time, which `approve` relies on when its close loses.
393
+ const issuedAt = runtime.now();
394
+ if (record.expiresAt.getTime() <= issuedAt.getTime()) {
395
+ throw deviceError('expired_token', 'Device code has expired');
396
+ }
397
+ // As for a code: the staged tokens become valid only when the claim on the
398
+ // device code commits, and a concurrent exchange that loses is a replay.
399
+ const { tokens, claimId } = await stageTokens(runtime.store, grant, grant.scopes, issuedAt, record.id);
400
+ if (!(await claimDeviceCode(runtime.store, record.id, issuedAt, claimId))) {
401
+ await revokeGrant(runtime.store, record.grantId, 'code_replay', issuedAt);
402
+ throw deviceError('invalid_grant', 'Device code has already been used');
403
+ }
404
+ if (!(await findLiveGrant(runtime.store, record.grantId))) {
405
+ throw deviceError('invalid_grant', 'Authorization grant is no longer valid');
406
+ }
407
+ return tokens;
408
+ }
409
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/device/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,MAAM,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