authlet 0.1.0-beta.3 → 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 +118 -128
- package/dist/authlet.js +20 -12
- package/dist/client.d.ts +16 -0
- package/dist/client.js +107 -0
- package/dist/endpoints/authorize.js +12 -11
- package/dist/endpoints/consent.js +27 -16
- package/dist/endpoints/metadata.d.ts +1 -1
- package/dist/endpoints/metadata.js +4 -1
- package/dist/endpoints/register.d.ts +3 -1
- package/dist/endpoints/register.js +6 -4
- package/dist/endpoints/token.js +7 -1
- package/dist/http.d.ts +3 -4
- package/dist/http.js +28 -8
- package/dist/seal.d.ts +2 -0
- package/dist/types.d.ts +28 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -3,49 +3,72 @@
|
|
|
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),
|
|
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
|
+
});
|
|
32
|
+
|
|
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
|
+
```
|
|
16
40
|
|
|
17
|
-
|
|
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.
|
|
41
|
+
## How it works
|
|
21
42
|
|
|
22
|
-
|
|
23
|
-
|
|
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.
|
|
24
46
|
|
|
25
|
-
The app owns the user
|
|
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
|
+
The app also owns the user, the consent screen and the access tokens:
|
|
30
48
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
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.
|
|
34
57
|
|
|
35
|
-
|
|
36
|
-
|
|
58
|
+
```ts
|
|
59
|
+
const auth = await authlet.authenticate(req, verifyToken);
|
|
37
60
|
|
|
38
|
-
|
|
61
|
+
if (auth instanceof Response) {
|
|
62
|
+
return auth;
|
|
63
|
+
}
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### Consent
|
|
39
67
|
|
|
40
68
|
The consent screen can collect data of its own, such as the capabilities a user allows a client.
|
|
41
|
-
The
|
|
42
|
-
[`src/types.test-d.ts`](src/types.test-d.ts) writes this out for an MCP server, and `yarn check`
|
|
43
|
-
compiles it, so the example can't drift from the types:
|
|
69
|
+
The POST handler validates it and passes it to `decide`:
|
|
44
70
|
|
|
45
71
|
```ts
|
|
46
|
-
const authlet = createAuthlet<Capabilities>({/* ... */});
|
|
47
|
-
|
|
48
|
-
// The consent form's POST handler, in the app
|
|
49
72
|
export const POST = async (req: Request) => {
|
|
50
73
|
const form = await req.formData();
|
|
51
74
|
const consent = String(form.get("consent"));
|
|
@@ -59,101 +82,83 @@ export const POST = async (req: Request) => {
|
|
|
59
82
|
};
|
|
60
83
|
```
|
|
61
84
|
|
|
62
|
-
`decide`
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
an authorization code valid for 60 seconds
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
`issue` may return `null` to refuse a user who lost access since the consent page was shown; the
|
|
69
|
-
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`.
|
|
70
91
|
|
|
71
|
-
Redeeming the code calls `tokens.refresh` with `grantType: "authorization_code"`, which mints the
|
|
72
|
-
token pair
|
|
73
|
-
|
|
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.
|
|
74
95
|
|
|
75
|
-
A
|
|
76
|
-
|
|
96
|
+
A consent stays valid for 20 minutes, so submitting the form twice creates two grants for the
|
|
97
|
+
same client.
|
|
77
98
|
|
|
78
99
|
## What the host app must do
|
|
79
100
|
|
|
80
101
|
authlet can't check these, because they happen in the app:
|
|
81
102
|
|
|
82
|
-
1. Make `grantType: "authorization_code"` single-use atomically. Mark the refresh token used with
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
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).
|
|
86
107
|
2. Treat the consent page as a security boundary:
|
|
87
|
-
- Show the client name as unverified
|
|
108
|
+
- Show the client name as unverified, since anyone can register any name or put it in a
|
|
109
|
+
metadata document. For `client.kind === "metadata"`, show `client.host` as the client's
|
|
110
|
+
identity instead.
|
|
88
111
|
- Show the redirect URI's host (`new URL(client.redirectUri).host`), which is where the code
|
|
89
|
-
goes.
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
- Never skip the page for a client the user allowed before
|
|
93
|
-
`client_id`,
|
|
94
|
-
3. On the login page, only follow a `returnTo` that starts with a single `/`.
|
|
95
|
-
|
|
96
|
-
4. Use a session cookie with `SameSite=Lax` or stricter. `decide` refuses cross-site submissions
|
|
97
|
-
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.
|
|
98
119
|
5. Use a random secret of at least 32 bytes, or a generated `CryptoKey`, and keep it out of source
|
|
99
120
|
control. Anyone with it can forge client IDs and consents, and there is no key rotation yet.
|
|
100
|
-
6. Derive a function-valued `resource` or `issuer` from trusted configuration only
|
|
101
|
-
|
|
121
|
+
6. Derive a function-valued `resource` or `issuer` from trusted configuration only, never from
|
|
122
|
+
`Host` or `X-Forwarded-*` headers without an allowlist.
|
|
102
123
|
|
|
103
|
-
##
|
|
124
|
+
## Client ID Metadata Documents
|
|
104
125
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
`/admin/login?redirect=${encodeURIComponent(returnTo)}`,
|
|
113
|
-
consentPage: "/admin/mcp/authorize", // gets ?consent=… or ?error=…
|
|
114
|
-
secret: process.env.AUTHLET_SECRET!, // >= 32 chars, or an AES-GCM CryptoKey
|
|
115
|
-
tokens: {
|
|
116
|
-
issue: async ({ user, client, authorization, resource }) => ({
|
|
117
|
-
refreshToken,
|
|
118
|
-
}), // or null to refuse
|
|
119
|
-
refresh: async ({ refreshToken, grantType, client }) => rotated ?? null, // grantType: "authorization_code" | "refresh_token"
|
|
120
|
-
},
|
|
121
|
-
});
|
|
126
|
+
MCP clients may use an https URL as their `client_id` instead of registering. The URL serves a
|
|
127
|
+
JSON document with the client's name and redirect URIs
|
|
128
|
+
([draft-ietf-oauth-client-id-metadata-document](https://datatracker.ietf.org/doc/draft-ietf-oauth-client-id-metadata-document/)).
|
|
129
|
+
authlet supports this when the app passes `fetchClientMetadata`, a `fetch`-compatible function,
|
|
130
|
+
and then advertises `client_id_metadata_document_supported: true`. Without it, nothing is
|
|
131
|
+
fetched and URL client IDs are refused at every endpoint, including for codes and consents issued
|
|
132
|
+
while it was on.
|
|
122
133
|
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
authlet.decide(req, { consent, allow: true, authorization }); // Promise<Response>: redirect with a code
|
|
127
|
-
authlet.decide(req, { consent, allow: false }); // Promise<Response>: redirect with access_denied
|
|
134
|
+
```ts
|
|
135
|
+
fetchClientMetadata: (url, init) => guardedFetch(url, init), // Node: a fetch that blocks private IPs
|
|
136
|
+
fetchClientMetadata: (url, init) => fetch(url, init), // Workers: can't reach private ranges, add a rate limit
|
|
128
137
|
```
|
|
129
138
|
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
- `src/redirect-uri.ts`: redirect URI validation (https; http only to loopback; app schemes;
|
|
149
|
-
no browser-handled schemes such as `javascript:`, `data:`, `blob:`, `file:`; no fragments) and
|
|
150
|
-
matching, with loopback URIs on any port (RFC 8252 section 7.3).
|
|
151
|
-
- `src/pkce.ts`: S256 verification, tested with the RFC 7636 vector.
|
|
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`.
|
|
144
|
+
|
|
145
|
+
The function is the app's SSRF control, so it must:
|
|
146
|
+
|
|
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
|
|
149
|
+
URL.
|
|
150
|
+
- Allowlist hosts or rate-limit fetches. Any site can send a signed-in user's browser to
|
|
151
|
+
`/authorize` with a `client_id` URL of its choosing.
|
|
152
|
+
- Cache only by HTTP cache headers, and never cache errors.
|
|
153
|
+
|
|
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`.
|
|
152
157
|
|
|
153
158
|
## Base URLs
|
|
154
159
|
|
|
155
|
-
With `resource: "https://cms.example.com/api/mcp"
|
|
156
|
-
`
|
|
160
|
+
The issuer defaults to `${resource}/oauth`. With `resource: "https://cms.example.com/api/mcp"`,
|
|
161
|
+
`handle` answers:
|
|
157
162
|
|
|
158
163
|
| Path | Serves | Root route needed |
|
|
159
164
|
| ------------------------------------------------------- | --------------------------------------------- | ----------------- |
|
|
@@ -164,25 +169,10 @@ With `resource: "https://cms.example.com/api/mcp"` the issuer is
|
|
|
164
169
|
| `/.well-known/openid-configuration/api/mcp/oauth` | AS metadata (OpenID, path inserted) | yes, optional |
|
|
165
170
|
| `/.well-known/oauth-protected-resource/api/mcp` | resource metadata (RFC 9728 default) | yes, optional |
|
|
166
171
|
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
`handle` as well.
|
|
170
|
-
|
|
171
|
-
Clients check that the issuer and resource in the metadata match exactly. authlet therefore
|
|
172
|
-
refuses a value the URL parser would change: a trailing slash, credentials, a query or fragment,
|
|
173
|
-
an uppercase host, a default port or dot segments. Fixed strings are checked at setup, functions
|
|
174
|
-
on each request.
|
|
175
|
-
|
|
176
|
-
`handle` matches requests on their path only, so it works behind a TLS-terminating proxy whose
|
|
177
|
-
request URLs carry an internal scheme or host, as long as the proxy keeps the public path. An
|
|
178
|
-
issuer at a host root claims `/authorize`, `/token` and `/register`, so pass `handle` only that
|
|
179
|
-
host's requests.
|
|
180
|
-
|
|
181
|
-
## 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.
|
|
182
174
|
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
- A private example app that runs the flow against MCP Inspector over real HTTP.
|
|
188
|
-
- 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/dist/authlet.js
CHANGED
|
@@ -7,6 +7,8 @@ import { token } from "./endpoints/token.js";
|
|
|
7
7
|
import { methodNotAllowed, preflight, withParams } from "./http.js";
|
|
8
8
|
import { createSealer } from "./seal.js";
|
|
9
9
|
import { deriveUrls, matchEndpoint } from "./urls.js";
|
|
10
|
+
// RFC 6750 section 2.1 b64token.
|
|
11
|
+
const BEARER = /^Bearer +([\w.~+/-]+=*)$/i;
|
|
10
12
|
const createAuthlet = (options) => {
|
|
11
13
|
const sealer = createSealer(options.secret);
|
|
12
14
|
const contextFor = (req) => ({
|
|
@@ -35,7 +37,7 @@ const createAuthlet = (options) => {
|
|
|
35
37
|
authorizationServerMetadata: {
|
|
36
38
|
method: "GET",
|
|
37
39
|
cors: true,
|
|
38
|
-
run: ({ urls }) => authorizationServerMetadata(urls),
|
|
40
|
+
run: ({ urls }) => authorizationServerMetadata(urls, Boolean(options.fetchClientMetadata)),
|
|
39
41
|
},
|
|
40
42
|
resourceMetadata: {
|
|
41
43
|
method: "GET",
|
|
@@ -43,6 +45,18 @@ const createAuthlet = (options) => {
|
|
|
43
45
|
run: ({ urls }) => resourceMetadata(urls),
|
|
44
46
|
},
|
|
45
47
|
};
|
|
48
|
+
const challenge = (req) => {
|
|
49
|
+
const { urls } = contextFor(req);
|
|
50
|
+
const params = [`resource_metadata="${urls.resourceMetadata}"`];
|
|
51
|
+
// RFC 6750 section 3.1: a request that sent a bearer token learns it was rejected.
|
|
52
|
+
if (/^bearer\b/i.test(req.headers.get("Authorization") ?? "")) {
|
|
53
|
+
params.unshift('error="invalid_token"');
|
|
54
|
+
}
|
|
55
|
+
return new Response(null, {
|
|
56
|
+
status: 401,
|
|
57
|
+
headers: { "WWW-Authenticate": `Bearer ${params.join(", ")}` },
|
|
58
|
+
});
|
|
59
|
+
};
|
|
46
60
|
return {
|
|
47
61
|
handle: async (req) => {
|
|
48
62
|
const ctx = contextFor(req);
|
|
@@ -59,17 +73,11 @@ const createAuthlet = (options) => {
|
|
|
59
73
|
}
|
|
60
74
|
return await route.run(ctx);
|
|
61
75
|
},
|
|
62
|
-
challenge
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
params.unshift('error="invalid_token"');
|
|
68
|
-
}
|
|
69
|
-
return new Response(null, {
|
|
70
|
-
status: 401,
|
|
71
|
-
headers: { "WWW-Authenticate": `Bearer ${params.join(", ")}` },
|
|
72
|
-
});
|
|
76
|
+
challenge,
|
|
77
|
+
authenticate: async (req, verify) => {
|
|
78
|
+
// A malformed or empty Bearer header gets invalid_token, not RFC 6750's 400 invalid_request.
|
|
79
|
+
const token = BEARER.exec(req.headers.get("Authorization") ?? "")?.[1];
|
|
80
|
+
return (token ? await verify(token) : null) ?? challenge(req);
|
|
73
81
|
},
|
|
74
82
|
readConsent: async (req, consent) => await readConsent(contextFor(req), consent),
|
|
75
83
|
decide: async (req, args) => await decide(contextFor(req), args),
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { Context } from "./context.js";
|
|
2
|
+
import type { SealedValues } from "./seal.js";
|
|
3
|
+
import type { AuthletUser } from "./types.js";
|
|
4
|
+
/** Whether a `client_id` names a metadata document. Sealed client IDs are compact JWE and never match. */
|
|
5
|
+
declare const isClientIdUrl: (id: string) => boolean;
|
|
6
|
+
/**
|
|
7
|
+
* The URL of a metadata document client ID, or `null` when it isn't one authlet may fetch: it must
|
|
8
|
+
* be in canonical form (compared as a string), with a path, no credentials or fragment, and not
|
|
9
|
+
* the issuer, an IP literal or a `localhost` name.
|
|
10
|
+
*/
|
|
11
|
+
declare const parseClientIdUrl: (id: string, issuer: string) => URL | null;
|
|
12
|
+
/** The client behind a metadata document, if it describes a public client at `url`. */
|
|
13
|
+
declare const parseClientMetadata: (doc: unknown, url: string) => SealedValues["client"] | null;
|
|
14
|
+
/** The client behind a `client_id`: its metadata document when enabled, else its sealed registration. */
|
|
15
|
+
declare const resolveClient: <TAuthorization, TUser extends AuthletUser>({ urls, sealer, options }: Context<TAuthorization, TUser>, clientId: string) => Promise<SealedValues["client"] | null>;
|
|
16
|
+
export { isClientIdUrl, parseClientIdUrl, parseClientMetadata, resolveClient };
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { toClientName } from "./endpoints/register.js";
|
|
2
|
+
import { readBody } from "./http.js";
|
|
3
|
+
import { isValidRedirectUri } from "./redirect-uri.js";
|
|
4
|
+
const MAX_URL_LENGTH = 2048;
|
|
5
|
+
const MAX_DOCUMENT_LENGTH = 5_120;
|
|
6
|
+
const FETCH_TIMEOUT = 5_000;
|
|
7
|
+
const JSON_TYPE = /^application\/([\w.+-]+\+)?json\s*(;|$)/i;
|
|
8
|
+
/** Whether a `client_id` names a metadata document. Sealed client IDs are compact JWE and never match. */
|
|
9
|
+
const isClientIdUrl = (id) => id.startsWith("https://");
|
|
10
|
+
/**
|
|
11
|
+
* The URL of a metadata document client ID, or `null` when it isn't one authlet may fetch: it must
|
|
12
|
+
* be in canonical form (compared as a string), with a path, no credentials or fragment, and not
|
|
13
|
+
* the issuer, an IP literal or a `localhost` name.
|
|
14
|
+
*/
|
|
15
|
+
const parseClientIdUrl = (id, issuer) => {
|
|
16
|
+
if (id.length > MAX_URL_LENGTH ||
|
|
17
|
+
id === issuer ||
|
|
18
|
+
id.includes("#") ||
|
|
19
|
+
!URL.canParse(id)) {
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
const url = new URL(id);
|
|
23
|
+
const host = url.hostname.replace(/\.+$/, "");
|
|
24
|
+
return url.protocol === "https:" &&
|
|
25
|
+
url.href === id &&
|
|
26
|
+
!url.username &&
|
|
27
|
+
!url.password &&
|
|
28
|
+
url.pathname !== "/" &&
|
|
29
|
+
!/^\d+(\.\d+){3}$/.test(host) &&
|
|
30
|
+
!host.startsWith("[") &&
|
|
31
|
+
host !== "localhost" &&
|
|
32
|
+
!host.endsWith(".localhost")
|
|
33
|
+
? url
|
|
34
|
+
: null;
|
|
35
|
+
};
|
|
36
|
+
/** Absent, or a list containing `value`. */
|
|
37
|
+
const allows = (list, value) => list === undefined || (Array.isArray(list) && list.includes(value));
|
|
38
|
+
/** The client behind a metadata document, if it describes a public client at `url`. */
|
|
39
|
+
const parseClientMetadata = (doc, url) => {
|
|
40
|
+
if (typeof doc !== "object" || doc === null) {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
const { client_id: clientId, client_name: clientName, redirect_uris: redirectUris, token_endpoint_auth_method: authMethod, token_endpoint_auth_methods_supported: authMethods, grant_types: grantTypes, response_types: responseTypes, } = doc;
|
|
44
|
+
return clientId === url &&
|
|
45
|
+
Array.isArray(redirectUris) &&
|
|
46
|
+
redirectUris.length > 0 &&
|
|
47
|
+
redirectUris.every(isValidRedirectUri) &&
|
|
48
|
+
!("client_secret" in doc) &&
|
|
49
|
+
!("client_secret_expires_at" in doc) &&
|
|
50
|
+
(authMethod === undefined || authMethod === "none") &&
|
|
51
|
+
allows(authMethods, "none") &&
|
|
52
|
+
allows(grantTypes, "authorization_code") &&
|
|
53
|
+
allows(responseTypes, "code")
|
|
54
|
+
? { name: toClientName(clientName), redirectUris }
|
|
55
|
+
: null;
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* The parsed metadata document, or `null` on any failure. One deadline covers the fetch and the
|
|
59
|
+
* body read, so a fetch that ignores its signal still can't hold the request.
|
|
60
|
+
*/
|
|
61
|
+
const fetchClientMetadata = async (fetcher, url) => {
|
|
62
|
+
const controller = new AbortController();
|
|
63
|
+
let timer;
|
|
64
|
+
const deadline = new Promise((resolve) => {
|
|
65
|
+
timer = setTimeout(() => {
|
|
66
|
+
resolve(null);
|
|
67
|
+
}, FETCH_TIMEOUT);
|
|
68
|
+
});
|
|
69
|
+
const load = async () => {
|
|
70
|
+
const res = await fetcher(url, {
|
|
71
|
+
headers: { Accept: "application/json" },
|
|
72
|
+
redirect: "manual",
|
|
73
|
+
signal: controller.signal,
|
|
74
|
+
});
|
|
75
|
+
if (res.status !== 200 ||
|
|
76
|
+
res.redirected ||
|
|
77
|
+
(res.url && res.url !== url) ||
|
|
78
|
+
!JSON_TYPE.test(res.headers.get("Content-Type") ?? "")) {
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
const text = await readBody(res, MAX_DOCUMENT_LENGTH, controller.signal);
|
|
82
|
+
return text === null ? null : JSON.parse(text);
|
|
83
|
+
};
|
|
84
|
+
try {
|
|
85
|
+
// Caught here, so a rejection after the deadline is never unhandled.
|
|
86
|
+
return await Promise.race([load().catch(() => null), deadline]);
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
clearTimeout(timer);
|
|
90
|
+
controller.abort();
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
/** The client behind a `client_id`: its metadata document when enabled, else its sealed registration. */
|
|
94
|
+
const resolveClient = async ({ urls, sealer, options }, clientId) => {
|
|
95
|
+
if (!isClientIdUrl(clientId)) {
|
|
96
|
+
return ((await sealer.unseal({
|
|
97
|
+
issuer: urls.issuer,
|
|
98
|
+
type: "client",
|
|
99
|
+
value: clientId,
|
|
100
|
+
})) ?? null);
|
|
101
|
+
}
|
|
102
|
+
const fetcher = options.fetchClientMetadata;
|
|
103
|
+
return fetcher && parseClientIdUrl(clientId, urls.issuer)
|
|
104
|
+
? parseClientMetadata(await fetchClientMetadata(fetcher, clientId), clientId)
|
|
105
|
+
: null;
|
|
106
|
+
};
|
|
107
|
+
export { isClientIdUrl, parseClientIdUrl, parseClientMetadata, resolveClient };
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isClientIdUrl, resolveClient } from "../client.js";
|
|
1
2
|
import { getBrowserUser, toConsentPage } from "../context.js";
|
|
2
3
|
import { redirect } from "../http.js";
|
|
3
4
|
import { isCodeChallenge } from "../pkce.js";
|
|
@@ -16,22 +17,11 @@ const authorize = async (ctx) => {
|
|
|
16
17
|
const url = new URL(req.url);
|
|
17
18
|
const params = url.searchParams;
|
|
18
19
|
const clientId = params.get("client_id");
|
|
19
|
-
const client = await sealer.unseal({
|
|
20
|
-
issuer: urls.issuer,
|
|
21
|
-
type: "client",
|
|
22
|
-
value: clientId,
|
|
23
|
-
});
|
|
24
|
-
// Optional when the client registered only one.
|
|
25
|
-
const redirectUri = params.get("redirect_uri") ??
|
|
26
|
-
(client?.redirectUris.length === 1 ? client.redirectUris[0] : undefined);
|
|
27
20
|
const codeChallenge = params.get("code_challenge");
|
|
28
21
|
const state = params.get("state");
|
|
29
22
|
// RFC 8707: clients name the resource; absent means the only one there is.
|
|
30
23
|
const resource = params.get("resource") ?? urls.resource;
|
|
31
24
|
if (!clientId ||
|
|
32
|
-
!client ||
|
|
33
|
-
!redirectUri ||
|
|
34
|
-
!isRegisteredRedirectUri(redirectUri, client.redirectUris) ||
|
|
35
25
|
params.get("response_type") !== "code" ||
|
|
36
26
|
params.get("code_challenge_method") !== "S256" ||
|
|
37
27
|
!codeChallenge ||
|
|
@@ -41,10 +31,20 @@ const authorize = async (ctx) => {
|
|
|
41
31
|
(state?.length ?? 0) > MAX_STATE_LENGTH) {
|
|
42
32
|
return toConsentPage(ctx, { error: "invalid_link" });
|
|
43
33
|
}
|
|
34
|
+
// Before resolving the client, so signed-out requests never fetch a metadata document.
|
|
44
35
|
const user = await getBrowserUser(ctx);
|
|
45
36
|
if (!user) {
|
|
46
37
|
return redirect(options.loginUrl(url.pathname + url.search, req));
|
|
47
38
|
}
|
|
39
|
+
const client = await resolveClient(ctx, clientId);
|
|
40
|
+
// Optional when the client registered only one.
|
|
41
|
+
const redirectUri = params.get("redirect_uri") ??
|
|
42
|
+
(client?.redirectUris.length === 1 ? client.redirectUris[0] : undefined);
|
|
43
|
+
if (!client ||
|
|
44
|
+
!redirectUri ||
|
|
45
|
+
!isRegisteredRedirectUri(redirectUri, client.redirectUris)) {
|
|
46
|
+
return toConsentPage(ctx, { error: "invalid_link" });
|
|
47
|
+
}
|
|
48
48
|
const consent = await sealer.seal({
|
|
49
49
|
issuer: urls.issuer,
|
|
50
50
|
type: "consent",
|
|
@@ -55,6 +55,7 @@ const authorize = async (ctx) => {
|
|
|
55
55
|
resource,
|
|
56
56
|
userId: user.id,
|
|
57
57
|
...(state === null ? {} : { state }),
|
|
58
|
+
...(isClientIdUrl(clientId) ? { clientName: client.name } : {}),
|
|
58
59
|
},
|
|
59
60
|
});
|
|
60
61
|
return toConsentPage(ctx, { consent });
|
|
@@ -1,28 +1,39 @@
|
|
|
1
|
+
import { isClientIdUrl } from "../client.js";
|
|
1
2
|
import { getBrowserUser, toConsentPage } from "../context.js";
|
|
2
3
|
import { redirect, withParams } from "../http.js";
|
|
3
4
|
/** The consent behind a sealed value, if it is valid and shown to the user signed in now. */
|
|
4
5
|
const loadConsent = async (ctx, value) => {
|
|
5
6
|
const { issuer } = ctx.urls;
|
|
6
7
|
const consent = await ctx.sealer.unseal({ issuer, type: "consent", value });
|
|
7
|
-
const client = consent &&
|
|
8
|
-
(await ctx.sealer.unseal({
|
|
9
|
-
issuer,
|
|
10
|
-
type: "client",
|
|
11
|
-
value: consent.clientId,
|
|
12
|
-
}));
|
|
13
8
|
const user = await getBrowserUser(ctx);
|
|
14
|
-
if (!consent ||
|
|
9
|
+
if (!consent || user?.id !== consent.userId) {
|
|
15
10
|
return null;
|
|
16
11
|
}
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
12
|
+
const { clientId: id, redirectUri, clientName } = consent;
|
|
13
|
+
let client;
|
|
14
|
+
if (isClientIdUrl(id)) {
|
|
15
|
+
// Refused once the app turns Client ID Metadata Documents off.
|
|
16
|
+
if (ctx.options.fetchClientMetadata && clientName !== undefined) {
|
|
17
|
+
client = {
|
|
18
|
+
id,
|
|
19
|
+
kind: "metadata",
|
|
20
|
+
host: new URL(id).hostname,
|
|
21
|
+
name: clientName,
|
|
22
|
+
redirectUri,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
else {
|
|
27
|
+
const registered = await ctx.sealer.unseal({
|
|
28
|
+
issuer,
|
|
29
|
+
type: "client",
|
|
30
|
+
value: id,
|
|
31
|
+
});
|
|
32
|
+
if (registered) {
|
|
33
|
+
client = { id, kind: "registered", name: registered.name, redirectUri };
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return client ? { consent, client, user } : null;
|
|
26
37
|
};
|
|
27
38
|
const readConsent = async (ctx, value) => {
|
|
28
39
|
const loaded = await loadConsent(ctx, value);
|
|
@@ -4,7 +4,7 @@ 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) => Response;
|
|
7
|
+
declare const authorizationServerMetadata: (urls: AuthletUrls, clientMetadataDocuments: boolean) => Response;
|
|
8
8
|
/** Protected resource metadata (RFC 9728) for the resource. */
|
|
9
9
|
declare const resourceMetadata: (urls: AuthletUrls) => Response;
|
|
10
10
|
declare const jwks: () => Response;
|
|
@@ -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) => json({
|
|
7
|
+
const authorizationServerMetadata = (urls, clientMetadataDocuments) => json({
|
|
8
8
|
issuer: urls.issuer,
|
|
9
9
|
authorization_endpoint: urls.authorizationEndpoint,
|
|
10
10
|
token_endpoint: urls.tokenEndpoint,
|
|
@@ -17,6 +17,9 @@ const authorizationServerMetadata = (urls) => json({
|
|
|
17
17
|
authorization_response_iss_parameter_supported: true,
|
|
18
18
|
subject_types_supported: ["public"],
|
|
19
19
|
id_token_signing_alg_values_supported: ["RS256"],
|
|
20
|
+
...(clientMetadataDocuments
|
|
21
|
+
? { client_id_metadata_document_supported: true }
|
|
22
|
+
: {}),
|
|
20
23
|
});
|
|
21
24
|
/** Protected resource metadata (RFC 9728) for the resource. */
|
|
22
25
|
const resourceMetadata = (urls) => json({
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import type { Context } from "../context.js";
|
|
2
2
|
import type { AuthletUser } from "../types.js";
|
|
3
|
+
/** A client's self-asserted name, trimmed and capped, or a neutral default. */
|
|
4
|
+
declare const toClientName: (name: unknown) => string;
|
|
3
5
|
/**
|
|
4
6
|
* Dynamic client registration (RFC 7591) for public clients. Nothing is stored: the client's
|
|
5
7
|
* name and redirect URIs are sealed into its `client_id`. Requested auth methods, grant and
|
|
6
8
|
* response types are replaced by the only ones supported, as section 3.2.1 allows.
|
|
7
9
|
*/
|
|
8
10
|
declare const register: ({ req, urls, sealer, }: Pick<Context<unknown, AuthletUser>, "req" | "urls" | "sealer">) => Promise<Response>;
|
|
9
|
-
export { register };
|
|
11
|
+
export { register, toClientName };
|
|
@@ -12,6 +12,10 @@ const DEFAULT_CLIENT_NAME = "An OAuth client";
|
|
|
12
12
|
/** Limits that keep the sealed `client_id` short enough to travel in URLs. */
|
|
13
13
|
const MAX_NAME_LENGTH = 100;
|
|
14
14
|
const MAX_REDIRECT_URIS = 10;
|
|
15
|
+
/** A client's self-asserted name, trimmed and capped, or a neutral default. */
|
|
16
|
+
const toClientName = (name) => typeof name === "string" && name.trim()
|
|
17
|
+
? name.trim().slice(0, MAX_NAME_LENGTH)
|
|
18
|
+
: DEFAULT_CLIENT_NAME;
|
|
15
19
|
/**
|
|
16
20
|
* Dynamic client registration (RFC 7591) for public clients. Nothing is stored: the client's
|
|
17
21
|
* name and redirect URIs are sealed into its `client_id`. Requested auth methods, grant and
|
|
@@ -30,9 +34,7 @@ const register = async ({ req, urls, sealer, }) => {
|
|
|
30
34
|
!redirectUris.every(isValidRedirectUri)) {
|
|
31
35
|
return oauthError("invalid_redirect_uri");
|
|
32
36
|
}
|
|
33
|
-
const name =
|
|
34
|
-
? clientName.trim().slice(0, MAX_NAME_LENGTH)
|
|
35
|
-
: DEFAULT_CLIENT_NAME;
|
|
37
|
+
const name = toClientName(clientName);
|
|
36
38
|
const clientId = await sealer.seal({
|
|
37
39
|
issuer: urls.issuer,
|
|
38
40
|
type: "client",
|
|
@@ -48,4 +50,4 @@ const register = async ({ req, urls, sealer, }) => {
|
|
|
48
50
|
token_endpoint_auth_method: "none",
|
|
49
51
|
}, 201);
|
|
50
52
|
};
|
|
51
|
-
export { register };
|
|
53
|
+
export { register, toClientName };
|
package/dist/endpoints/token.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isClientIdUrl } from "../client.js";
|
|
1
2
|
import { json, oauthError, readBody } from "../http.js";
|
|
2
3
|
import { verifyCodeChallenge } from "../pkce.js";
|
|
3
4
|
/** A parameter the client may leave out, but that must match when sent. */
|
|
@@ -49,6 +50,11 @@ const token = async (ctx) => {
|
|
|
49
50
|
if (!clientId || REQUIRED_PARAMS[grantType].some((name) => !form.get(name))) {
|
|
50
51
|
return oauthError("invalid_request");
|
|
51
52
|
}
|
|
53
|
+
const kind = isClientIdUrl(clientId) ? "metadata" : "registered";
|
|
54
|
+
// Metadata clients lose access as soon as the app turns Client ID Metadata Documents off.
|
|
55
|
+
if (kind === "metadata" && !ctx.options.fetchClientMetadata) {
|
|
56
|
+
return oauthError("invalid_client");
|
|
57
|
+
}
|
|
52
58
|
const isCode = grantType === "authorization_code";
|
|
53
59
|
const grant = isCode
|
|
54
60
|
? await unsealCode(ctx, form, clientId)
|
|
@@ -60,7 +66,7 @@ const token = async (ctx) => {
|
|
|
60
66
|
const tokens = grant &&
|
|
61
67
|
(await ctx.options.tokens.refresh({
|
|
62
68
|
refreshToken: grant.refreshToken,
|
|
63
|
-
client: { id: clientId },
|
|
69
|
+
client: { id: clientId, kind },
|
|
64
70
|
grantType,
|
|
65
71
|
}));
|
|
66
72
|
if (!grant || !tokens) {
|
package/dist/http.d.ts
CHANGED
|
@@ -3,11 +3,10 @@ declare const json: (body: unknown, status?: number) => Response;
|
|
|
3
3
|
/** An OAuth error response (RFC 6749 section 5.2). */
|
|
4
4
|
declare const oauthError: (error: string, status?: number) => Response;
|
|
5
5
|
/**
|
|
6
|
-
* The
|
|
7
|
-
*
|
|
8
|
-
* a byte cap if hosts don't limit bodies themselves.
|
|
6
|
+
* The body as text, or `null` once it passes `max` bytes, which cancels the stream. `signal`
|
|
7
|
+
* cancels it too, for a caller whose deadline fires mid-read.
|
|
9
8
|
*/
|
|
10
|
-
declare const readBody: (
|
|
9
|
+
declare const readBody: (message: Request | Response, max?: number, signal?: AbortSignal) => Promise<string | null>;
|
|
11
10
|
/** 302 for GET requests; 303 after a form POST, so the browser follows with a GET. */
|
|
12
11
|
declare const redirect: (location: string, status?: 302 | 303) => Response;
|
|
13
12
|
/**
|
package/dist/http.js
CHANGED
|
@@ -10,16 +10,36 @@ const oauthError = (error, status = 400) => json({ error }, status);
|
|
|
10
10
|
/** Larger than any legitimate registration or token request. */
|
|
11
11
|
const MAX_BODY_LENGTH = 16_384;
|
|
12
12
|
/**
|
|
13
|
-
* The
|
|
14
|
-
*
|
|
15
|
-
* a byte cap if hosts don't limit bodies themselves.
|
|
13
|
+
* The body as text, or `null` once it passes `max` bytes, which cancels the stream. `signal`
|
|
14
|
+
* cancels it too, for a caller whose deadline fires mid-read.
|
|
16
15
|
*/
|
|
17
|
-
const readBody = async (
|
|
18
|
-
if (
|
|
19
|
-
return
|
|
16
|
+
const readBody = async (message, max = MAX_BODY_LENGTH, signal) => {
|
|
17
|
+
if (!message.body) {
|
|
18
|
+
return "";
|
|
20
19
|
}
|
|
21
|
-
const
|
|
22
|
-
|
|
20
|
+
const reader = message.body.getReader();
|
|
21
|
+
const decoder = new TextDecoder();
|
|
22
|
+
let length = 0;
|
|
23
|
+
let text = "";
|
|
24
|
+
// An aborted fetch errors its stream, which makes `cancel` reject.
|
|
25
|
+
signal?.addEventListener("abort", () => {
|
|
26
|
+
reader.cancel().catch(() => undefined);
|
|
27
|
+
}, { once: true });
|
|
28
|
+
// Chunks are read in order, one at a time.
|
|
29
|
+
/* eslint-disable no-await-in-loop */
|
|
30
|
+
for (;;) {
|
|
31
|
+
const { done, value } = await reader.read();
|
|
32
|
+
if (done) {
|
|
33
|
+
return text + decoder.decode();
|
|
34
|
+
}
|
|
35
|
+
length += value.byteLength;
|
|
36
|
+
if (length > max) {
|
|
37
|
+
await reader.cancel();
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
text += decoder.decode(value, { stream: true });
|
|
41
|
+
}
|
|
42
|
+
/* eslint-enable no-await-in-loop */
|
|
23
43
|
};
|
|
24
44
|
/** 302 for GET requests; 303 after a form POST, so the browser follows with a GET. */
|
|
25
45
|
const redirect = (location, status = 302) => new Response(null, { status, headers: { Location: location } });
|
package/dist/seal.d.ts
CHANGED
|
@@ -16,6 +16,8 @@ interface SealedValues {
|
|
|
16
16
|
state?: string;
|
|
17
17
|
resource: string;
|
|
18
18
|
userId: string;
|
|
19
|
+
/** The metadata document's client name, so the consent page needs no second fetch. */
|
|
20
|
+
clientName?: string;
|
|
19
21
|
};
|
|
20
22
|
/** The authorization code, carrying the refresh token the app issued on consent. */
|
|
21
23
|
code: {
|
package/dist/types.d.ts
CHANGED
|
@@ -8,14 +8,24 @@ export type Resolvable<T> = T | ((req: Request) => T);
|
|
|
8
8
|
export interface AuthletUser {
|
|
9
9
|
id: string;
|
|
10
10
|
}
|
|
11
|
-
/**
|
|
12
|
-
|
|
11
|
+
/**
|
|
12
|
+
* The client being authorized, as known from its registration (`kind: "registered"`) or its
|
|
13
|
+
* metadata document (`kind: "metadata"`).
|
|
14
|
+
*/
|
|
15
|
+
export type AuthletClient = {
|
|
13
16
|
/** The `client_id`: a sealed registration (RFC 7591) or an https metadata document URL. */
|
|
14
17
|
id: string;
|
|
18
|
+
/** Asserted by the client itself, so unverified. */
|
|
15
19
|
name: string;
|
|
16
20
|
/** The redirect URI used for this authorization, one of those the client registered. */
|
|
17
21
|
redirectUri: string;
|
|
18
|
-
}
|
|
22
|
+
} & ({
|
|
23
|
+
kind: "registered";
|
|
24
|
+
} | {
|
|
25
|
+
kind: "metadata";
|
|
26
|
+
/** The hostname of the metadata document URL: the client's identity to show on the consent page. */
|
|
27
|
+
host: string;
|
|
28
|
+
});
|
|
19
29
|
/**
|
|
20
30
|
* What `issue` creates for a new authorization: only the app's refresh token. It is sealed into
|
|
21
31
|
* the code, and redeeming the code rotates it into the client's first token pair, so no access
|
|
@@ -44,7 +54,7 @@ export interface IssueTokensArgs<TAuthorization, TUser extends AuthletUser> {
|
|
|
44
54
|
}
|
|
45
55
|
export interface RefreshTokensArgs {
|
|
46
56
|
refreshToken: string;
|
|
47
|
-
client: Pick<AuthletClient, "id">;
|
|
57
|
+
client: Pick<AuthletClient, "id" | "kind">;
|
|
48
58
|
/**
|
|
49
59
|
* The token request's `grant_type`. On `"authorization_code"` the token must never have been
|
|
50
60
|
* used, so the code works once: refuse a second redemption (and revoke the token family). On
|
|
@@ -108,6 +118,15 @@ export interface AuthletOptions<TAuthorization = unknown, TUser extends AuthletU
|
|
|
108
118
|
/** For the built-in AES-GCM sealer: at least 32 characters, or an AES-GCM `CryptoKey`. */
|
|
109
119
|
secret: string | CryptoKey;
|
|
110
120
|
tokens: TokenHooks<TAuthorization, TUser>;
|
|
121
|
+
/**
|
|
122
|
+
* Enables Client ID Metadata Documents: an https `client_id` names a JSON document describing
|
|
123
|
+
* the client, fetched with this function at the authorization endpoint for signed-in users.
|
|
124
|
+
* authlet passes `Accept: application/json`, `redirect: "manual"` and an abort signal, and bounds
|
|
125
|
+
* the fetch and body read itself (5 seconds, 5 KB). It must refuse private and special-use
|
|
126
|
+
* addresses and allowlist or rate-limit hosts, since any site can make a signed-in user's
|
|
127
|
+
* browser trigger a fetch. It may cache by HTTP cache headers, but never errors.
|
|
128
|
+
*/
|
|
129
|
+
fetchClientMetadata?: (url: string, init: RequestInit) => Promise<Response>;
|
|
111
130
|
}
|
|
112
131
|
/** A pending authorization, as shown on the consent page. */
|
|
113
132
|
export interface Consent<TUser extends AuthletUser = AuthletUser> {
|
|
@@ -140,6 +159,11 @@ export interface Authlet<TAuthorization = unknown, TUser extends AuthletUser = A
|
|
|
140
159
|
* below the issuer, which RFC 9728 clients follow, so discovery works under a base path.
|
|
141
160
|
*/
|
|
142
161
|
challenge: (req: Request) => Response;
|
|
162
|
+
/**
|
|
163
|
+
* The app's auth info for a request bearing `Authorization: Bearer <token>` that `verify`
|
|
164
|
+
* accepts, else the `challenge` 401 (with `error="invalid_token"` when a bearer token was sent).
|
|
165
|
+
*/
|
|
166
|
+
authenticate: <T extends object>(req: Request, verify: (token: string) => Promise<T | null>) => Promise<T | Response>;
|
|
143
167
|
/** The pending authorization behind a sealed consent, or `null` if it's invalid, expired or for another user. */
|
|
144
168
|
readConsent: (req: Request, consent: string) => Promise<Consent<TUser> | null>;
|
|
145
169
|
/**
|
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",
|