authlet 0.1.0-beta.5 → 0.1.0-beta.8
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 +48 -6
- package/dist/authlet.js +29 -5
- package/dist/endpoints/authorize.js +5 -0
- package/dist/endpoints/consent.js +11 -0
- package/dist/endpoints/metadata.d.ts +3 -2
- package/dist/endpoints/metadata.js +11 -3
- package/dist/endpoints/revoke.d.ts +9 -0
- package/dist/endpoints/revoke.js +42 -0
- package/dist/endpoints/token.js +36 -9
- package/dist/scope.d.ts +10 -0
- package/dist/scope.js +24 -0
- package/dist/seal.d.ts +6 -0
- package/dist/types.d.ts +41 -3
- package/dist/urls.d.ts +2 -1
- package/dist/urls.js +2 -0
- package/package.json +7 -7
package/README.md
CHANGED
|
@@ -5,9 +5,11 @@ so it runs on Node, Deno, Bun and edge runtimes. Bring your own users, sessions
|
|
|
5
5
|
|
|
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
|
-
resource indicators (RFC 8707), protected resource metadata (RFC 9728)
|
|
9
|
-
|
|
10
|
-
|
|
8
|
+
resource indicators (RFC 8707), protected resource metadata (RFC 9728), refresh token rotation,
|
|
9
|
+
optional token revocation (RFC 7009),
|
|
10
|
+
and optional [scopes](#scopes) with step-up (RFC 6750 `insufficient_scope`). MCP clients use this
|
|
11
|
+
profile, so an MCP server is the typical host, but any API can use it. There is no client
|
|
12
|
+
credentials or device flow, and no OpenID Connect ID tokens.
|
|
11
13
|
|
|
12
14
|
## Usage
|
|
13
15
|
|
|
@@ -22,17 +24,21 @@ const authlet = createAuthlet<Capabilities, AppUser>({
|
|
|
22
24
|
consentPage: "/admin/mcp/authorize", // gets ?consent=… or ?error=…
|
|
23
25
|
secret: process.env.AUTHLET_SECRET!, // >= 32 chars, or an AES-GCM CryptoKey
|
|
24
26
|
fetchClientMetadata: guardedFetch, // optional, enables Client ID Metadata Documents
|
|
27
|
+
scopes: ["read", "write"], // optional, advertised as scopes_supported
|
|
25
28
|
tokens: {
|
|
26
|
-
issue: async ({ user, client, authorization, resource }) => ({
|
|
29
|
+
issue: async ({ user, client, authorization, resource, scope }) => ({
|
|
27
30
|
refreshToken,
|
|
28
31
|
}), // or null to refuse
|
|
29
|
-
refresh: async ({ refreshToken, grantType, client }) =>
|
|
32
|
+
refresh: async ({ refreshToken, grantType, client, scope }) =>
|
|
33
|
+
rotated ?? null, // grantType: "authorization_code" | "refresh_token"
|
|
34
|
+
revoke: async ({ token, tokenType, client }) => {}, // optional, enables /revoke
|
|
30
35
|
},
|
|
31
36
|
});
|
|
32
37
|
|
|
33
38
|
authlet.handle(req); // Promise<Response | null>: OAuth endpoints, AS and resource metadata
|
|
34
39
|
authlet.authenticate(req, verify); // Promise<T | Response>: the app's auth info, or the 401
|
|
35
40
|
authlet.challenge(req); // 401 with WWW-Authenticate: Bearer resource_metadata="..."
|
|
41
|
+
authlet.challenge(req, { scope: ["write"] }); // 403 insufficient_scope
|
|
36
42
|
authlet.readConsent(req, consent); // Promise<Consent<AppUser> | null>, for rendering the consent page
|
|
37
43
|
authlet.decide(req, { consent, allow: true, authorization }); // Promise<Response>: redirect with a code
|
|
38
44
|
authlet.decide(req, { consent, allow: false }); // Promise<Response>: redirect with access_denied
|
|
@@ -93,9 +99,43 @@ Redeeming the code calls `tokens.refresh` with `grantType: "authorization_code"`
|
|
|
93
99
|
client's first token pair. Refusing a refresh token that was already used makes the code
|
|
94
100
|
single-use.
|
|
95
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
|
+
|
|
96
107
|
A consent stays valid for 20 minutes, so submitting the form twice creates two grants for the
|
|
97
108
|
same client.
|
|
98
109
|
|
|
110
|
+
### Scopes
|
|
111
|
+
|
|
112
|
+
Scopes are off until the app sets `scopes`. Clients then request a `scope`, and values not in
|
|
113
|
+
`scopes` are dropped. `readConsent` returns the requested scope, so the page can pre-check it.
|
|
114
|
+
`decide` takes the `scope` the user grants (default: the requested scope). It can only narrow the
|
|
115
|
+
request, or pick any configured scope when the client asked for none.
|
|
116
|
+
|
|
117
|
+
`tokens.issue` gets the granted scope. `tokens.refresh` gets the scope for the new access token:
|
|
118
|
+
the grant, or a subset the client asked for on refresh. Anything else is `invalid_scope`, and the
|
|
119
|
+
app's refresh token stays unused. The grant itself never changes, and the token response echoes
|
|
120
|
+
the access token's scope, except for a grant from before scopes were enabled.
|
|
121
|
+
|
|
122
|
+
`scope: undefined` in `issue` means scopes are off. In `refresh` it means scopes are off, or the
|
|
123
|
+
grant was made before they were enabled. Map it from the stored authorization, grant a default,
|
|
124
|
+
or return `null` to force re-authorization, but never read it as "all configured scopes". A grant
|
|
125
|
+
from before scopes stays unscoped across refreshes until the client authorizes again.
|
|
126
|
+
|
|
127
|
+
For step-up, a route whose token lacks a scope answers with every scope the request needs:
|
|
128
|
+
|
|
129
|
+
```ts
|
|
130
|
+
if (!auth.scope.includes("write")) {
|
|
131
|
+
return authlet.challenge(req, { scope: ["read", "write"] }); // 403 insufficient_scope
|
|
132
|
+
}
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
The client then authorizes again. It should request the scopes it holds plus the new ones, since
|
|
136
|
+
the new grant replaces the old one. `scope` in client registrations and metadata documents is
|
|
137
|
+
ignored.
|
|
138
|
+
|
|
99
139
|
## What the host app must do
|
|
100
140
|
|
|
101
141
|
authlet can't check these, because they happen in the app:
|
|
@@ -120,6 +160,8 @@ authlet can't check these, because they happen in the app:
|
|
|
120
160
|
control. Anyone with it can forge client IDs and consents, and there is no key rotation yet.
|
|
121
161
|
6. Derive a function-valued `resource` or `issuer` from trusted configuration only, never from
|
|
122
162
|
`Host` or `X-Forwarded-*` headers without an allowlist.
|
|
163
|
+
7. When `tokens.refresh` gets a `scope` array, mint the access token with exactly that scope and
|
|
164
|
+
check it in `verify` or the route. When it gets `undefined`, apply your own policy.
|
|
123
165
|
|
|
124
166
|
## Client ID Metadata Documents
|
|
125
167
|
|
|
@@ -162,7 +204,7 @@ The issuer defaults to `${resource}/oauth`. With `resource: "https://cms.example
|
|
|
162
204
|
|
|
163
205
|
| Path | Serves | Root route needed |
|
|
164
206
|
| ------------------------------------------------------- | --------------------------------------------- | ----------------- |
|
|
165
|
-
| `/api/mcp/oauth/authorize`, `/token`, `/register` | the endpoints
|
|
207
|
+
| `/api/mcp/oauth/authorize`, `/token`, `/register` | the endpoints (and `/revoke`, if enabled) | no |
|
|
166
208
|
| `/api/mcp/oauth/.well-known/openid-configuration` | AS metadata (OpenID discovery, path appended) | no |
|
|
167
209
|
| `/api/mcp/oauth/.well-known/oauth-protected-resource` | resource metadata, linked from `challenge` | no |
|
|
168
210
|
| `/.well-known/oauth-authorization-server/api/mcp/oauth` | AS metadata (RFC 8414) | yes, optional |
|
package/dist/authlet.js
CHANGED
|
@@ -3,8 +3,10 @@ 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";
|
|
9
|
+
import { assertScopes } from "./scope.js";
|
|
8
10
|
import { createSealer } from "./seal.js";
|
|
9
11
|
import { deriveUrls, matchEndpoint } from "./urls.js";
|
|
10
12
|
// RFC 6750 section 2.1 b64token.
|
|
@@ -29,25 +31,47 @@ const createAuthlet = (options) => {
|
|
|
29
31
|
if (typeof options.consentPage === "string") {
|
|
30
32
|
withParams(options.consentPage, {});
|
|
31
33
|
}
|
|
34
|
+
if (options.scopes) {
|
|
35
|
+
assertScopes(options.scopes, true);
|
|
36
|
+
}
|
|
32
37
|
const routes = {
|
|
33
38
|
authorize: { method: "GET", cors: false, run: authorize },
|
|
34
39
|
token: { method: "POST", cors: true, run: token },
|
|
35
40
|
register: { method: "POST", cors: true, run: register },
|
|
41
|
+
...(options.tokens.revoke
|
|
42
|
+
? { revoke: { method: "POST", cors: true, run: revoke } }
|
|
43
|
+
: {}),
|
|
36
44
|
jwks: { method: "GET", cors: true, run: jwks },
|
|
37
45
|
authorizationServerMetadata: {
|
|
38
46
|
method: "GET",
|
|
39
47
|
cors: true,
|
|
40
|
-
run: ({ urls }) => authorizationServerMetadata(urls,
|
|
48
|
+
run: ({ urls }) => authorizationServerMetadata(urls, options),
|
|
41
49
|
},
|
|
42
50
|
resourceMetadata: {
|
|
43
51
|
method: "GET",
|
|
44
52
|
cors: true,
|
|
45
|
-
run: ({ urls }) => resourceMetadata(urls),
|
|
53
|
+
run: ({ urls }) => resourceMetadata(urls, options.scopes),
|
|
46
54
|
},
|
|
47
55
|
};
|
|
48
|
-
const challenge = (req) => {
|
|
56
|
+
const challenge = (req, challengeOptions) => {
|
|
49
57
|
const { urls } = contextFor(req);
|
|
50
58
|
const params = [`resource_metadata="${urls.resourceMetadata}"`];
|
|
59
|
+
// RFC 6750 section 3.1: a token without the scopes the request needs.
|
|
60
|
+
if (challengeOptions?.scope !== undefined) {
|
|
61
|
+
const { scope } = challengeOptions;
|
|
62
|
+
// Also keeps quotes and separators out of the header.
|
|
63
|
+
assertScopes(scope, false);
|
|
64
|
+
return new Response(null, {
|
|
65
|
+
status: 403,
|
|
66
|
+
headers: {
|
|
67
|
+
"WWW-Authenticate": `Bearer ${[
|
|
68
|
+
'error="insufficient_scope"',
|
|
69
|
+
...(scope.length ? [`scope="${scope.join(" ")}"`] : []),
|
|
70
|
+
...params,
|
|
71
|
+
].join(", ")}`,
|
|
72
|
+
},
|
|
73
|
+
});
|
|
74
|
+
}
|
|
51
75
|
// RFC 6750 section 3.1: a request that sent a bearer token learns it was rejected.
|
|
52
76
|
if (/^bearer\b/i.test(req.headers.get("Authorization") ?? "")) {
|
|
53
77
|
params.unshift('error="invalid_token"');
|
|
@@ -61,10 +85,10 @@ const createAuthlet = (options) => {
|
|
|
61
85
|
handle: async (req) => {
|
|
62
86
|
const ctx = contextFor(req);
|
|
63
87
|
const endpoint = matchEndpoint(req.url, ctx.urls);
|
|
64
|
-
|
|
88
|
+
const route = endpoint && routes[endpoint];
|
|
89
|
+
if (!route) {
|
|
65
90
|
return null;
|
|
66
91
|
}
|
|
67
|
-
const route = routes[endpoint];
|
|
68
92
|
if (route.cors && req.method === "OPTIONS") {
|
|
69
93
|
return preflight(route.method);
|
|
70
94
|
}
|
|
@@ -3,6 +3,7 @@ import { getBrowserUser, toConsentPage } from "../context.js";
|
|
|
3
3
|
import { redirect } from "../http.js";
|
|
4
4
|
import { isCodeChallenge } from "../pkce.js";
|
|
5
5
|
import { isRegisteredRedirectUri } from "../redirect-uri.js";
|
|
6
|
+
import { parseScope } from "../scope.js";
|
|
6
7
|
const MAX_STATE_LENGTH = 1024;
|
|
7
8
|
/**
|
|
8
9
|
* The authorization endpoint. A valid request from a signed-in browser user goes to the app's
|
|
@@ -56,6 +57,10 @@ const authorize = async (ctx) => {
|
|
|
56
57
|
userId: user.id,
|
|
57
58
|
...(state === null ? {} : { state }),
|
|
58
59
|
...(isClientIdUrl(clientId) ? { clientName: client.name } : {}),
|
|
60
|
+
// Unknown scopes are dropped, since errors never go back to the client.
|
|
61
|
+
...(options.scopes?.length
|
|
62
|
+
? { scope: parseScope(params.get("scope"), options.scopes) }
|
|
63
|
+
: {}),
|
|
59
64
|
},
|
|
60
65
|
});
|
|
61
66
|
return toConsentPage(ctx, { consent });
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { isClientIdUrl } from "../client.js";
|
|
2
2
|
import { getBrowserUser, toConsentPage } from "../context.js";
|
|
3
3
|
import { redirect, withParams } from "../http.js";
|
|
4
|
+
import { parseScope } from "../scope.js";
|
|
4
5
|
/** The consent behind a sealed value, if it is valid and shown to the user signed in now. */
|
|
5
6
|
const loadConsent = async (ctx, value) => {
|
|
6
7
|
const { issuer } = ctx.urls;
|
|
@@ -41,6 +42,7 @@ const readConsent = async (ctx, value) => {
|
|
|
41
42
|
client: loaded.client,
|
|
42
43
|
user: loaded.user,
|
|
43
44
|
resource: loaded.consent.resource,
|
|
45
|
+
scope: loaded.consent.scope ?? [],
|
|
44
46
|
});
|
|
45
47
|
};
|
|
46
48
|
/**
|
|
@@ -82,11 +84,19 @@ const decide = async (ctx, args) => {
|
|
|
82
84
|
if (!args.allow) {
|
|
83
85
|
return toClient({ error: "access_denied" });
|
|
84
86
|
}
|
|
87
|
+
const { scopes } = ctx.options;
|
|
88
|
+
let scope;
|
|
89
|
+
if (scopes?.length) {
|
|
90
|
+
// The request is a ceiling the user can only lower; an empty one allows any configured scope.
|
|
91
|
+
const requested = parseScope(consent.scope, scopes);
|
|
92
|
+
scope = parseScope(args.scope ?? requested, requested.length ? requested : scopes);
|
|
93
|
+
}
|
|
85
94
|
const issued = await ctx.options.tokens.issue({
|
|
86
95
|
user,
|
|
87
96
|
client,
|
|
88
97
|
authorization: args.authorization,
|
|
89
98
|
resource: consent.resource,
|
|
99
|
+
scope,
|
|
90
100
|
});
|
|
91
101
|
if (!issued) {
|
|
92
102
|
return toConsentPage(ctx, { error: "forbidden" }, 303);
|
|
@@ -100,6 +110,7 @@ const decide = async (ctx, args) => {
|
|
|
100
110
|
codeChallenge: consent.codeChallenge,
|
|
101
111
|
resource: consent.resource,
|
|
102
112
|
refreshToken: issued.refreshToken,
|
|
113
|
+
...(scope ? { scope } : {}),
|
|
103
114
|
},
|
|
104
115
|
});
|
|
105
116
|
return toClient({ code });
|
|
@@ -1,11 +1,12 @@
|
|
|
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,
|
|
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
|
-
declare const resourceMetadata: (urls: AuthletUrls) => Response;
|
|
10
|
+
declare const resourceMetadata: (urls: AuthletUrls, scopes: readonly string[] | undefined) => Response;
|
|
10
11
|
declare const jwks: () => Response;
|
|
11
12
|
export { authorizationServerMetadata, jwks, resourceMetadata };
|
|
@@ -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,
|
|
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,15 +17,23 @@ const authorizationServerMetadata = (urls, clientMetadataDocuments) => 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
|
-
...(
|
|
20
|
+
...(fetchClientMetadata
|
|
21
21
|
? { client_id_metadata_document_supported: true }
|
|
22
22
|
: {}),
|
|
23
|
+
...(scopes?.length ? { scopes_supported: [...scopes] } : {}),
|
|
24
|
+
...(tokens.revoke
|
|
25
|
+
? {
|
|
26
|
+
revocation_endpoint: urls.revocationEndpoint,
|
|
27
|
+
revocation_endpoint_auth_methods_supported: ["none"],
|
|
28
|
+
}
|
|
29
|
+
: {}),
|
|
23
30
|
});
|
|
24
31
|
/** Protected resource metadata (RFC 9728) for the resource. */
|
|
25
|
-
const resourceMetadata = (urls) => json({
|
|
32
|
+
const resourceMetadata = (urls, scopes) => json({
|
|
26
33
|
resource: urls.resource,
|
|
27
34
|
authorization_servers: [urls.issuer],
|
|
28
35
|
bearer_methods_supported: ["header"],
|
|
36
|
+
...(scopes?.length ? { scopes_supported: [...scopes] } : {}),
|
|
29
37
|
});
|
|
30
38
|
const jwks = () => json({ keys: [] });
|
|
31
39
|
export { authorizationServerMetadata, jwks, resourceMetadata };
|
|
@@ -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/endpoints/token.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { isClientIdUrl } from "../client.js";
|
|
2
2
|
import { json, oauthError, readBody } from "../http.js";
|
|
3
3
|
import { verifyCodeChallenge } from "../pkce.js";
|
|
4
|
+
import { parseScope, splitScope } from "../scope.js";
|
|
4
5
|
/** A parameter the client may leave out, but that must match when sent. */
|
|
5
6
|
const matchesIfSent = (form, name, expected) => !form.has(name) || form.get(name) === expected;
|
|
6
7
|
/** The grant behind a code, if the code is valid for this client and its PKCE verifier. */
|
|
@@ -17,7 +18,11 @@ const unsealCode = async ({ urls, sealer }, form, clientId) => {
|
|
|
17
18
|
!(await verifyCodeChallenge(form.get("code_verifier") ?? "", code.codeChallenge))) {
|
|
18
19
|
return null;
|
|
19
20
|
}
|
|
20
|
-
return {
|
|
21
|
+
return {
|
|
22
|
+
refreshToken: code.refreshToken,
|
|
23
|
+
resource: code.resource,
|
|
24
|
+
rawScope: code.scope,
|
|
25
|
+
};
|
|
21
26
|
};
|
|
22
27
|
/** The grant behind a refresh token, if it was issued to this client. */
|
|
23
28
|
const unsealRefreshToken = async ({ urls, sealer }, form, clientId) => {
|
|
@@ -28,7 +33,11 @@ const unsealRefreshToken = async ({ urls, sealer }, form, clientId) => {
|
|
|
28
33
|
});
|
|
29
34
|
return wrapper?.clientId === clientId &&
|
|
30
35
|
matchesIfSent(form, "resource", wrapper.resource)
|
|
31
|
-
? {
|
|
36
|
+
? {
|
|
37
|
+
refreshToken: wrapper.refreshToken,
|
|
38
|
+
resource: wrapper.resource,
|
|
39
|
+
rawScope: wrapper.scope,
|
|
40
|
+
}
|
|
32
41
|
: null;
|
|
33
42
|
};
|
|
34
43
|
const REQUIRED_PARAMS = {
|
|
@@ -59,17 +68,32 @@ const token = async (ctx) => {
|
|
|
59
68
|
const grant = isCode
|
|
60
69
|
? await unsealCode(ctx, form, clientId)
|
|
61
70
|
: await unsealRefreshToken(ctx, form, clientId);
|
|
71
|
+
if (!grant) {
|
|
72
|
+
return oauthError("invalid_grant");
|
|
73
|
+
}
|
|
74
|
+
const { scopes } = ctx.options;
|
|
75
|
+
let scope;
|
|
76
|
+
// A refresh may narrow the grant, never widen it, and is checked before the app's token is used.
|
|
77
|
+
if (scopes?.length) {
|
|
78
|
+
const requested = isCode ? [] : splitScope(form.get("scope"));
|
|
79
|
+
const granted = grant.rawScope && parseScope(grant.rawScope, scopes);
|
|
80
|
+
if (requested.some((value) => !granted?.includes(value))) {
|
|
81
|
+
return oauthError("invalid_scope");
|
|
82
|
+
}
|
|
83
|
+
scope =
|
|
84
|
+
granted && (requested.length ? parseScope(requested, granted) : granted);
|
|
85
|
+
}
|
|
62
86
|
/*
|
|
63
87
|
* Redeeming a code rotates the refresh token sealed in it. The app refuses a used one, so a
|
|
64
88
|
* code works only once.
|
|
65
89
|
*/
|
|
66
|
-
const tokens =
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
if (!
|
|
90
|
+
const tokens = await ctx.options.tokens.refresh({
|
|
91
|
+
refreshToken: grant.refreshToken,
|
|
92
|
+
client: { id: clientId, kind },
|
|
93
|
+
grantType,
|
|
94
|
+
scope,
|
|
95
|
+
});
|
|
96
|
+
if (!tokens) {
|
|
73
97
|
return oauthError("invalid_grant");
|
|
74
98
|
}
|
|
75
99
|
const refreshToken = await ctx.sealer.seal({
|
|
@@ -79,6 +103,8 @@ const token = async (ctx) => {
|
|
|
79
103
|
clientId,
|
|
80
104
|
resource: grant.resource,
|
|
81
105
|
refreshToken: tokens.refreshToken,
|
|
106
|
+
// The grant itself never changes, whatever this access token got.
|
|
107
|
+
...(grant.rawScope ? { scope: grant.rawScope } : {}),
|
|
82
108
|
},
|
|
83
109
|
});
|
|
84
110
|
return json({
|
|
@@ -86,6 +112,7 @@ const token = async (ctx) => {
|
|
|
86
112
|
token_type: "Bearer",
|
|
87
113
|
refresh_token: refreshToken,
|
|
88
114
|
...(tokens.expiresIn === undefined ? {} : { expires_in: tokens.expiresIn }),
|
|
115
|
+
...(scope ? { scope: scope.join(" ") } : {}),
|
|
89
116
|
});
|
|
90
117
|
};
|
|
91
118
|
export { token };
|
package/dist/scope.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Splits a space-delimited `scope` parameter into its entries. */
|
|
2
|
+
declare const splitScope: (value: string | null | undefined) => string[];
|
|
3
|
+
/**
|
|
4
|
+
* The entries of `allowed` present in `value`, in `allowed` order and without duplicates.
|
|
5
|
+
* Anything else is dropped.
|
|
6
|
+
*/
|
|
7
|
+
declare const parseScope: (value: string | null | readonly string[] | undefined, allowed: readonly string[]) => string[];
|
|
8
|
+
/** Throws on a value that isn't a scope token, or, with `unique`, on a duplicate. */
|
|
9
|
+
declare const assertScopes: (scopes: readonly string[], unique: boolean) => void;
|
|
10
|
+
export { assertScopes, parseScope, splitScope };
|
package/dist/scope.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// RFC 6749 section 3.3 scope-token: %x21 / %x23-5B / %x5D-7E.
|
|
2
|
+
const SCOPE_TOKEN = /^[\x21\x23-\x5b\x5d-\x7e]+$/;
|
|
3
|
+
/** Splits a space-delimited `scope` parameter into its entries. */
|
|
4
|
+
const splitScope = (value) => (value ?? "").split(" ").filter(Boolean);
|
|
5
|
+
/**
|
|
6
|
+
* The entries of `allowed` present in `value`, in `allowed` order and without duplicates.
|
|
7
|
+
* Anything else is dropped.
|
|
8
|
+
*/
|
|
9
|
+
const parseScope = (value, allowed) => {
|
|
10
|
+
const entries = new Set(typeof value === "string" || !value ? splitScope(value) : value);
|
|
11
|
+
return allowed.filter((scope) => entries.has(scope));
|
|
12
|
+
};
|
|
13
|
+
/** Throws on a value that isn't a scope token, or, with `unique`, on a duplicate. */
|
|
14
|
+
const assertScopes = (scopes, unique) => {
|
|
15
|
+
for (const [index, scope] of scopes.entries()) {
|
|
16
|
+
if (!SCOPE_TOKEN.test(scope)) {
|
|
17
|
+
throw new Error(`A scope must be a scope token, got "${scope}".`);
|
|
18
|
+
}
|
|
19
|
+
if (unique && scopes.indexOf(scope) !== index) {
|
|
20
|
+
throw new Error(`The authlet scope "${scope}" is listed twice.`);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
export { assertScopes, parseScope, splitScope };
|
package/dist/seal.d.ts
CHANGED
|
@@ -18,6 +18,8 @@ interface SealedValues {
|
|
|
18
18
|
userId: string;
|
|
19
19
|
/** The metadata document's client name, so the consent page needs no second fetch. */
|
|
20
20
|
clientName?: string;
|
|
21
|
+
/** Requested scope within `scopes`. Present on scoped hosts, even empty. */
|
|
22
|
+
scope?: string[];
|
|
21
23
|
};
|
|
22
24
|
/** The authorization code, carrying the refresh token the app issued on consent. */
|
|
23
25
|
code: {
|
|
@@ -26,12 +28,16 @@ interface SealedValues {
|
|
|
26
28
|
codeChallenge: string;
|
|
27
29
|
resource: string;
|
|
28
30
|
refreshToken: string;
|
|
31
|
+
/** Granted scope. Present on scoped hosts, even empty. */
|
|
32
|
+
scope?: string[];
|
|
29
33
|
};
|
|
30
34
|
/** The `refresh_token` handed to the client, wrapping the app's own refresh token. */
|
|
31
35
|
refresh: {
|
|
32
36
|
clientId: string;
|
|
33
37
|
resource: string;
|
|
34
38
|
refreshToken: string;
|
|
39
|
+
/** Granted scope, resealed unchanged on every rotation. Absent: no scoped grant. */
|
|
40
|
+
scope?: string[];
|
|
35
41
|
};
|
|
36
42
|
}
|
|
37
43
|
type SealType = keyof SealedValues;
|
package/dist/types.d.ts
CHANGED
|
@@ -51,6 +51,8 @@ export interface IssueTokensArgs<TAuthorization, TUser extends AuthletUser> {
|
|
|
51
51
|
authorization: TAuthorization;
|
|
52
52
|
/** The protected resource (RFC 8707) the tokens are for. */
|
|
53
53
|
resource: string;
|
|
54
|
+
/** The scope the user granted, within the requested scope. `undefined` when scopes are off. */
|
|
55
|
+
scope: string[] | undefined;
|
|
54
56
|
}
|
|
55
57
|
export interface RefreshTokensArgs {
|
|
56
58
|
refreshToken: string;
|
|
@@ -61,6 +63,18 @@ export interface RefreshTokensArgs {
|
|
|
61
63
|
* `"refresh_token"` the app may allow its own reuse leeway.
|
|
62
64
|
*/
|
|
63
65
|
grantType: "authorization_code" | "refresh_token";
|
|
66
|
+
/**
|
|
67
|
+
* The scope to mint the access token with: the granted scope, or the subset the client asked
|
|
68
|
+
* for. `undefined` when scopes are off, or for a grant made before they were enabled; the app
|
|
69
|
+
* then applies its own policy (or returns `null` to force re-authorization).
|
|
70
|
+
*/
|
|
71
|
+
scope: string[] | undefined;
|
|
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">;
|
|
64
78
|
}
|
|
65
79
|
/** Token storage and minting, owned by the app. */
|
|
66
80
|
export interface TokenHooks<TAuthorization, TUser extends AuthletUser> {
|
|
@@ -77,6 +91,13 @@ export interface TokenHooks<TAuthorization, TUser extends AuthletUser> {
|
|
|
77
91
|
* access token issued with it. `null` refuses it. Redeeming a code goes through here too.
|
|
78
92
|
*/
|
|
79
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>;
|
|
80
101
|
}
|
|
81
102
|
/** Why the authorization request can't be shown to the user. Never sent to the client's redirect URI. */
|
|
82
103
|
export type AuthorizeError = "invalid_link" | "expired" | "forbidden";
|
|
@@ -127,12 +148,20 @@ export interface AuthletOptions<TAuthorization = unknown, TUser extends AuthletU
|
|
|
127
148
|
* browser trigger a fetch. It may cache by HTTP cache headers, but never errors.
|
|
128
149
|
*/
|
|
129
150
|
fetchClientMetadata?: (url: string, init: RequestInit) => Promise<Response>;
|
|
151
|
+
/**
|
|
152
|
+
* Scopes clients may request (RFC 6749 section 3.3), advertised as `scopes_supported`.
|
|
153
|
+
* Others are dropped at the authorization endpoint. Unset or empty turns scopes off, and
|
|
154
|
+
* `scope` parameters are ignored.
|
|
155
|
+
*/
|
|
156
|
+
scopes?: readonly string[];
|
|
130
157
|
}
|
|
131
158
|
/** A pending authorization, as shown on the consent page. */
|
|
132
159
|
export interface Consent<TUser extends AuthletUser = AuthletUser> {
|
|
133
160
|
client: AuthletClient;
|
|
134
161
|
user: TUser;
|
|
135
162
|
resource: string;
|
|
163
|
+
/** The scope the client requested, within `scopes`, for pre-checking the consent form. */
|
|
164
|
+
scope: string[];
|
|
136
165
|
}
|
|
137
166
|
/**
|
|
138
167
|
* The user's answer on the consent page. `consent` is the sealed consent the page was opened
|
|
@@ -142,6 +171,11 @@ export type DecideArgs<TAuthorization> = {
|
|
|
142
171
|
consent: string;
|
|
143
172
|
allow: true;
|
|
144
173
|
authorization: TAuthorization;
|
|
174
|
+
/**
|
|
175
|
+
* The scope the user grants. Default: the requested scope. Kept within the requested
|
|
176
|
+
* scope, or within `scopes` when the client requested none.
|
|
177
|
+
*/
|
|
178
|
+
scope?: readonly string[];
|
|
145
179
|
} | {
|
|
146
180
|
consent: string;
|
|
147
181
|
allow: false;
|
|
@@ -155,10 +189,14 @@ export interface Authlet<TAuthorization = unknown, TUser extends AuthletUser = A
|
|
|
155
189
|
*/
|
|
156
190
|
handle: (req: Request) => Promise<Response | null>;
|
|
157
191
|
/**
|
|
158
|
-
*
|
|
159
|
-
* below the issuer, which RFC 9728 clients follow, so discovery
|
|
192
|
+
* Without `scope`: the 401 for a request to the resource without a valid token. Its
|
|
193
|
+
* `resource_metadata` points below the issuer, which RFC 9728 clients follow, so discovery
|
|
194
|
+
* works under a base path. With `scope`: the 403 `insufficient_scope` (RFC 6750 section 3.1)
|
|
195
|
+
* naming every scope the request needs. Throws on a value that isn't a scope token.
|
|
160
196
|
*/
|
|
161
|
-
challenge: (req: Request
|
|
197
|
+
challenge: (req: Request, options?: {
|
|
198
|
+
scope: readonly string[];
|
|
199
|
+
}) => Response;
|
|
162
200
|
/**
|
|
163
201
|
* The app's auth info for a request bearing `Authorization: Bearer <token>` that `verify`
|
|
164
202
|
* accepts, else the `challenge` 401 (with `error="invalid_token"` when a bearer token was sent).
|
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.
|
|
4
|
+
"version": "0.1.0-beta.8",
|
|
5
5
|
"description": "Stateless, runtime-agnostic OAuth 2.1 authorization server built on Web Request and Response.",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"oauth",
|
|
@@ -56,14 +56,14 @@
|
|
|
56
56
|
"@abinnovision/eslint-config-base": "^3.4.2",
|
|
57
57
|
"@abinnovision/prettier-config": "^2.2.0",
|
|
58
58
|
"@internal/tsconfig": "0.0.0",
|
|
59
|
-
"@types/node": "^
|
|
60
|
-
"@vitest/coverage-v8": "^5.
|
|
61
|
-
"eslint": "^10.
|
|
59
|
+
"@types/node": "^26",
|
|
60
|
+
"@vitest/coverage-v8": "^5.1.2",
|
|
61
|
+
"eslint": "^10.15.0",
|
|
62
62
|
"oauth4webapi": "^3.8.9",
|
|
63
|
-
"prettier": "^3.
|
|
63
|
+
"prettier": "^3.10.1",
|
|
64
64
|
"typescript": "^6.0.3",
|
|
65
|
-
"vite": "^8.
|
|
66
|
-
"vitest": "^5.
|
|
65
|
+
"vite": "^8.4.0",
|
|
66
|
+
"vitest": "^5.1.2"
|
|
67
67
|
},
|
|
68
68
|
"engines": {
|
|
69
69
|
"node": ">=22"
|