authlet 0.1.0-beta.4 → 0.1.0-beta.5

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 (2) hide show
  1. package/README.md +94 -153
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -3,39 +3,57 @@
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) and refresh token
9
+ rotation. MCP clients use this profile, so an MCP server is the typical host, but any API can use
10
+ it. There is no client credentials or device flow, no OpenID Connect ID tokens, and no scopes yet.
11
11
 
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.
12
+ ## Usage
14
13
 
15
- ## Design
14
+ ```ts
15
+ // TAuthorization: what the consent page collects. TUser: the app's user, default { id }.
16
+ const authlet = createAuthlet<Capabilities, AppUser>({
17
+ resource: "https://cms.example.com/api/mcp", // the protected resource, or (req) => string
18
+ issuer: "https://cms.example.com/api/mcp/oauth", // optional, this is the default
19
+ getUser: async (req) => sessionUser(req), // AppUser | null
20
+ loginUrl: (returnTo) =>
21
+ `/admin/login?redirect=${encodeURIComponent(returnTo)}`,
22
+ consentPage: "/admin/mcp/authorize", // gets ?consent=… or ?error=…
23
+ secret: process.env.AUTHLET_SECRET!, // >= 32 chars, or an AES-GCM CryptoKey
24
+ fetchClientMetadata: guardedFetch, // optional, enables Client ID Metadata Documents
25
+ tokens: {
26
+ issue: async ({ user, client, authorization, resource }) => ({
27
+ refreshToken,
28
+ }), // or null to refuse
29
+ refresh: async ({ refreshToken, grantType, client }) => rotated ?? null, // grantType: "authorization_code" | "refresh_token"
30
+ },
31
+ });
16
32
 
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.
33
+ authlet.handle(req); // Promise<Response | null>: OAuth endpoints, AS and resource metadata
34
+ authlet.authenticate(req, verify); // Promise<T | Response>: the app's auth info, or the 401
35
+ authlet.challenge(req); // 401 with WWW-Authenticate: Bearer resource_metadata="..."
36
+ authlet.readConsent(req, consent); // Promise<Consent<AppUser> | null>, for rendering the consent page
37
+ authlet.decide(req, { consent, allow: true, authorization }); // Promise<Response>: redirect with a code
38
+ authlet.decide(req, { consent, allow: false }); // Promise<Response>: redirect with access_denied
39
+ ```
21
40
 
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)).
41
+ ## How it works
24
42
 
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.
43
+ authlet stores nothing. Registered client IDs, consents, authorization codes and refresh token
44
+ wrappers are encrypted and held by the client or browser. The app's `tokens` hooks own all
45
+ persistence.
30
46
 
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`.
47
+ The app also owns the user, the consent screen and the access tokens:
34
48
 
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.
49
+ - `getUser` reads the browser session and returns the app's own user type. authlet only compares
50
+ `id`, so it must be unique across the app. Requests with an `Authorization` header never reach
51
+ `getUser`, so a token can't approve a client for itself.
52
+ - authlet redirects to `consentPage?consent=…`, or to `?error=…` for a broken link. The page reads
53
+ the request with `readConsent`, and its POST handler calls `decide`.
54
+ - On the protected resource, `authenticate` passes the bearer token to the app's `verify`, which
55
+ checks it, including that it was issued for this resource, and returns the app's auth info or
56
+ `null`. A missing or rejected token gets the `challenge` 401.
39
57
 
40
58
  ```ts
41
59
  const auth = await authlet.authenticate(req, verifyToken);
@@ -45,17 +63,12 @@ if (auth instanceof Response) {
45
63
  }
46
64
  ```
47
65
 
48
- ### App-specific authorization data
66
+ ### Consent
49
67
 
50
68
  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:
69
+ The POST handler validates it and passes it to `decide`:
54
70
 
55
71
  ```ts
56
- const authlet = createAuthlet<Capabilities>({/* ... */});
57
-
58
- // The consent form's POST handler, in the app
59
72
  export const POST = async (req: Request) => {
60
73
  const form = await req.formData();
61
74
  const consent = String(form.get("consent"));
@@ -69,143 +82,83 @@ export const POST = async (req: Request) => {
69
82
  };
70
83
  ```
71
84
 
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.
77
-
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.
85
+ `decide` accepts only a top-level same-origin form submission without an `Authorization` header,
86
+ from the user the consent was shown to. It calls `tokens.issue({ user, client, authorization,
87
+ resource })`, and the app stores the authorization and returns a refresh token for it. authlet
88
+ seals that token into an authorization code valid for 60 seconds. No access token exists yet, so
89
+ none passes through the browser. `issue` may return `null` to refuse a user who lost access; the
90
+ browser then goes to `consentPage?error=forbidden`.
80
91
 
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.
92
+ Redeeming the code calls `tokens.refresh` with `grantType: "authorization_code"`, which mints the
93
+ client's first token pair. Refusing a refresh token that was already used makes the code
94
+ single-use.
84
95
 
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.
96
+ A consent stays valid for 20 minutes, so submitting the form twice creates two grants for the
97
+ same client.
87
98
 
88
99
  ## What the host app must do
89
100
 
90
101
  authlet can't check these, because they happen in the app:
91
102
 
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).
103
+ 1. Make `grantType: "authorization_code"` single-use atomically. Mark the refresh token used with
104
+ a compare-and-set, or two parallel redemptions of one code both succeed. Never apply a reuse
105
+ leeway to `"authorization_code"`, and revoke the whole token family when a used refresh token
106
+ comes back (RFC 9700 section 4.14).
96
107
  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
108
+ - Show the client name as unverified, since anyone can register any name or put it in a
98
109
  metadata document. For `client.kind === "metadata"`, show `client.host` as the client's
99
110
  identity instead.
100
111
  - 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.
112
+ goes. For a metadata client, warn when it is loopback (`127.0.0.1`, `localhost`), since
113
+ anyone can claim a public client's document from their own machine.
114
+ - Send `Content-Security-Policy: frame-ancestors 'none'` and `Referrer-Policy: no-referrer`.
115
+ - Never skip the page for a client the user allowed before. Every registration gets a new
116
+ `client_id`, and a metadata client is only as trustworthy as its host.
117
+ 3. On the login page, only follow a `returnTo` that starts with a single `/`.
118
+ 4. Use a session cookie with `SameSite=Lax` or stricter.
112
119
  5. Use a random secret of at least 32 bytes, or a generated `CryptoKey`, and keep it out of source
113
120
  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.
121
+ 6. Derive a function-valued `resource` or `issuer` from trusted configuration only, never from
122
+ `Host` or `X-Forwarded-*` headers without an allowlist.
116
123
 
117
124
  ## Client ID Metadata Documents
118
125
 
119
- MCP clients may use an https URL as their `client_id` instead of registering: the URL serves a
126
+ MCP clients may use an https URL as their `client_id` instead of registering. The URL serves a
120
127
  JSON document with the client's name and redirect URIs
121
128
  ([draft-ietf-oauth-client-id-metadata-document](https://datatracker.ietf.org/doc/draft-ietf-oauth-client-id-metadata-document/)).
122
129
  authlet supports this when the app passes `fetchClientMetadata`, a `fetch`-compatible function,
123
130
  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.
131
+ fetched and URL client IDs are refused at every endpoint, including for codes and consents issued
132
+ while it was on.
126
133
 
127
134
  ```ts
128
135
  fetchClientMetadata: (url, init) => guardedFetch(url, init), // Node: a fetch that blocks private IPs
129
136
  fetchClientMetadata: (url, init) => fetch(url, init), // Workers: can't reach private ranges, add a rate limit
130
137
  ```
131
138
 
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`.
139
+ authlet fetches the document at the authorization endpoint, only for signed-in users. It refuses
140
+ IP literals, `localhost` names and the issuer's own URL before fetching. It accepts only a 200
141
+ JSON response that wasn't redirected and arrives within 5 seconds and 5 KB. The client name is
142
+ sealed into the consent, so each authorization fetches the document once. Any failure sends the
143
+ browser to `consentPage?error=invalid_link`.
137
144
 
138
145
  The function is the app's SSRF control, so it must:
139
146
 
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
147
+ - Refuse private and special-use addresses (RFC 6890) after DNS resolution, for example through
148
+ an undici `Agent` with a checking `lookup` or an egress proxy. authlet's own checks see only the
142
149
  URL.
143
150
  - 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.
151
+ `/authorize` with a `client_id` URL of its choosing.
152
+ - Cache only by HTTP cache headers, and never cache errors.
147
153
 
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
- });
172
-
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.
154
+ The token endpoint never fetches the document again, so a client whose document is withdrawn
155
+ keeps its refresh tokens. To cut it off, refuse it in `tokens.refresh`, which gets `client.id`
156
+ (the URL) and `client.kind`.
204
157
 
205
158
  ## Base URLs
206
159
 
207
- With `resource: "https://cms.example.com/api/mcp"` the issuer is
208
- `https://cms.example.com/api/mcp/oauth`, and `handle` answers:
160
+ The issuer defaults to `${resource}/oauth`. With `resource: "https://cms.example.com/api/mcp"`,
161
+ `handle` answers:
209
162
 
210
163
  | Path | Serves | Root route needed |
211
164
  | ------------------------------------------------------- | --------------------------------------------- | ----------------- |
@@ -216,22 +169,10 @@ With `resource: "https://cms.example.com/api/mcp"` the issuer is
216
169
  | `/.well-known/openid-configuration/api/mcp/oauth` | AS metadata (OpenID, path inserted) | yes, optional |
217
170
  | `/.well-known/oauth-protected-resource/api/mcp` | resource metadata (RFC 9728 default) | yes, optional |
218
171
 
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
172
+ MCP clients need only the first three rows. Hosts that can serve root paths can forward those
173
+ requests to `handle` as well.
234
174
 
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.
175
+ `issuer` and `resource` must be canonical URLs: no trailing slash, credentials, query, fragment,
176
+ uppercase host, default port or dot segments. `handle` matches on the path only, so it works
177
+ behind a TLS-terminating proxy that keeps the public path. An issuer at a host root claims
178
+ `/authorize`, `/token` and `/register`, so pass `handle` only that host's requests.
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.5",
5
5
  "description": "Stateless, runtime-agnostic OAuth 2.1 authorization server built on Web Request and Response.",
6
6
  "keywords": [
7
7
  "oauth",