authlet 0.1.0-beta.3 → 0.1.0-beta.4

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
@@ -4,7 +4,7 @@ A small, stateless OAuth 2.1 authorization server built only on Web `Request` an
4
4
  so it runs on Node, Deno, Bun and edge runtimes. Bring your own users, sessions and tokens.
5
5
 
6
6
  It serves the authorization code flow with PKCE for public clients: dynamic client registration
7
- (RFC 7591), resource indicators (RFC 8707), protected resource metadata (RFC 9728) and refresh
7
+ (RFC 7591), optional [Client ID Metadata Documents](#client-id-metadata-documents), resource indicators (RFC 8707), protected resource metadata (RFC 9728) and refresh
8
8
  token rotation. That is the profile MCP clients use, so an MCP server is the typical host, but
9
9
  any API that wants this flow can use it. It has no client credentials or device flow, and no
10
10
  OpenID Connect ID tokens.
@@ -32,8 +32,18 @@ The app also owns the consent screen. authlet redirects to `consentPage?consent=
32
32
  `?error=…` for a broken link. The page reads the request with `readConsent`, and its POST handler
33
33
  calls `decide`.
34
34
 
35
- Access tokens belong to the app too: authlet never validates them. The protected resource checks
36
- them with the app's own auth and calls `challenge(req)` when there is none.
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.
39
+
40
+ ```ts
41
+ const auth = await authlet.authenticate(req, verifyToken);
42
+
43
+ if (auth instanceof Response) {
44
+ return auth;
45
+ }
46
+ ```
37
47
 
38
48
  ### App-specific authorization data
39
49
 
@@ -84,13 +94,17 @@ authlet can't check these, because they happen in the app:
84
94
  one code both succeed. Never apply a reuse leeway to `"authorization_code"`, and revoke the whole token
85
95
  family when a used refresh token comes back (RFC 9700 section 4.14).
86
96
  2. Treat the consent page as a security boundary:
87
- - Show the client name as unverified: anyone can register any name.
97
+ - Show the client name as unverified: anyone can register any name or write it into a
98
+ metadata document. For `client.kind === "metadata"`, show `client.host` as the client's
99
+ identity instead.
88
100
  - Show the redirect URI's host (`new URL(client.redirectUri).host`), which is where the code
89
- goes.
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.
90
103
  - Send `Content-Security-Policy: frame-ancestors 'none'` and `Referrer-Policy: no-referrer`
91
104
  (the URL carries the sealed consent).
92
105
  - Never skip the page for a client the user allowed before: every registration gets a new
93
- `client_id`, so there is no stable client identity to remember.
106
+ `client_id`, and a metadata client is only as trustworthy as its host, so there is no
107
+ stable client identity to remember.
94
108
  3. On the login page, only follow a `returnTo` that starts with a single `/`. authlet always
95
109
  passes a relative path, but the login page must not become an open redirect.
96
110
  4. Use a session cookie with `SameSite=Lax` or stricter. `decide` refuses cross-site submissions
@@ -100,6 +114,41 @@ authlet can't check these, because they happen in the app:
100
114
  6. Derive a function-valued `resource` or `issuer` from trusted configuration only. Never take it
101
115
  from `Host` or `X-Forwarded-*` headers without an allowlist.
102
116
 
117
+ ## Client ID Metadata Documents
118
+
119
+ MCP clients may use an https URL as their `client_id` instead of registering: the URL serves a
120
+ JSON document with the client's name and redirect URIs
121
+ ([draft-ietf-oauth-client-id-metadata-document](https://datatracker.ietf.org/doc/draft-ietf-oauth-client-id-metadata-document/)).
122
+ authlet supports this when the app passes `fetchClientMetadata`, a `fetch`-compatible function,
123
+ 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.
126
+
127
+ ```ts
128
+ fetchClientMetadata: (url, init) => guardedFetch(url, init), // Node: a fetch that blocks private IPs
129
+ fetchClientMetadata: (url, init) => fetch(url, init), // Workers: can't reach private ranges, add a rate limit
130
+ ```
131
+
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`.
137
+
138
+ The function is the app's SSRF control, so it must:
139
+
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
142
+ URL.
143
+ - 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
+
103
152
  ## Interface
104
153
 
105
154
  ```ts
@@ -112,6 +161,7 @@ const authlet = createAuthlet<Capabilities, AppUser>({
112
161
  `/admin/login?redirect=${encodeURIComponent(returnTo)}`,
113
162
  consentPage: "/admin/mcp/authorize", // gets ?consent=… or ?error=…
114
163
  secret: process.env.AUTHLET_SECRET!, // >= 32 chars, or an AES-GCM CryptoKey
164
+ fetchClientMetadata: guardedFetch, // optional, enables Client ID Metadata Documents
115
165
  tokens: {
116
166
  issue: async ({ user, client, authorization, resource }) => ({
117
167
  refreshToken,
@@ -139,6 +189,8 @@ The full types are in [`src/types.ts`](src/types.ts).
139
189
  invalid requests go to `consentPage?error=invalid_link`, never to the client.
140
190
  - `consent.ts`: `readConsent` and `decide`, with `Sec-Fetch-*` checks and `iss` (RFC 9207).
141
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.
142
194
  - `src/conformance.spec.ts`: the full flow driven by `oauth4webapi` with both discovery styles.
143
195
  - `src/types.ts`: the public types; `src/types.test-d.ts`: an MCP server's usage, type-checked.
144
196
  - `src/seal.ts`: the sealer, typed per sealed value (jose JWE, HKDF-derived key, `typ` and `iss`
@@ -180,9 +232,6 @@ host's requests.
180
232
 
181
233
  ## Planned
182
234
 
183
- - Client ID Metadata Documents (MCP `2026-07-28` prefers them over dynamic registration):
184
- `client_id_metadata_document_supported` in metadata, fetching and validating https `client_id`
185
- documents, with a decision on restricting what it may fetch.
186
235
  - `authlet/node`: a `node:http` / Express bridge.
187
236
  - A private example app that runs the flow against MCP Inspector over real HTTP.
188
237
  - Scopes (`scopes_supported`, `scope` in the challenge, `insufficient_scope`), key rotation.
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: (req) => {
63
- const { urls } = contextFor(req);
64
- const params = [`resource_metadata="${urls.resourceMetadata}"`];
65
- // RFC 6750 section 3.1: a request that sent a token learns it was rejected.
66
- if (req.headers.has("Authorization")) {
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),
@@ -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 || !client || user?.id !== consent.userId) {
9
+ if (!consent || user?.id !== consent.userId) {
15
10
  return null;
16
11
  }
17
- return {
18
- consent,
19
- client: {
20
- id: consent.clientId,
21
- name: client.name,
22
- redirectUri: consent.redirectUri,
23
- },
24
- user,
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 = typeof clientName === "string" && clientName.trim()
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 };
@@ -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 request body as text, or `null` when it is too large.
7
- * shortcut: a chunked body without `Content-Length` is buffered before the check; stream it with
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: (req: Request) => Promise<string | null>;
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 request body as text, or `null` when it is too large.
14
- * shortcut: a chunked body without `Content-Length` is buffered before the check; stream it with
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 (req) => {
18
- if (Number(req.headers.get("Content-Length")) > MAX_BODY_LENGTH) {
19
- return null;
16
+ const readBody = async (message, max = MAX_BODY_LENGTH, signal) => {
17
+ if (!message.body) {
18
+ return "";
20
19
  }
21
- const body = await req.text();
22
- return body.length > MAX_BODY_LENGTH ? null : body;
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
- /** The client being authorized, as known from its registration or metadata document. */
12
- export interface AuthletClient {
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.3",
4
+ "version": "0.1.0-beta.4",
5
5
  "description": "Stateless, runtime-agnostic OAuth 2.1 authorization server built on Web Request and Response.",
6
6
  "keywords": [
7
7
  "oauth",