@lushly-dev/afd-server 2.2.1 → 2.4.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/README.md +468 -6
- package/dist/approval-crypto.d.ts +26 -4
- package/dist/approval-crypto.d.ts.map +1 -1
- package/dist/approval-crypto.js +90 -7
- package/dist/approval-crypto.js.map +1 -1
- package/dist/approval-relay.d.ts +5 -5
- package/dist/approval-relay.d.ts.map +1 -1
- package/dist/approval.d.ts +6 -1
- package/dist/approval.d.ts.map +1 -1
- package/dist/approval.js +43 -32
- package/dist/approval.js.map +1 -1
- package/dist/bootstrap/afd-context.d.ts +2 -27
- package/dist/bootstrap/afd-context.d.ts.map +1 -1
- package/dist/bootstrap/afd-context.js +6 -36
- package/dist/bootstrap/afd-context.js.map +1 -1
- package/dist/bootstrap/afd-help.d.ts +24 -2
- package/dist/bootstrap/afd-help.d.ts.map +1 -1
- package/dist/bootstrap/afd-help.js +17 -2
- package/dist/bootstrap/afd-help.js.map +1 -1
- package/dist/bootstrap/described-command.d.ts +1 -0
- package/dist/bootstrap/described-command.d.ts.map +1 -1
- package/dist/bootstrap/described-command.js.map +1 -1
- package/dist/bootstrap/registry.d.ts +13 -0
- package/dist/bootstrap/registry.d.ts.map +1 -1
- package/dist/bootstrap/registry.js +30 -1
- package/dist/bootstrap/registry.js.map +1 -1
- package/dist/command-allow.d.ts +31 -0
- package/dist/command-allow.d.ts.map +1 -0
- package/dist/command-allow.js +55 -0
- package/dist/command-allow.js.map +1 -0
- package/dist/command-names.d.ts +17 -0
- package/dist/command-names.d.ts.map +1 -1
- package/dist/command-names.js +55 -0
- package/dist/command-names.js.map +1 -1
- package/dist/command-routing.d.ts +10 -3
- package/dist/command-routing.d.ts.map +1 -1
- package/dist/command-routing.js +18 -7
- package/dist/command-routing.js.map +1 -1
- package/dist/confirmation-gate.d.ts +32 -0
- package/dist/confirmation-gate.d.ts.map +1 -0
- package/dist/confirmation-gate.js +140 -0
- package/dist/confirmation-gate.js.map +1 -0
- package/dist/confirmations.d.ts +15 -23
- package/dist/confirmations.d.ts.map +1 -1
- package/dist/confirmations.js +8 -127
- package/dist/confirmations.js.map +1 -1
- package/dist/context-fields-describe.d.ts +18 -0
- package/dist/context-fields-describe.d.ts.map +1 -0
- package/dist/context-fields-describe.js +17 -0
- package/dist/context-fields-describe.js.map +1 -0
- package/dist/context-fields.d.ts +50 -0
- package/dist/context-fields.d.ts.map +1 -0
- package/dist/context-fields.js +146 -0
- package/dist/context-fields.js.map +1 -0
- package/dist/context-scope.d.ts +29 -2
- package/dist/context-scope.d.ts.map +1 -1
- package/dist/context-scope.js +37 -1
- package/dist/context-scope.js.map +1 -1
- package/dist/credentials.d.ts +17 -0
- package/dist/credentials.d.ts.map +1 -0
- package/dist/credentials.js +16 -0
- package/dist/credentials.js.map +1 -0
- package/dist/define-core.d.ts +213 -0
- package/dist/define-core.d.ts.map +1 -0
- package/dist/define-core.js +161 -0
- package/dist/define-core.js.map +1 -0
- package/dist/define.d.ts +13 -8
- package/dist/define.d.ts.map +1 -1
- package/dist/define.js +13 -8
- package/dist/define.js.map +1 -1
- package/dist/direct-registry.d.ts +154 -7
- package/dist/direct-registry.d.ts.map +1 -1
- package/dist/direct-registry.js +111 -13
- package/dist/direct-registry.js.map +1 -1
- package/dist/direct-tool-surface.d.ts +66 -0
- package/dist/direct-tool-surface.d.ts.map +1 -0
- package/dist/direct-tool-surface.js +162 -0
- package/dist/direct-tool-surface.js.map +1 -0
- package/dist/direct.d.ts +68 -0
- package/dist/direct.d.ts.map +1 -0
- package/dist/direct.js +66 -0
- package/dist/direct.js.map +1 -0
- package/dist/execution.d.ts +11 -1
- package/dist/execution.d.ts.map +1 -1
- package/dist/execution.js +18 -4
- package/dist/execution.js.map +1 -1
- package/dist/frontmatter.d.ts +16 -0
- package/dist/frontmatter.d.ts.map +1 -0
- package/dist/frontmatter.js +111 -0
- package/dist/frontmatter.js.map +1 -0
- package/dist/http-handler.d.ts +11 -2
- package/dist/http-handler.d.ts.map +1 -1
- package/dist/http-handler.js +46 -15
- package/dist/http-handler.js.map +1 -1
- package/dist/http-security.d.ts.map +1 -1
- package/dist/http-security.js.map +1 -1
- package/dist/http-sessions.d.ts +12 -4
- package/dist/http-sessions.d.ts.map +1 -1
- package/dist/http-sessions.js +4 -4
- package/dist/http-sessions.js.map +1 -1
- package/dist/http-sse.js.map +1 -1
- package/dist/index.d.ts +16 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +20 -4
- package/dist/index.js.map +1 -1
- package/dist/issue-message.d.ts +20 -0
- package/dist/issue-message.d.ts.map +1 -0
- package/dist/issue-message.js +55 -0
- package/dist/issue-message.js.map +1 -0
- package/dist/journal-replay.d.ts +7 -0
- package/dist/journal-replay.d.ts.map +1 -1
- package/dist/journal-replay.js +18 -1
- package/dist/journal-replay.js.map +1 -1
- package/dist/journal.d.ts +9 -1
- package/dist/journal.d.ts.map +1 -1
- package/dist/journal.js +44 -1
- package/dist/journal.js.map +1 -1
- package/dist/json-rpc.d.ts +2 -2
- package/dist/json-rpc.d.ts.map +1 -1
- package/dist/json-rpc.js.map +1 -1
- package/dist/json-schema.d.ts +30 -0
- package/dist/json-schema.d.ts.map +1 -0
- package/dist/json-schema.js +25 -0
- package/dist/json-schema.js.map +1 -0
- package/dist/lazy-tools.d.ts +3 -0
- package/dist/lazy-tools.d.ts.map +1 -1
- package/dist/lazy-tools.js +2 -0
- package/dist/lazy-tools.js.map +1 -1
- package/dist/mcp-auth-bearer.d.ts +23 -0
- package/dist/mcp-auth-bearer.d.ts.map +1 -0
- package/dist/mcp-auth-bearer.js +50 -0
- package/dist/mcp-auth-bearer.js.map +1 -0
- package/dist/mcp-auth-jwt.d.ts +178 -0
- package/dist/mcp-auth-jwt.d.ts.map +1 -0
- package/dist/mcp-auth-jwt.js +365 -0
- package/dist/mcp-auth-jwt.js.map +1 -0
- package/dist/mcp-auth-resource.d.ts +74 -0
- package/dist/mcp-auth-resource.d.ts.map +1 -0
- package/dist/mcp-auth-resource.js +196 -0
- package/dist/mcp-auth-resource.js.map +1 -0
- package/dist/mcp-auth-rules.d.ts +135 -0
- package/dist/mcp-auth-rules.d.ts.map +1 -0
- package/dist/mcp-auth-rules.js +306 -0
- package/dist/mcp-auth-rules.js.map +1 -0
- package/dist/mcp-auth.d.ts +81 -0
- package/dist/mcp-auth.d.ts.map +1 -0
- package/dist/mcp-auth.js +256 -0
- package/dist/mcp-auth.js.map +1 -0
- package/dist/mcp-modern.d.ts +29 -5
- package/dist/mcp-modern.d.ts.map +1 -1
- package/dist/mcp-modern.js +99 -19
- package/dist/mcp-modern.js.map +1 -1
- package/dist/meta-argument.d.ts +42 -0
- package/dist/meta-argument.d.ts.map +1 -0
- package/dist/meta-argument.js +102 -0
- package/dist/meta-argument.js.map +1 -0
- package/dist/meta-keys.d.ts +29 -0
- package/dist/meta-keys.d.ts.map +1 -0
- package/dist/meta-keys.js +90 -0
- package/dist/meta-keys.js.map +1 -0
- package/dist/meta-tools.d.ts +8 -1
- package/dist/meta-tools.d.ts.map +1 -1
- package/dist/meta-tools.js +17 -7
- package/dist/meta-tools.js.map +1 -1
- package/dist/middleware.d.ts.map +1 -1
- package/dist/middleware.js +0 -1
- package/dist/middleware.js.map +1 -1
- package/dist/patterns.d.ts +46 -0
- package/dist/patterns.d.ts.map +1 -0
- package/dist/patterns.js +38 -0
- package/dist/patterns.js.map +1 -0
- package/dist/principal-binding.d.ts +42 -0
- package/dist/principal-binding.d.ts.map +1 -0
- package/dist/principal-binding.js +70 -0
- package/dist/principal-binding.js.map +1 -0
- package/dist/request-context.d.ts +7 -1
- package/dist/request-context.d.ts.map +1 -1
- package/dist/request-context.js +14 -3
- package/dist/request-context.js.map +1 -1
- package/dist/resources.d.ts +122 -0
- package/dist/resources.d.ts.map +1 -0
- package/dist/resources.js +256 -0
- package/dist/resources.js.map +1 -0
- package/dist/schema.d.ts +7 -171
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +10 -135
- package/dist/schema.js.map +1 -1
- package/dist/server-types.d.ts +94 -7
- package/dist/server-types.d.ts.map +1 -1
- package/dist/server-types.js +2 -0
- package/dist/server-types.js.map +1 -1
- package/dist/server.d.ts +2 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +45 -31
- package/dist/server.js.map +1 -1
- package/dist/skills.d.ts +95 -0
- package/dist/skills.d.ts.map +1 -0
- package/dist/skills.js +340 -0
- package/dist/skills.js.map +1 -0
- package/dist/strict-json.d.ts +17 -0
- package/dist/strict-json.d.ts.map +1 -0
- package/dist/strict-json.js +93 -0
- package/dist/strict-json.js.map +1 -0
- package/dist/tool-router.d.ts +13 -1
- package/dist/tool-router.d.ts.map +1 -1
- package/dist/tool-router.js +44 -10
- package/dist/tool-router.js.map +1 -1
- package/dist/tools.d.ts +10 -5
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +48 -22
- package/dist/tools.js.map +1 -1
- package/dist/validation.d.ts +6 -45
- package/dist/validation.d.ts.map +1 -1
- package/dist/validation.js +25 -58
- package/dist/validation.js.map +1 -1
- package/dist/verified-credentials.d.ts +34 -0
- package/dist/verified-credentials.d.ts.map +1 -0
- package/dist/verified-credentials.js +51 -0
- package/dist/verified-credentials.js.map +1 -0
- package/package.json +18 -6
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Token rules that need no key and no network (`spec/authorization.md`, M3 rules 2,
|
|
3
|
+
* 3 and 5 to 10, M3.2 and M4), shared by AFD's JWT verifier and a host's introspection verifier.
|
|
4
|
+
* Each rule is checked here explicitly, in the specification's order: no library default is
|
|
5
|
+
* relied on.
|
|
6
|
+
*/
|
|
7
|
+
import { assertHttpsUrl, audienceAccepts, isScopeToken } from './mcp-auth-resource.js';
|
|
8
|
+
/** Every rule code, in the specification's order. */
|
|
9
|
+
export const AUTH_RULE_CODES = Object.freeze([
|
|
10
|
+
'no-token',
|
|
11
|
+
'token-location',
|
|
12
|
+
'token-malformed',
|
|
13
|
+
'unknown-issuer',
|
|
14
|
+
'typ',
|
|
15
|
+
'alg',
|
|
16
|
+
'kid',
|
|
17
|
+
'crit',
|
|
18
|
+
'key-reference',
|
|
19
|
+
'key',
|
|
20
|
+
'signature',
|
|
21
|
+
'issuer',
|
|
22
|
+
'audience',
|
|
23
|
+
'claims',
|
|
24
|
+
'expired',
|
|
25
|
+
'not-yet-valid',
|
|
26
|
+
'lifetime',
|
|
27
|
+
'scope-malformed',
|
|
28
|
+
'scopes-too-many',
|
|
29
|
+
'dpop-unsupported',
|
|
30
|
+
'binding',
|
|
31
|
+
'inactive',
|
|
32
|
+
'unavailable',
|
|
33
|
+
]);
|
|
34
|
+
/** The largest clock skew a verifier may allow, in seconds. */
|
|
35
|
+
export const MAX_CLOCK_SKEW_S = 300;
|
|
36
|
+
/** The default clock skew, in seconds. */
|
|
37
|
+
export const DEFAULT_CLOCK_SKEW_S = 60;
|
|
38
|
+
/** The default longest token lifetime (`exp - iat`), in seconds. */
|
|
39
|
+
export const DEFAULT_MAX_TOKEN_LIFETIME_S = 3600;
|
|
40
|
+
/** The default scope limit. */
|
|
41
|
+
export const DEFAULT_SCOPE_LIMIT = 64;
|
|
42
|
+
/** The most Unicode code points a `jti`, `sub`, `client_id` or `acr` may hold. */
|
|
43
|
+
export const MAX_CLAIM_CHARS = 255;
|
|
44
|
+
function wholeNumber(what, value, min, max = Number.MAX_SAFE_INTEGER) {
|
|
45
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < min || value > max) {
|
|
46
|
+
throw new Error(`[AFD] ${what} must be a whole number from ${min} to ${max}`);
|
|
47
|
+
}
|
|
48
|
+
return value;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The claim rules for tokens whose audience is `options.resource`.
|
|
52
|
+
*
|
|
53
|
+
* @throws Error when the resource is not an absolute `https` URL without user information, query
|
|
54
|
+
* or fragment, the skew is over 300 seconds, the lifetime or limit is under 1, or the prefix
|
|
55
|
+
* is not a scope token
|
|
56
|
+
*/
|
|
57
|
+
export function createTokenRules(options) {
|
|
58
|
+
assertHttpsUrl('resource', options.resource);
|
|
59
|
+
const prefix = options.scopePrefix;
|
|
60
|
+
if (prefix !== undefined && !isScopeToken(prefix)) {
|
|
61
|
+
throw new Error(`[AFD] scope prefix ${JSON.stringify(prefix)} is not an OAuth scope token`);
|
|
62
|
+
}
|
|
63
|
+
return Object.freeze({
|
|
64
|
+
resource: options.resource,
|
|
65
|
+
clockSkewS: wholeNumber('clockSkewS', options.clockSkewS ?? DEFAULT_CLOCK_SKEW_S, 0, MAX_CLOCK_SKEW_S),
|
|
66
|
+
maxTokenLifetimeS: wholeNumber('maxTokenLifetimeS', options.maxTokenLifetimeS ?? DEFAULT_MAX_TOKEN_LIFETIME_S, 1),
|
|
67
|
+
scopePrefix: prefix,
|
|
68
|
+
scopeLimit: wholeNumber('scopeLimit', options.scopeLimit ?? DEFAULT_SCOPE_LIMIT, 1),
|
|
69
|
+
requireBoundTokens: options.requireBoundTokens === true,
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
const pass = (value) => ({ ok: true, value });
|
|
73
|
+
const refuse = (rule) => ({ ok: false, rule });
|
|
74
|
+
function isRecord(value) {
|
|
75
|
+
return !!value && typeof value === 'object' && !Array.isArray(value);
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* A `scope` claim parsed (`spec/authorization.md`, M3.2; `undefined` when absent): scope tokens
|
|
79
|
+
* separated by single spaces, each kept once at its first place. An empty string or no claim
|
|
80
|
+
* grants no scope. Only scopes starting with `<prefix>:` count against `limit` when a prefix is
|
|
81
|
+
* given. Refused with `scope-malformed` or `scopes-too-many`.
|
|
82
|
+
*/
|
|
83
|
+
export function parseScopeClaim(scope, prefix, limit) {
|
|
84
|
+
if (scope === undefined)
|
|
85
|
+
return pass([]);
|
|
86
|
+
if (typeof scope !== 'string')
|
|
87
|
+
return refuse('scope-malformed');
|
|
88
|
+
if (scope === '')
|
|
89
|
+
return pass([]);
|
|
90
|
+
const scopes = [];
|
|
91
|
+
for (const token of scope.split(' ')) {
|
|
92
|
+
if (!isScopeToken(token))
|
|
93
|
+
return refuse('scope-malformed');
|
|
94
|
+
if (!scopes.includes(token))
|
|
95
|
+
scopes.push(token);
|
|
96
|
+
}
|
|
97
|
+
const counted = prefix === undefined
|
|
98
|
+
? scopes.length
|
|
99
|
+
: scopes.filter((held) => held.startsWith(`${prefix}:`)).length;
|
|
100
|
+
return counted > limit ? refuse('scopes-too-many') : pass(scopes);
|
|
101
|
+
}
|
|
102
|
+
/** Every {@link SigningAlgorithm}. */
|
|
103
|
+
export const SIGNING_ALGORITHMS = Object.freeze([
|
|
104
|
+
'RS256',
|
|
105
|
+
'RS384',
|
|
106
|
+
'RS512',
|
|
107
|
+
'PS256',
|
|
108
|
+
'PS384',
|
|
109
|
+
'PS512',
|
|
110
|
+
'ES256',
|
|
111
|
+
'ES384',
|
|
112
|
+
'EdDSA',
|
|
113
|
+
]);
|
|
114
|
+
const TYP = new Set(['at+jwt', 'application/at+jwt']);
|
|
115
|
+
const KEY_REFERENCES = ['jku', 'x5u', 'x5c', 'jwk'];
|
|
116
|
+
/**
|
|
117
|
+
* Rule 2 on a decoded JWS header, against the issuer's algorithm list: `typ`, then `alg`, `kid`,
|
|
118
|
+
* `crit` and the key references, the first broken rule refusing. `none` and every `HS*`
|
|
119
|
+
* algorithm are refused whatever the list says.
|
|
120
|
+
*/
|
|
121
|
+
export function checkJwsHeader(header, algorithms) {
|
|
122
|
+
if (!isRecord(header))
|
|
123
|
+
return refuse('typ');
|
|
124
|
+
const { typ, alg, kid } = header;
|
|
125
|
+
if (typeof typ !== 'string' || !TYP.has(typ.toLowerCase()))
|
|
126
|
+
return refuse('typ');
|
|
127
|
+
if (typeof alg !== 'string' ||
|
|
128
|
+
alg === 'none' ||
|
|
129
|
+
alg.startsWith('HS') ||
|
|
130
|
+
!algorithms.includes(alg)) {
|
|
131
|
+
return refuse('alg');
|
|
132
|
+
}
|
|
133
|
+
if (typeof kid !== 'string' || kid === '')
|
|
134
|
+
return refuse('kid');
|
|
135
|
+
if (Object.hasOwn(header, 'crit'))
|
|
136
|
+
return refuse('crit');
|
|
137
|
+
if (KEY_REFERENCES.some((member) => Object.hasOwn(header, member))) {
|
|
138
|
+
return refuse('key-reference');
|
|
139
|
+
}
|
|
140
|
+
return pass(undefined);
|
|
141
|
+
}
|
|
142
|
+
/** The `kty`, and `crv` when it matters, each algorithm needs (RFC 7518 3.4, RFC 8037 3.1). */
|
|
143
|
+
function keyFits(alg, kty, crv) {
|
|
144
|
+
switch (alg) {
|
|
145
|
+
case 'RS256':
|
|
146
|
+
case 'RS384':
|
|
147
|
+
case 'RS512':
|
|
148
|
+
case 'PS256':
|
|
149
|
+
case 'PS384':
|
|
150
|
+
case 'PS512':
|
|
151
|
+
return kty === 'RSA';
|
|
152
|
+
case 'ES256':
|
|
153
|
+
return kty === 'EC' && crv === 'P-256';
|
|
154
|
+
case 'ES384':
|
|
155
|
+
return kty === 'EC' && crv === 'P-384';
|
|
156
|
+
case 'ES512':
|
|
157
|
+
return kty === 'EC' && crv === 'P-521';
|
|
158
|
+
case 'EdDSA':
|
|
159
|
+
return kty === 'OKP' && (crv === 'Ed25519' || crv === 'Ed448');
|
|
160
|
+
default:
|
|
161
|
+
return false;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Rule 3 on a header that passed rule 2 and the issuer's key with its `kid` (`undefined` for
|
|
166
|
+
* none): the key's `kid` is the header's; its `kty` is the `alg`'s family; its `alg`, when
|
|
167
|
+
* present, is the header's; its `use`, when present, is `sig`; its `key_ops`, when present,
|
|
168
|
+
* contain `verify`. Refused with `key`.
|
|
169
|
+
*/
|
|
170
|
+
export function checkKeyFit(header, key) {
|
|
171
|
+
if (!isRecord(header) || !isRecord(key))
|
|
172
|
+
return refuse('key');
|
|
173
|
+
const { alg, kid } = header;
|
|
174
|
+
if (typeof alg !== 'string' || typeof kid !== 'string' || key.kid !== kid)
|
|
175
|
+
return refuse('key');
|
|
176
|
+
if (!keyFits(alg, key.kty, key.crv))
|
|
177
|
+
return refuse('key');
|
|
178
|
+
if (Object.hasOwn(key, 'alg') && key.alg !== alg)
|
|
179
|
+
return refuse('key');
|
|
180
|
+
if (Object.hasOwn(key, 'use') && key.use !== 'sig')
|
|
181
|
+
return refuse('key');
|
|
182
|
+
if (Object.hasOwn(key, 'key_ops')) {
|
|
183
|
+
const ops = key.key_ops;
|
|
184
|
+
if (!Array.isArray(ops) || !ops.includes('verify'))
|
|
185
|
+
return refuse('key');
|
|
186
|
+
}
|
|
187
|
+
return pass(undefined);
|
|
188
|
+
}
|
|
189
|
+
const CONTROL = /\p{Cc}/u;
|
|
190
|
+
/** A string claim of rule 7: non-empty, at most 255 code points, no control character. */
|
|
191
|
+
function claimText(value) {
|
|
192
|
+
return (typeof value === 'string' &&
|
|
193
|
+
value !== '' &&
|
|
194
|
+
[...value].length <= MAX_CLAIM_CHARS &&
|
|
195
|
+
!CONTROL.test(value));
|
|
196
|
+
}
|
|
197
|
+
const isTime = (value) => typeof value === 'number' && Number.isFinite(value);
|
|
198
|
+
/** Redacted debug output (M4): every field but `issuer` and `expiresAt` prints `[redacted]`. */
|
|
199
|
+
function inspectRedacted() {
|
|
200
|
+
const fields = this;
|
|
201
|
+
const shown = Object.keys(fields).map((key) => key === 'issuer' || key === 'expiresAt'
|
|
202
|
+
? `${key}: ${JSON.stringify(fields[key])}`
|
|
203
|
+
: `${key}: '[redacted]'`);
|
|
204
|
+
return `Credentials { ${shown.join(', ')} }`;
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* `fields` as credentials whose Node.js debug form (`util.inspect`, `console.log`) redacts every
|
|
208
|
+
* field but `issuer` and `expiresAt` (M4). JSON keeps every field.
|
|
209
|
+
*/
|
|
210
|
+
export function withRedactedInspect(fields) {
|
|
211
|
+
Object.defineProperty(fields, Symbol.for('nodejs.util.inspect.custom'), {
|
|
212
|
+
value: inspectRedacted,
|
|
213
|
+
enumerable: false,
|
|
214
|
+
});
|
|
215
|
+
return fields;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Rules 5 to 10 on a token's claims after its signature (or on an introspection response), at
|
|
219
|
+
* `now` (whole seconds since the epoch), for `issuer` (its exact configured string) under
|
|
220
|
+
* `rules`. `certificate` is the SHA-256 thumbprint (unpadded base64url) of the request's TLS
|
|
221
|
+
* client certificate, `undefined` for none.
|
|
222
|
+
*
|
|
223
|
+
* Rule 10 also refuses a `cnf` that is not an object, and one holding a confirmation method
|
|
224
|
+
* other than `x5t#S256` (`jkt` is `dpop-unsupported`, anything else `binding`).
|
|
225
|
+
*/
|
|
226
|
+
export function checkClaims(claims, issuer, rules, now, certificate) {
|
|
227
|
+
// 5. Issuer.
|
|
228
|
+
if (claims.iss !== issuer)
|
|
229
|
+
return refuse('issuer');
|
|
230
|
+
// 6. Audience: never optional.
|
|
231
|
+
if (!audienceAccepts(claims.aud, rules.resource))
|
|
232
|
+
return refuse('audience');
|
|
233
|
+
// 7. Required claims.
|
|
234
|
+
const { exp, iat, nbf, auth_time: authTime, acr, jti, sub, client_id: clientId } = claims;
|
|
235
|
+
if (!isTime(exp) || !isTime(iat))
|
|
236
|
+
return refuse('claims');
|
|
237
|
+
if (!claimText(jti) || !claimText(sub) || !claimText(clientId))
|
|
238
|
+
return refuse('claims');
|
|
239
|
+
if (Object.hasOwn(claims, 'nbf') && !isTime(nbf))
|
|
240
|
+
return refuse('claims');
|
|
241
|
+
if (Object.hasOwn(claims, 'auth_time') && !isTime(authTime))
|
|
242
|
+
return refuse('claims');
|
|
243
|
+
if (Object.hasOwn(claims, 'acr') && !claimText(acr))
|
|
244
|
+
return refuse('claims');
|
|
245
|
+
// 8. Time.
|
|
246
|
+
const skew = rules.clockSkewS;
|
|
247
|
+
if (now >= exp + skew)
|
|
248
|
+
return refuse('expired');
|
|
249
|
+
if (iat > now + skew || (isTime(nbf) && nbf > now + skew))
|
|
250
|
+
return refuse('not-yet-valid');
|
|
251
|
+
// A token that expires before it was issued has no lifetime at all.
|
|
252
|
+
if (exp < iat || exp - iat > rules.maxTokenLifetimeS)
|
|
253
|
+
return refuse('lifetime');
|
|
254
|
+
// 9. Scopes.
|
|
255
|
+
const scopes = parseScopeClaim(claims.scope, rules.scopePrefix, rules.scopeLimit);
|
|
256
|
+
if (!scopes.ok)
|
|
257
|
+
return scopes;
|
|
258
|
+
// 10. Binding.
|
|
259
|
+
let thumbprint;
|
|
260
|
+
if (Object.hasOwn(claims, 'cnf')) {
|
|
261
|
+
const cnf = claims.cnf;
|
|
262
|
+
if (!isRecord(cnf))
|
|
263
|
+
return refuse('binding');
|
|
264
|
+
if (Object.hasOwn(cnf, 'jkt'))
|
|
265
|
+
return refuse('dpop-unsupported');
|
|
266
|
+
if (Object.keys(cnf).some((method) => method !== 'x5t#S256'))
|
|
267
|
+
return refuse('binding');
|
|
268
|
+
if (Object.hasOwn(cnf, 'x5t#S256')) {
|
|
269
|
+
const bound = cnf['x5t#S256'];
|
|
270
|
+
if (typeof bound !== 'string' || certificate === undefined || bound !== certificate) {
|
|
271
|
+
return refuse('binding');
|
|
272
|
+
}
|
|
273
|
+
thumbprint = bound;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
if (thumbprint === undefined && rules.requireBoundTokens)
|
|
277
|
+
return refuse('binding');
|
|
278
|
+
return pass(withRedactedInspect({
|
|
279
|
+
issuer,
|
|
280
|
+
subject: sub,
|
|
281
|
+
clientId,
|
|
282
|
+
scopes: scopes.value,
|
|
283
|
+
resource: rules.resource,
|
|
284
|
+
expiresAt: Math.floor(exp),
|
|
285
|
+
issuedAt: Math.floor(iat),
|
|
286
|
+
...(isTime(authTime) ? { authTime: Math.floor(authTime) } : {}),
|
|
287
|
+
...(typeof acr === 'string' ? { acr } : {}),
|
|
288
|
+
...(thumbprint !== undefined ? { cnf: { 'x5t#S256': thumbprint } } : {}),
|
|
289
|
+
}));
|
|
290
|
+
}
|
|
291
|
+
const INTROSPECTION_REQUIRED = ['exp', 'iat', 'iss', 'aud', 'sub', 'client_id'];
|
|
292
|
+
/**
|
|
293
|
+
* An RFC 7662 introspection response for the one issuer configured for introspection
|
|
294
|
+
* (`spec/authorization.md`, M3, "Introspection"): `active` must be `true` (else `inactive`), and
|
|
295
|
+
* `exp`, `iat`, `iss`, `aud`, `sub` and `client_id` must be present (else `claims`); rules 5 to
|
|
296
|
+
* 10 ({@link checkClaims}) then apply to it, `jti` among rule 7's claims.
|
|
297
|
+
*/
|
|
298
|
+
export function checkIntrospection(response, issuer, rules, now, certificate) {
|
|
299
|
+
if (!isRecord(response) || response.active !== true)
|
|
300
|
+
return refuse('inactive');
|
|
301
|
+
if (INTROSPECTION_REQUIRED.some((field) => !Object.hasOwn(response, field))) {
|
|
302
|
+
return refuse('claims');
|
|
303
|
+
}
|
|
304
|
+
return checkClaims(response, issuer, rules, now, certificate);
|
|
305
|
+
}
|
|
306
|
+
//# sourceMappingURL=mcp-auth-rules.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcp-auth-rules.js","sourceRoot":"","sources":["../src/mcp-auth-rules.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AA4BvF,qDAAqD;AACrD,MAAM,CAAC,MAAM,eAAe,GAA4B,MAAM,CAAC,MAAM,CAAC;IACrE,UAAU;IACV,gBAAgB;IAChB,iBAAiB;IACjB,gBAAgB;IAChB,KAAK;IACL,KAAK;IACL,KAAK;IACL,MAAM;IACN,eAAe;IACf,KAAK;IACL,WAAW;IACX,QAAQ;IACR,UAAU;IACV,QAAQ;IACR,SAAS;IACT,eAAe;IACf,UAAU;IACV,iBAAiB;IACjB,iBAAiB;IACjB,kBAAkB;IAClB,SAAS;IACT,UAAU;IACV,aAAa;CACb,CAAC,CAAC;AA6BH,+DAA+D;AAC/D,MAAM,CAAC,MAAM,gBAAgB,GAAG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EAAE,KAAK,CAAC,CAAC,EAAE,CAAC;QAC7E,OAAO,MAAM,CAAC,QAAQ,CAAC,CAAC;IACzB,CAAC;IACD,OAAO,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,EAAE,WAAW,CAAC,CAAC;AAC/D,CAAC"}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview MCP authorization on HTTP (`spec/authorization.md`, M1 to M5 and M7): the options
|
|
3
|
+
* of `createMcpHandler({ auth })`, and the layer the HTTP handler runs before every route.
|
|
4
|
+
*
|
|
5
|
+
* For each request the layer serves the protected-resource metadata at its two paths without
|
|
6
|
+
* authentication (M7); otherwise it takes the one bearer token (M2), verifies it (M3), and either
|
|
7
|
+
* answers 401 with M5's exact challenge and body, or removes the `Authorization` header and
|
|
8
|
+
* admits the verified credentials (M4), frozen and branded, for that request alone: the brand is
|
|
9
|
+
* removed when the response closes. A route that runs a command without admitted credentials is
|
|
10
|
+
* refused (M1: fail closed).
|
|
11
|
+
*/
|
|
12
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
13
|
+
import { type Actor, type Clock } from '@lushly-dev/afd-core';
|
|
14
|
+
import type { TokenVerifier } from './mcp-auth-jwt.js';
|
|
15
|
+
import { type ProtectedResource } from './mcp-auth-resource.js';
|
|
16
|
+
import { type Credentials } from './mcp-auth-rules.js';
|
|
17
|
+
/** A refused token, as {@link McpAuthOptions.onRefusal} receives it. Never the token or a claim. */
|
|
18
|
+
export interface AuthRefusal {
|
|
19
|
+
/** The rule code (M5), or a host verifier's own code. */
|
|
20
|
+
rule: string;
|
|
21
|
+
/** The alias of the issuer the token was routed to, once known. */
|
|
22
|
+
issuer?: string;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* `createMcpHandler`'s `auth` option (`spec/authorization.md`, "Options"): the server becomes an
|
|
26
|
+
* OAuth 2.1 protected resource on every HTTP route. stdio, `server.execute` and in-process
|
|
27
|
+
* registries are unaffected.
|
|
28
|
+
*/
|
|
29
|
+
export interface McpAuthOptions {
|
|
30
|
+
/** The MCP endpoint's absolute `https` URL, with no query or fragment: the token audience. */
|
|
31
|
+
resource: string;
|
|
32
|
+
/** The issuers named in the metadata's `authorization_servers`, in order; at least one. */
|
|
33
|
+
authorizationServers: readonly string[];
|
|
34
|
+
/**
|
|
35
|
+
* Verifies each request's token: AFD's `JwtVerifier` (with `createIntrospectionVerifier` for
|
|
36
|
+
* opaque tokens), or the host's own. When it states its `rules`, their `resource` must be
|
|
37
|
+
* `resource` exactly.
|
|
38
|
+
*/
|
|
39
|
+
verifier: TokenVerifier;
|
|
40
|
+
/** The metadata's `scopes_supported`, and the 401's `scope`. Default: none. */
|
|
41
|
+
scopesSupported?: readonly string[];
|
|
42
|
+
/** The metadata's `resource_name`. Default: none. */
|
|
43
|
+
resourceName?: string;
|
|
44
|
+
/**
|
|
45
|
+
* Publish `tls_client_certificate_bound_access_tokens: true`. Default: the verifier's
|
|
46
|
+
* `rules.requireBoundTokens`; it must agree with them.
|
|
47
|
+
*/
|
|
48
|
+
requireBoundTokens?: boolean;
|
|
49
|
+
/**
|
|
50
|
+
* Receives each refused token's rule code and issuer alias, never the token or a claim value.
|
|
51
|
+
* Default: a `console.warn` line.
|
|
52
|
+
*/
|
|
53
|
+
onRefusal?: (refusal: AuthRefusal) => void;
|
|
54
|
+
}
|
|
55
|
+
/** The default actor of a verified call (M4), when `createContext` maps none. */
|
|
56
|
+
export declare function credentialsActor(credentials: Credentials): Actor;
|
|
57
|
+
/** The layer one HTTP handler runs before its routes. */
|
|
58
|
+
export interface AuthLayer {
|
|
59
|
+
readonly protectedResource: ProtectedResource;
|
|
60
|
+
/**
|
|
61
|
+
* Serve the metadata, or verify the request's token. `true` when the request may go on to its
|
|
62
|
+
* route with credentials admitted; `false` when the layer answered it.
|
|
63
|
+
*/
|
|
64
|
+
admit(req: IncomingMessage, res: ServerResponse, url: URL): Promise<boolean>;
|
|
65
|
+
/**
|
|
66
|
+
* The credentials this layer admitted for `req`.
|
|
67
|
+
*
|
|
68
|
+
* @throws HttpRequestError 401 when it admitted none (M1: fail closed)
|
|
69
|
+
*/
|
|
70
|
+
credentialsFor(req: IncomingMessage): Credentials;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* The authorization layer of one HTTP handler.
|
|
74
|
+
*
|
|
75
|
+
* @throws Error for invalid options: the resource, an authorization server or a published scope
|
|
76
|
+
* malformed; a verifier missing or whose rules name another resource or binding requirement;
|
|
77
|
+
* or an M6 option (`requiredScopes`, `resolver`, `filterToolsByScope`), which this version
|
|
78
|
+
* does not enforce
|
|
79
|
+
*/
|
|
80
|
+
export declare function createAuthLayer(options: McpAuthOptions, maxBodyBytes: number, clock?: Clock): AuthLayer;
|
|
81
|
+
//# sourceMappingURL=mcp-auth.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcp-auth.d.ts","sourceRoot":"","sources":["../src/mcp-auth.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAEjE,OAAO,EAAE,KAAK,KAAK,EAAE,KAAK,KAAK,EAAe,MAAM,sBAAsB,CAAC;AAG3E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AACvD,OAAO,EAGN,KAAK,iBAAiB,EACtB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAqB,KAAK,WAAW,EAAuB,MAAM,qBAAqB,CAAC;AAG/F,oGAAoG;AACpG,MAAM,WAAW,WAAW;IAC3B,yDAAyD;IACzD,IAAI,EAAE,MAAM,CAAC;IACb,mEAAmE;IACnE,MAAM,CAAC,EAAE,MAAM,CAAC;CAChB;AAED;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC9B,8FAA8F;IAC9F,QAAQ,EAAE,MAAM,CAAC;IACjB,2FAA2F;IAC3F,oBAAoB,EAAE,SAAS,MAAM,EAAE,CAAC;IACxC;;;;OAIG;IACH,QAAQ,EAAE,aAAa,CAAC;IACxB,+EAA+E;IAC/E,eAAe,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACpC,qDAAqD;IACrD,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;OAGG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B;;;OAGG;IACH,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,WAAW,KAAK,IAAI,CAAC;CAC3C;AAKD,iFAAiF;AACjF,wBAAgB,gBAAgB,CAAC,WAAW,EAAE,WAAW,GAAG,KAAK,CAEhE;AAED,yDAAyD;AACzD,MAAM,WAAW,SAAS;IACzB,QAAQ,CAAC,iBAAiB,EAAE,iBAAiB,CAAC;IAC9C;;;OAGG;IACH,KAAK,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,cAAc,EAAE,GAAG,EAAE,GAAG,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAC7E;;;;OAIG;IACH,cAAc,CAAC,GAAG,EAAE,eAAe,GAAG,WAAW,CAAC;CAClD;AAmID;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAC9B,OAAO,EAAE,cAAc,EACvB,YAAY,EAAE,MAAM,EACpB,KAAK,GAAE,KAAmB,GACxB,SAAS,CA0HX"}
|
package/dist/mcp-auth.js
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview MCP authorization on HTTP (`spec/authorization.md`, M1 to M5 and M7): the options
|
|
3
|
+
* of `createMcpHandler({ auth })`, and the layer the HTTP handler runs before every route.
|
|
4
|
+
*
|
|
5
|
+
* For each request the layer serves the protected-resource metadata at its two paths without
|
|
6
|
+
* authentication (M7); otherwise it takes the one bearer token (M2), verifies it (M3), and either
|
|
7
|
+
* answers 401 with M5's exact challenge and body, or removes the `Authorization` header and
|
|
8
|
+
* admits the verified credentials (M4), frozen and branded, for that request alone: the brand is
|
|
9
|
+
* removed when the response closes. A route that runs a command without admitted credentials is
|
|
10
|
+
* refused (M1: fail closed).
|
|
11
|
+
*/
|
|
12
|
+
import { createHash } from 'node:crypto';
|
|
13
|
+
import { TLSSocket } from 'node:tls';
|
|
14
|
+
import { systemClock } from '@lushly-dev/afd-core';
|
|
15
|
+
import { HttpRequestError } from './http-security.js';
|
|
16
|
+
import { extractBearer } from './mcp-auth-bearer.js';
|
|
17
|
+
import { createProtectedResource, isScopeToken, } from './mcp-auth-resource.js';
|
|
18
|
+
import { withRedactedInspect } from './mcp-auth-rules.js';
|
|
19
|
+
import { brandVerifiedCredentials, unbrandVerifiedCredentials } from './verified-credentials.js';
|
|
20
|
+
/** Options of M6 (scopes), which this version does not enforce; passing one fails closed. */
|
|
21
|
+
const SCOPE_OPTIONS = ['requiredScopes', 'resolver', 'filterToolsByScope'];
|
|
22
|
+
/** The default actor of a verified call (M4), when `createContext` maps none. */
|
|
23
|
+
export function credentialsActor(credentials) {
|
|
24
|
+
return { kind: 'agent', id: credentials.clientId, onBehalfOf: credentials.subject };
|
|
25
|
+
}
|
|
26
|
+
const SAFE_RULE = /^[A-Za-z0-9_.:-]{1,64}$/;
|
|
27
|
+
/** What an issuer alias may be (`JwtVerifier`'s rule): visible ASCII, at most 256 characters. */
|
|
28
|
+
const SAFE_ALIAS = /^[\x21-\x7E]{1,256}$/;
|
|
29
|
+
function defaultRefusal({ rule, issuer }) {
|
|
30
|
+
console.warn(`[afd] refused a request's bearer token: rule=${rule} issuer=${issuer ?? '-'}`);
|
|
31
|
+
}
|
|
32
|
+
function isFormBody(req) {
|
|
33
|
+
return (req.headers['content-type']?.split(';')[0]?.trim().toLowerCase() ===
|
|
34
|
+
'application/x-www-form-urlencoded');
|
|
35
|
+
}
|
|
36
|
+
/** Read a body of at most `maxBytes` (413 over it) as Latin-1 text: names are ASCII. */
|
|
37
|
+
async function readFormBody(req, maxBytes) {
|
|
38
|
+
const length = Number(req.headers['content-length']);
|
|
39
|
+
if (Number.isFinite(length) && length > maxBytes) {
|
|
40
|
+
throw new HttpRequestError(413, 'Request body is too large');
|
|
41
|
+
}
|
|
42
|
+
const chunks = [];
|
|
43
|
+
let size = 0;
|
|
44
|
+
for await (const chunk of req) {
|
|
45
|
+
size += chunk.length;
|
|
46
|
+
if (size > maxBytes)
|
|
47
|
+
throw new HttpRequestError(413, 'Request body is too large');
|
|
48
|
+
chunks.push(chunk);
|
|
49
|
+
}
|
|
50
|
+
return Buffer.concat(chunks).toString('latin1');
|
|
51
|
+
}
|
|
52
|
+
/** Every `Authorization` value, in order, from the raw headers (Node keeps only the first). */
|
|
53
|
+
function authorizationValues(req) {
|
|
54
|
+
const values = [];
|
|
55
|
+
for (let index = 0; index + 1 < req.rawHeaders.length; index += 2) {
|
|
56
|
+
if (req.rawHeaders[index]?.toLowerCase() === 'authorization') {
|
|
57
|
+
values.push(req.rawHeaders[index + 1] ?? '');
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return values;
|
|
61
|
+
}
|
|
62
|
+
/** Remove the `Authorization` header from every view of `req` (M2). */
|
|
63
|
+
function removeAuthorization(req) {
|
|
64
|
+
// Node builds `headers` and `headersDistinct` lazily from `rawHeaders` and a count it keeps,
|
|
65
|
+
// so both are built before `rawHeaders` shrinks, then edited.
|
|
66
|
+
const headers = req.headers;
|
|
67
|
+
const distinct = req.headersDistinct;
|
|
68
|
+
for (let index = req.rawHeaders.length - 2; index >= 0; index -= 2) {
|
|
69
|
+
if (req.rawHeaders[index]?.toLowerCase() === 'authorization')
|
|
70
|
+
req.rawHeaders.splice(index, 2);
|
|
71
|
+
}
|
|
72
|
+
delete headers.authorization;
|
|
73
|
+
delete distinct.authorization;
|
|
74
|
+
}
|
|
75
|
+
/** The SHA-256 thumbprint of the TLS client certificate (RFC 8705 3.1), when there is one. */
|
|
76
|
+
function certificateThumbprint(req) {
|
|
77
|
+
if (!(req.socket instanceof TLSSocket))
|
|
78
|
+
return undefined;
|
|
79
|
+
const certificate = req.socket.getPeerCertificate();
|
|
80
|
+
const der = certificate && 'raw' in certificate ? certificate.raw : undefined;
|
|
81
|
+
return der?.length ? createHash('sha256').update(der).digest('base64url') : undefined;
|
|
82
|
+
}
|
|
83
|
+
const isWhole = (value) => typeof value === 'number' && Number.isSafeInteger(value);
|
|
84
|
+
const isName = (value) => typeof value === 'string' && value !== '';
|
|
85
|
+
/**
|
|
86
|
+
* A fresh copy of a verifier's credentials when they have M4's shape for the resource and still
|
|
87
|
+
* hold on this request, else the rule they break: a host verifier whose own rules are looser
|
|
88
|
+
* fails closed (`claims` for the shape; `binding` for a bound token's missing or other
|
|
89
|
+
* certificate, or no binding where one is required; `expired` past `expiresAt` and the skew).
|
|
90
|
+
* Nothing the verifier keeps can change the copy.
|
|
91
|
+
*/
|
|
92
|
+
function admissible(value, admission) {
|
|
93
|
+
const { resource } = admission;
|
|
94
|
+
if (!value || typeof value !== 'object')
|
|
95
|
+
return 'claims';
|
|
96
|
+
const c = value;
|
|
97
|
+
const scopes = c.scopes;
|
|
98
|
+
const cnf = c.cnf;
|
|
99
|
+
if (!isName(c.issuer) ||
|
|
100
|
+
!isName(c.subject) ||
|
|
101
|
+
!isName(c.clientId) ||
|
|
102
|
+
c.resource !== resource ||
|
|
103
|
+
!isWhole(c.expiresAt) ||
|
|
104
|
+
!isWhole(c.issuedAt) ||
|
|
105
|
+
!Array.isArray(scopes) ||
|
|
106
|
+
!scopes.every((scope) => isScopeToken(scope)) ||
|
|
107
|
+
(c.authTime !== undefined && !isWhole(c.authTime)) ||
|
|
108
|
+
(c.acr !== undefined && typeof c.acr !== 'string') ||
|
|
109
|
+
(cnf !== undefined &&
|
|
110
|
+
(typeof cnf !== 'object' ||
|
|
111
|
+
cnf === null ||
|
|
112
|
+
Object.keys(cnf).join() !== 'x5t#S256' ||
|
|
113
|
+
!isName(cnf['x5t#S256'])))) {
|
|
114
|
+
return 'claims';
|
|
115
|
+
}
|
|
116
|
+
// M3 rules 8 and 10 again, against this layer's own settings and this request.
|
|
117
|
+
if (cnf !== undefined && cnf['x5t#S256'] !== admission.certificate)
|
|
118
|
+
return 'binding';
|
|
119
|
+
if (cnf === undefined && admission.requireBoundTokens)
|
|
120
|
+
return 'binding';
|
|
121
|
+
if (admission.now >= c.expiresAt + admission.skewS)
|
|
122
|
+
return 'expired';
|
|
123
|
+
return withRedactedInspect({
|
|
124
|
+
issuer: c.issuer,
|
|
125
|
+
subject: c.subject,
|
|
126
|
+
clientId: c.clientId,
|
|
127
|
+
scopes: [...new Set(scopes)],
|
|
128
|
+
resource,
|
|
129
|
+
expiresAt: c.expiresAt,
|
|
130
|
+
issuedAt: c.issuedAt,
|
|
131
|
+
...(c.authTime !== undefined ? { authTime: c.authTime } : {}),
|
|
132
|
+
...(c.acr !== undefined ? { acr: c.acr } : {}),
|
|
133
|
+
...(cnf !== undefined ? { cnf: { 'x5t#S256': cnf['x5t#S256'] } } : {}),
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* The authorization layer of one HTTP handler.
|
|
138
|
+
*
|
|
139
|
+
* @throws Error for invalid options: the resource, an authorization server or a published scope
|
|
140
|
+
* malformed; a verifier missing or whose rules name another resource or binding requirement;
|
|
141
|
+
* or an M6 option (`requiredScopes`, `resolver`, `filterToolsByScope`), which this version
|
|
142
|
+
* does not enforce
|
|
143
|
+
*/
|
|
144
|
+
export function createAuthLayer(options, maxBodyBytes, clock = systemClock) {
|
|
145
|
+
for (const name of SCOPE_OPTIONS) {
|
|
146
|
+
if (options[name] !== undefined) {
|
|
147
|
+
throw new Error(`[AFD] auth.${name} is not supported yet: scopes (spec/authorization.md, M6) are not enforced by this version, so the server refuses to start rather than ignore it`);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const { verifier } = options;
|
|
151
|
+
if (typeof verifier?.verify !== 'function') {
|
|
152
|
+
throw new Error('[AFD] auth.verifier must be a TokenVerifier, such as a JwtVerifier');
|
|
153
|
+
}
|
|
154
|
+
const rules = verifier.rules;
|
|
155
|
+
if (rules && rules.resource !== options.resource) {
|
|
156
|
+
throw new Error(`[AFD] the verifier accepts the audience ${JSON.stringify(rules.resource)} but auth.resource is ${JSON.stringify(options.resource)}`);
|
|
157
|
+
}
|
|
158
|
+
const requireBoundTokens = options.requireBoundTokens ?? rules?.requireBoundTokens ?? false;
|
|
159
|
+
if (rules && rules.requireBoundTokens !== requireBoundTokens) {
|
|
160
|
+
throw new Error('[AFD] the verifier and auth.requireBoundTokens disagree on whether certificate-bound tokens are required');
|
|
161
|
+
}
|
|
162
|
+
const resource = createProtectedResource({
|
|
163
|
+
resource: options.resource,
|
|
164
|
+
authorizationServers: options.authorizationServers,
|
|
165
|
+
scopesSupported: options.scopesSupported,
|
|
166
|
+
resourceName: options.resourceName,
|
|
167
|
+
requireBoundTokens,
|
|
168
|
+
});
|
|
169
|
+
const servers = new Set(options.authorizationServers ?? []);
|
|
170
|
+
for (const issuer of verifier.issuers ?? []) {
|
|
171
|
+
if (!servers.has(issuer)) {
|
|
172
|
+
throw new Error(`[AFD] the verifier accepts tokens from ${JSON.stringify(issuer)}, which auth.authorizationServers does not name`);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
const onRefusal = options.onRefusal ?? defaultRefusal;
|
|
176
|
+
// Only this layer's admissions count: a request admitted by another handler's layer is not.
|
|
177
|
+
const admitted = new WeakMap();
|
|
178
|
+
function json(res, status, body, challenge) {
|
|
179
|
+
res.writeHead(status, {
|
|
180
|
+
'Content-Type': 'application/json',
|
|
181
|
+
...(challenge ? { 'WWW-Authenticate': challenge } : {}),
|
|
182
|
+
});
|
|
183
|
+
res.end(JSON.stringify(body));
|
|
184
|
+
}
|
|
185
|
+
function unauthorized(res, rule, issuer) {
|
|
186
|
+
try {
|
|
187
|
+
onRefusal({
|
|
188
|
+
rule: SAFE_RULE.test(rule) ? rule : 'host',
|
|
189
|
+
// A host verifier's issuer is held to the alias pattern before it is logged.
|
|
190
|
+
...(issuer !== undefined ? { issuer: SAFE_ALIAS.test(issuer) ? issuer : 'host' } : {}),
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
catch { }
|
|
194
|
+
json(res, 401, resource.unauthorizedBody(), resource.unauthorizedChallenge(rule !== 'no-token'));
|
|
195
|
+
return false;
|
|
196
|
+
}
|
|
197
|
+
async function admit(req, res, url) {
|
|
198
|
+
// M7: the metadata is public.
|
|
199
|
+
if (resource.metadataPaths.includes(url.pathname)) {
|
|
200
|
+
if (req.method !== 'GET') {
|
|
201
|
+
res.writeHead(405, { Allow: 'GET' });
|
|
202
|
+
res.end();
|
|
203
|
+
return false;
|
|
204
|
+
}
|
|
205
|
+
json(res, 200, resource.document());
|
|
206
|
+
return false;
|
|
207
|
+
}
|
|
208
|
+
// M2: a form body is read before the token, since a token in it refuses the request.
|
|
209
|
+
const form = isFormBody(req) ? await readFormBody(req, maxBodyBytes) : undefined;
|
|
210
|
+
const query = url.search === '' ? undefined : url.search.slice(1);
|
|
211
|
+
const bearer = extractBearer(authorizationValues(req), query, form);
|
|
212
|
+
if ('refused' in bearer)
|
|
213
|
+
return unauthorized(res, bearer.refused);
|
|
214
|
+
removeAuthorization(req);
|
|
215
|
+
// M3: verify, then forget the token.
|
|
216
|
+
const certificate = certificateThumbprint(req);
|
|
217
|
+
let verification;
|
|
218
|
+
try {
|
|
219
|
+
verification = await verifier.verify(bearer.token, { certificate });
|
|
220
|
+
}
|
|
221
|
+
catch {
|
|
222
|
+
return unauthorized(res, 'unavailable');
|
|
223
|
+
}
|
|
224
|
+
if (!verification.ok)
|
|
225
|
+
return unauthorized(res, verification.rule, verification.issuer);
|
|
226
|
+
const credentials = admissible(verification.credentials, {
|
|
227
|
+
resource: resource.resource,
|
|
228
|
+
requireBoundTokens,
|
|
229
|
+
certificate,
|
|
230
|
+
now: Math.floor(clock.now() / 1000),
|
|
231
|
+
skewS: rules?.clockSkewS ?? 0,
|
|
232
|
+
});
|
|
233
|
+
if (typeof credentials === 'string')
|
|
234
|
+
return unauthorized(res, credentials);
|
|
235
|
+
// Every route takes JSON; a form body has served its one purpose (M2).
|
|
236
|
+
if (form !== undefined)
|
|
237
|
+
throw new HttpRequestError(415, 'Content-Type must be application/json');
|
|
238
|
+
if (res.destroyed || res.writableEnded)
|
|
239
|
+
return false;
|
|
240
|
+
brandVerifiedCredentials(credentials);
|
|
241
|
+
admitted.set(req, credentials);
|
|
242
|
+
// No credentials outlive their request as verified.
|
|
243
|
+
res.once('close', () => unbrandVerifiedCredentials(credentials));
|
|
244
|
+
return true;
|
|
245
|
+
}
|
|
246
|
+
function credentialsFor(req) {
|
|
247
|
+
const credentials = admitted.get(req);
|
|
248
|
+
if (credentials)
|
|
249
|
+
return credentials;
|
|
250
|
+
throw new HttpRequestError(401, 'This server requires a verified access token', {
|
|
251
|
+
suggestion: resource.unauthorizedBody().suggestion,
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
return { protectedResource: resource, admit, credentialsFor };
|
|
255
|
+
}
|
|
256
|
+
//# sourceMappingURL=mcp-auth.js.map
|