@qauth-labs/resource-guard 0.0.0-stage → 0.1.4-rc.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 +246 -2
- package/dist/fastify.d.ts +9 -0
- package/dist/fastify.js +9 -0
- package/dist/index.d.ts +25 -0
- package/dist/index.js +30 -0
- package/dist/lib/challenge.d.ts +32 -0
- package/dist/lib/challenge.js +72 -0
- package/dist/lib/core.d.ts +75 -0
- package/dist/lib/core.js +217 -0
- package/dist/lib/errors.d.ts +116 -0
- package/dist/lib/errors.js +137 -0
- package/dist/lib/fastify-plugin.d.ts +76 -0
- package/dist/lib/fastify-plugin.js +167 -0
- package/dist/lib/introspection-validator.d.ts +53 -0
- package/dist/lib/introspection-validator.js +120 -0
- package/dist/lib/jwt-validator.d.ts +72 -0
- package/dist/lib/jwt-validator.js +181 -0
- package/dist/lib/metadata.d.ts +59 -0
- package/dist/lib/metadata.js +88 -0
- package/dist/lib/scope.d.ts +38 -0
- package/dist/lib/scope.js +73 -0
- package/dist/types.d.ts +160 -0
- package/dist/types.js +14 -0
- package/package.json +66 -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 2025 QAuth Labs
|
|
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,247 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @qauth-labs/resource-guard
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> Targets the **MCP Authorization** specification, **revision 2026-07-28**, and
|
|
4
|
+
> **RFC 9728** (OAuth 2.0 Protected Resource Metadata).
|
|
5
|
+
|
|
6
|
+
The resource-server (RS) side SDK for protecting an **MCP server** with a
|
|
7
|
+
self-hosted **[QAuth](../../../README.md)** OAuth 2.1 authorization server.
|
|
8
|
+
|
|
9
|
+
Drop it into an MCP server and you get spec-correct OAuth in minutes:
|
|
10
|
+
|
|
11
|
+
- **RFC 9728** Protected Resource Metadata at
|
|
12
|
+
`/.well-known/oauth-protected-resource[/<path>]`
|
|
13
|
+
- **RFC 6750 §3** `401` / `403` `WWW-Authenticate: Bearer` challenges, with the
|
|
14
|
+
`resource_metadata` pointer (and the well-known doc as the fallback per MCP
|
|
15
|
+
2026-07-28)
|
|
16
|
+
- **Scope guidance on the first 401**: the scopes the operation needs are
|
|
17
|
+
advertised on the credential-absent `401` as well as the `403`, so a client
|
|
18
|
+
authorizes in one round instead of fetching PRM and guessing. `offline_access`
|
|
19
|
+
is filtered out of both advertisement surfaces — it concerns refresh-token
|
|
20
|
+
issuance at the AS, not access to this resource
|
|
21
|
+
- Bearer-token validation in two modes — local **JWT** verification against the
|
|
22
|
+
QAuth JWKS, or **RFC 7662** introspection
|
|
23
|
+
- **No token passthrough**: tokens not audience-bound to this resource
|
|
24
|
+
(**RFC 8707**) are rejected, and the inbound token is never forwarded upstream
|
|
25
|
+
- **Step-up** `403 insufficient_scope` scope challenges for incremental consent
|
|
26
|
+
|
|
27
|
+
It ships both a **Fastify 5 plugin** and a **framework-agnostic core**
|
|
28
|
+
(`ResourceGuard`) for non-Fastify hosts.
|
|
29
|
+
|
|
30
|
+
> Targets the MCP Authorization profile **revision 2026-07-28** and QAuth's AS
|
|
31
|
+
> contract (JWKS at `/.well-known/jwks.json`, discovery at
|
|
32
|
+
> `/.well-known/oauth-authorization-server`, introspection at
|
|
33
|
+
> `/oauth/introspect`). See [ADR-007](../../../docs/adr/007-mcp-first-positioning.md).
|
|
34
|
+
|
|
35
|
+
## Install
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pnpm add @qauth-labs/resource-guard
|
|
39
|
+
# The Fastify entry also needs fastify@5 (an optional peer dependency).
|
|
40
|
+
pnpm add fastify
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Two entry points: `@qauth-labs/resource-guard` is the framework-agnostic core
|
|
44
|
+
and never imports Fastify; `@qauth-labs/resource-guard/fastify` is the Fastify 5
|
|
45
|
+
plugin. `jose` comes with the package.
|
|
46
|
+
|
|
47
|
+
## Quick start (Fastify)
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
import Fastify from 'fastify';
|
|
51
|
+
import { resourceGuardPlugin } from '@qauth-labs/resource-guard/fastify';
|
|
52
|
+
|
|
53
|
+
const app = Fastify();
|
|
54
|
+
|
|
55
|
+
await app.register(resourceGuardPlugin, {
|
|
56
|
+
// This resource's canonical URL — the `aud` every accepted token must carry.
|
|
57
|
+
resource: 'https://memory.mcp.example.com',
|
|
58
|
+
// Your QAuth instance (the issuer identifier).
|
|
59
|
+
authorizationServer: 'https://auth.example.com',
|
|
60
|
+
// Default scopes required for any protected route.
|
|
61
|
+
requiredScopes: ['mcp:read'],
|
|
62
|
+
// 'jwt' (default, offline) | 'introspection' (RFC 7662, online).
|
|
63
|
+
validationMode: 'jwt',
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
// Require a valid, audience-bound bearer carrying the default scopes:
|
|
67
|
+
app.get('/mcp/memory', { preHandler: app.requireBearer }, async (req) => {
|
|
68
|
+
return { subject: req.tokenClaims?.sub };
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
// Step-up: this route additionally requires `mcp:write`. A token missing it
|
|
72
|
+
// gets a 403 insufficient_scope challenge advertising the full required set.
|
|
73
|
+
app.put('/mcp/memory/:key', { preHandler: app.requireScopes('mcp:write') }, async (req) => {
|
|
74
|
+
return { ok: true };
|
|
75
|
+
});
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Registering the plugin automatically:
|
|
79
|
+
|
|
80
|
+
1. serves the RFC 9728 metadata document (`GET /.well-known/oauth-protected-resource`,
|
|
81
|
+
plus the nested path for a path-bearing `resource`),
|
|
82
|
+
2. decorates the instance with `resourceGuard`, `requireBearer`, and `requireScopes(...)`,
|
|
83
|
+
3. converts guard failures into the correct Bearer challenge responses.
|
|
84
|
+
|
|
85
|
+
The validated claims are available on `request.tokenClaims`
|
|
86
|
+
(`{ sub, clientId, scopes, audience, issuer, expiresAt, issuedAt, raw }`).
|
|
87
|
+
|
|
88
|
+
### Several resources in one app
|
|
89
|
+
|
|
90
|
+
A Fastify scope carries one guard. Register each further guard, together with the
|
|
91
|
+
routes it protects, in an encapsulated child scope; there the decorators refer to
|
|
92
|
+
that scope's guard. A second registration on the same scope fails at boot with
|
|
93
|
+
`ResourceGuardConfigError`.
|
|
94
|
+
|
|
95
|
+
```ts
|
|
96
|
+
await app.register(async (admin) => {
|
|
97
|
+
await admin.register(resourceGuardPlugin, {
|
|
98
|
+
resource: 'https://mcp.example.com/admin',
|
|
99
|
+
authorizationServer: 'https://auth.example.com',
|
|
100
|
+
requiredScopes: ['mcp:admin'],
|
|
101
|
+
});
|
|
102
|
+
admin.get('/admin', { preHandler: admin.requireBearer }, async () => ({ ok: true }));
|
|
103
|
+
});
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## The handshake (what an MCP client sees)
|
|
107
|
+
|
|
108
|
+
```
|
|
109
|
+
client → GET /mcp/memory (no token)
|
|
110
|
+
server → 401 WWW-Authenticate: Bearer scope="mcp:read",
|
|
111
|
+
resource_metadata="https://…/.well-known/oauth-protected-resource"
|
|
112
|
+
client → GET /.well-known/oauth-protected-resource
|
|
113
|
+
server → 200 { resource, authorization_servers: ["https://auth.example.com"], … }
|
|
114
|
+
client → (discovers AS, runs authorization_code + PKCE against QAuth, gets a
|
|
115
|
+
token with aud=https://memory.mcp.example.com)
|
|
116
|
+
client → GET /mcp/memory Authorization: Bearer <token>
|
|
117
|
+
server → 200 ✅ (resource-guard verified signature, issuer, audience, scopes)
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
## Validation modes
|
|
121
|
+
|
|
122
|
+
### `jwt` (default, recommended)
|
|
123
|
+
|
|
124
|
+
Verifies the bearer locally against the QAuth JWKS using `jose`
|
|
125
|
+
(`createRemoteJWKSet`). Checks the EdDSA signature, `iss`, `exp`, and that
|
|
126
|
+
`aud` contains this resource. No per-request call to the AS. The JWKS is cached
|
|
127
|
+
in-process; control freshness with `jwksCacheTtlMs` (default 5 min) so rotated
|
|
128
|
+
AS keys are picked up automatically.
|
|
129
|
+
|
|
130
|
+
### `introspection` (RFC 7662)
|
|
131
|
+
|
|
132
|
+
Verifies the bearer locally exactly as `jwt` mode does, then calls the QAuth
|
|
133
|
+
introspection endpoint for the authoritative verdict — use for near-real-time
|
|
134
|
+
revocation (or to receive the detached PQC signature QAuth delivers over
|
|
135
|
+
introspection). Only a token that passes the local check is introspected: the
|
|
136
|
+
AS never reports a token it did not sign as active, so a made-up bearer is
|
|
137
|
+
refused here without spending one of the RS's rate-limited introspection
|
|
138
|
+
calls. If the JWKS cannot be fetched, the token is introspected anyway rather
|
|
139
|
+
than refused. For an AS that issues opaque tokens, set
|
|
140
|
+
`introspectionLocalCheck: false`; every bearer is then introspected, so rate-limit
|
|
141
|
+
your own callers. QAuth limits introspection per caller address
|
|
142
|
+
(`INTROSPECT_RATE_LIMIT`, 30 per minute by default), so size it for this RS's
|
|
143
|
+
traffic. Requires confidential client credentials (RFC 7662 mandates client
|
|
144
|
+
authentication):
|
|
145
|
+
|
|
146
|
+
```ts
|
|
147
|
+
await app.register(resourceGuardPlugin, {
|
|
148
|
+
resource: 'https://memory.mcp.example.com',
|
|
149
|
+
authorizationServer: 'https://auth.example.com',
|
|
150
|
+
validationMode: 'introspection',
|
|
151
|
+
introspectionClient: {
|
|
152
|
+
clientId: process.env.INTROSPECT_CLIENT_ID!,
|
|
153
|
+
clientSecret: process.env.INTROSPECT_CLIENT_SECRET!,
|
|
154
|
+
},
|
|
155
|
+
});
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
Even though QAuth only returns `active: true` to an audience-authoritative
|
|
159
|
+
introspection client, `resource-guard` re-checks `aud` locally as defence-in-depth,
|
|
160
|
+
so the no-passthrough guarantee never depends solely on AS-side configuration.
|
|
161
|
+
|
|
162
|
+
## Configuration
|
|
163
|
+
|
|
164
|
+
| Option | Type | Default | Notes |
|
|
165
|
+
| ------------------------- | ---------------------------- | ---------------------------------------------- | ------------------------------------------------------------------- |
|
|
166
|
+
| `resource` | `string` (required) | — | Resource identifier; `aud` tokens must carry (RFC 8707) |
|
|
167
|
+
| `authorizationServer` | `string` (required) | — | QAuth issuer identifier |
|
|
168
|
+
| `requiredScopes` | `string[]` | `[]` | Default scopes for any protected route |
|
|
169
|
+
| `validationMode` | `'jwt' \| 'introspection'` | `'jwt'` | Token-validation strategy |
|
|
170
|
+
| `jwksUri` | `string` | `${authorizationServer}/.well-known/jwks.json` | Both modes: introspection verifies locally first |
|
|
171
|
+
| `jwksCacheTtlMs` | `number` | `300000` | JWKS cache/cooldown |
|
|
172
|
+
| `introspectionEndpoint` | `string` | `${authorizationServer}/oauth/introspect` | Introspection mode |
|
|
173
|
+
| `introspectionClient` | `{ clientId, clientSecret }` | — | **Required** in introspection mode |
|
|
174
|
+
| `introspectionLocalCheck` | `boolean` | `true` | Verify locally before introspecting; `false` only for opaque tokens |
|
|
175
|
+
| `allowedAlgorithms` | `string[]` | `['EdDSA']` | Pinned to defend against alg-confusion |
|
|
176
|
+
| `metadataCacheControl` | `string` | `public, max-age=3600` | `Cache-Control` for the PRM document |
|
|
177
|
+
| `fetch` | `FetchLike` | global `fetch` | Injectable (tests / SSRF-guarded client) |
|
|
178
|
+
|
|
179
|
+
## Framework-agnostic core
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
import { ResourceGuard, ResourceGuardError } from '@qauth-labs/resource-guard';
|
|
183
|
+
|
|
184
|
+
const guard = new ResourceGuard({
|
|
185
|
+
resource: 'https://memory.mcp.example.com',
|
|
186
|
+
authorizationServer: 'https://auth.example.com',
|
|
187
|
+
requiredScopes: ['mcp:read'],
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
try {
|
|
191
|
+
const claims = await guard.authenticate(req.headers.authorization, ['mcp:write']);
|
|
192
|
+
// claims.sub, claims.scopes, claims.audience, …
|
|
193
|
+
} catch (err) {
|
|
194
|
+
if (err instanceof ResourceGuardError) {
|
|
195
|
+
res.statusCode = err.statusCode; // 401 | 403
|
|
196
|
+
res.setHeader('WWW-Authenticate', guard.challengeHeader(err));
|
|
197
|
+
res.end();
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
- `guard.getProtectedResourceMetadata()` — the RFC 9728 document to serve.
|
|
203
|
+
- `guard.getMetadataPath()` / `getMetadataUrl()` — well-known path / absolute URL.
|
|
204
|
+
- `guard.assertScopes(claims, ['mcp:write'])` — mid-handler step-up check.
|
|
205
|
+
|
|
206
|
+
## Security model
|
|
207
|
+
|
|
208
|
+
- **Audience binding (RFC 8707).** Both validators reject any token whose `aud`
|
|
209
|
+
does not include `resource`. This is the no-passthrough control: a token
|
|
210
|
+
minted for another resource cannot be replayed here.
|
|
211
|
+
- **No upstream forwarding.** The core only validates and returns _claims_; it
|
|
212
|
+
never returns the raw token to a call site or forwards it to upstream APIs.
|
|
213
|
+
- **Algorithm pinning.** JWT mode accepts `EdDSA` only by default, closing
|
|
214
|
+
algorithm-confusion attacks.
|
|
215
|
+
- **Exact scope matching.** Scopes are compared exactly and case-sensitively
|
|
216
|
+
(RFC 6749 §3.3) — no prefix or wildcard semantics. QAuth's scope vocabulary
|
|
217
|
+
declares no scope hierarchy (no scope implies another), so the MCP 2026-07-28
|
|
218
|
+
requirement that servers account for hierarchies is satisfied by construction.
|
|
219
|
+
A host whose own vocabulary _is_ hierarchical must list the implied scopes
|
|
220
|
+
itself in `requiredScopes` / `requireScopes(...)`.
|
|
221
|
+
- **Fail closed.** Transport errors, non-2xx introspection responses, malformed
|
|
222
|
+
tokens, and unknown signing keys all fail validation. Error reasons are short
|
|
223
|
+
and non-sensitive; **the token is never echoed** in a challenge or a log.
|
|
224
|
+
|
|
225
|
+
## Runnable example
|
|
226
|
+
|
|
227
|
+
A minimal MCP-style memory server is in [`examples/memory-mcp/server.ts`](./examples/memory-mcp/server.ts).
|
|
228
|
+
It is the RS half of the Claude Code → QAuth → MCP quickstart:
|
|
229
|
+
|
|
230
|
+
```bash
|
|
231
|
+
QAUTH_ISSUER=http://localhost:3000 \
|
|
232
|
+
MCP_RESOURCE=http://localhost:8088 \
|
|
233
|
+
npx tsx examples/memory-mcp/server.ts
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
## Standards
|
|
237
|
+
|
|
238
|
+
RFC 9728 (Protected Resource Metadata) · RFC 8707 (Resource Indicators) ·
|
|
239
|
+
RFC 7662 (Token Introspection) · RFC 6750 §3 (Bearer challenges) ·
|
|
240
|
+
RFC 8414 (AS Metadata) · MCP Authorization 2026-07-28.
|
|
241
|
+
|
|
242
|
+
## Testing
|
|
243
|
+
|
|
244
|
+
```bash
|
|
245
|
+
pnpm nx test resource-guard
|
|
246
|
+
pnpm nx build resource-guard
|
|
247
|
+
```
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@qauth-labs/resource-guard/fastify` — the Fastify 5 adapter.
|
|
3
|
+
*
|
|
4
|
+
* {@link resourceGuardPlugin} (also the default export) serves RFC 9728
|
|
5
|
+
* metadata and decorates the instance with `resourceGuard`, `requireBearer`
|
|
6
|
+
* and `requireScopes`. It needs `fastify` (an optional peer dependency of the
|
|
7
|
+
* package); the root entry `@qauth-labs/resource-guard` does not.
|
|
8
|
+
*/
|
|
9
|
+
export { default, resourceGuardPlugin, type ResourceGuardPluginOptions, sendBearerChallenge, } from './lib/fastify-plugin.js';
|
package/dist/fastify.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@qauth-labs/resource-guard/fastify` — the Fastify 5 adapter.
|
|
3
|
+
*
|
|
4
|
+
* {@link resourceGuardPlugin} (also the default export) serves RFC 9728
|
|
5
|
+
* metadata and decorates the instance with `resourceGuard`, `requireBearer`
|
|
6
|
+
* and `requireScopes`. It needs `fastify` (an optional peer dependency of the
|
|
7
|
+
* package); the root entry `@qauth-labs/resource-guard` does not.
|
|
8
|
+
*/
|
|
9
|
+
export { default, resourceGuardPlugin, sendBearerChallenge, } from './lib/fastify-plugin.js';
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@qauth-labs/resource-guard` — the resource-server-side SDK for wiring an
|
|
3
|
+
* MCP server (or any OAuth 2.1 resource server) to a self-hosted QAuth
|
|
4
|
+
* authorization server.
|
|
5
|
+
*
|
|
6
|
+
* Two entry points:
|
|
7
|
+
*
|
|
8
|
+
* - this one, the framework-agnostic core: {@link ResourceGuard}, the
|
|
9
|
+
* validators, the RFC 9728 metadata and RFC 6750 challenge helpers. It never
|
|
10
|
+
* imports Fastify.
|
|
11
|
+
* - `@qauth-labs/resource-guard/fastify` — the Fastify 5 plugin, which serves
|
|
12
|
+
* RFC 9728 metadata and decorates the instance with `requireBearer` /
|
|
13
|
+
* `requireScopes` preHandlers. `fastify` is an optional peer dependency,
|
|
14
|
+
* needed only for that entry.
|
|
15
|
+
*
|
|
16
|
+
* See the package README and `examples/memory-mcp` for usage.
|
|
17
|
+
*/
|
|
18
|
+
export { extractBearerToken, ResourceGuard } from './lib/core.js';
|
|
19
|
+
export { type BearerErrorCode, InsufficientScopeError, IntrospectionError, InvalidTokenError, MissingTokenError, ResourceGuardConfigError, ResourceGuardError, } from './lib/errors.js';
|
|
20
|
+
export { buildProtectedResourceMetadata, metadataPathForResource, metadataUrlForResource, PRM_WELL_KNOWN_PREFIX, type ProtectedResourceMetadata, } from './lib/metadata.js';
|
|
21
|
+
export { buildWwwAuthenticate, type ChallengeParams } from './lib/challenge.js';
|
|
22
|
+
export { hasRequiredScopes, missingScopes, parseScopes } from './lib/scope.js';
|
|
23
|
+
export { IntrospectionValidator, type IntrospectionValidatorOptions, } from './lib/introspection-validator.js';
|
|
24
|
+
export { JwtValidator, type JwtValidatorOptions } from './lib/jwt-validator.js';
|
|
25
|
+
export type { FetchLike, IntrospectionClientCredentials, ResourceGuardConfig, ValidatedToken, ValidationMode, } from './types.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@qauth-labs/resource-guard` — the resource-server-side SDK for wiring an
|
|
3
|
+
* MCP server (or any OAuth 2.1 resource server) to a self-hosted QAuth
|
|
4
|
+
* authorization server.
|
|
5
|
+
*
|
|
6
|
+
* Two entry points:
|
|
7
|
+
*
|
|
8
|
+
* - this one, the framework-agnostic core: {@link ResourceGuard}, the
|
|
9
|
+
* validators, the RFC 9728 metadata and RFC 6750 challenge helpers. It never
|
|
10
|
+
* imports Fastify.
|
|
11
|
+
* - `@qauth-labs/resource-guard/fastify` — the Fastify 5 plugin, which serves
|
|
12
|
+
* RFC 9728 metadata and decorates the instance with `requireBearer` /
|
|
13
|
+
* `requireScopes` preHandlers. `fastify` is an optional peer dependency,
|
|
14
|
+
* needed only for that entry.
|
|
15
|
+
*
|
|
16
|
+
* See the package README and `examples/memory-mcp` for usage.
|
|
17
|
+
*/
|
|
18
|
+
// Framework-agnostic core.
|
|
19
|
+
export { extractBearerToken, ResourceGuard } from './lib/core.js';
|
|
20
|
+
// Errors (for `instanceof` checks and custom error handling).
|
|
21
|
+
export { InsufficientScopeError, IntrospectionError, InvalidTokenError, MissingTokenError, ResourceGuardConfigError, ResourceGuardError, } from './lib/errors.js';
|
|
22
|
+
// RFC 9728 metadata helpers.
|
|
23
|
+
export { buildProtectedResourceMetadata, metadataPathForResource, metadataUrlForResource, PRM_WELL_KNOWN_PREFIX, } from './lib/metadata.js';
|
|
24
|
+
// Challenge construction (RFC 6750 §3.1).
|
|
25
|
+
export { buildWwwAuthenticate } from './lib/challenge.js';
|
|
26
|
+
// Scope helpers.
|
|
27
|
+
export { hasRequiredScopes, missingScopes, parseScopes } from './lib/scope.js';
|
|
28
|
+
// Validators (advanced / custom wiring).
|
|
29
|
+
export { IntrospectionValidator, } from './lib/introspection-validator.js';
|
|
30
|
+
export { JwtValidator } from './lib/jwt-validator.js';
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `WWW-Authenticate: Bearer` challenge construction.
|
|
3
|
+
*
|
|
4
|
+
* RFC 6750 §3 defines the challenge sent with a 401/403 to a Bearer-protected
|
|
5
|
+
* resource. RFC 9728 §5.1 adds the `resource_metadata` parameter so the client
|
|
6
|
+
* can discover the AS. Under MCP 2026-07-28 this header is OPTIONAL when the
|
|
7
|
+
* resource exposes the `.well-known` PRM document, but emitting it is the
|
|
8
|
+
* fastest path for a client and is recommended — `resource-guard` always emits it.
|
|
9
|
+
*/
|
|
10
|
+
import type { ResourceGuardError } from './errors.js';
|
|
11
|
+
export interface ChallengeParams {
|
|
12
|
+
/** Absolute URL of the RFC 9728 PRM document (`resource_metadata`). */
|
|
13
|
+
resourceMetadataUrl: string;
|
|
14
|
+
/** RFC 6750 `error` code; omit for a credential-absent challenge. */
|
|
15
|
+
error?: string;
|
|
16
|
+
/** Human-readable `error_description` (never include the token). */
|
|
17
|
+
errorDescription?: string;
|
|
18
|
+
/** Space-separated scopes that would satisfy the request (`scope`). */
|
|
19
|
+
scope?: string[];
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Build the `WWW-Authenticate` header value. Parameter order follows common
|
|
23
|
+
* practice (`error` first, then descriptors); RFC 6750 does not mandate order.
|
|
24
|
+
*/
|
|
25
|
+
export declare function buildWwwAuthenticate(params: ChallengeParams): string;
|
|
26
|
+
/**
|
|
27
|
+
* Derive the `WWW-Authenticate` value for a guard error. Centralises the
|
|
28
|
+
* RFC 6750 §3.1 mapping so the Fastify layer and any other adapter stay
|
|
29
|
+
* consistent. `InsufficientScopeError` and `MissingTokenError` both contribute
|
|
30
|
+
* the `scope` challenge (see below).
|
|
31
|
+
*/
|
|
32
|
+
export declare function challengeForError(error: ResourceGuardError, resourceMetadataUrl: string): string;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `WWW-Authenticate: Bearer` challenge construction.
|
|
3
|
+
*
|
|
4
|
+
* RFC 6750 §3 defines the challenge sent with a 401/403 to a Bearer-protected
|
|
5
|
+
* resource. RFC 9728 §5.1 adds the `resource_metadata` parameter so the client
|
|
6
|
+
* can discover the AS. Under MCP 2026-07-28 this header is OPTIONAL when the
|
|
7
|
+
* resource exposes the `.well-known` PRM document, but emitting it is the
|
|
8
|
+
* fastest path for a client and is recommended — `resource-guard` always emits it.
|
|
9
|
+
*/
|
|
10
|
+
import { advertisableScopes } from './scope.js';
|
|
11
|
+
/**
|
|
12
|
+
* Escape a value for an HTTP `auth-param` quoted-string (RFC 7235 / RFC 9110).
|
|
13
|
+
* Only `"` and `\` are special inside a quoted-string; the values we emit
|
|
14
|
+
* (URLs, fixed error codes, scope tokens) contain neither in practice, but we
|
|
15
|
+
* escape defensively to keep the header well-formed and uninjectable.
|
|
16
|
+
*/
|
|
17
|
+
function quote(value) {
|
|
18
|
+
return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Build the `WWW-Authenticate` header value. Parameter order follows common
|
|
22
|
+
* practice (`error` first, then descriptors); RFC 6750 does not mandate order.
|
|
23
|
+
*/
|
|
24
|
+
export function buildWwwAuthenticate(params) {
|
|
25
|
+
const parts = [];
|
|
26
|
+
if (params.error) {
|
|
27
|
+
parts.push(`error=${quote(params.error)}`);
|
|
28
|
+
}
|
|
29
|
+
if (params.errorDescription) {
|
|
30
|
+
parts.push(`error_description=${quote(params.errorDescription)}`);
|
|
31
|
+
}
|
|
32
|
+
if (params.scope && params.scope.length > 0) {
|
|
33
|
+
parts.push(`scope=${quote(params.scope.join(' '))}`);
|
|
34
|
+
}
|
|
35
|
+
parts.push(`resource_metadata=${quote(params.resourceMetadataUrl)}`);
|
|
36
|
+
return `Bearer ${parts.join(', ')}`;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Derive the `WWW-Authenticate` value for a guard error. Centralises the
|
|
40
|
+
* RFC 6750 §3.1 mapping so the Fastify layer and any other adapter stay
|
|
41
|
+
* consistent. `InsufficientScopeError` and `MissingTokenError` both contribute
|
|
42
|
+
* the `scope` challenge (see below).
|
|
43
|
+
*/
|
|
44
|
+
export function challengeForError(error, resourceMetadataUrl) {
|
|
45
|
+
const params = { resourceMetadataUrl };
|
|
46
|
+
if (error.bearerError) {
|
|
47
|
+
params.error = error.bearerError;
|
|
48
|
+
}
|
|
49
|
+
// Only attach a description for token errors; a bare 401 (missing token)
|
|
50
|
+
// carries no `error`, and we avoid leaking validator internals beyond the
|
|
51
|
+
// short, non-sensitive reason already on the error.
|
|
52
|
+
if (error.bearerError === 'invalid_token' && 'reason' in error) {
|
|
53
|
+
params.errorDescription = error.reason;
|
|
54
|
+
}
|
|
55
|
+
// `scope` is advertised on the 403 step-up challenge and — since #284 — on
|
|
56
|
+
// the credential-absent 401 as well: MCP Authorization 2026-07-28 ("Scope
|
|
57
|
+
// Selection Strategy") says the RS SHOULD tell an unauthenticated client
|
|
58
|
+
// what the operation needs, so it can authorize in one round instead of
|
|
59
|
+
// fetching PRM and guessing. The 401 still carries NO `error` parameter:
|
|
60
|
+
// RFC 6750 §3.1 omits it when no credentials were presented, and only
|
|
61
|
+
// `scope` is added.
|
|
62
|
+
//
|
|
63
|
+
// `invalid_token` is deliberately excluded — the client already holds a
|
|
64
|
+
// token, so the remedy is re-authentication, not a wider scope set, and
|
|
65
|
+
// repeating the requirement there would invite pointless re-consent loops.
|
|
66
|
+
if (error.bearerError !== 'invalid_token' && 'requiredScopes' in error) {
|
|
67
|
+
// `buildWwwAuthenticate` omits an empty `scope`, so a route with no
|
|
68
|
+
// configured scopes yields a bare challenge rather than `scope=""`.
|
|
69
|
+
params.scope = advertisableScopes(error.requiredScopes);
|
|
70
|
+
}
|
|
71
|
+
return buildWwwAuthenticate(params);
|
|
72
|
+
}
|