authlet 0.1.0-beta.2 → 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
@@ -1,7 +1,13 @@
1
1
  # authlet
2
2
 
3
- A small, runtime-agnostic OAuth 2.1 authorization server for MCP endpoints, built only on Web
4
- `Request` and `Response`. Bring your own users, sessions and tokens.
3
+ A small, stateless OAuth 2.1 authorization server built only on Web `Request` and `Response`,
4
+ so it runs on Node, Deno, Bun and edge runtimes. Bring your own users, sessions and tokens.
5
+
6
+ It serves the authorization code flow with PKCE for public clients: dynamic client registration
7
+ (RFC 7591), optional [Client ID Metadata Documents](#client-id-metadata-documents), resource indicators (RFC 8707), protected resource metadata (RFC 9728) and refresh
8
+ token rotation. That is the profile MCP clients use, so an MCP server is the typical host, but
9
+ any API that wants this flow can use it. It has no client credentials or device flow, and no
10
+ OpenID Connect ID tokens.
5
11
 
6
12
  > Status: pre-release, not yet published. `createAuthlet` and all endpoints work, and an
7
13
  > end-to-end run with `oauth4webapi` passes. [Planned](#planned) lists what is missing.
@@ -26,15 +32,25 @@ The app also owns the consent screen. authlet redirects to `consentPage?consent=
26
32
  `?error=…` for a broken link. The page reads the request with `readConsent`, and its POST handler
27
33
  calls `decide`.
28
34
 
29
- Access tokens belong to the app too: authlet never validates them. The MCP endpoint checks them
30
- 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);
31
42
 
32
- ### App-specific grant data
43
+ if (auth instanceof Response) {
44
+ return auth;
45
+ }
46
+ ```
33
47
 
34
- The consent screen can collect data of its own, such as the capability matrix a user picks for an
35
- MCP client. The app's consent POST handler parses and validates it, then passes it to `decide`.
36
- [`src/types.test-d.ts`](src/types.test-d.ts) writes this out for mcpx, and `yarn check` compiles
37
- it, so the example can't drift from the types:
48
+ ### App-specific authorization data
49
+
50
+ The consent screen can collect data of its own, such as the capabilities a user allows a client.
51
+ The app's consent POST handler parses and validates it, then passes it to `decide`.
52
+ [`src/types.test-d.ts`](src/types.test-d.ts) writes this out for an MCP server, and `yarn check`
53
+ compiles it, so the example can't drift from the types:
38
54
 
39
55
  ```ts
40
56
  const authlet = createAuthlet<Capabilities>({/* ... */});
@@ -47,22 +63,22 @@ export const POST = async (req: Request) => {
47
63
  return authlet.decide(
48
64
  req,
49
65
  form.get("decision") === "allow"
50
- ? { consent, allow: true, grant: parseCapabilities(form) }
66
+ ? { consent, allow: true, authorization: parseCapabilities(form) }
51
67
  : { consent, allow: false },
52
68
  );
53
69
  };
54
70
  ```
55
71
 
56
72
  `decide` checks the request (top-level same-origin form submission, no `Authorization` header,
57
- same user the consent was shown to) and calls `tokens.issue({ user, client, grant, resource })`.
58
- The app stores the grant and returns only a refresh token for it. authlet seals that token into
73
+ same user the consent was shown to) and calls `tokens.issue({ user, client, authorization, resource })`.
74
+ The app stores the authorization and returns only a refresh token for it. authlet seals that token into
59
75
  an authorization code valid for 60 seconds, plus 5 seconds of clock tolerance. No access token
60
- exists yet, so none travels through the browser, and the grant never leaves the server.
76
+ exists yet, so none travels through the browser, and the authorization never leaves the server.
61
77
 
62
78
  `issue` may return `null` to refuse a user who lost access since the consent page was shown; the
63
79
  browser goes to `consentPage?error=forbidden` and the client gets nothing.
64
80
 
65
- Redeeming the code calls `tokens.refresh` with `kind: "code"`, which mints the client's first
81
+ Redeeming the code calls `tokens.refresh` with `grantType: "authorization_code"`, which mints the client's first
66
82
  token pair and must refuse a refresh token that was already used. This makes a code single-use
67
83
  without authlet storing anything.
68
84
 
@@ -73,18 +89,22 @@ two grants for the same client. Both show up in the app's token store.
73
89
 
74
90
  authlet can't check these, because they happen in the app:
75
91
 
76
- 1. Make `kind: "code"` single-use atomically. Mark the refresh token used with a compare-and-set
92
+ 1. Make `grantType: "authorization_code"` single-use atomically. Mark the refresh token used with a compare-and-set
77
93
  (a conditional update rather than a read followed by a write), or two parallel redemptions of
78
- one code both succeed. Never apply a reuse leeway to `kind: "code"`, and revoke the whole token
94
+ one code both succeed. Never apply a reuse leeway to `"authorization_code"`, and revoke the whole token
79
95
  family when a used refresh token comes back (RFC 9700 section 4.14).
80
96
  2. Treat the consent page as a security boundary:
81
- - 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.
82
100
  - Show the redirect URI's host (`new URL(client.redirectUri).host`), which is where the code
83
- 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.
84
103
  - Send `Content-Security-Policy: frame-ancestors 'none'` and `Referrer-Policy: no-referrer`
85
104
  (the URL carries the sealed consent).
86
105
  - Never skip the page for a client the user allowed before: every registration gets a new
87
- `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.
88
108
  3. On the login page, only follow a `returnTo` that starts with a single `/`. authlet always
89
109
  passes a relative path, but the login page must not become an open redirect.
90
110
  4. Use a session cookie with `SameSite=Lax` or stricter. `decide` refuses cross-site submissions
@@ -94,28 +114,66 @@ authlet can't check these, because they happen in the app:
94
114
  6. Derive a function-valued `resource` or `issuer` from trusted configuration only. Never take it
95
115
  from `Host` or `X-Forwarded-*` headers without an allowlist.
96
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
+
97
152
  ## Interface
98
153
 
99
154
  ```ts
100
- // TGrant: what the consent page collects. TUser: the app's user, default { id }.
101
- const authlet = createAuthlet<Capabilities, McpUser>({
102
- resource: "https://cms.example.com/api/mcp", // the MCP endpoint, or (req) => string
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
103
158
  issuer: "https://cms.example.com/api/mcp/oauth", // optional, this is the default
104
- getUser: async (req) => sessionUser(req), // McpUser | null
159
+ getUser: async (req) => sessionUser(req), // AppUser | null
105
160
  loginUrl: (returnTo) =>
106
161
  `/admin/login?redirect=${encodeURIComponent(returnTo)}`,
107
162
  consentPage: "/admin/mcp/authorize", // gets ?consent=… or ?error=…
108
163
  secret: process.env.AUTHLET_SECRET!, // >= 32 chars, or an AES-GCM CryptoKey
164
+ fetchClientMetadata: guardedFetch, // optional, enables Client ID Metadata Documents
109
165
  tokens: {
110
- issue: async ({ user, client, grant, resource }) => ({ refreshToken }), // or null to refuse
111
- refresh: async ({ refreshToken, kind, client }) => rotated ?? null, // kind: "code" | "refresh"
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"
112
170
  },
113
171
  });
114
172
 
115
173
  authlet.handle(req); // Promise<Response | null>: OAuth endpoints, AS and resource metadata
116
174
  authlet.challenge(req); // 401 with WWW-Authenticate: Bearer resource_metadata="..."
117
- authlet.readConsent(req, consent); // Promise<Consent<McpUser> | null>, for rendering the consent page
118
- authlet.decide(req, { consent, allow: true, grant }); // Promise<Response>: redirect with a code
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
119
177
  authlet.decide(req, { consent, allow: false }); // Promise<Response>: redirect with access_denied
120
178
  ```
121
179
 
@@ -131,8 +189,10 @@ The full types are in [`src/types.ts`](src/types.ts).
131
189
  invalid requests go to `consentPage?error=invalid_link`, never to the client.
132
190
  - `consent.ts`: `readConsent` and `decide`, with `Sec-Fetch-*` checks and `iss` (RFC 9207).
133
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.
134
194
  - `src/conformance.spec.ts`: the full flow driven by `oauth4webapi` with both discovery styles.
135
- - `src/types.ts`: the public types; `src/types.test-d.ts`: mcpx's usage, type-checked.
195
+ - `src/types.ts`: the public types; `src/types.test-d.ts`: an MCP server's usage, type-checked.
136
196
  - `src/seal.ts`: the sealer, typed per sealed value (jose JWE, HKDF-derived key, `typ` and `iss`
137
197
  checked on unseal, fixed lifetimes: consent 20 min, code 60 s, each plus 5 s clock tolerance).
138
198
  - `src/urls.ts`: issuer and resource canonicalisation, endpoint URLs, and matching a request to
@@ -156,8 +216,8 @@ With `resource: "https://cms.example.com/api/mcp"` the issuer is
156
216
  | `/.well-known/openid-configuration/api/mcp/oauth` | AS metadata (OpenID, path inserted) | yes, optional |
157
217
  | `/.well-known/oauth-protected-resource/api/mcp` | resource metadata (RFC 9728 default) | yes, optional |
158
218
 
159
- MCP clients try every AS metadata location and follow `resource_metadata` from the 401, so the
160
- first three rows are enough. Hosts that can serve root paths can forward those requests to
219
+ Clients that follow `resource_metadata` from the 401 and try the OpenID location below the
220
+ issuer, as MCP clients do, need only the first three rows. Hosts that can serve root paths can forward those requests to
161
221
  `handle` as well.
162
222
 
163
223
  Clients check that the issuer and resource in the metadata match exactly. authlet therefore
@@ -172,9 +232,6 @@ host's requests.
172
232
 
173
233
  ## Planned
174
234
 
175
- - Client ID Metadata Documents (MCP `2026-07-28` prefers them over dynamic registration):
176
- `client_id_metadata_document_supported` in metadata, fetching and validating https `client_id`
177
- documents, with a decision on restricting what it may fetch.
178
235
  - `authlet/node`: a `node:http` / Express bridge.
179
236
  - A private example app that runs the flow against MCP Inspector over real HTTP.
180
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 };
package/dist/context.d.ts CHANGED
@@ -2,16 +2,16 @@ import type { Sealer } from "./seal.js";
2
2
  import type { AuthletOptions, AuthletUser, AuthorizeError, Resolvable } from "./types.js";
3
3
  import type { AuthletUrls } from "./urls.js";
4
4
  /** Everything an endpoint needs for one request. */
5
- interface Context<TGrant, TUser extends AuthletUser> {
5
+ interface Context<TAuthorization, TUser extends AuthletUser> {
6
6
  req: Request;
7
7
  urls: AuthletUrls;
8
8
  sealer: Sealer;
9
- options: AuthletOptions<TGrant, TUser>;
9
+ options: AuthletOptions<TAuthorization, TUser>;
10
10
  }
11
11
  declare const resolve: <T extends string>(value: Resolvable<T>, req: Request) => T;
12
12
  /**
13
13
  * The user signed in to this browser. Requests carrying an `Authorization` header never count,
14
- * or an MCP client could use its access token to approve a new client for itself.
14
+ * or a client could use its access token to approve a new client for itself.
15
15
  */
16
16
  declare const getBrowserUser: <TUser extends AuthletUser>({ req, options, }: {
17
17
  req: Request;
package/dist/context.js CHANGED
@@ -2,7 +2,7 @@ import { redirect, withParams } from "./http.js";
2
2
  const resolve = (value, req) => typeof value === "function" ? value(req) : value;
3
3
  /**
4
4
  * The user signed in to this browser. Requests carrying an `Authorization` header never count,
5
- * or an MCP client could use its access token to approve a new client for itself.
5
+ * or a client could use its access token to approve a new client for itself.
6
6
  */
7
7
  const getBrowserUser = async ({ req, options, }) => req.headers.has("Authorization") ? null : await options.getUser(req);
8
8
  /** Sends the browser to the app's consent page, with a sealed consent or an error. */
@@ -8,5 +8,5 @@ import type { AuthletUser } from "../types.js";
8
8
  * redirect URI, so that would turn this endpoint into an open redirector. They go to the
9
9
  * consent page with `error=invalid_link` instead.
10
10
  */
11
- declare const authorize: <TGrant, TUser extends AuthletUser>(ctx: Context<TGrant, TUser>) => Promise<Response>;
11
+ declare const authorize: <TAuthorization, TUser extends AuthletUser>(ctx: Context<TAuthorization, TUser>) => Promise<Response>;
12
12
  export { authorize };
@@ -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,5 +1,5 @@
1
1
  import type { Context } from "../context.js";
2
2
  import type { AuthletUser, Consent, DecideArgs } from "../types.js";
3
- declare const readConsent: <TGrant, TUser extends AuthletUser>(ctx: Context<TGrant, TUser>, value: string) => Promise<Consent<TUser> | null>;
4
- declare const decide: <TGrant, TUser extends AuthletUser>(ctx: Context<TGrant, TUser>, args: DecideArgs<TGrant>) => Promise<Response>;
3
+ declare const readConsent: <TAuthorization, TUser extends AuthletUser>(ctx: Context<TAuthorization, TUser>, value: string) => Promise<Consent<TUser> | null>;
4
+ declare const decide: <TAuthorization, TUser extends AuthletUser>(ctx: Context<TAuthorization, TUser>, args: DecideArgs<TAuthorization>) => Promise<Response>;
5
5
  export { decide, readConsent };
@@ -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);
@@ -74,7 +85,7 @@ const decide = async (ctx, args) => {
74
85
  const issued = await ctx.options.tokens.issue({
75
86
  user,
76
87
  client,
77
- grant: args.grant,
88
+ authorization: args.authorization,
78
89
  resource: consent.resource,
79
90
  });
80
91
  if (!issued) {
@@ -1,11 +1,11 @@
1
1
  import type { AuthletUrls } from "../urls.js";
2
2
  /**
3
3
  * Authorization server metadata (RFC 8414), served at every discovery location. It also
4
- * carries the fields OpenID discovery requires, since MCP clients may read it from
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;
8
- /** Protected resource metadata (RFC 9728) for the MCP endpoint. */
7
+ declare const authorizationServerMetadata: (urls: AuthletUrls, clientMetadataDocuments: boolean) => Response;
8
+ /** Protected resource metadata (RFC 9728) for the resource. */
9
9
  declare const resourceMetadata: (urls: AuthletUrls) => Response;
10
10
  declare const jwks: () => Response;
11
11
  export { authorizationServerMetadata, jwks, resourceMetadata };
@@ -1,10 +1,10 @@
1
1
  import { json } from "../http.js";
2
2
  /**
3
3
  * Authorization server metadata (RFC 8414), served at every discovery location. It also
4
- * carries the fields OpenID discovery requires, since MCP clients may read it from
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,8 +17,11 @@ 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
- /** Protected resource metadata (RFC 9728) for the MCP endpoint. */
24
+ /** Protected resource metadata (RFC 9728) for the resource. */
22
25
  const resourceMetadata = (urls) => json({
23
26
  resource: urls.resource,
24
27
  authorization_servers: [urls.issuer],
@@ -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 };
@@ -8,10 +8,14 @@ const parseJson = (text) => {
8
8
  return null;
9
9
  }
10
10
  };
11
- const DEFAULT_CLIENT_NAME = "An MCP client";
11
+ 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,5 +1,5 @@
1
1
  import type { Context } from "../context.js";
2
2
  import type { AuthletUser } from "../types.js";
3
3
  /** The token endpoint for public clients: authorization code (PKCE) and refresh token grants. */
4
- declare const token: <TGrant, TUser extends AuthletUser>(ctx: Context<TGrant, TUser>) => Promise<Response>;
4
+ declare const token: <TAuthorization, TUser extends AuthletUser>(ctx: Context<TAuthorization, TUser>) => Promise<Response>;
5
5
  export { token };
@@ -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,8 +66,8 @@ 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 },
64
- kind: isCode ? "code" : "refresh",
69
+ client: { id: clientId, kind },
70
+ grantType,
65
71
  }));
66
72
  if (!grant || !tokens) {
67
73
  return oauthError("invalid_grant");
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,20 +8,30 @@ 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
22
32
  * token ever travels through the browser.
23
33
  */
24
- export interface IssuedGrant {
34
+ export interface IssuedRefreshToken {
25
35
  refreshToken: string;
26
36
  }
27
37
  /** Tokens created by the app. authlet passes them through and never inspects them. */
@@ -31,34 +41,37 @@ export interface IssuedTokens {
31
41
  /** Required, so the next refresh rotates it. Wrapped in a sealed, client-bound value before it reaches the client. */
32
42
  refreshToken: string;
33
43
  }
34
- export interface IssueTokensArgs<TGrant, TUser extends AuthletUser> {
44
+ export interface IssueTokensArgs<TAuthorization, TUser extends AuthletUser> {
35
45
  user: TUser;
36
46
  client: AuthletClient;
37
- /** The app data passed to `decide`, such as the capabilities the user picked on the consent screen. */
38
- grant: TGrant;
47
+ /**
48
+ * What the user allowed, as passed to `decide`, such as the capabilities picked on the consent
49
+ * screen. RFC 9396 calls this kind of data authorization details.
50
+ */
51
+ authorization: TAuthorization;
39
52
  /** The protected resource (RFC 8707) the tokens are for. */
40
53
  resource: string;
41
54
  }
42
55
  export interface RefreshTokensArgs {
43
56
  refreshToken: string;
44
- client: Pick<AuthletClient, "id">;
57
+ client: Pick<AuthletClient, "id" | "kind">;
45
58
  /**
46
- * `"code"` when redeeming an authorization code: the token must never have been used, so the
47
- * code works once, and a second redemption must be refused (and should revoke the token family).
48
- * `"refresh"` on a refresh grant, where the app may allow its own reuse leeway.
59
+ * The token request's `grant_type`. On `"authorization_code"` the token must never have been
60
+ * used, so the code works once: refuse a second redemption (and revoke the token family). On
61
+ * `"refresh_token"` the app may allow its own reuse leeway.
49
62
  */
50
- kind: "code" | "refresh";
63
+ grantType: "authorization_code" | "refresh_token";
51
64
  }
52
65
  /** Token storage and minting, owned by the app. */
53
- export interface TokenHooks<TGrant, TUser extends AuthletUser> {
66
+ export interface TokenHooks<TAuthorization, TUser extends AuthletUser> {
54
67
  /**
55
- * Called when the user allows a client: stores the grant and returns a refresh token for it,
68
+ * Called when the user allows a client: stores the authorization and returns a refresh token for it,
56
69
  * which is sealed into the authorization code. `null` refuses the user (e.g. lost access since
57
70
  * the consent page was shown), who is sent to `consentPage?error=forbidden`. Give that refresh
58
- * token a short lifetime until its first `kind: "code"` rotation, since a code that is never
71
+ * token a short lifetime until its first `"authorization_code"` rotation, since a code that is never
59
72
  * redeemed leaves it unused.
60
73
  */
61
- issue: (args: IssueTokensArgs<TGrant, TUser>) => Promise<IssuedGrant | null>;
74
+ issue: (args: IssueTokensArgs<TAuthorization, TUser>) => Promise<IssuedRefreshToken | null>;
62
75
  /**
63
76
  * Rotates a refresh token into a new token pair, invalidating the old refresh token and any
64
77
  * access token issued with it. `null` refuses it. Redeeming a code goes through here too.
@@ -67,9 +80,9 @@ export interface TokenHooks<TGrant, TUser extends AuthletUser> {
67
80
  }
68
81
  /** Why the authorization request can't be shown to the user. Never sent to the client's redirect URI. */
69
82
  export type AuthorizeError = "invalid_link" | "expired" | "forbidden";
70
- export interface AuthletOptions<TGrant = unknown, TUser extends AuthletUser = AuthletUser> {
83
+ export interface AuthletOptions<TAuthorization = unknown, TUser extends AuthletUser = AuthletUser> {
71
84
  /**
72
- * The protected resource, the MCP endpoint URL, in canonical form: absolute https (http only
85
+ * The protected resource (an API or MCP endpoint URL) in canonical form: absolute https (http only
73
86
  * to loopback), no credentials, query, fragment or trailing slash, lowercase host, no default
74
87
  * port. Clients compare it exactly, so any other form is refused. Fixed
75
88
  * strings are checked at setup, functions on each request. A function must not derive it
@@ -104,7 +117,16 @@ export interface AuthletOptions<TGrant = unknown, TUser extends AuthletUser = Au
104
117
  consentPage: Resolvable<string>;
105
118
  /** For the built-in AES-GCM sealer: at least 32 characters, or an AES-GCM `CryptoKey`. */
106
119
  secret: string | CryptoKey;
107
- tokens: TokenHooks<TGrant, TUser>;
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>;
108
130
  }
109
131
  /** A pending authorization, as shown on the consent page. */
110
132
  export interface Consent<TUser extends AuthletUser = AuthletUser> {
@@ -114,17 +136,17 @@ export interface Consent<TUser extends AuthletUser = AuthletUser> {
114
136
  }
115
137
  /**
116
138
  * The user's answer on the consent page. `consent` is the sealed consent the page was opened
117
- * with; `grant` is what the user allowed, passed to `tokens.issue`.
139
+ * with; `authorization` is what the user allowed, passed to `tokens.issue`.
118
140
  */
119
- export type DecideArgs<TGrant> = {
141
+ export type DecideArgs<TAuthorization> = {
120
142
  consent: string;
121
143
  allow: true;
122
- grant: TGrant;
144
+ authorization: TAuthorization;
123
145
  } | {
124
146
  consent: string;
125
147
  allow: false;
126
148
  };
127
- export interface Authlet<TGrant = unknown, TUser extends AuthletUser = AuthletUser> {
149
+ export interface Authlet<TAuthorization = unknown, TUser extends AuthletUser = AuthletUser> {
128
150
  /**
129
151
  * Serves the authorization endpoints (`/authorize`, `/token`, `/register`) and the
130
152
  * authorization server and protected resource (RFC 9728) metadata. Hosts that route the
@@ -133,10 +155,15 @@ export interface Authlet<TGrant = unknown, TUser extends AuthletUser = AuthletUs
133
155
  */
134
156
  handle: (req: Request) => Promise<Response | null>;
135
157
  /**
136
- * The 401 for an MCP request without a valid token. Its `resource_metadata` points below the
137
- * issuer, which MCP clients must follow, so discovery works under a base path.
158
+ * The 401 for a request to the resource without a valid token. Its `resource_metadata` points
159
+ * below the issuer, which RFC 9728 clients follow, so discovery works under a base path.
138
160
  */
139
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>;
140
167
  /** The pending authorization behind a sealed consent, or `null` if it's invalid, expired or for another user. */
141
168
  readConsent: (req: Request, consent: string) => Promise<Consent<TUser> | null>;
142
169
  /**
@@ -146,6 +173,6 @@ export interface Authlet<TGrant = unknown, TUser extends AuthletUser = AuthletUs
146
173
  * submission (`Sec-Fetch-Dest`, `Sec-Fetch-Site`, or `Origin` in older browsers), carry an
147
174
  * `Authorization` header, or come from another user than the one the consent was shown to.
148
175
  */
149
- decide: (req: Request, args: DecideArgs<TGrant>) => Promise<Response>;
176
+ decide: (req: Request, args: DecideArgs<TAuthorization>) => Promise<Response>;
150
177
  }
151
- export type CreateAuthlet = <TGrant = unknown, TUser extends AuthletUser = AuthletUser>(options: AuthletOptions<TGrant, TUser>) => Authlet<TGrant, TUser>;
178
+ export type CreateAuthlet = <TAuthorization = unknown, TUser extends AuthletUser = AuthletUser>(options: AuthletOptions<TAuthorization, TUser>) => Authlet<TAuthorization, TUser>;
package/dist/urls.d.ts CHANGED
@@ -9,8 +9,8 @@ interface AuthletUrls {
9
9
  jwksUri: string;
10
10
  /**
11
11
  * The protected resource metadata (RFC 9728) that `challenge` points to. It sits below the
12
- * issuer, so a host mounted under a base path needs no route at the site root: MCP clients
13
- * must follow `resource_metadata` from the challenge.
12
+ * issuer, so a host mounted under a base path needs no route at the site root: clients
13
+ * following RFC 9728 (MCP clients must) read `resource_metadata` from the challenge.
14
14
  */
15
15
  resourceMetadata: string;
16
16
  }
@@ -23,7 +23,7 @@ declare const deriveUrls: (args: {
23
23
  /**
24
24
  * Which endpoint a request URL addresses, or `null`. Only the path is compared, because behind
25
25
  * a TLS-terminating proxy the request URL can carry another scheme or host than the public one.
26
- * Metadata answers at every location an MCP client tries: path-appended OpenID discovery below
26
+ * Metadata answers at every location clients try: path-appended OpenID discovery below
27
27
  * the issuer, which needs no root route, and the root-level well-known paths for hosts that
28
28
  * route them here.
29
29
  */
package/dist/urls.js CHANGED
@@ -39,7 +39,7 @@ const insertWellKnown = (url, wellKnown) => {
39
39
  /**
40
40
  * Which endpoint a request URL addresses, or `null`. Only the path is compared, because behind
41
41
  * a TLS-terminating proxy the request URL can carry another scheme or host than the public one.
42
- * Metadata answers at every location an MCP client tries: path-appended OpenID discovery below
42
+ * Metadata answers at every location clients try: path-appended OpenID discovery below
43
43
  * the issuer, which needs no root route, and the root-level well-known paths for hosts that
44
44
  * route them here.
45
45
  */
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "authlet",
4
- "version": "0.1.0-beta.2",
5
- "description": "Runtime-agnostic OAuth 2.1 authorization server for MCP endpoints, built on Web Request and Response.",
4
+ "version": "0.1.0-beta.4",
5
+ "description": "Stateless, runtime-agnostic OAuth 2.1 authorization server built on Web Request and Response.",
6
6
  "keywords": [
7
7
  "oauth",
8
8
  "oauth2",