authlet 0.1.0-beta.4 → 0.1.0-beta.7

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/README.md CHANGED
@@ -3,39 +3,61 @@
3
3
  A small, stateless OAuth 2.1 authorization server built only on Web `Request` and `Response`,
4
4
  so it runs on Node, Deno, Bun and edge runtimes. Bring your own users, sessions and tokens.
5
5
 
6
- It serves the authorization code flow with PKCE for public clients: dynamic client registration
7
- (RFC 7591), optional [Client ID Metadata Documents](#client-id-metadata-documents), resource indicators (RFC 8707), protected resource metadata (RFC 9728) and refresh
8
- token rotation. That is the profile MCP clients use, so an MCP server is the typical host, but
9
- any API that wants this flow can use it. It has no client credentials or device flow, and no
10
- OpenID Connect ID tokens.
6
+ It serves the authorization code flow with PKCE for public clients, with dynamic client
7
+ registration (RFC 7591), optional [Client ID Metadata Documents](#client-id-metadata-documents),
8
+ resource indicators (RFC 8707), protected resource metadata (RFC 9728), refresh token rotation,
9
+ and optional [scopes](#scopes) with step-up (RFC 6750 `insufficient_scope`). MCP clients use this
10
+ profile, so an MCP server is the typical host, but any API can use it. There is no client
11
+ credentials or device flow, and no OpenID Connect ID tokens.
11
12
 
12
- > Status: pre-release, not yet published. `createAuthlet` and all endpoints work, and an
13
- > end-to-end run with `oauth4webapi` passes. [Planned](#planned) lists what is missing.
13
+ ## Usage
14
14
 
15
- ## Design
15
+ ```ts
16
+ // TAuthorization: what the consent page collects. TUser: the app's user, default { id }.
17
+ const authlet = createAuthlet<Capabilities, AppUser>({
18
+ resource: "https://cms.example.com/api/mcp", // the protected resource, or (req) => string
19
+ issuer: "https://cms.example.com/api/mcp/oauth", // optional, this is the default
20
+ getUser: async (req) => sessionUser(req), // AppUser | null
21
+ loginUrl: (returnTo) =>
22
+ `/admin/login?redirect=${encodeURIComponent(returnTo)}`,
23
+ consentPage: "/admin/mcp/authorize", // gets ?consent=… or ?error=…
24
+ secret: process.env.AUTHLET_SECRET!, // >= 32 chars, or an AES-GCM CryptoKey
25
+ fetchClientMetadata: guardedFetch, // optional, enables Client ID Metadata Documents
26
+ scopes: ["read", "write"], // optional, advertised as scopes_supported
27
+ tokens: {
28
+ issue: async ({ user, client, authorization, resource, scope }) => ({
29
+ refreshToken,
30
+ }), // or null to refuse
31
+ refresh: async ({ refreshToken, grantType, client, scope }) =>
32
+ rotated ?? null, // grantType: "authorization_code" | "refresh_token"
33
+ },
34
+ });
16
35
 
17
- authlet stores nothing. Client IDs from dynamic registration, consent forms, authorization codes
18
- and refresh token wrappers are encrypted JWTs (jose, `dir` + `A256GCM`) bound to their type and
19
- issuer, with an expiry, and the client or browser holds them. The app's `tokens` hooks own all
20
- persistence. [`src/seal.ts`](src/seal.ts) lists every sealed value.
36
+ authlet.handle(req); // Promise<Response | null>: OAuth endpoints, AS and resource metadata
37
+ authlet.authenticate(req, verify); // Promise<T | Response>: the app's auth info, or the 401
38
+ authlet.challenge(req); // 401 with WWW-Authenticate: Bearer resource_metadata="..."
39
+ authlet.challenge(req, { scope: ["write"] }); // 403 insufficient_scope
40
+ authlet.readConsent(req, consent); // Promise<Consent<AppUser> | null>, for rendering the consent page
41
+ authlet.decide(req, { consent, allow: true, authorization }); // Promise<Response>: redirect with a code
42
+ authlet.decide(req, { consent, allow: false }); // Promise<Response>: redirect with access_denied
43
+ ```
21
44
 
22
- Every URL derives from the issuer, which defaults to `${resource}/oauth`, so discovery works under
23
- a base path without routes at the site root ([Base URLs](#base-urls)).
45
+ ## How it works
24
46
 
25
- The app owns the user. `getUser` reads the browser session and returns the app's own user type
26
- (`TUser`), and `tokens.issue` and the consent page get that type back. authlet only compares
27
- `id`, so it must be unique across the app; prefix it when there are several user collections.
28
- Requests with an `Authorization` header never reach `getUser`, so a token can't approve a client
29
- for itself.
47
+ authlet stores nothing. Registered client IDs, consents, authorization codes and refresh token
48
+ wrappers are encrypted and held by the client or browser. The app's `tokens` hooks own all
49
+ persistence.
30
50
 
31
- The app also owns the consent screen. authlet redirects to `consentPage?consent=…`, or to
32
- `?error=…` for a broken link. The page reads the request with `readConsent`, and its POST handler
33
- calls `decide`.
51
+ The app also owns the user, the consent screen and the access tokens:
34
52
 
35
- Access tokens belong to the app too. On the protected resource, `authenticate` reads the bearer
36
- token and hands it to the app's `verify`, which checks it, including that it was issued for this
37
- resource (the audience), and returns the app's auth info or `null`. A missing or rejected token
38
- gets the `challenge` 401.
53
+ - `getUser` reads the browser session and returns the app's own user type. authlet only compares
54
+ `id`, so it must be unique across the app. Requests with an `Authorization` header never reach
55
+ `getUser`, so a token can't approve a client for itself.
56
+ - authlet redirects to `consentPage?consent=…`, or to `?error=…` for a broken link. The page reads
57
+ the request with `readConsent`, and its POST handler calls `decide`.
58
+ - On the protected resource, `authenticate` passes the bearer token to the app's `verify`, which
59
+ checks it, including that it was issued for this resource, and returns the app's auth info or
60
+ `null`. A missing or rejected token gets the `challenge` 401.
39
61
 
40
62
  ```ts
41
63
  const auth = await authlet.authenticate(req, verifyToken);
@@ -45,17 +67,12 @@ if (auth instanceof Response) {
45
67
  }
46
68
  ```
47
69
 
48
- ### App-specific authorization data
70
+ ### Consent
49
71
 
50
72
  The consent screen can collect data of its own, such as the capabilities a user allows a client.
51
- The app's consent POST handler parses and validates it, then passes it to `decide`.
52
- [`src/types.test-d.ts`](src/types.test-d.ts) writes this out for an MCP server, and `yarn check`
53
- compiles it, so the example can't drift from the types:
73
+ The POST handler validates it and passes it to `decide`:
54
74
 
55
75
  ```ts
56
- const authlet = createAuthlet<Capabilities>({/* ... */});
57
-
58
- // The consent form's POST handler, in the app
59
76
  export const POST = async (req: Request) => {
60
77
  const form = await req.formData();
61
78
  const consent = String(form.get("consent"));
@@ -69,143 +86,114 @@ export const POST = async (req: Request) => {
69
86
  };
70
87
  ```
71
88
 
72
- `decide` checks the request (top-level same-origin form submission, no `Authorization` header,
73
- same user the consent was shown to) and calls `tokens.issue({ user, client, authorization, resource })`.
74
- The app stores the authorization and returns only a refresh token for it. authlet seals that token into
75
- an authorization code valid for 60 seconds, plus 5 seconds of clock tolerance. No access token
76
- exists yet, so none travels through the browser, and the authorization never leaves the server.
89
+ `decide` accepts only a top-level same-origin form submission without an `Authorization` header,
90
+ from the user the consent was shown to. It calls `tokens.issue({ user, client, authorization,
91
+ resource })`, and the app stores the authorization and returns a refresh token for it. authlet
92
+ seals that token into an authorization code valid for 60 seconds. No access token exists yet, so
93
+ none passes through the browser. `issue` may return `null` to refuse a user who lost access; the
94
+ browser then goes to `consentPage?error=forbidden`.
95
+
96
+ Redeeming the code calls `tokens.refresh` with `grantType: "authorization_code"`, which mints the
97
+ client's first token pair. Refusing a refresh token that was already used makes the code
98
+ single-use.
77
99
 
78
- `issue` may return `null` to refuse a user who lost access since the consent page was shown; the
79
- browser goes to `consentPage?error=forbidden` and the client gets nothing.
100
+ A consent stays valid for 20 minutes, so submitting the form twice creates two grants for the
101
+ same client.
80
102
 
81
- Redeeming the code calls `tokens.refresh` with `grantType: "authorization_code"`, which mints the client's first
82
- token pair and must refuse a refresh token that was already used. This makes a code single-use
83
- without authlet storing anything.
103
+ ### Scopes
84
104
 
85
- A sealed consent stays valid for 20 minutes, so a user who submits the consent form twice creates
86
- two grants for the same client. Both show up in the app's token store.
105
+ Scopes are off until the app sets `scopes`. Clients then request a `scope`, and values not in
106
+ `scopes` are dropped. `readConsent` returns the requested scope, so the page can pre-check it.
107
+ `decide` takes the `scope` the user grants (default: the requested scope). It can only narrow the
108
+ request, or pick any configured scope when the client asked for none.
109
+
110
+ `tokens.issue` gets the granted scope. `tokens.refresh` gets the scope for the new access token:
111
+ the grant, or a subset the client asked for on refresh. Anything else is `invalid_scope`, and the
112
+ app's refresh token stays unused. The grant itself never changes, and the token response echoes
113
+ the access token's scope, except for a grant from before scopes were enabled.
114
+
115
+ `scope: undefined` in `issue` means scopes are off. In `refresh` it means scopes are off, or the
116
+ grant was made before they were enabled. Map it from the stored authorization, grant a default,
117
+ or return `null` to force re-authorization, but never read it as "all configured scopes". A grant
118
+ from before scopes stays unscoped across refreshes until the client authorizes again.
119
+
120
+ For step-up, a route whose token lacks a scope answers with every scope the request needs:
121
+
122
+ ```ts
123
+ if (!auth.scope.includes("write")) {
124
+ return authlet.challenge(req, { scope: ["read", "write"] }); // 403 insufficient_scope
125
+ }
126
+ ```
127
+
128
+ The client then authorizes again. It should request the scopes it holds plus the new ones, since
129
+ the new grant replaces the old one. `scope` in client registrations and metadata documents is
130
+ ignored.
87
131
 
88
132
  ## What the host app must do
89
133
 
90
134
  authlet can't check these, because they happen in the app:
91
135
 
92
- 1. Make `grantType: "authorization_code"` single-use atomically. Mark the refresh token used with a compare-and-set
93
- (a conditional update rather than a read followed by a write), or two parallel redemptions of
94
- one code both succeed. Never apply a reuse leeway to `"authorization_code"`, and revoke the whole token
95
- family when a used refresh token comes back (RFC 9700 section 4.14).
136
+ 1. Make `grantType: "authorization_code"` single-use atomically. Mark the refresh token used with
137
+ a compare-and-set, or two parallel redemptions of one code both succeed. Never apply a reuse
138
+ leeway to `"authorization_code"`, and revoke the whole token family when a used refresh token
139
+ comes back (RFC 9700 section 4.14).
96
140
  2. Treat the consent page as a security boundary:
97
- - Show the client name as unverified: anyone can register any name or write it into a
141
+ - Show the client name as unverified, since anyone can register any name or put it in a
98
142
  metadata document. For `client.kind === "metadata"`, show `client.host` as the client's
99
143
  identity instead.
100
144
  - Show the redirect URI's host (`new URL(client.redirectUri).host`), which is where the code
101
- goes. For a metadata client, warn when it is loopback (`127.0.0.1`, `localhost`): anyone can
102
- claim a public client's document from their own machine.
103
- - Send `Content-Security-Policy: frame-ancestors 'none'` and `Referrer-Policy: no-referrer`
104
- (the URL carries the sealed consent).
105
- - Never skip the page for a client the user allowed before: every registration gets a new
106
- `client_id`, and a metadata client is only as trustworthy as its host, so there is no
107
- stable client identity to remember.
108
- 3. On the login page, only follow a `returnTo` that starts with a single `/`. authlet always
109
- passes a relative path, but the login page must not become an open redirect.
110
- 4. Use a session cookie with `SameSite=Lax` or stricter. `decide` refuses cross-site submissions
111
- by their `Sec-Fetch-*` headers, or by `Origin` in browsers that don't send those.
145
+ goes. For a metadata client, warn when it is loopback (`127.0.0.1`, `localhost`), since
146
+ anyone can claim a public client's document from their own machine.
147
+ - Send `Content-Security-Policy: frame-ancestors 'none'` and `Referrer-Policy: no-referrer`.
148
+ - Never skip the page for a client the user allowed before. Every registration gets a new
149
+ `client_id`, and a metadata client is only as trustworthy as its host.
150
+ 3. On the login page, only follow a `returnTo` that starts with a single `/`.
151
+ 4. Use a session cookie with `SameSite=Lax` or stricter.
112
152
  5. Use a random secret of at least 32 bytes, or a generated `CryptoKey`, and keep it out of source
113
153
  control. Anyone with it can forge client IDs and consents, and there is no key rotation yet.
114
- 6. Derive a function-valued `resource` or `issuer` from trusted configuration only. Never take it
115
- from `Host` or `X-Forwarded-*` headers without an allowlist.
154
+ 6. Derive a function-valued `resource` or `issuer` from trusted configuration only, never from
155
+ `Host` or `X-Forwarded-*` headers without an allowlist.
156
+ 7. When `tokens.refresh` gets a `scope` array, mint the access token with exactly that scope and
157
+ check it in `verify` or the route. When it gets `undefined`, apply your own policy.
116
158
 
117
159
  ## Client ID Metadata Documents
118
160
 
119
- MCP clients may use an https URL as their `client_id` instead of registering: the URL serves a
161
+ MCP clients may use an https URL as their `client_id` instead of registering. The URL serves a
120
162
  JSON document with the client's name and redirect URIs
121
163
  ([draft-ietf-oauth-client-id-metadata-document](https://datatracker.ietf.org/doc/draft-ietf-oauth-client-id-metadata-document/)).
122
164
  authlet supports this when the app passes `fetchClientMetadata`, a `fetch`-compatible function,
123
165
  and then advertises `client_id_metadata_document_supported: true`. Without it, nothing is
124
- fetched and URL client IDs are refused at every endpoint, including codes and consents issued
125
- before it was turned off.
166
+ fetched and URL client IDs are refused at every endpoint, including for codes and consents issued
167
+ while it was on.
126
168
 
127
169
  ```ts
128
170
  fetchClientMetadata: (url, init) => guardedFetch(url, init), // Node: a fetch that blocks private IPs
129
171
  fetchClientMetadata: (url, init) => fetch(url, init), // Workers: can't reach private ranges, add a rate limit
130
172
  ```
131
173
 
132
- authlet fetches the document at the authorization endpoint, only for signed-in users, with
133
- `Accept: application/json` and `redirect: "manual"`. It refuses IP literals, `localhost` names and
134
- the issuer before fetching, and accepts only a 200 JSON response that wasn't redirected, read
135
- within 5 seconds and 5 KB. The client name is sealed into the consent, so the document is fetched
136
- once per authorization. Any failure sends the browser to `consentPage?error=invalid_link`.
174
+ authlet fetches the document at the authorization endpoint, only for signed-in users. It refuses
175
+ IP literals, `localhost` names and the issuer's own URL before fetching. It accepts only a 200
176
+ JSON response that wasn't redirected and arrives within 5 seconds and 5 KB. The client name is
177
+ sealed into the consent, so each authorization fetches the document once. Any failure sends the
178
+ browser to `consentPage?error=invalid_link`.
137
179
 
138
180
  The function is the app's SSRF control, so it must:
139
181
 
140
- - Refuse private and special-use addresses (RFC 6890) after DNS resolution, such as through an
141
- undici `Agent` with a checking `lookup` or an egress proxy. authlet's own checks see only the
182
+ - Refuse private and special-use addresses (RFC 6890) after DNS resolution, for example through
183
+ an undici `Agent` with a checking `lookup` or an egress proxy. authlet's own checks see only the
142
184
  URL.
143
185
  - Allowlist hosts or rate-limit fetches. Any site can send a signed-in user's browser to
144
- `/authorize` with a URL `client_id` of its choosing, so signed-in users can be made to trigger
145
- fetches of arbitrary URLs.
146
- - Cache by HTTP cache headers if it caches at all, but never cache errors.
147
-
148
- The token endpoint never refetches the document, so a client whose document is withdrawn keeps
149
- its refresh tokens. To cut it off, refuse it in `tokens.refresh`, which gets `client.id` (the URL)
150
- and `client.kind`.
151
-
152
- ## Interface
153
-
154
- ```ts
155
- // TAuthorization: what the consent page collects. TUser: the app's user, default { id }.
156
- const authlet = createAuthlet<Capabilities, AppUser>({
157
- resource: "https://cms.example.com/api/mcp", // the protected resource, or (req) => string
158
- issuer: "https://cms.example.com/api/mcp/oauth", // optional, this is the default
159
- getUser: async (req) => sessionUser(req), // AppUser | null
160
- loginUrl: (returnTo) =>
161
- `/admin/login?redirect=${encodeURIComponent(returnTo)}`,
162
- consentPage: "/admin/mcp/authorize", // gets ?consent=… or ?error=…
163
- secret: process.env.AUTHLET_SECRET!, // >= 32 chars, or an AES-GCM CryptoKey
164
- fetchClientMetadata: guardedFetch, // optional, enables Client ID Metadata Documents
165
- tokens: {
166
- issue: async ({ user, client, authorization, resource }) => ({
167
- refreshToken,
168
- }), // or null to refuse
169
- refresh: async ({ refreshToken, grantType, client }) => rotated ?? null, // grantType: "authorization_code" | "refresh_token"
170
- },
171
- });
186
+ `/authorize` with a `client_id` URL of its choosing.
187
+ - Cache only by HTTP cache headers, and never cache errors.
172
188
 
173
- authlet.handle(req); // Promise<Response | null>: OAuth endpoints, AS and resource metadata
174
- authlet.challenge(req); // 401 with WWW-Authenticate: Bearer resource_metadata="..."
175
- authlet.readConsent(req, consent); // Promise<Consent<AppUser> | null>, for rendering the consent page
176
- authlet.decide(req, { consent, allow: true, authorization }); // Promise<Response>: redirect with a code
177
- authlet.decide(req, { consent, allow: false }); // Promise<Response>: redirect with access_denied
178
- ```
179
-
180
- The full types are in [`src/types.ts`](src/types.ts).
181
-
182
- ## Built
183
-
184
- - `src/authlet.ts`: `createAuthlet`, routing requests to the endpoints in `src/endpoints/`:
185
- - `metadata.ts`: authorization server metadata (RFC 8414, with the OpenID discovery fields),
186
- protected resource metadata (RFC 9728), an empty JWKS.
187
- - `register.ts`: dynamic client registration (RFC 7591) for public clients, `client_id` sealed.
188
- - `authorize.ts`: PKCE S256 only, RFC 8707 `resource` checked, login and consent redirects;
189
- invalid requests go to `consentPage?error=invalid_link`, never to the client.
190
- - `consent.ts`: `readConsent` and `decide`, with `Sec-Fetch-*` checks and `iss` (RFC 9207).
191
- - `token.ts`: authorization code and refresh grants, single-use codes via refresh rotation.
192
- - `src/client.ts`: Client ID Metadata Documents: client ID URL checks, the bounded fetch and
193
- document validation.
194
- - `src/conformance.spec.ts`: the full flow driven by `oauth4webapi` with both discovery styles.
195
- - `src/types.ts`: the public types; `src/types.test-d.ts`: an MCP server's usage, type-checked.
196
- - `src/seal.ts`: the sealer, typed per sealed value (jose JWE, HKDF-derived key, `typ` and `iss`
197
- checked on unseal, fixed lifetimes: consent 20 min, code 60 s, each plus 5 s clock tolerance).
198
- - `src/urls.ts`: issuer and resource canonicalisation, endpoint URLs, and matching a request to
199
- an endpoint, including every discovery location.
200
- - `src/redirect-uri.ts`: redirect URI validation (https; http only to loopback; app schemes;
201
- no browser-handled schemes such as `javascript:`, `data:`, `blob:`, `file:`; no fragments) and
202
- matching, with loopback URIs on any port (RFC 8252 section 7.3).
203
- - `src/pkce.ts`: S256 verification, tested with the RFC 7636 vector.
189
+ The token endpoint never fetches the document again, so a client whose document is withdrawn
190
+ keeps its refresh tokens. To cut it off, refuse it in `tokens.refresh`, which gets `client.id`
191
+ (the URL) and `client.kind`.
204
192
 
205
193
  ## Base URLs
206
194
 
207
- With `resource: "https://cms.example.com/api/mcp"` the issuer is
208
- `https://cms.example.com/api/mcp/oauth`, and `handle` answers:
195
+ The issuer defaults to `${resource}/oauth`. With `resource: "https://cms.example.com/api/mcp"`,
196
+ `handle` answers:
209
197
 
210
198
  | Path | Serves | Root route needed |
211
199
  | ------------------------------------------------------- | --------------------------------------------- | ----------------- |
@@ -216,22 +204,10 @@ With `resource: "https://cms.example.com/api/mcp"` the issuer is
216
204
  | `/.well-known/openid-configuration/api/mcp/oauth` | AS metadata (OpenID, path inserted) | yes, optional |
217
205
  | `/.well-known/oauth-protected-resource/api/mcp` | resource metadata (RFC 9728 default) | yes, optional |
218
206
 
219
- Clients that follow `resource_metadata` from the 401 and try the OpenID location below the
220
- issuer, as MCP clients do, need only the first three rows. Hosts that can serve root paths can forward those requests to
221
- `handle` as well.
222
-
223
- Clients check that the issuer and resource in the metadata match exactly. authlet therefore
224
- refuses a value the URL parser would change: a trailing slash, credentials, a query or fragment,
225
- an uppercase host, a default port or dot segments. Fixed strings are checked at setup, functions
226
- on each request.
227
-
228
- `handle` matches requests on their path only, so it works behind a TLS-terminating proxy whose
229
- request URLs carry an internal scheme or host, as long as the proxy keeps the public path. An
230
- issuer at a host root claims `/authorize`, `/token` and `/register`, so pass `handle` only that
231
- host's requests.
232
-
233
- ## Planned
207
+ MCP clients need only the first three rows. Hosts that can serve root paths can forward those
208
+ requests to `handle` as well.
234
209
 
235
- - `authlet/node`: a `node:http` / Express bridge.
236
- - A private example app that runs the flow against MCP Inspector over real HTTP.
237
- - Scopes (`scopes_supported`, `scope` in the challenge, `insufficient_scope`), key rotation.
210
+ `issuer` and `resource` must be canonical URLs: no trailing slash, credentials, query, fragment,
211
+ uppercase host, default port or dot segments. `handle` matches on the path only, so it works
212
+ behind a TLS-terminating proxy that keeps the public path. An issuer at a host root claims
213
+ `/authorize`, `/token` and `/register`, so pass `handle` only that host's requests.
package/dist/authlet.js CHANGED
@@ -5,6 +5,7 @@ import { authorizationServerMetadata, jwks, resourceMetadata, } from "./endpoint
5
5
  import { register } from "./endpoints/register.js";
6
6
  import { token } from "./endpoints/token.js";
7
7
  import { methodNotAllowed, preflight, withParams } from "./http.js";
8
+ import { assertScopes } from "./scope.js";
8
9
  import { createSealer } from "./seal.js";
9
10
  import { deriveUrls, matchEndpoint } from "./urls.js";
10
11
  // RFC 6750 section 2.1 b64token.
@@ -29,6 +30,9 @@ const createAuthlet = (options) => {
29
30
  if (typeof options.consentPage === "string") {
30
31
  withParams(options.consentPage, {});
31
32
  }
33
+ if (options.scopes) {
34
+ assertScopes(options.scopes, true);
35
+ }
32
36
  const routes = {
33
37
  authorize: { method: "GET", cors: false, run: authorize },
34
38
  token: { method: "POST", cors: true, run: token },
@@ -37,17 +41,33 @@ const createAuthlet = (options) => {
37
41
  authorizationServerMetadata: {
38
42
  method: "GET",
39
43
  cors: true,
40
- run: ({ urls }) => authorizationServerMetadata(urls, Boolean(options.fetchClientMetadata)),
44
+ run: ({ urls }) => authorizationServerMetadata(urls, Boolean(options.fetchClientMetadata), options.scopes),
41
45
  },
42
46
  resourceMetadata: {
43
47
  method: "GET",
44
48
  cors: true,
45
- run: ({ urls }) => resourceMetadata(urls),
49
+ run: ({ urls }) => resourceMetadata(urls, options.scopes),
46
50
  },
47
51
  };
48
- const challenge = (req) => {
52
+ const challenge = (req, challengeOptions) => {
49
53
  const { urls } = contextFor(req);
50
54
  const params = [`resource_metadata="${urls.resourceMetadata}"`];
55
+ // RFC 6750 section 3.1: a token without the scopes the request needs.
56
+ if (challengeOptions?.scope !== undefined) {
57
+ const { scope } = challengeOptions;
58
+ // Also keeps quotes and separators out of the header.
59
+ assertScopes(scope, false);
60
+ return new Response(null, {
61
+ status: 403,
62
+ headers: {
63
+ "WWW-Authenticate": `Bearer ${[
64
+ 'error="insufficient_scope"',
65
+ ...(scope.length ? [`scope="${scope.join(" ")}"`] : []),
66
+ ...params,
67
+ ].join(", ")}`,
68
+ },
69
+ });
70
+ }
51
71
  // RFC 6750 section 3.1: a request that sent a bearer token learns it was rejected.
52
72
  if (/^bearer\b/i.test(req.headers.get("Authorization") ?? "")) {
53
73
  params.unshift('error="invalid_token"');
@@ -3,6 +3,7 @@ import { getBrowserUser, toConsentPage } from "../context.js";
3
3
  import { redirect } from "../http.js";
4
4
  import { isCodeChallenge } from "../pkce.js";
5
5
  import { isRegisteredRedirectUri } from "../redirect-uri.js";
6
+ import { parseScope } from "../scope.js";
6
7
  const MAX_STATE_LENGTH = 1024;
7
8
  /**
8
9
  * The authorization endpoint. A valid request from a signed-in browser user goes to the app's
@@ -56,6 +57,10 @@ const authorize = async (ctx) => {
56
57
  userId: user.id,
57
58
  ...(state === null ? {} : { state }),
58
59
  ...(isClientIdUrl(clientId) ? { clientName: client.name } : {}),
60
+ // Unknown scopes are dropped, since errors never go back to the client.
61
+ ...(options.scopes?.length
62
+ ? { scope: parseScope(params.get("scope"), options.scopes) }
63
+ : {}),
59
64
  },
60
65
  });
61
66
  return toConsentPage(ctx, { consent });
@@ -1,6 +1,7 @@
1
1
  import { isClientIdUrl } from "../client.js";
2
2
  import { getBrowserUser, toConsentPage } from "../context.js";
3
3
  import { redirect, withParams } from "../http.js";
4
+ import { parseScope } from "../scope.js";
4
5
  /** The consent behind a sealed value, if it is valid and shown to the user signed in now. */
5
6
  const loadConsent = async (ctx, value) => {
6
7
  const { issuer } = ctx.urls;
@@ -41,6 +42,7 @@ const readConsent = async (ctx, value) => {
41
42
  client: loaded.client,
42
43
  user: loaded.user,
43
44
  resource: loaded.consent.resource,
45
+ scope: loaded.consent.scope ?? [],
44
46
  });
45
47
  };
46
48
  /**
@@ -82,11 +84,19 @@ const decide = async (ctx, args) => {
82
84
  if (!args.allow) {
83
85
  return toClient({ error: "access_denied" });
84
86
  }
87
+ const { scopes } = ctx.options;
88
+ let scope;
89
+ if (scopes?.length) {
90
+ // The request is a ceiling the user can only lower; an empty one allows any configured scope.
91
+ const requested = parseScope(consent.scope, scopes);
92
+ scope = parseScope(args.scope ?? requested, requested.length ? requested : scopes);
93
+ }
85
94
  const issued = await ctx.options.tokens.issue({
86
95
  user,
87
96
  client,
88
97
  authorization: args.authorization,
89
98
  resource: consent.resource,
99
+ scope,
90
100
  });
91
101
  if (!issued) {
92
102
  return toConsentPage(ctx, { error: "forbidden" }, 303);
@@ -100,6 +110,7 @@ const decide = async (ctx, args) => {
100
110
  codeChallenge: consent.codeChallenge,
101
111
  resource: consent.resource,
102
112
  refreshToken: issued.refreshToken,
113
+ ...(scope ? { scope } : {}),
103
114
  },
104
115
  });
105
116
  return toClient({ code });
@@ -4,8 +4,8 @@ import type { AuthletUrls } from "../urls.js";
4
4
  * carries the fields OpenID discovery requires, since some clients (MCP among them) read it from
5
5
  * `openid-configuration`; no ID tokens are issued.
6
6
  */
7
- declare const authorizationServerMetadata: (urls: AuthletUrls, clientMetadataDocuments: boolean) => Response;
7
+ declare const authorizationServerMetadata: (urls: AuthletUrls, clientMetadataDocuments: boolean, scopes: readonly string[] | undefined) => Response;
8
8
  /** Protected resource metadata (RFC 9728) for the resource. */
9
- declare const resourceMetadata: (urls: AuthletUrls) => Response;
9
+ declare const resourceMetadata: (urls: AuthletUrls, scopes: readonly string[] | undefined) => Response;
10
10
  declare const jwks: () => Response;
11
11
  export { authorizationServerMetadata, jwks, resourceMetadata };
@@ -4,7 +4,7 @@ import { json } from "../http.js";
4
4
  * carries the fields OpenID discovery requires, since some clients (MCP among them) read it from
5
5
  * `openid-configuration`; no ID tokens are issued.
6
6
  */
7
- const authorizationServerMetadata = (urls, clientMetadataDocuments) => json({
7
+ const authorizationServerMetadata = (urls, clientMetadataDocuments, scopes) => json({
8
8
  issuer: urls.issuer,
9
9
  authorization_endpoint: urls.authorizationEndpoint,
10
10
  token_endpoint: urls.tokenEndpoint,
@@ -20,12 +20,14 @@ const authorizationServerMetadata = (urls, clientMetadataDocuments) => json({
20
20
  ...(clientMetadataDocuments
21
21
  ? { client_id_metadata_document_supported: true }
22
22
  : {}),
23
+ ...(scopes?.length ? { scopes_supported: [...scopes] } : {}),
23
24
  });
24
25
  /** Protected resource metadata (RFC 9728) for the resource. */
25
- const resourceMetadata = (urls) => json({
26
+ const resourceMetadata = (urls, scopes) => json({
26
27
  resource: urls.resource,
27
28
  authorization_servers: [urls.issuer],
28
29
  bearer_methods_supported: ["header"],
30
+ ...(scopes?.length ? { scopes_supported: [...scopes] } : {}),
29
31
  });
30
32
  const jwks = () => json({ keys: [] });
31
33
  export { authorizationServerMetadata, jwks, resourceMetadata };
@@ -1,6 +1,7 @@
1
1
  import { isClientIdUrl } from "../client.js";
2
2
  import { json, oauthError, readBody } from "../http.js";
3
3
  import { verifyCodeChallenge } from "../pkce.js";
4
+ import { parseScope, splitScope } from "../scope.js";
4
5
  /** A parameter the client may leave out, but that must match when sent. */
5
6
  const matchesIfSent = (form, name, expected) => !form.has(name) || form.get(name) === expected;
6
7
  /** The grant behind a code, if the code is valid for this client and its PKCE verifier. */
@@ -17,7 +18,11 @@ const unsealCode = async ({ urls, sealer }, form, clientId) => {
17
18
  !(await verifyCodeChallenge(form.get("code_verifier") ?? "", code.codeChallenge))) {
18
19
  return null;
19
20
  }
20
- return { refreshToken: code.refreshToken, resource: code.resource };
21
+ return {
22
+ refreshToken: code.refreshToken,
23
+ resource: code.resource,
24
+ rawScope: code.scope,
25
+ };
21
26
  };
22
27
  /** The grant behind a refresh token, if it was issued to this client. */
23
28
  const unsealRefreshToken = async ({ urls, sealer }, form, clientId) => {
@@ -28,7 +33,11 @@ const unsealRefreshToken = async ({ urls, sealer }, form, clientId) => {
28
33
  });
29
34
  return wrapper?.clientId === clientId &&
30
35
  matchesIfSent(form, "resource", wrapper.resource)
31
- ? { refreshToken: wrapper.refreshToken, resource: wrapper.resource }
36
+ ? {
37
+ refreshToken: wrapper.refreshToken,
38
+ resource: wrapper.resource,
39
+ rawScope: wrapper.scope,
40
+ }
32
41
  : null;
33
42
  };
34
43
  const REQUIRED_PARAMS = {
@@ -59,17 +68,32 @@ const token = async (ctx) => {
59
68
  const grant = isCode
60
69
  ? await unsealCode(ctx, form, clientId)
61
70
  : await unsealRefreshToken(ctx, form, clientId);
71
+ if (!grant) {
72
+ return oauthError("invalid_grant");
73
+ }
74
+ const { scopes } = ctx.options;
75
+ let scope;
76
+ // A refresh may narrow the grant, never widen it, and is checked before the app's token is used.
77
+ if (scopes?.length) {
78
+ const requested = isCode ? [] : splitScope(form.get("scope"));
79
+ const granted = grant.rawScope && parseScope(grant.rawScope, scopes);
80
+ if (requested.some((value) => !granted?.includes(value))) {
81
+ return oauthError("invalid_scope");
82
+ }
83
+ scope =
84
+ granted && (requested.length ? parseScope(requested, granted) : granted);
85
+ }
62
86
  /*
63
87
  * Redeeming a code rotates the refresh token sealed in it. The app refuses a used one, so a
64
88
  * code works only once.
65
89
  */
66
- const tokens = grant &&
67
- (await ctx.options.tokens.refresh({
68
- refreshToken: grant.refreshToken,
69
- client: { id: clientId, kind },
70
- grantType,
71
- }));
72
- if (!grant || !tokens) {
90
+ const tokens = await ctx.options.tokens.refresh({
91
+ refreshToken: grant.refreshToken,
92
+ client: { id: clientId, kind },
93
+ grantType,
94
+ scope,
95
+ });
96
+ if (!tokens) {
73
97
  return oauthError("invalid_grant");
74
98
  }
75
99
  const refreshToken = await ctx.sealer.seal({
@@ -79,6 +103,8 @@ const token = async (ctx) => {
79
103
  clientId,
80
104
  resource: grant.resource,
81
105
  refreshToken: tokens.refreshToken,
106
+ // The grant itself never changes, whatever this access token got.
107
+ ...(grant.rawScope ? { scope: grant.rawScope } : {}),
82
108
  },
83
109
  });
84
110
  return json({
@@ -86,6 +112,7 @@ const token = async (ctx) => {
86
112
  token_type: "Bearer",
87
113
  refresh_token: refreshToken,
88
114
  ...(tokens.expiresIn === undefined ? {} : { expires_in: tokens.expiresIn }),
115
+ ...(scope ? { scope: scope.join(" ") } : {}),
89
116
  });
90
117
  };
91
118
  export { token };
@@ -0,0 +1,10 @@
1
+ /** Splits a space-delimited `scope` parameter into its entries. */
2
+ declare const splitScope: (value: string | null | undefined) => string[];
3
+ /**
4
+ * The entries of `allowed` present in `value`, in `allowed` order and without duplicates.
5
+ * Anything else is dropped.
6
+ */
7
+ declare const parseScope: (value: string | null | readonly string[] | undefined, allowed: readonly string[]) => string[];
8
+ /** Throws on a value that isn't a scope token, or, with `unique`, on a duplicate. */
9
+ declare const assertScopes: (scopes: readonly string[], unique: boolean) => void;
10
+ export { assertScopes, parseScope, splitScope };
package/dist/scope.js ADDED
@@ -0,0 +1,24 @@
1
+ // RFC 6749 section 3.3 scope-token: %x21 / %x23-5B / %x5D-7E.
2
+ const SCOPE_TOKEN = /^[\x21\x23-\x5b\x5d-\x7e]+$/;
3
+ /** Splits a space-delimited `scope` parameter into its entries. */
4
+ const splitScope = (value) => (value ?? "").split(" ").filter(Boolean);
5
+ /**
6
+ * The entries of `allowed` present in `value`, in `allowed` order and without duplicates.
7
+ * Anything else is dropped.
8
+ */
9
+ const parseScope = (value, allowed) => {
10
+ const entries = new Set(typeof value === "string" || !value ? splitScope(value) : value);
11
+ return allowed.filter((scope) => entries.has(scope));
12
+ };
13
+ /** Throws on a value that isn't a scope token, or, with `unique`, on a duplicate. */
14
+ const assertScopes = (scopes, unique) => {
15
+ for (const [index, scope] of scopes.entries()) {
16
+ if (!SCOPE_TOKEN.test(scope)) {
17
+ throw new Error(`A scope must be a scope token, got "${scope}".`);
18
+ }
19
+ if (unique && scopes.indexOf(scope) !== index) {
20
+ throw new Error(`The authlet scope "${scope}" is listed twice.`);
21
+ }
22
+ }
23
+ };
24
+ export { assertScopes, parseScope, splitScope };
package/dist/seal.d.ts CHANGED
@@ -18,6 +18,8 @@ interface SealedValues {
18
18
  userId: string;
19
19
  /** The metadata document's client name, so the consent page needs no second fetch. */
20
20
  clientName?: string;
21
+ /** Requested scope within `scopes`. Present on scoped hosts, even empty. */
22
+ scope?: string[];
21
23
  };
22
24
  /** The authorization code, carrying the refresh token the app issued on consent. */
23
25
  code: {
@@ -26,12 +28,16 @@ interface SealedValues {
26
28
  codeChallenge: string;
27
29
  resource: string;
28
30
  refreshToken: string;
31
+ /** Granted scope. Present on scoped hosts, even empty. */
32
+ scope?: string[];
29
33
  };
30
34
  /** The `refresh_token` handed to the client, wrapping the app's own refresh token. */
31
35
  refresh: {
32
36
  clientId: string;
33
37
  resource: string;
34
38
  refreshToken: string;
39
+ /** Granted scope, resealed unchanged on every rotation. Absent: no scoped grant. */
40
+ scope?: string[];
35
41
  };
36
42
  }
37
43
  type SealType = keyof SealedValues;
package/dist/types.d.ts CHANGED
@@ -51,6 +51,8 @@ export interface IssueTokensArgs<TAuthorization, TUser extends AuthletUser> {
51
51
  authorization: TAuthorization;
52
52
  /** The protected resource (RFC 8707) the tokens are for. */
53
53
  resource: string;
54
+ /** The scope the user granted, within the requested scope. `undefined` when scopes are off. */
55
+ scope: string[] | undefined;
54
56
  }
55
57
  export interface RefreshTokensArgs {
56
58
  refreshToken: string;
@@ -61,6 +63,12 @@ export interface RefreshTokensArgs {
61
63
  * `"refresh_token"` the app may allow its own reuse leeway.
62
64
  */
63
65
  grantType: "authorization_code" | "refresh_token";
66
+ /**
67
+ * The scope to mint the access token with: the granted scope, or the subset the client asked
68
+ * for. `undefined` when scopes are off, or for a grant made before they were enabled; the app
69
+ * then applies its own policy (or returns `null` to force re-authorization).
70
+ */
71
+ scope: string[] | undefined;
64
72
  }
65
73
  /** Token storage and minting, owned by the app. */
66
74
  export interface TokenHooks<TAuthorization, TUser extends AuthletUser> {
@@ -127,12 +135,20 @@ export interface AuthletOptions<TAuthorization = unknown, TUser extends AuthletU
127
135
  * browser trigger a fetch. It may cache by HTTP cache headers, but never errors.
128
136
  */
129
137
  fetchClientMetadata?: (url: string, init: RequestInit) => Promise<Response>;
138
+ /**
139
+ * Scopes clients may request (RFC 6749 section 3.3), advertised as `scopes_supported`.
140
+ * Others are dropped at the authorization endpoint. Unset or empty turns scopes off, and
141
+ * `scope` parameters are ignored.
142
+ */
143
+ scopes?: readonly string[];
130
144
  }
131
145
  /** A pending authorization, as shown on the consent page. */
132
146
  export interface Consent<TUser extends AuthletUser = AuthletUser> {
133
147
  client: AuthletClient;
134
148
  user: TUser;
135
149
  resource: string;
150
+ /** The scope the client requested, within `scopes`, for pre-checking the consent form. */
151
+ scope: string[];
136
152
  }
137
153
  /**
138
154
  * The user's answer on the consent page. `consent` is the sealed consent the page was opened
@@ -142,6 +158,11 @@ export type DecideArgs<TAuthorization> = {
142
158
  consent: string;
143
159
  allow: true;
144
160
  authorization: TAuthorization;
161
+ /**
162
+ * The scope the user grants. Default: the requested scope. Kept within the requested
163
+ * scope, or within `scopes` when the client requested none.
164
+ */
165
+ scope?: readonly string[];
145
166
  } | {
146
167
  consent: string;
147
168
  allow: false;
@@ -155,10 +176,14 @@ export interface Authlet<TAuthorization = unknown, TUser extends AuthletUser = A
155
176
  */
156
177
  handle: (req: Request) => Promise<Response | null>;
157
178
  /**
158
- * The 401 for a request to the resource without a valid token. Its `resource_metadata` points
159
- * below the issuer, which RFC 9728 clients follow, so discovery works under a base path.
179
+ * Without `scope`: the 401 for a request to the resource without a valid token. Its
180
+ * `resource_metadata` points below the issuer, which RFC 9728 clients follow, so discovery
181
+ * works under a base path. With `scope`: the 403 `insufficient_scope` (RFC 6750 section 3.1)
182
+ * naming every scope the request needs. Throws on a value that isn't a scope token.
160
183
  */
161
- challenge: (req: Request) => Response;
184
+ challenge: (req: Request, options?: {
185
+ scope: readonly string[];
186
+ }) => Response;
162
187
  /**
163
188
  * The app's auth info for a request bearing `Authorization: Bearer <token>` that `verify`
164
189
  * accepts, else the `challenge` 401 (with `error="invalid_token"` when a bearer token was sent).
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "authlet",
4
- "version": "0.1.0-beta.4",
4
+ "version": "0.1.0-beta.7",
5
5
  "description": "Stateless, runtime-agnostic OAuth 2.1 authorization server built on Web Request and Response.",
6
6
  "keywords": [
7
7
  "oauth",
@@ -56,14 +56,14 @@
56
56
  "@abinnovision/eslint-config-base": "^3.4.2",
57
57
  "@abinnovision/prettier-config": "^2.2.0",
58
58
  "@internal/tsconfig": "0.0.0",
59
- "@types/node": "^24",
60
- "@vitest/coverage-v8": "^5.0.3",
61
- "eslint": "^10.12.0",
59
+ "@types/node": "^26",
60
+ "@vitest/coverage-v8": "^5.1.2",
61
+ "eslint": "^10.15.0",
62
62
  "oauth4webapi": "^3.8.9",
63
- "prettier": "^3.9.9",
63
+ "prettier": "^3.10.1",
64
64
  "typescript": "^6.0.3",
65
- "vite": "^8.3.4",
66
- "vitest": "^5.0.3"
65
+ "vite": "^8.4.0",
66
+ "vitest": "^5.1.2"
67
67
  },
68
68
  "engines": {
69
69
  "node": ">=22"