@lushly-dev/afd-server 2.3.0 → 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 +117 -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/http-handler.d.ts +6 -0
- package/dist/http-handler.d.ts.map +1 -1
- package/dist/http-handler.js +17 -5
- package/dist/http-handler.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/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -0
- package/dist/index.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 +3 -0
- package/dist/mcp-modern.d.ts.map +1 -1
- package/dist/mcp-modern.js +8 -2
- package/dist/mcp-modern.js.map +1 -1
- 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/server-types.d.ts +35 -2
- 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 +6 -1
- package/dist/server.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/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 +10 -5
|
@@ -0,0 +1,196 @@
|
|
|
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) => {
|
|
150
|
+
const joined = joinedTokens(missing);
|
|
151
|
+
return joined
|
|
152
|
+
? `Obtain a token for ${resource} that also grants ${joined}, then retry.`
|
|
153
|
+
: `Obtain a token for ${resource} that grants the scopes this call needs, then retry.`;
|
|
154
|
+
};
|
|
155
|
+
return Object.freeze({
|
|
156
|
+
resource,
|
|
157
|
+
metadataUrls,
|
|
158
|
+
metadataPaths,
|
|
159
|
+
scopesSupported: Object.freeze([...scopes]),
|
|
160
|
+
requireBoundTokens,
|
|
161
|
+
document() {
|
|
162
|
+
return {
|
|
163
|
+
resource,
|
|
164
|
+
authorization_servers: [...servers],
|
|
165
|
+
...(scopes.length ? { scopes_supported: [...scopes] } : {}),
|
|
166
|
+
bearer_methods_supported: ['header'],
|
|
167
|
+
...(resourceName !== undefined ? { resource_name: resourceName } : {}),
|
|
168
|
+
tls_client_certificate_bound_access_tokens: requireBoundTokens,
|
|
169
|
+
};
|
|
170
|
+
},
|
|
171
|
+
unauthorizedChallenge(tokenSent) {
|
|
172
|
+
let challenge = `Bearer resource_metadata="${metadata}"`;
|
|
173
|
+
if (scopes.length)
|
|
174
|
+
challenge += `, scope="${scopes.join(' ')}"`;
|
|
175
|
+
if (tokenSent)
|
|
176
|
+
challenge += ', error="invalid_token"';
|
|
177
|
+
return challenge;
|
|
178
|
+
},
|
|
179
|
+
unauthorizedBody() {
|
|
180
|
+
return {
|
|
181
|
+
error: 'UNAUTHORIZED',
|
|
182
|
+
suggestion: `Obtain a token for ${resource} from an authorization server named in ${metadata}.`,
|
|
183
|
+
};
|
|
184
|
+
},
|
|
185
|
+
forbiddenChallenge(missing) {
|
|
186
|
+
const joined = joinedTokens(missing);
|
|
187
|
+
return joined
|
|
188
|
+
? `Bearer error="insufficient_scope", scope="${joined}", resource_metadata="${metadata}"`
|
|
189
|
+
: `Bearer error="insufficient_scope", resource_metadata="${metadata}"`;
|
|
190
|
+
},
|
|
191
|
+
forbiddenBody(missing) {
|
|
192
|
+
return { error: 'INSUFFICIENT_SCOPE', suggestion: suggestion(missing) };
|
|
193
|
+
},
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
//# sourceMappingURL=mcp-auth-resource.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcp-auth-resource.js","sourceRoot":"","sources":["../src/mcp-auth-resource.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,2EAA2E;AAC3E,MAAM,CAAC,MAAM,6BAA6B,GAAG,uCAAuC,CAAC;AAErF,+EAA+E;AAC/E,MAAM,WAAW,GAAG,6BAA6B,CAAC;AAElD,+DAA+D;AAC/D,MAAM,UAAU,YAAY,CAAC,KAAc;IAC1C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC7D,CAAC;AAaD,MAAM,aAAa,GAAG,gBAAgB,CAAC;AACvC,MAAM,SAAS,GAAG,gBAAgB,CAAC;AACnC,MAAM,MAAM,GAAG,2BAA2B,CAAC;AAE3C;;;;GAIG;AACH,SAAS,QAAQ,CAAC,GAAW;IAC5B,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC;QAAE,OAAO,SAAS,CAAC;IACtE,MAAM,SAAS,GAAG,GAAG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@ -0,0 +1,135 @@
|
|
|
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
|
+
/** The rule a refused token or request broke (`spec/authorization.md`, M5). Logged, never sent. */
|
|
8
|
+
export type AuthRuleCode = 'no-token' | 'token-location' | 'token-malformed' | 'unknown-issuer' | 'typ' | 'alg' | 'kid' | 'crit' | 'key-reference' | 'key' | 'signature' | 'issuer' | 'audience' | 'claims' | 'expired' | 'not-yet-valid' | 'lifetime' | 'scope-malformed' | 'scopes-too-many' | 'dpop-unsupported' | 'binding' | 'inactive' | 'unavailable';
|
|
9
|
+
/** Every rule code, in the specification's order. */
|
|
10
|
+
export declare const AUTH_RULE_CODES: readonly AuthRuleCode[];
|
|
11
|
+
/**
|
|
12
|
+
* The verified claims of one request's access token (`spec/authorization.md`, M4): what a command
|
|
13
|
+
* sees as `context.credentials` on a call the server verified. Never the token.
|
|
14
|
+
*/
|
|
15
|
+
export interface Credentials {
|
|
16
|
+
/** `iss`: the issuer, exactly as configured. */
|
|
17
|
+
readonly issuer: string;
|
|
18
|
+
/** `sub`: the subject. */
|
|
19
|
+
readonly subject: string;
|
|
20
|
+
/** `client_id`: the OAuth client the token was issued to. */
|
|
21
|
+
readonly clientId: string;
|
|
22
|
+
/** `scope`, parsed (M3.2): each scope once, in token order. */
|
|
23
|
+
readonly scopes: readonly string[];
|
|
24
|
+
/** The server's configured resource, as configured (not the token's spelling of `aud`). */
|
|
25
|
+
readonly resource: string;
|
|
26
|
+
/** `exp`, in whole seconds since the epoch, rounded down. */
|
|
27
|
+
readonly expiresAt: number;
|
|
28
|
+
/** `iat`, in whole seconds since the epoch, rounded down. */
|
|
29
|
+
readonly issuedAt: number;
|
|
30
|
+
/** `auth_time`, in whole seconds since the epoch, rounded down, when present. */
|
|
31
|
+
readonly authTime?: number;
|
|
32
|
+
/** `acr`, when present. */
|
|
33
|
+
readonly acr?: string;
|
|
34
|
+
/** The TLS client certificate the token is bound to (RFC 8705 3.1), when it is bound. */
|
|
35
|
+
readonly cnf?: {
|
|
36
|
+
readonly 'x5t#S256': string;
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
/** The largest clock skew a verifier may allow, in seconds. */
|
|
40
|
+
export declare const MAX_CLOCK_SKEW_S = 300;
|
|
41
|
+
/** The default clock skew, in seconds. */
|
|
42
|
+
export declare const DEFAULT_CLOCK_SKEW_S = 60;
|
|
43
|
+
/** The default longest token lifetime (`exp - iat`), in seconds. */
|
|
44
|
+
export declare const DEFAULT_MAX_TOKEN_LIFETIME_S = 3600;
|
|
45
|
+
/** The default scope limit. */
|
|
46
|
+
export declare const DEFAULT_SCOPE_LIMIT = 64;
|
|
47
|
+
/** The most Unicode code points a `jti`, `sub`, `client_id` or `acr` may hold. */
|
|
48
|
+
export declare const MAX_CLAIM_CHARS = 255;
|
|
49
|
+
/** What {@link createTokenRules} takes. */
|
|
50
|
+
export interface TokenRulesOptions {
|
|
51
|
+
/** The resource: the only audience accepted, and the credentials' `resource`. */
|
|
52
|
+
resource: string;
|
|
53
|
+
/** The clock skew allowed on `exp`, `iat` and `nbf`, in seconds. Default 60, at most 300. */
|
|
54
|
+
clockSkewS?: number;
|
|
55
|
+
/** The longest `exp - iat` accepted, in seconds. Default 3600, at least 1. */
|
|
56
|
+
maxTokenLifetimeS?: number;
|
|
57
|
+
/** Count only scopes starting with `<prefix>:` against the limit. Default: every scope. */
|
|
58
|
+
scopePrefix?: string;
|
|
59
|
+
/** The most scopes a token may hold (under the prefix, when set). Default 64, at least 1. */
|
|
60
|
+
scopeLimit?: number;
|
|
61
|
+
/** Refuse every token that is not bound to the TLS client certificate. Default `false`. */
|
|
62
|
+
requireBoundTokens?: boolean;
|
|
63
|
+
}
|
|
64
|
+
/** The rules a verified token's claims must pass (M3 rules 6 to 10), checked and frozen. */
|
|
65
|
+
export interface TokenRules {
|
|
66
|
+
readonly resource: string;
|
|
67
|
+
readonly clockSkewS: number;
|
|
68
|
+
readonly maxTokenLifetimeS: number;
|
|
69
|
+
readonly scopePrefix: string | undefined;
|
|
70
|
+
readonly scopeLimit: number;
|
|
71
|
+
readonly requireBoundTokens: boolean;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* The claim rules for tokens whose audience is `options.resource`.
|
|
75
|
+
*
|
|
76
|
+
* @throws Error when the resource is not an absolute `https` URL without user information, query
|
|
77
|
+
* or fragment, the skew is over 300 seconds, the lifetime or limit is under 1, or the prefix
|
|
78
|
+
* is not a scope token
|
|
79
|
+
*/
|
|
80
|
+
export declare function createTokenRules(options: TokenRulesOptions): TokenRules;
|
|
81
|
+
/** A rule's outcome: a value, or the code of the rule that refused. */
|
|
82
|
+
export type RuleResult<T> = {
|
|
83
|
+
ok: true;
|
|
84
|
+
value: T;
|
|
85
|
+
} | {
|
|
86
|
+
ok: false;
|
|
87
|
+
rule: AuthRuleCode;
|
|
88
|
+
};
|
|
89
|
+
/**
|
|
90
|
+
* A `scope` claim parsed (`spec/authorization.md`, M3.2; `undefined` when absent): scope tokens
|
|
91
|
+
* separated by single spaces, each kept once at its first place. An empty string or no claim
|
|
92
|
+
* grants no scope. Only scopes starting with `<prefix>:` count against `limit` when a prefix is
|
|
93
|
+
* given. Refused with `scope-malformed` or `scopes-too-many`.
|
|
94
|
+
*/
|
|
95
|
+
export declare function parseScopeClaim(scope: unknown, prefix: string | undefined, limit: number): RuleResult<string[]>;
|
|
96
|
+
/** The JWS algorithms AFD's verifier can check. `none` and `HS*` are always refused. */
|
|
97
|
+
export type SigningAlgorithm = 'RS256' | 'RS384' | 'RS512' | 'PS256' | 'PS384' | 'PS512' | 'ES256' | 'ES384' | 'EdDSA';
|
|
98
|
+
/** Every {@link SigningAlgorithm}. */
|
|
99
|
+
export declare const SIGNING_ALGORITHMS: readonly SigningAlgorithm[];
|
|
100
|
+
/**
|
|
101
|
+
* Rule 2 on a decoded JWS header, against the issuer's algorithm list: `typ`, then `alg`, `kid`,
|
|
102
|
+
* `crit` and the key references, the first broken rule refusing. `none` and every `HS*`
|
|
103
|
+
* algorithm are refused whatever the list says.
|
|
104
|
+
*/
|
|
105
|
+
export declare function checkJwsHeader(header: unknown, algorithms: readonly string[]): RuleResult<void>;
|
|
106
|
+
/**
|
|
107
|
+
* Rule 3 on a header that passed rule 2 and the issuer's key with its `kid` (`undefined` for
|
|
108
|
+
* none): the key's `kid` is the header's; its `kty` is the `alg`'s family; its `alg`, when
|
|
109
|
+
* present, is the header's; its `use`, when present, is `sig`; its `key_ops`, when present,
|
|
110
|
+
* contain `verify`. Refused with `key`.
|
|
111
|
+
*/
|
|
112
|
+
export declare function checkKeyFit(header: unknown, key: unknown): RuleResult<void>;
|
|
113
|
+
/**
|
|
114
|
+
* `fields` as credentials whose Node.js debug form (`util.inspect`, `console.log`) redacts every
|
|
115
|
+
* field but `issuer` and `expiresAt` (M4). JSON keeps every field.
|
|
116
|
+
*/
|
|
117
|
+
export declare function withRedactedInspect(fields: Credentials): Credentials;
|
|
118
|
+
/**
|
|
119
|
+
* Rules 5 to 10 on a token's claims after its signature (or on an introspection response), at
|
|
120
|
+
* `now` (whole seconds since the epoch), for `issuer` (its exact configured string) under
|
|
121
|
+
* `rules`. `certificate` is the SHA-256 thumbprint (unpadded base64url) of the request's TLS
|
|
122
|
+
* client certificate, `undefined` for none.
|
|
123
|
+
*
|
|
124
|
+
* Rule 10 also refuses a `cnf` that is not an object, and one holding a confirmation method
|
|
125
|
+
* other than `x5t#S256` (`jkt` is `dpop-unsupported`, anything else `binding`).
|
|
126
|
+
*/
|
|
127
|
+
export declare function checkClaims(claims: Record<string, unknown>, issuer: string, rules: TokenRules, now: number, certificate?: string): RuleResult<Credentials>;
|
|
128
|
+
/**
|
|
129
|
+
* An RFC 7662 introspection response for the one issuer configured for introspection
|
|
130
|
+
* (`spec/authorization.md`, M3, "Introspection"): `active` must be `true` (else `inactive`), and
|
|
131
|
+
* `exp`, `iat`, `iss`, `aud`, `sub` and `client_id` must be present (else `claims`); rules 5 to
|
|
132
|
+
* 10 ({@link checkClaims}) then apply to it, `jti` among rule 7's claims.
|
|
133
|
+
*/
|
|
134
|
+
export declare function checkIntrospection(response: unknown, issuer: string, rules: TokenRules, now: number, certificate?: string): RuleResult<Credentials>;
|
|
135
|
+
//# sourceMappingURL=mcp-auth-rules.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcp-auth-rules.d.ts","sourceRoot":"","sources":["../src/mcp-auth-rules.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,mGAAmG;AACnG,MAAM,MAAM,YAAY,GACrB,UAAU,GACV,gBAAgB,GAChB,iBAAiB,GACjB,gBAAgB,GAChB,KAAK,GACL,KAAK,GACL,KAAK,GACL,MAAM,GACN,eAAe,GACf,KAAK,GACL,WAAW,GACX,QAAQ,GACR,UAAU,GACV,QAAQ,GACR,SAAS,GACT,eAAe,GACf,UAAU,GACV,iBAAiB,GACjB,iBAAiB,GACjB,kBAAkB,GAClB,SAAS,GACT,UAAU,GACV,aAAa,CAAC;AAEjB,qDAAqD;AACrD,eAAO,MAAM,eAAe,EAAE,SAAS,YAAY,EAwBjD,CAAC;AAEH;;;GAGG;AACH,MAAM,WAAW,WAAW;IAC3B,gDAAgD;IAChD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,0BAA0B;IAC1B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,6DAA6D;IAC7D,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,+DAA+D;IAC/D,QAAQ,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC;IACnC,2FAA2F;IAC3F,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,6DAA6D;IAC7D,QAAQ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,WAAW,CAAC,EAAE,MAAM,GAClB,UAAU,CAAC,WAAW,CAAC,CAmDzB;AAID;;;;;GAKG;AACH,wBAAgB,kBAAkB,CACjC,QAAQ,EAAE,OAAO,EACjB,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,UAAU,EACjB,GAAG,EAAE,MAAM,EACX,WAAW,CAAC,EAAE,MAAM,GAClB,UAAU,CAAC,WAAW,CAAC,CAMzB"}
|
|
@@ -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
|