@lushly-dev/afd-server 2.3.0 → 2.5.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 +277 -31
- package/dist/app-call-registry.d.ts +31 -0
- package/dist/app-call-registry.d.ts.map +1 -0
- package/dist/app-call-registry.js +56 -0
- package/dist/app-call-registry.js.map +1 -0
- package/dist/approval-admission.d.ts +93 -0
- package/dist/approval-admission.d.ts.map +1 -0
- package/dist/approval-admission.js +165 -0
- package/dist/approval-admission.js.map +1 -0
- package/dist/approval-crypto.d.ts +22 -16
- package/dist/approval-crypto.d.ts.map +1 -1
- package/dist/approval-crypto.js +41 -66
- package/dist/approval-crypto.js.map +1 -1
- package/dist/approval-process-state.d.ts +20 -0
- package/dist/approval-process-state.d.ts.map +1 -0
- package/dist/approval-process-state.js +28 -0
- package/dist/approval-process-state.js.map +1 -0
- package/dist/approval-relay.d.ts +171 -8
- package/dist/approval-relay.d.ts.map +1 -1
- package/dist/approval-relay.js +42 -3
- package/dist/approval-relay.js.map +1 -1
- package/dist/approval-up-front.d.ts +40 -0
- package/dist/approval-up-front.d.ts.map +1 -0
- package/dist/approval-up-front.js +365 -0
- package/dist/approval-up-front.js.map +1 -0
- package/dist/approval.d.ts +17 -12
- package/dist/approval.d.ts.map +1 -1
- package/dist/approval.js +178 -41
- package/dist/approval.js.map +1 -1
- package/dist/approver.d.ts +84 -0
- package/dist/approver.d.ts.map +1 -0
- package/dist/approver.js +107 -0
- package/dist/approver.js.map +1 -0
- package/dist/bootstrap/afd-docs.d.ts.map +1 -1
- package/dist/bootstrap/afd-docs.js +4 -0
- package/dist/bootstrap/afd-docs.js.map +1 -1
- package/dist/bootstrap/afd-help.d.ts +2 -1
- package/dist/bootstrap/afd-help.d.ts.map +1 -1
- package/dist/bootstrap/afd-help.js +17 -4
- package/dist/bootstrap/afd-help.js.map +1 -1
- package/dist/bootstrap/described-command.d.ts +2 -1
- package/dist/bootstrap/described-command.d.ts.map +1 -1
- package/dist/bootstrap/described-command.js.map +1 -1
- package/dist/command-timeout.d.ts +17 -0
- package/dist/command-timeout.d.ts.map +1 -0
- package/dist/command-timeout.js +92 -0
- package/dist/command-timeout.js.map +1 -0
- package/dist/context-fields.d.ts.map +1 -1
- package/dist/context-fields.js +9 -9
- package/dist/context-fields.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 +27 -1
- package/dist/define-core.d.ts.map +1 -1
- package/dist/define-core.js +8 -1
- package/dist/define-core.js.map +1 -1
- package/dist/define.d.ts +3 -2
- package/dist/define.d.ts.map +1 -1
- package/dist/define.js +1 -1
- package/dist/define.js.map +1 -1
- package/dist/direct-registry.d.ts +27 -3
- package/dist/direct-registry.d.ts.map +1 -1
- package/dist/direct-registry.js +41 -6
- package/dist/direct-registry.js.map +1 -1
- package/dist/direct-tool-surface.d.ts +1 -1
- package/dist/direct-tool-surface.d.ts.map +1 -1
- package/dist/direct-tool-surface.js +14 -4
- package/dist/direct-tool-surface.js.map +1 -1
- package/dist/direct.d.ts +3 -1
- package/dist/direct.d.ts.map +1 -1
- package/dist/direct.js +2 -1
- package/dist/direct.js.map +1 -1
- package/dist/elicitation-state.d.ts +5 -1
- package/dist/elicitation-state.d.ts.map +1 -1
- package/dist/elicitation-state.js +4 -1
- package/dist/elicitation-state.js.map +1 -1
- package/dist/execution.d.ts +17 -0
- package/dist/execution.d.ts.map +1 -1
- package/dist/execution.js +78 -7
- package/dist/execution.js.map +1 -1
- package/dist/http-handler.d.ts +26 -2
- package/dist/http-handler.d.ts.map +1 -1
- package/dist/http-handler.js +154 -19
- package/dist/http-handler.js.map +1 -1
- package/dist/http-security.d.ts +14 -1
- package/dist/http-security.d.ts.map +1 -1
- package/dist/http-security.js +79 -17
- package/dist/http-security.js.map +1 -1
- package/dist/http-sessions.d.ts +45 -7
- package/dist/http-sessions.d.ts.map +1 -1
- package/dist/http-sessions.js +44 -12
- package/dist/http-sessions.js.map +1 -1
- package/dist/index.d.ts +18 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +18 -3
- package/dist/index.js.map +1 -1
- package/dist/instance-state.d.ts +46 -0
- package/dist/instance-state.d.ts.map +1 -0
- package/dist/instance-state.js +91 -0
- package/dist/instance-state.js.map +1 -0
- package/dist/journal-replay.d.ts.map +1 -1
- package/dist/journal-replay.js +41 -3
- package/dist/journal-replay.js.map +1 -1
- package/dist/journal.d.ts +10 -1
- package/dist/journal.d.ts.map +1 -1
- package/dist/journal.js +95 -10
- package/dist/journal.js.map +1 -1
- package/dist/json-rpc.d.ts +3 -2
- package/dist/json-rpc.d.ts.map +1 -1
- package/dist/json-rpc.js +5 -3
- package/dist/json-rpc.js.map +1 -1
- package/dist/lazy-tools.d.ts +16 -1
- package/dist/lazy-tools.d.ts.map +1 -1
- package/dist/lazy-tools.js +13 -2
- package/dist/lazy-tools.js.map +1 -1
- package/dist/mcp-auth-bearer.d.ts +25 -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-dispatch.d.ts +38 -0
- package/dist/mcp-auth-dispatch.d.ts.map +1 -0
- package/dist/mcp-auth-dispatch.js +113 -0
- package/dist/mcp-auth-dispatch.js.map +1 -0
- package/dist/mcp-auth-jwt.d.ts +179 -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 +78 -0
- package/dist/mcp-auth-resource.d.ts.map +1 -0
- package/dist/mcp-auth-resource.js +197 -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-scopes.d.ts +84 -0
- package/dist/mcp-auth-scopes.d.ts.map +1 -0
- package/dist/mcp-auth-scopes.js +125 -0
- package/dist/mcp-auth-scopes.js.map +1 -0
- package/dist/mcp-auth-view.d.ts +50 -0
- package/dist/mcp-auth-view.d.ts.map +1 -0
- package/dist/mcp-auth-view.js +166 -0
- package/dist/mcp-auth-view.js.map +1 -0
- package/dist/mcp-auth.d.ts +157 -0
- package/dist/mcp-auth.d.ts.map +1 -0
- package/dist/mcp-auth.js +442 -0
- package/dist/mcp-auth.js.map +1 -0
- package/dist/mcp-modern.d.ts +15 -1
- package/dist/mcp-modern.d.ts.map +1 -1
- package/dist/mcp-modern.js +218 -31
- package/dist/mcp-modern.js.map +1 -1
- package/dist/meta-argument.d.ts +8 -8
- package/dist/meta-argument.d.ts.map +1 -1
- package/dist/meta-argument.js +17 -10
- package/dist/meta-argument.js.map +1 -1
- package/dist/meta-tools.js +1 -1
- package/dist/meta-tools.js.map +1 -1
- package/dist/middleware.d.ts.map +1 -1
- package/dist/middleware.js +16 -6
- package/dist/middleware.js.map +1 -1
- package/dist/output-budget.d.ts +77 -0
- package/dist/output-budget.d.ts.map +1 -0
- package/dist/output-budget.js +200 -0
- package/dist/output-budget.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 +35 -10
- package/dist/resources.d.ts.map +1 -1
- package/dist/resources.js +59 -18
- package/dist/resources.js.map +1 -1
- package/dist/scope-view.d.ts +59 -0
- package/dist/scope-view.d.ts.map +1 -0
- package/dist/scope-view.js +44 -0
- package/dist/scope-view.js.map +1 -0
- package/dist/server-types.d.ts +191 -26
- package/dist/server-types.d.ts.map +1 -1
- package/dist/server-types.js.map +1 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +165 -18
- package/dist/server.js.map +1 -1
- package/dist/skills.d.ts.map +1 -1
- package/dist/skills.js +99 -3
- package/dist/skills.js.map +1 -1
- 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/task-dispatch.d.ts +34 -0
- package/dist/task-dispatch.d.ts.map +1 -0
- package/dist/task-dispatch.js +26 -0
- package/dist/task-dispatch.js.map +1 -0
- package/dist/tasks-runtime.d.ts +113 -0
- package/dist/tasks-runtime.d.ts.map +1 -0
- package/dist/tasks-runtime.js +687 -0
- package/dist/tasks-runtime.js.map +1 -0
- package/dist/tasks.d.ts +210 -0
- package/dist/tasks.d.ts.map +1 -0
- package/dist/tasks.js +289 -0
- package/dist/tasks.js.map +1 -0
- package/dist/tool-router.d.ts +4 -0
- package/dist/tool-router.d.ts.map +1 -1
- package/dist/tool-router.js +103 -26
- package/dist/tool-router.js.map +1 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +11 -18
- package/dist/tools.js.map +1 -1
- package/dist/up-front-steps.d.ts +27 -0
- package/dist/up-front-steps.d.ts.map +1 -0
- package/dist/up-front-steps.js +110 -0
- package/dist/up-front-steps.js.map +1 -0
- package/dist/validation.d.ts +24 -3
- package/dist/validation.d.ts.map +1 -1
- package/dist/validation.js +56 -6
- package/dist/validation.js.map +1 -1
- package/dist/verified-credentials.d.ts +42 -0
- package/dist/verified-credentials.d.ts.map +1 -0
- package/dist/verified-credentials.js +84 -0
- package/dist/verified-credentials.js.map +1 -0
- package/package.json +12 -7
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview AFD's JWT access-token verifier (`spec/authorization.md`, M3, RFC 9068), its key
|
|
3
|
+
* sources, and introspection as the alternative for opaque tokens.
|
|
4
|
+
*
|
|
5
|
+
* `jose` checks the signature, through WebCrypto, and nothing else: AFD never calls `jwtVerify`,
|
|
6
|
+
* so no library default applies. Routing, every header and key rule, and every claim rule are
|
|
7
|
+
* this module's and `mcp-auth-rules.ts`'s own code, in the specification's order. AFD opens no
|
|
8
|
+
* socket: keys and introspection answers come from the host.
|
|
9
|
+
*/
|
|
10
|
+
import { createHash } from 'node:crypto';
|
|
11
|
+
import { systemClock } from '@lushly-dev/afd-core';
|
|
12
|
+
import { compactVerify, errors, importJWK } from 'jose';
|
|
13
|
+
import { assertHttpsUrl } from './mcp-auth-resource.js';
|
|
14
|
+
import { checkClaims, checkIntrospection, checkJwsHeader, checkKeyFit, createTokenRules, SIGNING_ALGORITHMS, } from './mcp-auth-rules.js';
|
|
15
|
+
import { decodeBase64url, decodeJoseObject } from './strict-json.js';
|
|
16
|
+
function isRecord(value) {
|
|
17
|
+
return !!value && typeof value === 'object' && !Array.isArray(value);
|
|
18
|
+
}
|
|
19
|
+
/** The keys of a JWKS document by `kid`, or the reason it is not one. */
|
|
20
|
+
function readJwks(document) {
|
|
21
|
+
const keys = isRecord(document) ? document.keys : undefined;
|
|
22
|
+
if (!Array.isArray(keys))
|
|
23
|
+
return 'a JWKS document has a "keys" array';
|
|
24
|
+
const byKid = new Map();
|
|
25
|
+
for (const key of keys) {
|
|
26
|
+
if (!isRecord(key) || typeof key.kid !== 'string' || key.kid === '') {
|
|
27
|
+
return 'every key of a JWKS document is an object with a non-empty kid';
|
|
28
|
+
}
|
|
29
|
+
if (byKid.has(key.kid))
|
|
30
|
+
return `kid ${JSON.stringify(key.kid)} appears more than once`;
|
|
31
|
+
byKid.set(key.kid, Object.freeze({ ...key }));
|
|
32
|
+
}
|
|
33
|
+
return byKid;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* A {@link KeySource} over a JWKS document (RFC 7517 5): fixed, or loaded by the host's `load`
|
|
37
|
+
* (which fetches the issuer's `jwks_uri`, say). Loaded keys are used for `maxAgeMs`; an unknown
|
|
38
|
+
* `kid` loads again at most once per `minRefetchIntervalMs`; a failed load keeps the last good
|
|
39
|
+
* keys for up to `maxStaleMs`, and with none (or when a load for an unknown `kid` fails, or the
|
|
40
|
+
* keys are older than `maxStaleMs`) answers `unavailable`.
|
|
41
|
+
*
|
|
42
|
+
* Give each issuer a key source of its own: a `kid` names a key only within one issuer's set,
|
|
43
|
+
* and `JwtVerifier` refuses two issuers that share one.
|
|
44
|
+
*
|
|
45
|
+
* @throws Error for a fixed document that has no `keys` array, or a key without a non-empty
|
|
46
|
+
* `kid` or with one another key has; or `maxStaleMs` shorter than `maxAgeMs`
|
|
47
|
+
*/
|
|
48
|
+
export function jwksKeySource(jwks, options = {}) {
|
|
49
|
+
if (typeof jwks !== 'function') {
|
|
50
|
+
const keys = readJwks(jwks);
|
|
51
|
+
if (typeof keys === 'string')
|
|
52
|
+
throw new Error(`[AFD] ${keys}`);
|
|
53
|
+
return {
|
|
54
|
+
key: async (_issuer, kid) => {
|
|
55
|
+
const key = keys.get(kid);
|
|
56
|
+
return key ? { key } : { error: 'unknown' };
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
const load = jwks;
|
|
61
|
+
const clock = options.clock ?? systemClock;
|
|
62
|
+
const minInterval = options.minRefetchIntervalMs ?? 30_000;
|
|
63
|
+
const maxAge = options.maxAgeMs ?? 300_000;
|
|
64
|
+
const maxStale = options.maxStaleMs ?? 3_600_000;
|
|
65
|
+
if (!(maxStale >= maxAge))
|
|
66
|
+
throw new Error('[AFD] maxStaleMs must be at least maxAgeMs');
|
|
67
|
+
let keys;
|
|
68
|
+
let loadedAt = Number.NEGATIVE_INFINITY;
|
|
69
|
+
let attemptedAt = Number.NEGATIVE_INFINITY;
|
|
70
|
+
let pending;
|
|
71
|
+
async function attempt() {
|
|
72
|
+
try {
|
|
73
|
+
const read = readJwks(await load());
|
|
74
|
+
if (typeof read === 'string')
|
|
75
|
+
return false;
|
|
76
|
+
keys = read;
|
|
77
|
+
loadedAt = clock.now();
|
|
78
|
+
return true;
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/** Load once, shared by concurrent callers; whether this load succeeded. */
|
|
85
|
+
function refresh() {
|
|
86
|
+
if (!pending) {
|
|
87
|
+
attemptedAt = clock.now();
|
|
88
|
+
pending = attempt().finally(() => {
|
|
89
|
+
pending = undefined;
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
return pending;
|
|
93
|
+
}
|
|
94
|
+
return {
|
|
95
|
+
async key(_issuer, kid) {
|
|
96
|
+
const now = clock.now();
|
|
97
|
+
const mayLoad = now - attemptedAt >= minInterval;
|
|
98
|
+
if ((keys === undefined || now - loadedAt >= maxAge) && (mayLoad || pending)) {
|
|
99
|
+
await refresh();
|
|
100
|
+
}
|
|
101
|
+
// Keys older than `maxStaleMs` (every load since has failed) verify nothing.
|
|
102
|
+
if (keys === undefined || clock.now() - loadedAt >= maxStale)
|
|
103
|
+
return { error: 'unavailable' };
|
|
104
|
+
const known = keys.get(kid);
|
|
105
|
+
if (known)
|
|
106
|
+
return { key: known };
|
|
107
|
+
if (clock.now() - attemptedAt >= minInterval || pending) {
|
|
108
|
+
if (!(await refresh()))
|
|
109
|
+
return { error: 'unavailable' };
|
|
110
|
+
const fetched = keys?.get(kid);
|
|
111
|
+
if (fetched)
|
|
112
|
+
return { key: fetched };
|
|
113
|
+
}
|
|
114
|
+
return { error: 'unknown' };
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
const COMPACT_PART = /^[A-Za-z0-9_-]*$/;
|
|
119
|
+
/** The three parts of a compact JWS (the first two non-empty), or `undefined` (M3 rule 1). */
|
|
120
|
+
function compactJwsParts(token) {
|
|
121
|
+
const parts = token.split('.');
|
|
122
|
+
if (parts.length !== 3)
|
|
123
|
+
return undefined;
|
|
124
|
+
const [header, payload, signature] = parts;
|
|
125
|
+
if (header === '' || payload === '' || !parts.every((part) => COMPACT_PART.test(part))) {
|
|
126
|
+
return undefined;
|
|
127
|
+
}
|
|
128
|
+
return [header, payload, signature];
|
|
129
|
+
}
|
|
130
|
+
/** Whether `token` has the shape of a compact JWS: the routing test of M3 rule 1. */
|
|
131
|
+
export function isCompactJws(token) {
|
|
132
|
+
return compactJwsParts(token) !== undefined;
|
|
133
|
+
}
|
|
134
|
+
/** The public members each key type needs for verification; nothing else reaches `jose`. */
|
|
135
|
+
const PUBLIC_MEMBERS = {
|
|
136
|
+
RSA: ['n', 'e'],
|
|
137
|
+
EC: ['crv', 'x', 'y'],
|
|
138
|
+
OKP: ['crv', 'x'],
|
|
139
|
+
};
|
|
140
|
+
/** Coordinate sizes in bytes, where the curve fixes them. */
|
|
141
|
+
const COORDINATE_BYTES = {
|
|
142
|
+
ES256: 32,
|
|
143
|
+
ES384: 48,
|
|
144
|
+
EdDSA: 32,
|
|
145
|
+
};
|
|
146
|
+
/**
|
|
147
|
+
* The verification key of a JWK that passed rule 3, holding only its public members, or
|
|
148
|
+
* `undefined` when its material is unusable (bad base64url, a coordinate of the wrong length, an
|
|
149
|
+
* Ed448 key, which this verifier does not implement).
|
|
150
|
+
*/
|
|
151
|
+
async function verificationKey(alg, jwk) {
|
|
152
|
+
const kty = jwk.kty;
|
|
153
|
+
const members = PUBLIC_MEMBERS[kty] ?? [];
|
|
154
|
+
const material = { kty };
|
|
155
|
+
for (const member of members) {
|
|
156
|
+
const value = jwk[member];
|
|
157
|
+
if (typeof value !== 'string' || value === '')
|
|
158
|
+
return undefined;
|
|
159
|
+
if (member !== 'crv' && !decodeBase64url(value)?.length)
|
|
160
|
+
return undefined;
|
|
161
|
+
material[member] = value;
|
|
162
|
+
}
|
|
163
|
+
if (alg === 'EdDSA' && material.crv !== 'Ed25519')
|
|
164
|
+
return undefined;
|
|
165
|
+
const size = COORDINATE_BYTES[alg];
|
|
166
|
+
if (size !== undefined) {
|
|
167
|
+
const coordinates = alg === 'EdDSA' ? ['x'] : ['x', 'y'];
|
|
168
|
+
for (const member of coordinates) {
|
|
169
|
+
if (decodeBase64url(material[member])?.length !== size)
|
|
170
|
+
return undefined;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
try {
|
|
174
|
+
return await importJWK(material, alg);
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
return undefined;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* AFD's verifier of JWT access tokens (RFC 9068), applying `spec/authorization.md` M3 in order.
|
|
182
|
+
*
|
|
183
|
+
* A compact JWS goes to the configured issuer its unverified `iss` names exactly (else
|
|
184
|
+
* `unknown-issuer`). Any other token goes to the introspection verifier, when one is configured,
|
|
185
|
+
* and is otherwise refused with `unknown-issuer`: a token is never sent to an issuer that did not
|
|
186
|
+
* issue it. A JWS whose header or payload is not a JSON object with unique member names is
|
|
187
|
+
* refused (`typ` for the header, `unknown-issuer` for the payload). The audience check (M3.1)
|
|
188
|
+
* always runs: `rules.resource` is required.
|
|
189
|
+
*/
|
|
190
|
+
export class JwtVerifier {
|
|
191
|
+
rules;
|
|
192
|
+
/** The `iss` strings accepted: the JWT issuers', then the introspection verifier's. */
|
|
193
|
+
issuers;
|
|
194
|
+
#issuers;
|
|
195
|
+
#introspection;
|
|
196
|
+
#clock;
|
|
197
|
+
/**
|
|
198
|
+
* @throws Error for invalid rules, no issuer, an issuer that is not an absolute `https` URL,
|
|
199
|
+
* one with no algorithm or an algorithm AFD cannot verify, two issuers with the same `iss`
|
|
200
|
+
* string, alias or key source object, or an introspection verifier whose rules name another
|
|
201
|
+
* resource or binding requirement
|
|
202
|
+
*/
|
|
203
|
+
constructor(options) {
|
|
204
|
+
this.rules = createTokenRules(options.rules);
|
|
205
|
+
const issuers = [];
|
|
206
|
+
for (const entry of options.issuers ?? []) {
|
|
207
|
+
assertHttpsUrl('issuer', entry.issuer);
|
|
208
|
+
const alias = entry.alias ?? entry.issuer;
|
|
209
|
+
if (typeof alias !== 'string' || !/^[\x21-\x7E]{1,256}$/.test(alias)) {
|
|
210
|
+
throw new Error(`[AFD] issuer alias ${JSON.stringify(alias)} is not visible ASCII`);
|
|
211
|
+
}
|
|
212
|
+
const algorithms = [...new Set(entry.algorithms ?? [])];
|
|
213
|
+
if (algorithms.length === 0) {
|
|
214
|
+
throw new Error(`[AFD] issuer ${JSON.stringify(alias)} lists no signing algorithm`);
|
|
215
|
+
}
|
|
216
|
+
for (const algorithm of algorithms) {
|
|
217
|
+
if (!SIGNING_ALGORITHMS.includes(algorithm)) {
|
|
218
|
+
throw new Error(`[AFD] AFD cannot verify ${JSON.stringify(algorithm)} signatures`);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
if (typeof entry.keys?.key !== 'function') {
|
|
222
|
+
throw new Error(`[AFD] issuer ${JSON.stringify(alias)} has no key source`);
|
|
223
|
+
}
|
|
224
|
+
if (issuers.some((kept) => kept.issuer === entry.issuer || kept.alias === alias)) {
|
|
225
|
+
throw new Error(`[AFD] issuer ${JSON.stringify(alias)} is configured twice`);
|
|
226
|
+
}
|
|
227
|
+
// A kid names a key only within one issuer's set: a shared source would let one
|
|
228
|
+
// issuer's token be checked against another issuer's key.
|
|
229
|
+
if (issuers.some((kept) => kept.keys === entry.keys)) {
|
|
230
|
+
throw new Error(`[AFD] issuer ${JSON.stringify(alias)} shares its key source with another issuer; give each issuer its own`);
|
|
231
|
+
}
|
|
232
|
+
issuers.push(Object.freeze({ ...entry, alias, algorithms: Object.freeze(algorithms) }));
|
|
233
|
+
}
|
|
234
|
+
if (issuers.length === 0)
|
|
235
|
+
throw new Error('[AFD] a JWT verifier needs at least one issuer');
|
|
236
|
+
const introspection = options.introspection;
|
|
237
|
+
const inner = introspection?.rules;
|
|
238
|
+
if (inner &&
|
|
239
|
+
(inner.resource !== this.rules.resource ||
|
|
240
|
+
inner.requireBoundTokens !== this.rules.requireBoundTokens)) {
|
|
241
|
+
throw new Error('[AFD] the introspection verifier accepts another audience or binding requirement than the JWT verifier');
|
|
242
|
+
}
|
|
243
|
+
this.#issuers = Object.freeze(issuers);
|
|
244
|
+
this.issuers = Object.freeze([
|
|
245
|
+
...issuers.map((entry) => entry.issuer),
|
|
246
|
+
...(introspection?.issuers ?? []),
|
|
247
|
+
]);
|
|
248
|
+
this.#introspection = introspection;
|
|
249
|
+
this.#clock = options.clock ?? systemClock;
|
|
250
|
+
}
|
|
251
|
+
async verify(token, request = {}) {
|
|
252
|
+
const parts = compactJwsParts(token);
|
|
253
|
+
if (!parts) {
|
|
254
|
+
return this.#introspection
|
|
255
|
+
? this.#introspection.verify(token, request)
|
|
256
|
+
: { ok: false, rule: 'unknown-issuer' };
|
|
257
|
+
}
|
|
258
|
+
const [headerPart, payloadPart, signaturePart] = parts;
|
|
259
|
+
// 1. Route by the unverified `iss`.
|
|
260
|
+
const payload = decodeJoseObject(payloadPart);
|
|
261
|
+
const iss = payload?.iss;
|
|
262
|
+
const issuer = this.#issuers.find((candidate) => candidate.issuer === iss);
|
|
263
|
+
if (!payload || !issuer)
|
|
264
|
+
return { ok: false, rule: 'unknown-issuer' };
|
|
265
|
+
const refused = (rule) => ({
|
|
266
|
+
ok: false,
|
|
267
|
+
rule,
|
|
268
|
+
issuer: issuer.alias,
|
|
269
|
+
});
|
|
270
|
+
const outcome = (result) => (result.ok ? undefined : refused(result.rule));
|
|
271
|
+
// 2. Header.
|
|
272
|
+
const header = decodeJoseObject(headerPart);
|
|
273
|
+
if (!header)
|
|
274
|
+
return refused('typ');
|
|
275
|
+
const headerRefusal = outcome(checkJwsHeader(header, issuer.algorithms));
|
|
276
|
+
if (headerRefusal)
|
|
277
|
+
return headerRefusal;
|
|
278
|
+
const alg = header.alg;
|
|
279
|
+
// 3. Key.
|
|
280
|
+
let lookup;
|
|
281
|
+
try {
|
|
282
|
+
lookup = await issuer.keys.key(issuer.issuer, header.kid);
|
|
283
|
+
}
|
|
284
|
+
catch {
|
|
285
|
+
return refused('unavailable');
|
|
286
|
+
}
|
|
287
|
+
if ('error' in lookup)
|
|
288
|
+
return refused(lookup.error === 'unknown' ? 'key' : 'unavailable');
|
|
289
|
+
const keyRefusal = outcome(checkKeyFit(header, lookup.key));
|
|
290
|
+
if (keyRefusal)
|
|
291
|
+
return keyRefusal;
|
|
292
|
+
const key = await verificationKey(alg, lookup.key);
|
|
293
|
+
if (!key)
|
|
294
|
+
return refused('key');
|
|
295
|
+
// 4. Signature.
|
|
296
|
+
if (!decodeBase64url(signaturePart))
|
|
297
|
+
return refused('signature');
|
|
298
|
+
try {
|
|
299
|
+
await compactVerify(token, key, { algorithms: [alg] });
|
|
300
|
+
}
|
|
301
|
+
catch (error) {
|
|
302
|
+
return refused(error instanceof errors.JWSSignatureVerificationFailed ? 'signature' : 'key');
|
|
303
|
+
}
|
|
304
|
+
// 5 to 10. Claims.
|
|
305
|
+
const now = Math.floor(this.#clock.now() / 1000);
|
|
306
|
+
const claims = checkClaims(payload, issuer.issuer, this.rules, now, request.certificate);
|
|
307
|
+
return claims.ok ? { ok: true, credentials: claims.value } : refused(claims.rule);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
/** How long an introspection answer may be reused (M3, "Introspection"). */
|
|
311
|
+
const INTROSPECTION_CACHE_MS = 60_000;
|
|
312
|
+
/**
|
|
313
|
+
* A {@link TokenVerifier} for opaque tokens through the host's introspection call
|
|
314
|
+
* (`spec/authorization.md`, M3, "Introspection"): `active: true` and the six required fields,
|
|
315
|
+
* then rules 5 to 10. Give it to {@link JwtVerifier} as `introspection`, so only tokens that are
|
|
316
|
+
* not a compact JWS reach it.
|
|
317
|
+
*
|
|
318
|
+
* @throws Error for invalid rules or an issuer that is not an absolute `https` URL
|
|
319
|
+
*/
|
|
320
|
+
export function createIntrospectionVerifier(options) {
|
|
321
|
+
assertHttpsUrl('issuer', options.issuer);
|
|
322
|
+
const rules = createTokenRules(options.rules);
|
|
323
|
+
const { issuer, introspect } = options;
|
|
324
|
+
const alias = options.alias ?? issuer;
|
|
325
|
+
const clock = options.clock ?? systemClock;
|
|
326
|
+
const cacheSize = options.cacheSize ?? 1000;
|
|
327
|
+
const cache = new Map();
|
|
328
|
+
async function response(token) {
|
|
329
|
+
const digest = createHash('sha256').update(token).digest('base64url');
|
|
330
|
+
const cached = cache.get(digest);
|
|
331
|
+
if (cached && cached.until > clock.now())
|
|
332
|
+
return cached.response;
|
|
333
|
+
cache.delete(digest);
|
|
334
|
+
const answer = await introspect(token);
|
|
335
|
+
const exp = isRecord(answer) && answer.active === true ? answer.exp : undefined;
|
|
336
|
+
if (cacheSize > 0 && typeof exp === 'number' && Number.isFinite(exp)) {
|
|
337
|
+
if (cache.size >= cacheSize)
|
|
338
|
+
cache.delete(cache.keys().next().value);
|
|
339
|
+
cache.set(digest, {
|
|
340
|
+
response: answer,
|
|
341
|
+
until: Math.min(exp * 1000, clock.now() + INTROSPECTION_CACHE_MS),
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
return answer;
|
|
345
|
+
}
|
|
346
|
+
return {
|
|
347
|
+
rules,
|
|
348
|
+
issuers: Object.freeze([issuer]),
|
|
349
|
+
async verify(token, request = {}) {
|
|
350
|
+
let answer;
|
|
351
|
+
try {
|
|
352
|
+
answer = await response(token);
|
|
353
|
+
}
|
|
354
|
+
catch {
|
|
355
|
+
return { ok: false, rule: 'unavailable', issuer: alias };
|
|
356
|
+
}
|
|
357
|
+
const now = Math.floor(clock.now() / 1000);
|
|
358
|
+
const checked = checkIntrospection(answer, issuer, rules, now, request.certificate);
|
|
359
|
+
return checked.ok
|
|
360
|
+
? { ok: true, credentials: checked.value }
|
|
361
|
+
: { ok: false, rule: checked.rule, issuer: alias };
|
|
362
|
+
},
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
//# sourceMappingURL=mcp-auth-jwt.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcp-auth-jwt.js","sourceRoot":"","sources":["../src/mcp-auth-jwt.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAc,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAC/D,OA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/**
|
|
2
|
+
* @fileoverview The protected resource: its URI, the audience rule, the RFC 9728 metadata and the
|
|
3
|
+
* challenges that point to it (`spec/authorization.md`, M3.1, M5 and M7).
|
|
4
|
+
*/
|
|
5
|
+
/** The well-known suffix of protected-resource metadata (RFC 9728 3.1). */
|
|
6
|
+
export declare const PROTECTED_RESOURCE_WELL_KNOWN = "/.well-known/oauth-protected-resource";
|
|
7
|
+
/** Whether `scope` is one OAuth scope token (RFC 6749 3.3). */
|
|
8
|
+
export declare function isScopeToken(scope: unknown): scope is string;
|
|
9
|
+
/**
|
|
10
|
+
* Whether an `aud` claim (`undefined` when absent) accepts `resource` (`spec/authorization.md`,
|
|
11
|
+
* M3.1): a string, or an array of exactly one string, naming the resource. A token with several
|
|
12
|
+
* audiences is refused even when one matches, since any of them could replay it here.
|
|
13
|
+
*/
|
|
14
|
+
export declare function audienceAccepts(aud: unknown, resource: string): boolean;
|
|
15
|
+
/**
|
|
16
|
+
* Throw unless `url` is an absolute `https` URL in visible ASCII with no user information, query
|
|
17
|
+
* or fragment: the form of the resource, an issuer and an authorization server.
|
|
18
|
+
*/
|
|
19
|
+
export declare function assertHttpsUrl(what: string, url: unknown): asserts url is string;
|
|
20
|
+
/** What the protected-resource metadata publishes (`spec/authorization.md`, M7 and "Options"). */
|
|
21
|
+
export interface ProtectedResourceOptions {
|
|
22
|
+
/** The MCP endpoint's absolute `https` URL, with no query or fragment: the token audience. */
|
|
23
|
+
resource: string;
|
|
24
|
+
/** The issuers whose access tokens the server accepts, in this order; at least one. */
|
|
25
|
+
authorizationServers: readonly string[];
|
|
26
|
+
/** The metadata's `scopes_supported`, and the 401's `scope`. Default: none. */
|
|
27
|
+
scopesSupported?: readonly string[];
|
|
28
|
+
/** The metadata's `resource_name`. Default: none. */
|
|
29
|
+
resourceName?: string;
|
|
30
|
+
/** Whether only certificate-bound tokens are accepted. Default: `false`. */
|
|
31
|
+
requireBoundTokens?: boolean;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* RFC 9728 protected-resource metadata, the URLs it is served at and the challenges that point
|
|
35
|
+
* to it (`spec/authorization.md`, M5 and M7). Built by {@link createProtectedResource}, which
|
|
36
|
+
* checks its options.
|
|
37
|
+
*/
|
|
38
|
+
export interface ProtectedResource {
|
|
39
|
+
/** The resource, as configured. */
|
|
40
|
+
readonly resource: string;
|
|
41
|
+
/** The metadata URLs: the path-inserted one first (every challenge's `resource_metadata`). */
|
|
42
|
+
readonly metadataUrls: readonly string[];
|
|
43
|
+
/** The request paths of {@link metadataUrls}, served without authentication. */
|
|
44
|
+
readonly metadataPaths: readonly string[];
|
|
45
|
+
/** The published scopes. */
|
|
46
|
+
readonly scopesSupported: readonly string[];
|
|
47
|
+
/** Whether only certificate-bound tokens are accepted. */
|
|
48
|
+
readonly requireBoundTokens: boolean;
|
|
49
|
+
/** The metadata document. Nothing else is published. */
|
|
50
|
+
document(): Record<string, unknown>;
|
|
51
|
+
/** The 401's `WWW-Authenticate` value; `error="invalid_token"` when a token was sent. */
|
|
52
|
+
unauthorizedChallenge(tokenSent: boolean): string;
|
|
53
|
+
/** The 401's JSON body. */
|
|
54
|
+
unauthorizedBody(): {
|
|
55
|
+
error: 'UNAUTHORIZED';
|
|
56
|
+
suggestion: string;
|
|
57
|
+
};
|
|
58
|
+
/** The 403's `WWW-Authenticate` value for the `missing` scopes, in order. */
|
|
59
|
+
forbiddenChallenge(missing: readonly string[]): string;
|
|
60
|
+
/**
|
|
61
|
+
* The 403's JSON body for the `missing` scopes. `scopeSource` names what a caller obtains to
|
|
62
|
+
* gain a scope when it is not a token for the resource (a host's own layer, M6): the
|
|
63
|
+
* suggestion then reads "Obtain `<scopeSource>` that also grants ...".
|
|
64
|
+
*/
|
|
65
|
+
forbiddenBody(missing: readonly string[], scopeSource?: string): {
|
|
66
|
+
error: 'INSUFFICIENT_SCOPE';
|
|
67
|
+
suggestion: string;
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* The protected-resource metadata of `options.resource`.
|
|
72
|
+
*
|
|
73
|
+
* @throws Error when the resource or an authorization server is not an absolute `https` URL
|
|
74
|
+
* without user information, query or fragment, no authorization server is named or one is
|
|
75
|
+
* named twice, or a published scope is not a scope token or is published twice
|
|
76
|
+
*/
|
|
77
|
+
export declare function createProtectedResource(options: ProtectedResourceOptions): ProtectedResource;
|
|
78
|
+
//# sourceMappingURL=mcp-auth-resource.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcp-auth-resource.d.ts","sourceRoot":"","sources":["../src/mcp-auth-resource.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,2EAA2E;AAC3E,eAAO,MAAM,6BAA6B,0CAA0C,CAAC;AAKrF,+DAA+D;AAC/D,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAE5D;AA6ED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAMvE;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,GAAG,OAAO,CAAC,GAAG,IAAI,MAAM,CAOhF;AAOD,kGAAkG;AAClG,MAAM,WAAW,wBAAwB;IACxC,8FAA8F;IAC9F,QAAQ,EAAE,MAAM,CAAC;IACjB,uFAAuF;IACvF,oBAAoB,EAAE,SAAS,MAAM,EAAE,CAAC;IACxC,+EAA+E;IAC/E,eAAe,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACpC,qDAAqD;IACrD,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,4EAA4E;IAC5E,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC7B;AAED;;;;GAIG;AACH,MAAM,WAAW,iBAAiB;IACjC,mCAAmC;IACnC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,8FAA8F;IAC9F,QAAQ,CAAC,YAAY,EAAE,SAAS,MAAM,EAAE,CAAC;IACzC,gFAAgF;IAChF,QAAQ,CAAC,aAAa,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1C,4BAA4B;IAC5B,QAAQ,CAAC,eAAe,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5C,0DAA0D;IAC1D,QAAQ,CAAC,kBAAkB,EAAE,OAAO,CAAC;IACrC,wDAAwD;IACxD,QAAQ,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACpC,yFAAyF;IACzF,qBAAqB,CAAC,SAAS,EAAE,OAAO,GAAG,MAAM,CAAC;IAClD,2BAA2B;IAC3B,gBAAgB,IAAI;QAAE,KAAK,EAAE,cAAc,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE,CAAC;IAClE,6EAA6E;IAC7E,kBAAkB,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,CAAC;IACvD;;;;OAIG;IACH,aAAa,CACZ,OAAO,EAAE,SAAS,MAAM,EAAE,EAC1B,WAAW,CAAC,EAAE,MAAM,GAClB;QAAE,KAAK,EAAE,oBAAoB,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE,CAAC;CACvD;AAED;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,wBAAwB,GAAG,iBAAiB,CAsF5F"}
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview The protected resource: its URI, the audience rule, the RFC 9728 metadata and the
|
|
3
|
+
* challenges that point to it (`spec/authorization.md`, M3.1, M5 and M7).
|
|
4
|
+
*/
|
|
5
|
+
/** The well-known suffix of protected-resource metadata (RFC 9728 3.1). */
|
|
6
|
+
export const PROTECTED_RESOURCE_WELL_KNOWN = '/.well-known/oauth-protected-resource';
|
|
7
|
+
/** A scope token (RFC 6749 3.3): one or more of `%x21 / %x23-5B / %x5D-7E`. */
|
|
8
|
+
const SCOPE_TOKEN = /^[\x21\x23-\x5B\x5D-\x7E]+$/;
|
|
9
|
+
/** Whether `scope` is one OAuth scope token (RFC 6749 3.3). */
|
|
10
|
+
export function isScopeToken(scope) {
|
|
11
|
+
return typeof scope === 'string' && SCOPE_TOKEN.test(scope);
|
|
12
|
+
}
|
|
13
|
+
const VISIBLE_ASCII = /^[\x21-\x7E]+$/;
|
|
14
|
+
const FORBIDDEN = /[?#"\\<>`{}|^]/;
|
|
15
|
+
const SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*$/;
|
|
16
|
+
/**
|
|
17
|
+
* `url` split for comparison, or `undefined` when it is not `scheme://host[:port][path]` in
|
|
18
|
+
* visible ASCII with no user information, query or fragment. Nothing is normalized: the parts
|
|
19
|
+
* are as written.
|
|
20
|
+
*/
|
|
21
|
+
function splitUrl(url) {
|
|
22
|
+
if (!VISIBLE_ASCII.test(url) || FORBIDDEN.test(url))
|
|
23
|
+
return undefined;
|
|
24
|
+
const separator = url.indexOf('://');
|
|
25
|
+
if (separator < 0)
|
|
26
|
+
return undefined;
|
|
27
|
+
const scheme = url.slice(0, separator);
|
|
28
|
+
if (!SCHEME.test(scheme))
|
|
29
|
+
return undefined;
|
|
30
|
+
const rest = url.slice(separator + 3);
|
|
31
|
+
const slash = rest.indexOf('/');
|
|
32
|
+
const authority = slash < 0 ? rest : rest.slice(0, slash);
|
|
33
|
+
const path = slash < 0 ? '' : rest.slice(slash);
|
|
34
|
+
if (authority === '' || authority.includes('@'))
|
|
35
|
+
return undefined;
|
|
36
|
+
let host;
|
|
37
|
+
let port;
|
|
38
|
+
if (authority.startsWith('[')) {
|
|
39
|
+
const close = authority.indexOf(']');
|
|
40
|
+
if (close < 0)
|
|
41
|
+
return undefined;
|
|
42
|
+
host = authority.slice(0, close + 1);
|
|
43
|
+
const after = authority.slice(close + 1);
|
|
44
|
+
if (after !== '') {
|
|
45
|
+
if (!after.startsWith(':'))
|
|
46
|
+
return undefined;
|
|
47
|
+
port = after.slice(1);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
const colon = authority.lastIndexOf(':');
|
|
52
|
+
host = colon < 0 ? authority : authority.slice(0, colon);
|
|
53
|
+
port = colon < 0 ? undefined : authority.slice(colon + 1);
|
|
54
|
+
}
|
|
55
|
+
if (host === '' ||
|
|
56
|
+
(host.includes(':') && !host.startsWith('[')) ||
|
|
57
|
+
(port !== undefined && !/^[0-9]*$/.test(port))) {
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
return { scheme, host, port, path, origin: url.slice(0, separator + 3 + authority.length) };
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Whether `candidate` names `resource` (`spec/authorization.md`, M3.1): the scheme and the host
|
|
64
|
+
* compare ignoring ASCII case; the port as written (`:443` is not the same as no port), the path
|
|
65
|
+
* (a trailing slash differs), percent-encoding and case compare exactly; a value with user
|
|
66
|
+
* information, a query or a fragment never matches.
|
|
67
|
+
*/
|
|
68
|
+
function sameResource(resource, candidate) {
|
|
69
|
+
const expected = splitUrl(resource);
|
|
70
|
+
const actual = splitUrl(candidate);
|
|
71
|
+
if (!expected || !actual)
|
|
72
|
+
return false;
|
|
73
|
+
return (expected.scheme.toLowerCase() === actual.scheme.toLowerCase() &&
|
|
74
|
+
expected.host.toLowerCase() === actual.host.toLowerCase() &&
|
|
75
|
+
expected.port === actual.port &&
|
|
76
|
+
expected.path === actual.path);
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Whether an `aud` claim (`undefined` when absent) accepts `resource` (`spec/authorization.md`,
|
|
80
|
+
* M3.1): a string, or an array of exactly one string, naming the resource. A token with several
|
|
81
|
+
* audiences is refused even when one matches, since any of them could replay it here.
|
|
82
|
+
*/
|
|
83
|
+
export function audienceAccepts(aud, resource) {
|
|
84
|
+
if (typeof aud === 'string')
|
|
85
|
+
return sameResource(resource, aud);
|
|
86
|
+
if (Array.isArray(aud) && aud.length === 1 && typeof aud[0] === 'string') {
|
|
87
|
+
return sameResource(resource, aud[0]);
|
|
88
|
+
}
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Throw unless `url` is an absolute `https` URL in visible ASCII with no user information, query
|
|
93
|
+
* or fragment: the form of the resource, an issuer and an authorization server.
|
|
94
|
+
*/
|
|
95
|
+
export function assertHttpsUrl(what, url) {
|
|
96
|
+
const parts = typeof url === 'string' ? splitUrl(url) : undefined;
|
|
97
|
+
if (parts?.scheme.toLowerCase() !== 'https') {
|
|
98
|
+
throw new Error(`[AFD] ${what} ${JSON.stringify(url)} is not an absolute https URL without user information, query or fragment`);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
/** The scope tokens of `scopes`, joined by single spaces; anything else is left out. */
|
|
102
|
+
function joinedTokens(scopes) {
|
|
103
|
+
return scopes.filter((scope) => isScopeToken(scope)).join(' ');
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* The protected-resource metadata of `options.resource`.
|
|
107
|
+
*
|
|
108
|
+
* @throws Error when the resource or an authorization server is not an absolute `https` URL
|
|
109
|
+
* without user information, query or fragment, no authorization server is named or one is
|
|
110
|
+
* named twice, or a published scope is not a scope token or is published twice
|
|
111
|
+
*/
|
|
112
|
+
export function createProtectedResource(options) {
|
|
113
|
+
const { resource } = options;
|
|
114
|
+
assertHttpsUrl('resource', resource);
|
|
115
|
+
const servers = [];
|
|
116
|
+
for (const server of options.authorizationServers ?? []) {
|
|
117
|
+
assertHttpsUrl('authorization server', server);
|
|
118
|
+
if (servers.includes(server)) {
|
|
119
|
+
throw new Error(`[AFD] authorization server ${JSON.stringify(server)} is named twice`);
|
|
120
|
+
}
|
|
121
|
+
servers.push(server);
|
|
122
|
+
}
|
|
123
|
+
if (servers.length === 0) {
|
|
124
|
+
throw new Error('[AFD] protected-resource metadata needs at least one authorization server');
|
|
125
|
+
}
|
|
126
|
+
const scopes = [];
|
|
127
|
+
for (const scope of options.scopesSupported ?? []) {
|
|
128
|
+
if (!isScopeToken(scope)) {
|
|
129
|
+
throw new Error(`[AFD] scope ${JSON.stringify(scope)} is not an OAuth scope token`);
|
|
130
|
+
}
|
|
131
|
+
if (scopes.includes(scope)) {
|
|
132
|
+
throw new Error(`[AFD] scope ${JSON.stringify(scope)} is published twice`);
|
|
133
|
+
}
|
|
134
|
+
scopes.push(scope);
|
|
135
|
+
}
|
|
136
|
+
const resourceName = options.resourceName;
|
|
137
|
+
if (resourceName !== undefined && typeof resourceName !== 'string') {
|
|
138
|
+
throw new Error('[AFD] resourceName must be a string');
|
|
139
|
+
}
|
|
140
|
+
const requireBoundTokens = options.requireBoundTokens === true;
|
|
141
|
+
const parts = splitUrl(resource);
|
|
142
|
+
const bare = `${parts.origin}${PROTECTED_RESOURCE_WELL_KNOWN}`;
|
|
143
|
+
const onlyOrigin = parts.path === '' || parts.path === '/';
|
|
144
|
+
const metadataUrls = Object.freeze(onlyOrigin ? [bare] : [`${bare}${parts.path}`, bare]);
|
|
145
|
+
const metadataPaths = Object.freeze(onlyOrigin
|
|
146
|
+
? [PROTECTED_RESOURCE_WELL_KNOWN]
|
|
147
|
+
: [`${PROTECTED_RESOURCE_WELL_KNOWN}${parts.path}`, PROTECTED_RESOURCE_WELL_KNOWN]);
|
|
148
|
+
const metadata = metadataUrls[0];
|
|
149
|
+
const suggestion = (missing, scopeSource) => {
|
|
150
|
+
const joined = joinedTokens(missing);
|
|
151
|
+
const source = scopeSource ?? `a token for ${resource}`;
|
|
152
|
+
return joined
|
|
153
|
+
? `Obtain ${source} that also grants ${joined}, then retry.`
|
|
154
|
+
: `Obtain ${source} that grants the scopes this call needs, then retry.`;
|
|
155
|
+
};
|
|
156
|
+
return Object.freeze({
|
|
157
|
+
resource,
|
|
158
|
+
metadataUrls,
|
|
159
|
+
metadataPaths,
|
|
160
|
+
scopesSupported: Object.freeze([...scopes]),
|
|
161
|
+
requireBoundTokens,
|
|
162
|
+
document() {
|
|
163
|
+
return {
|
|
164
|
+
resource,
|
|
165
|
+
authorization_servers: [...servers],
|
|
166
|
+
...(scopes.length ? { scopes_supported: [...scopes] } : {}),
|
|
167
|
+
bearer_methods_supported: ['header'],
|
|
168
|
+
...(resourceName !== undefined ? { resource_name: resourceName } : {}),
|
|
169
|
+
tls_client_certificate_bound_access_tokens: requireBoundTokens,
|
|
170
|
+
};
|
|
171
|
+
},
|
|
172
|
+
unauthorizedChallenge(tokenSent) {
|
|
173
|
+
let challenge = `Bearer resource_metadata="${metadata}"`;
|
|
174
|
+
if (scopes.length)
|
|
175
|
+
challenge += `, scope="${scopes.join(' ')}"`;
|
|
176
|
+
if (tokenSent)
|
|
177
|
+
challenge += ', error="invalid_token"';
|
|
178
|
+
return challenge;
|
|
179
|
+
},
|
|
180
|
+
unauthorizedBody() {
|
|
181
|
+
return {
|
|
182
|
+
error: 'UNAUTHORIZED',
|
|
183
|
+
suggestion: `Obtain a token for ${resource} from an authorization server named in ${metadata}.`,
|
|
184
|
+
};
|
|
185
|
+
},
|
|
186
|
+
forbiddenChallenge(missing) {
|
|
187
|
+
const joined = joinedTokens(missing);
|
|
188
|
+
return joined
|
|
189
|
+
? `Bearer error="insufficient_scope", scope="${joined}", resource_metadata="${metadata}"`
|
|
190
|
+
: `Bearer error="insufficient_scope", resource_metadata="${metadata}"`;
|
|
191
|
+
},
|
|
192
|
+
forbiddenBody(missing, scopeSource) {
|
|
193
|
+
return { error: 'INSUFFICIENT_SCOPE', suggestion: suggestion(missing, scopeSource) };
|
|
194
|
+
},
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
//# sourceMappingURL=mcp-auth-resource.js.map
|