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.
- package/README.md +94 -153
- 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
|
|
7
|
-
(RFC 7591), optional [Client ID Metadata Documents](#client-id-metadata-documents),
|
|
8
|
-
|
|
9
|
-
|
|
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
|
-
|
|
13
|
-
> end-to-end run with `oauth4webapi` passes. [Planned](#planned) lists what is missing.
|
|
12
|
+
## Usage
|
|
14
13
|
|
|
15
|
-
|
|
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
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
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
|
-
|
|
23
|
-
a base path without routes at the site root ([Base URLs](#base-urls)).
|
|
41
|
+
## How it works
|
|
24
42
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
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
|
|
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
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
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
|
-
###
|
|
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
|
|
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`
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
an authorization code valid for 60 seconds
|
|
76
|
-
|
|
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
|
|
82
|
-
token pair
|
|
83
|
-
|
|
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
|
|
86
|
-
|
|
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
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
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
|
|
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`)
|
|
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
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
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
|
|
115
|
-
|
|
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
|
|
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
|
-
|
|
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
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
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,
|
|
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
|
|
145
|
-
|
|
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
|
|
149
|
-
its refresh tokens. To cut it off, refuse it in `tokens.refresh`, which gets `client.id`
|
|
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"
|
|
208
|
-
`
|
|
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
|
-
|
|
220
|
-
|
|
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
|
-
|
|
236
|
-
|
|
237
|
-
-
|
|
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
|
+
"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",
|