authlet 0.1.0-beta.7 → 0.1.0-beta.9

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
@@ -6,6 +6,7 @@ so it runs on Node, Deno, Bun and edge runtimes. Bring your own users, sessions
6
6
  It serves the authorization code flow with PKCE for public clients, with dynamic client
7
7
  registration (RFC 7591), optional [Client ID Metadata Documents](#client-id-metadata-documents),
8
8
  resource indicators (RFC 8707), protected resource metadata (RFC 9728), refresh token rotation,
9
+ optional token revocation (RFC 7009),
9
10
  and optional [scopes](#scopes) with step-up (RFC 6750 `insufficient_scope`). MCP clients use this
10
11
  profile, so an MCP server is the typical host, but any API can use it. There is no client
11
12
  credentials or device flow, and no OpenID Connect ID tokens.
@@ -30,6 +31,7 @@ const authlet = createAuthlet<Capabilities, AppUser>({
30
31
  }), // or null to refuse
31
32
  refresh: async ({ refreshToken, grantType, client, scope }) =>
32
33
  rotated ?? null, // grantType: "authorization_code" | "refresh_token"
34
+ revoke: async ({ token, tokenType, client }) => {}, // optional, enables /revoke
33
35
  },
34
36
  });
35
37
 
@@ -97,6 +99,11 @@ Redeeming the code calls `tokens.refresh` with `grantType: "authorization_code"`
97
99
  client's first token pair. Refusing a refresh token that was already used makes the code
98
100
  single-use.
99
101
 
102
+ With `tokens.revoke`, clients can revoke their tokens on sign-out at `/revoke` (RFC 7009). A
103
+ refresh token reaches the hook unwrapped, and only when it was issued to the requesting client.
104
+ Anything else arrives as `tokenType: "access_token"`, exactly as the client sent it, so ignore
105
+ tokens you don't know or didn't issue to `client`. Revoke the whole grant either way.
106
+
100
107
  A consent stays valid for 20 minutes, so submitting the form twice creates two grants for the
101
108
  same client.
102
109
 
@@ -150,7 +157,10 @@ authlet can't check these, because they happen in the app:
150
157
  3. On the login page, only follow a `returnTo` that starts with a single `/`.
151
158
  4. Use a session cookie with `SameSite=Lax` or stricter.
152
159
  5. Use a random secret of at least 32 bytes, or a generated `CryptoKey`, and keep it out of source
153
- control. Anyone with it can forge client IDs and consents, and there is no key rotation yet.
160
+ control. Anyone with it can forge client IDs and consents. To rotate, pass
161
+ `secret: [newSecret, oldSecret]` and drop the old one later. Refresh tokens move to the new
162
+ secret on their next refresh. Registered client IDs never do, so dropping the old secret makes
163
+ those clients register again. After a leak, drop it right away.
154
164
  6. Derive a function-valued `resource` or `issuer` from trusted configuration only, never from
155
165
  `Host` or `X-Forwarded-*` headers without an allowlist.
156
166
  7. When `tokens.refresh` gets a `scope` array, mint the access token with exactly that scope and
@@ -197,7 +207,7 @@ The issuer defaults to `${resource}/oauth`. With `resource: "https://cms.example
197
207
 
198
208
  | Path | Serves | Root route needed |
199
209
  | ------------------------------------------------------- | --------------------------------------------- | ----------------- |
200
- | `/api/mcp/oauth/authorize`, `/token`, `/register` | the endpoints | no |
210
+ | `/api/mcp/oauth/authorize`, `/token`, `/register` | the endpoints (and `/revoke`, if enabled) | no |
201
211
  | `/api/mcp/oauth/.well-known/openid-configuration` | AS metadata (OpenID discovery, path appended) | no |
202
212
  | `/api/mcp/oauth/.well-known/oauth-protected-resource` | resource metadata, linked from `challenge` | no |
203
213
  | `/.well-known/oauth-authorization-server/api/mcp/oauth` | AS metadata (RFC 8414) | yes, optional |
package/dist/authlet.js CHANGED
@@ -3,6 +3,7 @@ import { authorize } from "./endpoints/authorize.js";
3
3
  import { decide, readConsent } from "./endpoints/consent.js";
4
4
  import { authorizationServerMetadata, jwks, resourceMetadata, } from "./endpoints/metadata.js";
5
5
  import { register } from "./endpoints/register.js";
6
+ import { revoke } from "./endpoints/revoke.js";
6
7
  import { token } from "./endpoints/token.js";
7
8
  import { methodNotAllowed, preflight, withParams } from "./http.js";
8
9
  import { assertScopes } from "./scope.js";
@@ -37,11 +38,14 @@ const createAuthlet = (options) => {
37
38
  authorize: { method: "GET", cors: false, run: authorize },
38
39
  token: { method: "POST", cors: true, run: token },
39
40
  register: { method: "POST", cors: true, run: register },
41
+ ...(options.tokens.revoke
42
+ ? { revoke: { method: "POST", cors: true, run: revoke } }
43
+ : {}),
40
44
  jwks: { method: "GET", cors: true, run: jwks },
41
45
  authorizationServerMetadata: {
42
46
  method: "GET",
43
47
  cors: true,
44
- run: ({ urls }) => authorizationServerMetadata(urls, Boolean(options.fetchClientMetadata), options.scopes),
48
+ run: ({ urls }) => authorizationServerMetadata(urls, options),
45
49
  },
46
50
  resourceMetadata: {
47
51
  method: "GET",
@@ -81,10 +85,10 @@ const createAuthlet = (options) => {
81
85
  handle: async (req) => {
82
86
  const ctx = contextFor(req);
83
87
  const endpoint = matchEndpoint(req.url, ctx.urls);
84
- if (!endpoint) {
88
+ const route = endpoint && routes[endpoint];
89
+ if (!route) {
85
90
  return null;
86
91
  }
87
- const route = routes[endpoint];
88
92
  if (route.cors && req.method === "OPTIONS") {
89
93
  return preflight(route.method);
90
94
  }
@@ -1,10 +1,11 @@
1
+ import type { AuthletOptions, AuthletUser } from "../types.js";
1
2
  import type { AuthletUrls } from "../urls.js";
2
3
  /**
3
4
  * Authorization server metadata (RFC 8414), served at every discovery location. It also
4
5
  * carries the fields OpenID discovery requires, since some clients (MCP among them) read it from
5
6
  * `openid-configuration`; no ID tokens are issued.
6
7
  */
7
- declare const authorizationServerMetadata: (urls: AuthletUrls, clientMetadataDocuments: boolean, scopes: readonly string[] | undefined) => Response;
8
+ declare const authorizationServerMetadata: <TAuthorization, TUser extends AuthletUser>(urls: AuthletUrls, { fetchClientMetadata, scopes, tokens, }: AuthletOptions<TAuthorization, TUser>) => Response;
8
9
  /** Protected resource metadata (RFC 9728) for the resource. */
9
10
  declare const resourceMetadata: (urls: AuthletUrls, scopes: readonly string[] | undefined) => Response;
10
11
  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, clientMetadataDocuments, scopes) => json({
7
+ const authorizationServerMetadata = (urls, { fetchClientMetadata, scopes, tokens, }) => json({
8
8
  issuer: urls.issuer,
9
9
  authorization_endpoint: urls.authorizationEndpoint,
10
10
  token_endpoint: urls.tokenEndpoint,
@@ -17,10 +17,16 @@ const authorizationServerMetadata = (urls, clientMetadataDocuments, scopes) => j
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
20
+ ...(fetchClientMetadata
21
21
  ? { client_id_metadata_document_supported: true }
22
22
  : {}),
23
23
  ...(scopes?.length ? { scopes_supported: [...scopes] } : {}),
24
+ ...(tokens.revoke
25
+ ? {
26
+ revocation_endpoint: urls.revocationEndpoint,
27
+ revocation_endpoint_auth_methods_supported: ["none"],
28
+ }
29
+ : {}),
24
30
  });
25
31
  /** Protected resource metadata (RFC 9728) for the resource. */
26
32
  const resourceMetadata = (urls, scopes) => json({
@@ -0,0 +1,9 @@
1
+ import type { Context } from "../context.js";
2
+ import type { AuthletUser } from "../types.js";
3
+ /**
4
+ * Token revocation (RFC 7009) for public clients. A refresh token is unwrapped and passed on
5
+ * only when it was issued to the requesting client; anything else is passed on as an access
6
+ * token. Unknown tokens succeed too, as section 2.2 requires.
7
+ */
8
+ declare const revoke: <TAuthorization, TUser extends AuthletUser>(ctx: Context<TAuthorization, TUser>) => Promise<Response>;
9
+ export { revoke };
@@ -0,0 +1,42 @@
1
+ import { isClientIdUrl } from "../client.js";
2
+ import { json, oauthError, readBody } from "../http.js";
3
+ /**
4
+ * Token revocation (RFC 7009) for public clients. A refresh token is unwrapped and passed on
5
+ * only when it was issued to the requesting client; anything else is passed on as an access
6
+ * token. Unknown tokens succeed too, as section 2.2 requires.
7
+ */
8
+ const revoke = async (ctx) => {
9
+ const body = await readBody(ctx.req);
10
+ const form = new URLSearchParams(body ?? "");
11
+ const token = form.get("token");
12
+ const clientId = form.get("client_id");
13
+ if (body === null || !token || !clientId) {
14
+ return oauthError("invalid_request");
15
+ }
16
+ const kind = isClientIdUrl(clientId) ? "metadata" : "registered";
17
+ if (kind === "metadata" && !ctx.options.fetchClientMetadata) {
18
+ return oauthError("invalid_client");
19
+ }
20
+ const wrapper = await ctx.sealer.unseal({
21
+ issuer: ctx.urls.issuer,
22
+ type: "refresh",
23
+ value: token,
24
+ });
25
+ const client = { id: clientId, kind };
26
+ if (!wrapper) {
27
+ await ctx.options.tokens.revoke?.({
28
+ token,
29
+ tokenType: "access_token",
30
+ client,
31
+ });
32
+ }
33
+ else if (wrapper.clientId === clientId) {
34
+ await ctx.options.tokens.revoke?.({
35
+ token: wrapper.refreshToken,
36
+ tokenType: "refresh_token",
37
+ client,
38
+ });
39
+ }
40
+ return json({});
41
+ };
42
+ export { revoke };
package/dist/seal.d.ts CHANGED
@@ -62,10 +62,13 @@ interface Sealer {
62
62
  /** The sealed data, or `undefined` when the value is malformed, tampered, of another type or issuer, or expired. */
63
63
  unseal: <K extends SealType>(args: UnsealArgs<K>) => Promise<SealedValues[K] | undefined>;
64
64
  }
65
+ type Secret = string | CryptoKey;
65
66
  /**
66
67
  * Creates a sealer from a secret string (at least 32 characters, stretched with HKDF) or a
67
- * 256-bit AES-GCM `CryptoKey` with the `encrypt` and `decrypt` usages.
68
+ * 256-bit AES-GCM `CryptoKey` with the `encrypt` and `decrypt` usages. A list seals with its
69
+ * first secret and unseals with any of them, so a new secret can be rolled out before the old
70
+ * one is dropped.
68
71
  */
69
- declare const createSealer: (secret: string | CryptoKey) => Sealer;
72
+ declare const createSealer: (secret: Secret | readonly Secret[]) => Sealer;
70
73
  export { createSealer };
71
74
  export type { Sealer, SealedValues };
package/dist/seal.js CHANGED
@@ -25,11 +25,7 @@ const isSealingKey = (key) => key.algorithm.name === "AES-GCM" &&
25
25
  key.algorithm.length === 256 &&
26
26
  key.usages.includes("encrypt") &&
27
27
  key.usages.includes("decrypt");
28
- /**
29
- * Creates a sealer from a secret string (at least 32 characters, stretched with HKDF) or a
30
- * 256-bit AES-GCM `CryptoKey` with the `encrypt` and `decrypt` usages.
31
- */
32
- const createSealer = (secret) => {
28
+ const toKey = (secret) => {
33
29
  // Checked here, not in deriveKey, so a bad secret fails at setup instead of as an unhandled rejection.
34
30
  if (typeof secret === "string" && secret.length < MIN_SECRET_LENGTH) {
35
31
  throw new Error(`The authlet secret must be at least ${String(MIN_SECRET_LENGTH)} characters long.`);
@@ -37,7 +33,22 @@ const createSealer = (secret) => {
37
33
  if (typeof secret !== "string" && !isSealingKey(secret)) {
38
34
  throw new Error("The authlet key must be a 256-bit AES-GCM CryptoKey with the encrypt and decrypt usages.");
39
35
  }
40
- const key = typeof secret === "string" ? deriveKey(secret) : Promise.resolve(secret);
36
+ return typeof secret === "string"
37
+ ? deriveKey(secret)
38
+ : Promise.resolve(secret);
39
+ };
40
+ /**
41
+ * Creates a sealer from a secret string (at least 32 characters, stretched with HKDF) or a
42
+ * 256-bit AES-GCM `CryptoKey` with the `encrypt` and `decrypt` usages. A list seals with its
43
+ * first secret and unseals with any of them, so a new secret can be rolled out before the old
44
+ * one is dropped.
45
+ */
46
+ const createSealer = (secret) => {
47
+ const keys = [secret].flat().map(toKey);
48
+ const [key] = keys;
49
+ if (!key) {
50
+ throw new Error("The authlet secret list must not be empty.");
51
+ }
41
52
  return {
42
53
  seal: async ({ issuer, type, data }) => {
43
54
  const jwt = new EncryptJWT({ data })
@@ -59,13 +70,13 @@ const createSealer = (secret) => {
59
70
  return undefined;
60
71
  }
61
72
  try {
62
- const { payload } = await jwtDecrypt(value, await key, {
73
+ const { payload } = await Promise.any(keys.map(async (candidate) => await jwtDecrypt(value, await candidate, {
63
74
  issuer,
64
75
  typ: typHeader(type),
65
76
  clockTolerance: CLOCK_TOLERANCE,
66
77
  keyManagementAlgorithms: ["dir"],
67
78
  contentEncryptionAlgorithms: ["A256GCM"],
68
- });
79
+ })));
69
80
  return payload.data;
70
81
  }
71
82
  catch {
package/dist/types.d.ts CHANGED
@@ -70,6 +70,12 @@ export interface RefreshTokensArgs {
70
70
  */
71
71
  scope: string[] | undefined;
72
72
  }
73
+ export interface RevokeTokenArgs {
74
+ /** The app's own refresh token, or the access token as the client sent it. */
75
+ token: string;
76
+ tokenType: "refresh_token" | "access_token";
77
+ client: Pick<AuthletClient, "id" | "kind">;
78
+ }
73
79
  /** Token storage and minting, owned by the app. */
74
80
  export interface TokenHooks<TAuthorization, TUser extends AuthletUser> {
75
81
  /**
@@ -85,6 +91,13 @@ export interface TokenHooks<TAuthorization, TUser extends AuthletUser> {
85
91
  * access token issued with it. `null` refuses it. Redeeming a code goes through here too.
86
92
  */
87
93
  refresh: (args: RefreshTokensArgs) => Promise<IssuedTokens | null>;
94
+ /**
95
+ * Revokes a token on the client's request (RFC 7009), and enables the revocation endpoint.
96
+ * A refresh token is checked to belong to `client` first. An access token is passed as sent,
97
+ * so ignore one that is unknown or was not issued to `client`. Revoking either should revoke
98
+ * the whole grant.
99
+ */
100
+ revoke?: (args: RevokeTokenArgs) => Promise<void>;
88
101
  }
89
102
  /** Why the authorization request can't be shown to the user. Never sent to the client's redirect URI. */
90
103
  export type AuthorizeError = "invalid_link" | "expired" | "forbidden";
@@ -123,8 +136,13 @@ export interface AuthletOptions<TAuthorization = unknown, TUser extends AuthletU
123
136
  * A relative URL stays relative in the `Location` header, so a proxy can't leak its own host.
124
137
  */
125
138
  consentPage: Resolvable<string>;
126
- /** For the built-in AES-GCM sealer: at least 32 characters, or an AES-GCM `CryptoKey`. */
127
- secret: string | CryptoKey;
139
+ /**
140
+ * For the built-in AES-GCM sealer: at least 32 characters, or an AES-GCM `CryptoKey`. To
141
+ * rotate, pass `[newSecret, oldSecret]`: new values are sealed with the first, and any of
142
+ * them unseals. Refresh tokens move to the new secret on their next refresh, but registered
143
+ * client IDs never do, so dropping the old secret makes those clients register again.
144
+ */
145
+ secret: string | CryptoKey | readonly (string | CryptoKey)[];
128
146
  tokens: TokenHooks<TAuthorization, TUser>;
129
147
  /**
130
148
  * Enables Client ID Metadata Documents: an https `client_id` names a JSON document describing
package/dist/urls.d.ts CHANGED
@@ -5,6 +5,7 @@ interface AuthletUrls {
5
5
  authorizationEndpoint: string;
6
6
  tokenEndpoint: string;
7
7
  registrationEndpoint: string;
8
+ revocationEndpoint: string;
8
9
  /** An empty key set: OpenID discovery requires `jwks_uri`, though no ID tokens are issued. */
9
10
  jwksUri: string;
10
11
  /**
@@ -14,7 +15,7 @@ interface AuthletUrls {
14
15
  */
15
16
  resourceMetadata: string;
16
17
  }
17
- type AuthletEndpoint = "authorize" | "token" | "register" | "jwks" | "authorizationServerMetadata" | "resourceMetadata";
18
+ type AuthletEndpoint = "authorize" | "token" | "register" | "revoke" | "jwks" | "authorizationServerMetadata" | "resourceMetadata";
18
19
  /** Derives all URLs. The issuer defaults to `${resource}/oauth`. */
19
20
  declare const deriveUrls: (args: {
20
21
  resource: string;
package/dist/urls.js CHANGED
@@ -27,6 +27,7 @@ const deriveUrls = (args) => {
27
27
  authorizationEndpoint: `${issuer}/authorize`,
28
28
  tokenEndpoint: `${issuer}/token`,
29
29
  registrationEndpoint: `${issuer}/register`,
30
+ revocationEndpoint: `${issuer}/revoke`,
30
31
  jwksUri: `${issuer}/jwks`,
31
32
  resourceMetadata: `${issuer}/.well-known/oauth-protected-resource`,
32
33
  };
@@ -49,6 +50,7 @@ const matchEndpoint = (requestUrl, urls) => {
49
50
  [urls.authorizationEndpoint, "authorize"],
50
51
  [urls.tokenEndpoint, "token"],
51
52
  [urls.registrationEndpoint, "register"],
53
+ [urls.revocationEndpoint, "revoke"],
52
54
  [urls.jwksUri, "jwks"],
53
55
  [
54
56
  `${urls.issuer}/.well-known/openid-configuration`,
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.7",
4
+ "version": "0.1.0-beta.9",
5
5
  "description": "Stateless, runtime-agnostic OAuth 2.1 authorization server built on Web Request and Response.",
6
6
  "keywords": [
7
7
  "oauth",