authlet 0.0.0-stage → 0.0.0-stage.0
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/LICENSE +201 -0
- package/README.md +179 -2
- package/dist/authlet.d.ts +3 -0
- package/dist/authlet.js +78 -0
- package/dist/context.d.ts +30 -0
- package/dist/context.js +10 -0
- package/dist/endpoints/authorize.d.ts +12 -0
- package/dist/endpoints/authorize.js +62 -0
- package/dist/endpoints/consent.d.ts +5 -0
- package/dist/endpoints/consent.js +96 -0
- package/dist/endpoints/metadata.d.ts +11 -0
- package/dist/endpoints/metadata.js +28 -0
- package/dist/endpoints/register.d.ts +9 -0
- package/dist/endpoints/register.js +51 -0
- package/dist/endpoints/token.d.ts +5 -0
- package/dist/endpoints/token.js +85 -0
- package/dist/http.d.ts +21 -0
- package/dist/http.js +57 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/pkce.d.ts +4 -0
- package/dist/pkce.js +15 -0
- package/dist/redirect-uri.d.ts +18 -0
- package/dist/redirect-uri.js +68 -0
- package/dist/seal.d.ts +63 -0
- package/dist/seal.js +77 -0
- package/dist/types.d.ts +151 -0
- package/dist/types.js +1 -0
- package/dist/urls.d.ts +32 -0
- package/dist/urls.js +73 -0
- package/package.json +72 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 abi group GmbH
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,180 @@
|
|
|
1
|
-
#
|
|
1
|
+
# authlet
|
|
2
2
|
|
|
3
|
-
|
|
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.
|
|
5
|
+
|
|
6
|
+
> Status: pre-release, not yet published. `createAuthlet` and all endpoints work, and an
|
|
7
|
+
> end-to-end run with `oauth4webapi` passes. [Planned](#planned) lists what is missing.
|
|
8
|
+
|
|
9
|
+
## Design
|
|
10
|
+
|
|
11
|
+
authlet stores nothing. Client IDs from dynamic registration, consent forms, authorization codes
|
|
12
|
+
and refresh token wrappers are encrypted JWTs (jose, `dir` + `A256GCM`) bound to their type and
|
|
13
|
+
issuer, with an expiry, and the client or browser holds them. The app's `tokens` hooks own all
|
|
14
|
+
persistence. [`src/seal.ts`](src/seal.ts) lists every sealed value.
|
|
15
|
+
|
|
16
|
+
Every URL derives from the issuer, which defaults to `${resource}/oauth`, so discovery works under
|
|
17
|
+
a base path without routes at the site root ([Base URLs](#base-urls)).
|
|
18
|
+
|
|
19
|
+
The app owns the user. `getUser` reads the browser session and returns the app's own user type
|
|
20
|
+
(`TUser`), and `tokens.issue` and the consent page get that type back. authlet only compares
|
|
21
|
+
`id`, so it must be unique across the app; prefix it when there are several user collections.
|
|
22
|
+
Requests with an `Authorization` header never reach `getUser`, so a token can't approve a client
|
|
23
|
+
for itself.
|
|
24
|
+
|
|
25
|
+
The app also owns the consent screen. authlet redirects to `consentPage?consent=…`, or to
|
|
26
|
+
`?error=…` for a broken link. The page reads the request with `readConsent`, and its POST handler
|
|
27
|
+
calls `decide`.
|
|
28
|
+
|
|
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.
|
|
31
|
+
|
|
32
|
+
### App-specific grant data
|
|
33
|
+
|
|
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:
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
const authlet = createAuthlet<Capabilities>({/* ... */});
|
|
41
|
+
|
|
42
|
+
// The consent form's POST handler, in the app
|
|
43
|
+
export const POST = async (req: Request) => {
|
|
44
|
+
const form = await req.formData();
|
|
45
|
+
const consent = String(form.get("consent"));
|
|
46
|
+
|
|
47
|
+
return authlet.decide(
|
|
48
|
+
req,
|
|
49
|
+
form.get("decision") === "allow"
|
|
50
|
+
? { consent, allow: true, grant: parseCapabilities(form) }
|
|
51
|
+
: { consent, allow: false },
|
|
52
|
+
);
|
|
53
|
+
};
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
`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
|
|
59
|
+
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.
|
|
61
|
+
|
|
62
|
+
`issue` may return `null` to refuse a user who lost access since the consent page was shown; the
|
|
63
|
+
browser goes to `consentPage?error=forbidden` and the client gets nothing.
|
|
64
|
+
|
|
65
|
+
Redeeming the code calls `tokens.refresh` with `kind: "code"`, which mints the client's first
|
|
66
|
+
token pair and must refuse a refresh token that was already used. This makes a code single-use
|
|
67
|
+
without authlet storing anything.
|
|
68
|
+
|
|
69
|
+
A sealed consent stays valid for 20 minutes, so a user who submits the consent form twice creates
|
|
70
|
+
two grants for the same client. Both show up in the app's token store.
|
|
71
|
+
|
|
72
|
+
## What the host app must do
|
|
73
|
+
|
|
74
|
+
authlet can't check these, because they happen in the app:
|
|
75
|
+
|
|
76
|
+
1. Make `kind: "code"` single-use atomically. Mark the refresh token used with a compare-and-set
|
|
77
|
+
(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
|
|
79
|
+
family when a used refresh token comes back (RFC 9700 section 4.14).
|
|
80
|
+
2. Treat the consent page as a security boundary:
|
|
81
|
+
- Show the client name as unverified: anyone can register any name.
|
|
82
|
+
- Show the redirect URI's host (`new URL(client.redirectUri).host`), which is where the code
|
|
83
|
+
goes.
|
|
84
|
+
- Send `Content-Security-Policy: frame-ancestors 'none'` and `Referrer-Policy: no-referrer`
|
|
85
|
+
(the URL carries the sealed consent).
|
|
86
|
+
- 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.
|
|
88
|
+
3. On the login page, only follow a `returnTo` that starts with a single `/`. authlet always
|
|
89
|
+
passes a relative path, but the login page must not become an open redirect.
|
|
90
|
+
4. Use a session cookie with `SameSite=Lax` or stricter. `decide` refuses cross-site submissions
|
|
91
|
+
by their `Sec-Fetch-*` headers, or by `Origin` in browsers that don't send those.
|
|
92
|
+
5. Use a random secret of at least 32 bytes, or a generated `CryptoKey`, and keep it out of source
|
|
93
|
+
control. Anyone with it can forge client IDs and consents, and there is no key rotation yet.
|
|
94
|
+
6. Derive a function-valued `resource` or `issuer` from trusted configuration only. Never take it
|
|
95
|
+
from `Host` or `X-Forwarded-*` headers without an allowlist.
|
|
96
|
+
|
|
97
|
+
## Interface
|
|
98
|
+
|
|
99
|
+
```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
|
|
103
|
+
issuer: "https://cms.example.com/api/mcp/oauth", // optional, this is the default
|
|
104
|
+
getUser: async (req) => sessionUser(req), // McpUser | null
|
|
105
|
+
loginUrl: (returnTo) =>
|
|
106
|
+
`/admin/login?redirect=${encodeURIComponent(returnTo)}`,
|
|
107
|
+
consentPage: "/admin/mcp/authorize", // gets ?consent=… or ?error=…
|
|
108
|
+
secret: process.env.AUTHLET_SECRET!, // >= 32 chars, or an AES-GCM CryptoKey
|
|
109
|
+
tokens: {
|
|
110
|
+
issue: async ({ user, client, grant, resource }) => ({ refreshToken }), // or null to refuse
|
|
111
|
+
refresh: async ({ refreshToken, kind, client }) => rotated ?? null, // kind: "code" | "refresh"
|
|
112
|
+
},
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
authlet.handle(req); // Promise<Response | null>: OAuth endpoints, AS and resource metadata
|
|
116
|
+
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
|
|
119
|
+
authlet.decide(req, { consent, allow: false }); // Promise<Response>: redirect with access_denied
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
The full types are in [`src/types.ts`](src/types.ts).
|
|
123
|
+
|
|
124
|
+
## Built
|
|
125
|
+
|
|
126
|
+
- `src/authlet.ts`: `createAuthlet`, routing requests to the endpoints in `src/endpoints/`:
|
|
127
|
+
- `metadata.ts`: authorization server metadata (RFC 8414, with the OpenID discovery fields),
|
|
128
|
+
protected resource metadata (RFC 9728), an empty JWKS.
|
|
129
|
+
- `register.ts`: dynamic client registration (RFC 7591) for public clients, `client_id` sealed.
|
|
130
|
+
- `authorize.ts`: PKCE S256 only, RFC 8707 `resource` checked, login and consent redirects;
|
|
131
|
+
invalid requests go to `consentPage?error=invalid_link`, never to the client.
|
|
132
|
+
- `consent.ts`: `readConsent` and `decide`, with `Sec-Fetch-*` checks and `iss` (RFC 9207).
|
|
133
|
+
- `token.ts`: authorization code and refresh grants, single-use codes via refresh rotation.
|
|
134
|
+
- `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.
|
|
136
|
+
- `src/seal.ts`: the sealer, typed per sealed value (jose JWE, HKDF-derived key, `typ` and `iss`
|
|
137
|
+
checked on unseal, fixed lifetimes: consent 20 min, code 60 s, each plus 5 s clock tolerance).
|
|
138
|
+
- `src/urls.ts`: issuer and resource canonicalisation, endpoint URLs, and matching a request to
|
|
139
|
+
an endpoint, including every discovery location.
|
|
140
|
+
- `src/redirect-uri.ts`: redirect URI validation (https; http only to loopback; app schemes;
|
|
141
|
+
no browser-handled schemes such as `javascript:`, `data:`, `blob:`, `file:`; no fragments) and
|
|
142
|
+
matching, with loopback URIs on any port (RFC 8252 section 7.3).
|
|
143
|
+
- `src/pkce.ts`: S256 verification, tested with the RFC 7636 vector.
|
|
144
|
+
|
|
145
|
+
## Base URLs
|
|
146
|
+
|
|
147
|
+
With `resource: "https://cms.example.com/api/mcp"` the issuer is
|
|
148
|
+
`https://cms.example.com/api/mcp/oauth`, and `handle` answers:
|
|
149
|
+
|
|
150
|
+
| Path | Serves | Root route needed |
|
|
151
|
+
| ------------------------------------------------------- | --------------------------------------------- | ----------------- |
|
|
152
|
+
| `/api/mcp/oauth/authorize`, `/token`, `/register` | the endpoints | no |
|
|
153
|
+
| `/api/mcp/oauth/.well-known/openid-configuration` | AS metadata (OpenID discovery, path appended) | no |
|
|
154
|
+
| `/api/mcp/oauth/.well-known/oauth-protected-resource` | resource metadata, linked from `challenge` | no |
|
|
155
|
+
| `/.well-known/oauth-authorization-server/api/mcp/oauth` | AS metadata (RFC 8414) | yes, optional |
|
|
156
|
+
| `/.well-known/openid-configuration/api/mcp/oauth` | AS metadata (OpenID, path inserted) | yes, optional |
|
|
157
|
+
| `/.well-known/oauth-protected-resource/api/mcp` | resource metadata (RFC 9728 default) | yes, optional |
|
|
158
|
+
|
|
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
|
|
161
|
+
`handle` as well.
|
|
162
|
+
|
|
163
|
+
Clients check that the issuer and resource in the metadata match exactly. authlet therefore
|
|
164
|
+
refuses a value the URL parser would change: a trailing slash, credentials, a query or fragment,
|
|
165
|
+
an uppercase host, a default port or dot segments. Fixed strings are checked at setup, functions
|
|
166
|
+
on each request.
|
|
167
|
+
|
|
168
|
+
`handle` matches requests on their path only, so it works behind a TLS-terminating proxy whose
|
|
169
|
+
request URLs carry an internal scheme or host, as long as the proxy keeps the public path. An
|
|
170
|
+
issuer at a host root claims `/authorize`, `/token` and `/register`, so pass `handle` only that
|
|
171
|
+
host's requests.
|
|
172
|
+
|
|
173
|
+
## Planned
|
|
174
|
+
|
|
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
|
+
- `authlet/node`: a `node:http` / Express bridge.
|
|
179
|
+
- A private example app that runs the flow against MCP Inspector over real HTTP.
|
|
180
|
+
- Scopes (`scopes_supported`, `scope` in the challenge, `insufficient_scope`), key rotation.
|
package/dist/authlet.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { resolve } from "./context.js";
|
|
2
|
+
import { authorize } from "./endpoints/authorize.js";
|
|
3
|
+
import { decide, readConsent } from "./endpoints/consent.js";
|
|
4
|
+
import { authorizationServerMetadata, jwks, resourceMetadata, } from "./endpoints/metadata.js";
|
|
5
|
+
import { register } from "./endpoints/register.js";
|
|
6
|
+
import { token } from "./endpoints/token.js";
|
|
7
|
+
import { methodNotAllowed, preflight, withParams } from "./http.js";
|
|
8
|
+
import { createSealer } from "./seal.js";
|
|
9
|
+
import { deriveUrls, matchEndpoint } from "./urls.js";
|
|
10
|
+
const createAuthlet = (options) => {
|
|
11
|
+
const sealer = createSealer(options.secret);
|
|
12
|
+
const contextFor = (req) => ({
|
|
13
|
+
req,
|
|
14
|
+
sealer,
|
|
15
|
+
options,
|
|
16
|
+
urls: deriveUrls({
|
|
17
|
+
resource: resolve(options.resource, req),
|
|
18
|
+
issuer: options.issuer && resolve(options.issuer, req),
|
|
19
|
+
}),
|
|
20
|
+
});
|
|
21
|
+
// Fixed URLs are checked at setup; functions only when a request resolves them.
|
|
22
|
+
if (typeof options.resource === "string" &&
|
|
23
|
+
typeof options.issuer !== "function") {
|
|
24
|
+
deriveUrls({ resource: options.resource, issuer: options.issuer });
|
|
25
|
+
}
|
|
26
|
+
// A fixed consent page is checked at setup: a relative one must start with a single "/".
|
|
27
|
+
if (typeof options.consentPage === "string") {
|
|
28
|
+
withParams(options.consentPage, {});
|
|
29
|
+
}
|
|
30
|
+
const routes = {
|
|
31
|
+
authorize: { method: "GET", cors: false, run: authorize },
|
|
32
|
+
token: { method: "POST", cors: true, run: token },
|
|
33
|
+
register: { method: "POST", cors: true, run: register },
|
|
34
|
+
jwks: { method: "GET", cors: true, run: jwks },
|
|
35
|
+
authorizationServerMetadata: {
|
|
36
|
+
method: "GET",
|
|
37
|
+
cors: true,
|
|
38
|
+
run: ({ urls }) => authorizationServerMetadata(urls),
|
|
39
|
+
},
|
|
40
|
+
resourceMetadata: {
|
|
41
|
+
method: "GET",
|
|
42
|
+
cors: true,
|
|
43
|
+
run: ({ urls }) => resourceMetadata(urls),
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
return {
|
|
47
|
+
handle: async (req) => {
|
|
48
|
+
const ctx = contextFor(req);
|
|
49
|
+
const endpoint = matchEndpoint(req.url, ctx.urls);
|
|
50
|
+
if (!endpoint) {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
const route = routes[endpoint];
|
|
54
|
+
if (route.cors && req.method === "OPTIONS") {
|
|
55
|
+
return preflight(route.method);
|
|
56
|
+
}
|
|
57
|
+
if (req.method !== route.method) {
|
|
58
|
+
return methodNotAllowed(route.method);
|
|
59
|
+
}
|
|
60
|
+
return await route.run(ctx);
|
|
61
|
+
},
|
|
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
|
+
});
|
|
73
|
+
},
|
|
74
|
+
readConsent: async (req, consent) => await readConsent(contextFor(req), consent),
|
|
75
|
+
decide: async (req, args) => await decide(contextFor(req), args),
|
|
76
|
+
};
|
|
77
|
+
};
|
|
78
|
+
export { createAuthlet };
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { Sealer } from "./seal.js";
|
|
2
|
+
import type { AuthletOptions, AuthletUser, AuthorizeError, Resolvable } from "./types.js";
|
|
3
|
+
import type { AuthletUrls } from "./urls.js";
|
|
4
|
+
/** Everything an endpoint needs for one request. */
|
|
5
|
+
interface Context<TGrant, TUser extends AuthletUser> {
|
|
6
|
+
req: Request;
|
|
7
|
+
urls: AuthletUrls;
|
|
8
|
+
sealer: Sealer;
|
|
9
|
+
options: AuthletOptions<TGrant, TUser>;
|
|
10
|
+
}
|
|
11
|
+
declare const resolve: <T extends string>(value: Resolvable<T>, req: Request) => T;
|
|
12
|
+
/**
|
|
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.
|
|
15
|
+
*/
|
|
16
|
+
declare const getBrowserUser: <TUser extends AuthletUser>({ req, options, }: {
|
|
17
|
+
req: Request;
|
|
18
|
+
options: Pick<AuthletOptions<never, TUser>, "getUser">;
|
|
19
|
+
}) => Promise<TUser | null>;
|
|
20
|
+
/** Sends the browser to the app's consent page, with a sealed consent or an error. */
|
|
21
|
+
declare const toConsentPage: ({ req, options, }: {
|
|
22
|
+
req: Request;
|
|
23
|
+
options: Pick<AuthletOptions, "consentPage">;
|
|
24
|
+
}, params: {
|
|
25
|
+
consent: string;
|
|
26
|
+
} | {
|
|
27
|
+
error: AuthorizeError;
|
|
28
|
+
}, status?: 302 | 303) => Response;
|
|
29
|
+
export { getBrowserUser, resolve, toConsentPage };
|
|
30
|
+
export type { Context };
|
package/dist/context.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { redirect, withParams } from "./http.js";
|
|
2
|
+
const resolve = (value, req) => typeof value === "function" ? value(req) : value;
|
|
3
|
+
/**
|
|
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.
|
|
6
|
+
*/
|
|
7
|
+
const getBrowserUser = async ({ req, options, }) => req.headers.has("Authorization") ? null : await options.getUser(req);
|
|
8
|
+
/** Sends the browser to the app's consent page, with a sealed consent or an error. */
|
|
9
|
+
const toConsentPage = ({ req, options, }, params, status = 302) => redirect(withParams(resolve(options.consentPage, req), params), status);
|
|
10
|
+
export { getBrowserUser, resolve, toConsentPage };
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Context } from "../context.js";
|
|
2
|
+
import type { AuthletUser } from "../types.js";
|
|
3
|
+
/**
|
|
4
|
+
* The authorization endpoint. A valid request from a signed-in browser user goes to the app's
|
|
5
|
+
* consent page with a sealed consent; a signed-out user goes to the login page first.
|
|
6
|
+
*
|
|
7
|
+
* Invalid requests never redirect to the client: anyone can register a client with any
|
|
8
|
+
* redirect URI, so that would turn this endpoint into an open redirector. They go to the
|
|
9
|
+
* consent page with `error=invalid_link` instead.
|
|
10
|
+
*/
|
|
11
|
+
declare const authorize: <TGrant, TUser extends AuthletUser>(ctx: Context<TGrant, TUser>) => Promise<Response>;
|
|
12
|
+
export { authorize };
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { getBrowserUser, toConsentPage } from "../context.js";
|
|
2
|
+
import { redirect } from "../http.js";
|
|
3
|
+
import { isCodeChallenge } from "../pkce.js";
|
|
4
|
+
import { isRegisteredRedirectUri } from "../redirect-uri.js";
|
|
5
|
+
const MAX_STATE_LENGTH = 1024;
|
|
6
|
+
/**
|
|
7
|
+
* The authorization endpoint. A valid request from a signed-in browser user goes to the app's
|
|
8
|
+
* consent page with a sealed consent; a signed-out user goes to the login page first.
|
|
9
|
+
*
|
|
10
|
+
* Invalid requests never redirect to the client: anyone can register a client with any
|
|
11
|
+
* redirect URI, so that would turn this endpoint into an open redirector. They go to the
|
|
12
|
+
* consent page with `error=invalid_link` instead.
|
|
13
|
+
*/
|
|
14
|
+
const authorize = async (ctx) => {
|
|
15
|
+
const { req, urls, sealer, options } = ctx;
|
|
16
|
+
const url = new URL(req.url);
|
|
17
|
+
const params = url.searchParams;
|
|
18
|
+
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
|
+
const codeChallenge = params.get("code_challenge");
|
|
28
|
+
const state = params.get("state");
|
|
29
|
+
// RFC 8707: clients name the resource; absent means the only one there is.
|
|
30
|
+
const resource = params.get("resource") ?? urls.resource;
|
|
31
|
+
if (!clientId ||
|
|
32
|
+
!client ||
|
|
33
|
+
!redirectUri ||
|
|
34
|
+
!isRegisteredRedirectUri(redirectUri, client.redirectUris) ||
|
|
35
|
+
params.get("response_type") !== "code" ||
|
|
36
|
+
params.get("code_challenge_method") !== "S256" ||
|
|
37
|
+
!codeChallenge ||
|
|
38
|
+
!isCodeChallenge(codeChallenge) ||
|
|
39
|
+
resource !== urls.resource ||
|
|
40
|
+
// It travels inside the sealed consent and back to the client, so it stays bounded.
|
|
41
|
+
(state?.length ?? 0) > MAX_STATE_LENGTH) {
|
|
42
|
+
return toConsentPage(ctx, { error: "invalid_link" });
|
|
43
|
+
}
|
|
44
|
+
const user = await getBrowserUser(ctx);
|
|
45
|
+
if (!user) {
|
|
46
|
+
return redirect(options.loginUrl(url.pathname + url.search, req));
|
|
47
|
+
}
|
|
48
|
+
const consent = await sealer.seal({
|
|
49
|
+
issuer: urls.issuer,
|
|
50
|
+
type: "consent",
|
|
51
|
+
data: {
|
|
52
|
+
clientId,
|
|
53
|
+
redirectUri,
|
|
54
|
+
codeChallenge,
|
|
55
|
+
resource,
|
|
56
|
+
userId: user.id,
|
|
57
|
+
...(state === null ? {} : { state }),
|
|
58
|
+
},
|
|
59
|
+
});
|
|
60
|
+
return toConsentPage(ctx, { consent });
|
|
61
|
+
};
|
|
62
|
+
export { authorize };
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { Context } from "../context.js";
|
|
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>;
|
|
5
|
+
export { decide, readConsent };
|