@c9up/visa 0.1.1 → 0.1.2
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/dist/VisaManager.d.ts +40 -7
- package/dist/VisaManager.d.ts.map +1 -1
- package/dist/VisaManager.js +79 -3
- package/dist/VisaManager.js.map +1 -1
- package/dist/VisaProvider.d.ts.map +1 -1
- package/dist/VisaProvider.js +56 -0
- package/dist/VisaProvider.js.map +1 -1
- package/dist/authorize.d.ts +18 -0
- package/dist/authorize.d.ts.map +1 -1
- package/dist/authorize.js +6 -0
- package/dist/authorize.js.map +1 -1
- package/dist/config.d.ts +35 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js.map +1 -1
- package/dist/errors.d.ts +9 -3
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js.map +1 -1
- package/dist/guard.d.ts +21 -0
- package/dist/guard.d.ts.map +1 -1
- package/dist/guard.js +19 -0
- package/dist/guard.js.map +1 -1
- package/dist/index.d.ts +5 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/introspect.d.ts +9 -1
- package/dist/introspect.d.ts.map +1 -1
- package/dist/introspect.js +18 -1
- package/dist/introspect.js.map +1 -1
- package/dist/protectedResource.d.ts +81 -0
- package/dist/protectedResource.d.ts.map +1 -0
- package/dist/protectedResource.js +124 -0
- package/dist/protectedResource.js.map +1 -0
- package/dist/register.d.ts +96 -0
- package/dist/register.d.ts.map +1 -0
- package/dist/register.js +173 -0
- package/dist/register.js.map +1 -0
- package/dist/resource.d.ts +50 -0
- package/dist/resource.d.ts.map +1 -0
- package/dist/resource.js +101 -0
- package/dist/resource.js.map +1 -0
- package/dist/store.d.ts +25 -0
- package/dist/store.d.ts.map +1 -1
- package/dist/stores/atlas.d.ts +7 -0
- package/dist/stores/atlas.d.ts.map +1 -1
- package/dist/stores/atlas.js +70 -16
- package/dist/stores/atlas.js.map +1 -1
- package/dist/stores/memory.d.ts +4 -0
- package/dist/stores/memory.d.ts.map +1 -1
- package/dist/stores/memory.js +25 -0
- package/dist/stores/memory.js.map +1 -1
- package/dist/token.d.ts +2 -0
- package/dist/token.d.ts.map +1 -1
- package/dist/token.js +21 -1
- package/dist/token.js.map +1 -1
- package/dist/types.d.ts +42 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/VisaManager.ts +109 -3
- package/src/VisaProvider.ts +64 -0
- package/src/authorize.ts +27 -0
- package/src/config.ts +35 -0
- package/src/errors.ts +16 -2
- package/src/guard.ts +30 -0
- package/src/index.ts +25 -0
- package/src/introspect.ts +17 -0
- package/src/protectedResource.ts +171 -0
- package/src/register.ts +296 -0
- package/src/resource.ts +123 -0
- package/src/store.ts +29 -0
- package/src/stores/atlas.ts +99 -15
- package/src/stores/memory.ts +33 -0
- package/src/token.ts +45 -1
- package/src/types.ts +43 -0
- package/stubs/database/migrations/9000_create_visa_tables.stub +9 -0
package/src/errors.ts
CHANGED
|
@@ -19,6 +19,8 @@ export type AuthorizationErrorCode =
|
|
|
19
19
|
| "access_denied"
|
|
20
20
|
| "unsupported_response_type"
|
|
21
21
|
| "invalid_scope"
|
|
22
|
+
/** RFC 8707 §2 — a resource this server will not issue for, or cannot parse. */
|
|
23
|
+
| "invalid_target"
|
|
22
24
|
| "server_error"
|
|
23
25
|
| "temporarily_unavailable";
|
|
24
26
|
|
|
@@ -29,9 +31,21 @@ export type TokenErrorCode =
|
|
|
29
31
|
| "invalid_grant"
|
|
30
32
|
| "unauthorized_client"
|
|
31
33
|
| "unsupported_grant_type"
|
|
32
|
-
| "invalid_scope"
|
|
34
|
+
| "invalid_scope"
|
|
35
|
+
/** RFC 8707 §2. */
|
|
36
|
+
| "invalid_target";
|
|
37
|
+
|
|
38
|
+
/** Error codes the registration endpoint may return (RFC 7591 §3.2.2). */
|
|
39
|
+
export type RegistrationErrorCode =
|
|
40
|
+
| "invalid_redirect_uri"
|
|
41
|
+
| "invalid_client_metadata"
|
|
42
|
+
| "invalid_software_statement"
|
|
43
|
+
| "unapproved_software_statement";
|
|
33
44
|
|
|
34
|
-
export type ProtocolErrorCode =
|
|
45
|
+
export type ProtocolErrorCode =
|
|
46
|
+
| AuthorizationErrorCode
|
|
47
|
+
| TokenErrorCode
|
|
48
|
+
| RegistrationErrorCode;
|
|
35
49
|
|
|
36
50
|
/**
|
|
37
51
|
* A failure the client is told about, in the words the spec chose.
|
package/src/guard.ts
CHANGED
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
|
|
22
22
|
import { hashSecret, randomToken } from "./crypto.js";
|
|
23
23
|
import { verifyAccessToken } from "./introspect.js";
|
|
24
|
+
import { wwwAuthenticate } from "./protectedResource.js";
|
|
24
25
|
import type { VisaStore } from "./store.js";
|
|
25
26
|
|
|
26
27
|
/**
|
|
@@ -214,6 +215,14 @@ export interface VisaGuardConfig {
|
|
|
214
215
|
tokenClientId?: string;
|
|
215
216
|
/** How long a minted token lasts — upstream's `expiresIn`, in seconds. */
|
|
216
217
|
expiresInSeconds?: number;
|
|
218
|
+
/**
|
|
219
|
+
* The protected resource this guard stands in front of (RFC 9728).
|
|
220
|
+
*
|
|
221
|
+
* Given, {@link VisaGuard.challenge} returns a `WWW-Authenticate` naming
|
|
222
|
+
* the metadata document, which is how an MCP client finds the
|
|
223
|
+
* authorization server without being told where it is.
|
|
224
|
+
*/
|
|
225
|
+
resource?: string;
|
|
217
226
|
}
|
|
218
227
|
|
|
219
228
|
/**
|
|
@@ -331,6 +340,27 @@ export class VisaGuard {
|
|
|
331
340
|
return { headers: { authorization: `Bearer ${token.value}` } };
|
|
332
341
|
}
|
|
333
342
|
|
|
343
|
+
/**
|
|
344
|
+
* The `WWW-Authenticate` value a 401 from this guard should carry.
|
|
345
|
+
*
|
|
346
|
+
* Returned rather than set: a warden strategy answers whether a credential
|
|
347
|
+
* is good, and the response belongs to whoever refuses the request. An
|
|
348
|
+
* exception handler sets it — `response.header('www-authenticate',
|
|
349
|
+
* guard.challenge())` — and with it a client that has no token learns
|
|
350
|
+
* where to get one instead of hitting a dead end.
|
|
351
|
+
*/
|
|
352
|
+
challenge(
|
|
353
|
+
options: { error?: string; scope?: readonly string[] } = {},
|
|
354
|
+
): string {
|
|
355
|
+
return wwwAuthenticate({
|
|
356
|
+
...(this.#config.resource === undefined
|
|
357
|
+
? {}
|
|
358
|
+
: { resource: this.#config.resource }),
|
|
359
|
+
...(options.error === undefined ? {} : { error: options.error }),
|
|
360
|
+
...(options.scope === undefined ? {} : { scope: options.scope }),
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
|
|
334
364
|
async verify(presented: string): Promise<GuardResult> {
|
|
335
365
|
const store = this.#store();
|
|
336
366
|
const now = new Date();
|
package/src/index.ts
CHANGED
|
@@ -36,6 +36,7 @@ export {
|
|
|
36
36
|
type AuthorizationErrorCode,
|
|
37
37
|
OAuthError,
|
|
38
38
|
type ProtocolErrorCode,
|
|
39
|
+
type RegistrationErrorCode,
|
|
39
40
|
type TokenErrorCode,
|
|
40
41
|
VisaError,
|
|
41
42
|
} from "./errors.js";
|
|
@@ -50,6 +51,29 @@ export {
|
|
|
50
51
|
visaGuard,
|
|
51
52
|
} from "./guard.js";
|
|
52
53
|
export { introspect, revoke, verifyAccessToken } from "./introspect.js";
|
|
54
|
+
export {
|
|
55
|
+
assertResourceIdentifier,
|
|
56
|
+
type ChallengeOptions,
|
|
57
|
+
PROTECTED_RESOURCE_PATH,
|
|
58
|
+
type ProtectedResourceMetadata,
|
|
59
|
+
type ProtectedResourceOptions,
|
|
60
|
+
protectedResourceMetadata,
|
|
61
|
+
protectedResourceMetadataUrl,
|
|
62
|
+
wwwAuthenticate,
|
|
63
|
+
} from "./protectedResource.js";
|
|
64
|
+
export {
|
|
65
|
+
type ClientRegistrationRequest,
|
|
66
|
+
type ClientRegistrationResponse,
|
|
67
|
+
type RegistrationOptions,
|
|
68
|
+
registrationResponse,
|
|
69
|
+
validateRegistration,
|
|
70
|
+
} from "./register.js";
|
|
71
|
+
export {
|
|
72
|
+
audienceAllows,
|
|
73
|
+
narrowResources,
|
|
74
|
+
readResourceParameter,
|
|
75
|
+
validateResources,
|
|
76
|
+
} from "./resource.js";
|
|
53
77
|
export {
|
|
54
78
|
clearVisa,
|
|
55
79
|
default as visa,
|
|
@@ -68,6 +92,7 @@ export { type TokenOptions, type TokenRequest, token } from "./token.js";
|
|
|
68
92
|
export type {
|
|
69
93
|
AccessToken,
|
|
70
94
|
AuthorizationCode,
|
|
95
|
+
AuthorizedApplication,
|
|
71
96
|
Client,
|
|
72
97
|
ClientAuthMethod,
|
|
73
98
|
Consent,
|
package/src/introspect.ts
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
import { authenticateClient, type ClientCredentials } from "./clients.js";
|
|
11
11
|
import { hashSecret } from "./crypto.js";
|
|
12
12
|
import { OAuthError } from "./errors.js";
|
|
13
|
+
import { audienceAllows } from "./resource.js";
|
|
13
14
|
import type { VisaStore } from "./store.js";
|
|
14
15
|
import type { IntrospectionResponse } from "./types.js";
|
|
15
16
|
|
|
@@ -55,6 +56,9 @@ export async function introspect(
|
|
|
55
56
|
token_type: "Bearer",
|
|
56
57
|
exp: Math.floor(access.expiresAt.getTime() / 1000),
|
|
57
58
|
...(access.userId === undefined ? {} : { sub: access.userId }),
|
|
59
|
+
// RFC 8707 §3 names introspection as where a resource server learns
|
|
60
|
+
// what a token was minted for.
|
|
61
|
+
...(access.audience === undefined ? {} : { aud: access.audience }),
|
|
58
62
|
};
|
|
59
63
|
}
|
|
60
64
|
|
|
@@ -125,16 +129,28 @@ export async function verifyAccessToken(
|
|
|
125
129
|
// not have to implement eleven methods it never calls.
|
|
126
130
|
store: Pick<VisaStore, "findAccessToken">,
|
|
127
131
|
now: Date = new Date(),
|
|
132
|
+
/**
|
|
133
|
+
* This resource's identifier (RFC 8707).
|
|
134
|
+
*
|
|
135
|
+
* Given, a token minted for a different resource is refused here rather
|
|
136
|
+
* than honoured — which is the entire point of binding one.
|
|
137
|
+
*/
|
|
138
|
+
resource?: string,
|
|
128
139
|
): Promise<{
|
|
129
140
|
clientId: string;
|
|
130
141
|
userId?: string;
|
|
131
142
|
scopes: string[];
|
|
132
143
|
expiresAt: Date;
|
|
133
144
|
lastUsedAt?: Date;
|
|
145
|
+
audience?: string[];
|
|
134
146
|
} | null> {
|
|
135
147
|
const token = await store.findAccessToken(hashSecret(presented));
|
|
136
148
|
if (token === null) return null;
|
|
137
149
|
if (token.revokedAt !== undefined || token.expiresAt <= now) return null;
|
|
150
|
+
// RFC 8707: a token bound to a resource is refused anywhere else. Unbound
|
|
151
|
+
// tokens are accepted — that is every token issued before a client started
|
|
152
|
+
// asking, and refusing them would break each one.
|
|
153
|
+
if (!audienceAllows(token.audience, resource)) return null;
|
|
138
154
|
return {
|
|
139
155
|
clientId: token.clientId,
|
|
140
156
|
...(token.userId === undefined ? {} : { userId: token.userId }),
|
|
@@ -145,6 +161,7 @@ export async function verifyAccessToken(
|
|
|
145
161
|
// The PREVIOUS use, before this one is recorded — which is what the
|
|
146
162
|
// upstream guard shows on `currentAccessToken.lastUsedAt`.
|
|
147
163
|
...(token.lastUsedAt === undefined ? {} : { lastUsedAt: token.lastUsedAt }),
|
|
164
|
+
...(token.audience === undefined ? {} : { audience: token.audience }),
|
|
148
165
|
};
|
|
149
166
|
}
|
|
150
167
|
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a protected resource says when it refuses, so a client can find its way
|
|
3
|
+
* in on its own (RFC 9728).
|
|
4
|
+
*
|
|
5
|
+
* Without this, a 401 is a dead end: the caller knows it needs a token and has
|
|
6
|
+
* no way to learn where tokens come from. With it, the refusal names a
|
|
7
|
+
* metadata document, the document names the authorization server, and an MCP
|
|
8
|
+
* client walks from one to the other unattended. That is the whole point — it
|
|
9
|
+
* is the difference between an agent that can connect and one that needs
|
|
10
|
+
* somebody to paste a URL into a config file.
|
|
11
|
+
*
|
|
12
|
+
* Nothing here is visa-specific: a resource server is free to be a different
|
|
13
|
+
* process from the authorization server, which is why the metadata takes the
|
|
14
|
+
* issuer as a value rather than reading one.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/** The metadata document, §3.2. Only `resource` is required. */
|
|
18
|
+
export interface ProtectedResourceMetadata {
|
|
19
|
+
resource: string;
|
|
20
|
+
authorization_servers?: string[];
|
|
21
|
+
scopes_supported?: string[];
|
|
22
|
+
bearer_methods_supported?: string[];
|
|
23
|
+
resource_name?: string;
|
|
24
|
+
resource_documentation?: string;
|
|
25
|
+
jwks_uri?: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface ProtectedResourceOptions {
|
|
29
|
+
/** This resource's identifier — an absolute URI, no fragment. */
|
|
30
|
+
resource: string;
|
|
31
|
+
/** The authorization servers that issue tokens for it. */
|
|
32
|
+
authorizationServers?: readonly string[];
|
|
33
|
+
/** What a client may ask for here. RECOMMENDED by §3.2. */
|
|
34
|
+
scopesSupported?: readonly string[];
|
|
35
|
+
/** Where the token may travel. Defaults to the header, which is all visa reads. */
|
|
36
|
+
bearerMethodsSupported?: readonly string[];
|
|
37
|
+
resourceName?: string;
|
|
38
|
+
resourceDocumentation?: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The path the document is served at, §3. */
|
|
42
|
+
export const PROTECTED_RESOURCE_PATH = "/.well-known/oauth-protected-resource";
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The well-known URL for a resource identifier.
|
|
46
|
+
*
|
|
47
|
+
* §3 inserts the well-known segment BETWEEN the host and the path, so a
|
|
48
|
+
* resource at `https://api.example/mcp` publishes at
|
|
49
|
+
* `https://api.example/.well-known/oauth-protected-resource/mcp` — not at the
|
|
50
|
+
* resource's own path with the segment appended, which is the easy mistake and
|
|
51
|
+
* the one that leaves a client fetching 404s.
|
|
52
|
+
*/
|
|
53
|
+
export function protectedResourceMetadataUrl(resource: string): string {
|
|
54
|
+
const url = new URL(resource);
|
|
55
|
+
const path = url.pathname === "/" ? "" : url.pathname.replace(/\/$/, "");
|
|
56
|
+
url.pathname = `${PROTECTED_RESOURCE_PATH}${path}`;
|
|
57
|
+
url.search = "";
|
|
58
|
+
url.hash = "";
|
|
59
|
+
return url.href;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Build the document a client fetches after a 401. */
|
|
63
|
+
export function protectedResourceMetadata(
|
|
64
|
+
options: ProtectedResourceOptions,
|
|
65
|
+
): ProtectedResourceMetadata {
|
|
66
|
+
assertResourceIdentifier(options.resource);
|
|
67
|
+
return {
|
|
68
|
+
resource: options.resource,
|
|
69
|
+
...(options.authorizationServers === undefined
|
|
70
|
+
? {}
|
|
71
|
+
: { authorization_servers: [...options.authorizationServers] }),
|
|
72
|
+
...(options.scopesSupported === undefined
|
|
73
|
+
? {}
|
|
74
|
+
: { scopes_supported: [...options.scopesSupported] }),
|
|
75
|
+
bearer_methods_supported: [
|
|
76
|
+
...(options.bearerMethodsSupported ?? ["header"]),
|
|
77
|
+
],
|
|
78
|
+
...(options.resourceName === undefined
|
|
79
|
+
? {}
|
|
80
|
+
: { resource_name: options.resourceName }),
|
|
81
|
+
...(options.resourceDocumentation === undefined
|
|
82
|
+
? {}
|
|
83
|
+
: { resource_documentation: options.resourceDocumentation }),
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export interface ChallengeOptions {
|
|
88
|
+
/** Where the metadata lives. Derived from the resource when omitted. */
|
|
89
|
+
resourceMetadata?: string;
|
|
90
|
+
/** This resource's identifier, used to derive the metadata URL. */
|
|
91
|
+
resource?: string;
|
|
92
|
+
/** `invalid_token`, `insufficient_scope` — RFC 6750 §3.1. */
|
|
93
|
+
error?: string;
|
|
94
|
+
errorDescription?: string;
|
|
95
|
+
/** What the caller would have needed, with `insufficient_scope`. */
|
|
96
|
+
scope?: readonly string[];
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* The `WWW-Authenticate` value for a 401, §5.1.
|
|
101
|
+
*
|
|
102
|
+
* Quoted values are checked rather than escaped: the header is a
|
|
103
|
+
* comma-separated list of quoted strings, and a value carrying a quote or a
|
|
104
|
+
* control character cannot be represented in it at all. A caller that built
|
|
105
|
+
* one from user input should hear about it here, not ship a header a client
|
|
106
|
+
* parses into something else.
|
|
107
|
+
*/
|
|
108
|
+
export function wwwAuthenticate(options: ChallengeOptions = {}): string {
|
|
109
|
+
const metadataUrl =
|
|
110
|
+
options.resourceMetadata ??
|
|
111
|
+
(options.resource === undefined
|
|
112
|
+
? undefined
|
|
113
|
+
: protectedResourceMetadataUrl(options.resource));
|
|
114
|
+
|
|
115
|
+
const parameters: Array<[string, string]> = [];
|
|
116
|
+
if (options.error !== undefined) parameters.push(["error", options.error]);
|
|
117
|
+
if (options.errorDescription !== undefined) {
|
|
118
|
+
parameters.push(["error_description", options.errorDescription]);
|
|
119
|
+
}
|
|
120
|
+
if (options.scope !== undefined && options.scope.length > 0) {
|
|
121
|
+
parameters.push(["scope", options.scope.join(" ")]);
|
|
122
|
+
}
|
|
123
|
+
if (metadataUrl !== undefined) {
|
|
124
|
+
parameters.push(["resource_metadata", metadataUrl]);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
if (parameters.length === 0) return "Bearer";
|
|
128
|
+
const rendered = parameters
|
|
129
|
+
.map(([key, value]) => `${key}="${quotable(value, key)}"`)
|
|
130
|
+
.join(", ");
|
|
131
|
+
return `Bearer ${rendered}`;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function quotable(value: string, parameter: string): string {
|
|
135
|
+
// A quoted-string holds neither a bare quote nor a control character, and
|
|
136
|
+
// neither can be escaped into one usefully — a client would read the header
|
|
137
|
+
// as a different set of parameters.
|
|
138
|
+
for (const character of value) {
|
|
139
|
+
const code = character.codePointAt(0) ?? 0;
|
|
140
|
+
if (
|
|
141
|
+
character === '"' ||
|
|
142
|
+
character === "\\" ||
|
|
143
|
+
code < 0x20 ||
|
|
144
|
+
code === 0x7f
|
|
145
|
+
) {
|
|
146
|
+
throw new Error(
|
|
147
|
+
`[visa] ${parameter} cannot go in a WWW-Authenticate header: it holds a quote, a backslash or a control character`,
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return value;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* A resource identifier is an absolute URI with no fragment (RFC 8707 §2).
|
|
156
|
+
*
|
|
157
|
+
* Checked where the metadata is built, because a resource that publishes an
|
|
158
|
+
* identifier its own tokens will not match is broken in a way only visible at
|
|
159
|
+
* the moment a client is refused.
|
|
160
|
+
*/
|
|
161
|
+
export function assertResourceIdentifier(resource: string): void {
|
|
162
|
+
let url: URL;
|
|
163
|
+
try {
|
|
164
|
+
url = new URL(resource);
|
|
165
|
+
} catch {
|
|
166
|
+
throw new Error(`[visa] resource must be an absolute URI: ${resource}`);
|
|
167
|
+
}
|
|
168
|
+
if (url.hash !== "") {
|
|
169
|
+
throw new Error(`[visa] resource must not carry a fragment: ${resource}`);
|
|
170
|
+
}
|
|
171
|
+
}
|
package/src/register.ts
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Clients that register themselves (RFC 7591).
|
|
3
|
+
*
|
|
4
|
+
* An MCP client such as claude.ai or ChatGPT has nobody to fill in a form for
|
|
5
|
+
* it: it discovers this server, registers, and comes back with an id. Without
|
|
6
|
+
* this the only way in is a human pasting credentials somewhere.
|
|
7
|
+
*
|
|
8
|
+
* OFF unless the application turns it on, and that is the important part. Open
|
|
9
|
+
* registration means anyone who can reach the endpoint can create a client —
|
|
10
|
+
* the RFC says a server SHOULD allow it for interoperability, and also says
|
|
11
|
+
* the endpoint MAY be protected (§1.2, §3). The safe default here is the one
|
|
12
|
+
* the RFC permits rather than the one it encourages, because an authorization
|
|
13
|
+
* server that silently accepts registrations is a thing nobody asked for. Turn
|
|
14
|
+
* it on deliberately, and with an initial access token if the deployment is
|
|
15
|
+
* not meant to be open.
|
|
16
|
+
*
|
|
17
|
+
* A registered client gets exactly what this server allows: the grants,
|
|
18
|
+
* scopes and auth methods in the configuration, never what the request asked
|
|
19
|
+
* for. That is the difference between letting a client name itself and letting
|
|
20
|
+
* it decide what it may do.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { OAuthError } from "./errors.js";
|
|
24
|
+
import type { Client, ClientAuthMethod, GrantType } from "./types.js";
|
|
25
|
+
|
|
26
|
+
/** The metadata a request may send (§2). Unknown members are ignored. */
|
|
27
|
+
export interface ClientRegistrationRequest {
|
|
28
|
+
redirect_uris?: unknown;
|
|
29
|
+
token_endpoint_auth_method?: unknown;
|
|
30
|
+
grant_types?: unknown;
|
|
31
|
+
response_types?: unknown;
|
|
32
|
+
client_name?: unknown;
|
|
33
|
+
client_uri?: unknown;
|
|
34
|
+
logo_uri?: unknown;
|
|
35
|
+
scope?: unknown;
|
|
36
|
+
contacts?: unknown;
|
|
37
|
+
tos_uri?: unknown;
|
|
38
|
+
policy_uri?: unknown;
|
|
39
|
+
software_id?: unknown;
|
|
40
|
+
software_version?: unknown;
|
|
41
|
+
software_statement?: unknown;
|
|
42
|
+
/**
|
|
43
|
+
* Whatever else the client sent.
|
|
44
|
+
*
|
|
45
|
+
* §2 says a server ignores metadata it does not understand, and this is a
|
|
46
|
+
* parsed HTTP body — a client that sends `client_id` hoping to pick its own
|
|
47
|
+
* is a real thing, and it lands here rather than being a type error nobody
|
|
48
|
+
* sees at run time.
|
|
49
|
+
*/
|
|
50
|
+
[member: string]: unknown;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The 201 body (§3.2.1). */
|
|
54
|
+
export interface ClientRegistrationResponse {
|
|
55
|
+
client_id: string;
|
|
56
|
+
client_secret?: string;
|
|
57
|
+
/** Seconds since the epoch. */
|
|
58
|
+
client_id_issued_at: number;
|
|
59
|
+
/** REQUIRED when a secret was issued. `0` means it does not expire. */
|
|
60
|
+
client_secret_expires_at?: number;
|
|
61
|
+
redirect_uris: string[];
|
|
62
|
+
grant_types: GrantType[];
|
|
63
|
+
token_endpoint_auth_method: ClientAuthMethod;
|
|
64
|
+
client_name: string;
|
|
65
|
+
scope?: string;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface RegistrationOptions {
|
|
69
|
+
/** Nothing happens unless this is true. */
|
|
70
|
+
enabled?: boolean;
|
|
71
|
+
/**
|
|
72
|
+
* Require this bearer token on the registration request.
|
|
73
|
+
*
|
|
74
|
+
* Left out, the endpoint is open — which is what an MCP client that has
|
|
75
|
+
* never met you needs, and what a deployment on the public internet should
|
|
76
|
+
* think about before shipping.
|
|
77
|
+
*/
|
|
78
|
+
initialAccessToken?: string;
|
|
79
|
+
/** What a self-registered client may ever ask for. Defaults to none. */
|
|
80
|
+
scopes?: readonly string[];
|
|
81
|
+
/** Which grants it may use. Defaults to the authorization code flow and refresh. */
|
|
82
|
+
grantTypes?: readonly GrantType[];
|
|
83
|
+
/** Seconds until an issued secret expires. Omitted means it does not (§3.2.1). */
|
|
84
|
+
secretTtlSeconds?: number;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const DEFAULT_GRANTS: readonly GrantType[] = [
|
|
88
|
+
"authorization_code",
|
|
89
|
+
"refresh_token",
|
|
90
|
+
];
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Check a registration request and say what the client may be.
|
|
94
|
+
*
|
|
95
|
+
* Returns the client to store and the plaintext secret, if one was issued —
|
|
96
|
+
* the caller persists the first and hands back the second, once.
|
|
97
|
+
*/
|
|
98
|
+
export function validateRegistration(
|
|
99
|
+
request: ClientRegistrationRequest,
|
|
100
|
+
options: RegistrationOptions,
|
|
101
|
+
presentedToken?: string,
|
|
102
|
+
): {
|
|
103
|
+
redirectUris: string[];
|
|
104
|
+
grantTypes: GrantType[];
|
|
105
|
+
scopes: string[];
|
|
106
|
+
tokenEndpointAuthMethod: ClientAuthMethod;
|
|
107
|
+
name: string;
|
|
108
|
+
} {
|
|
109
|
+
if (options.enabled !== true) {
|
|
110
|
+
throw new OAuthError(
|
|
111
|
+
"invalid_client_metadata",
|
|
112
|
+
"This server does not accept client registrations.",
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
if (options.initialAccessToken !== undefined) {
|
|
116
|
+
// Constant-time is not the point here: the token is compared once per
|
|
117
|
+
// registration, and a registration endpoint is not a guessing oracle
|
|
118
|
+
// worth the machinery. Absent or wrong reads the same to the caller.
|
|
119
|
+
if (presentedToken !== options.initialAccessToken) {
|
|
120
|
+
throw new OAuthError(
|
|
121
|
+
"invalid_client_metadata",
|
|
122
|
+
"Registration on this server needs an initial access token.",
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const redirectUris = readStringList(request.redirect_uris);
|
|
128
|
+
const grantTypes = resolveGrants(request.grant_types, options);
|
|
129
|
+
|
|
130
|
+
// A client using the authorization code flow has somewhere to come back to,
|
|
131
|
+
// and this is the last moment anyone checks.
|
|
132
|
+
if (grantTypes.includes("authorization_code") && redirectUris.length === 0) {
|
|
133
|
+
throw new OAuthError(
|
|
134
|
+
"invalid_redirect_uri",
|
|
135
|
+
"redirect_uris is required for the authorization_code grant.",
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
for (const uri of redirectUris) assertRedirectUri(uri);
|
|
139
|
+
|
|
140
|
+
const allowed = options.scopes ?? [];
|
|
141
|
+
const requested = readScope(request.scope);
|
|
142
|
+
const outside = requested.filter((scope) => !allowed.includes(scope));
|
|
143
|
+
if (outside.length > 0) {
|
|
144
|
+
throw new OAuthError(
|
|
145
|
+
"invalid_client_metadata",
|
|
146
|
+
`This server does not grant ${outside.join(", ")} to a self-registered client.`,
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return {
|
|
151
|
+
redirectUris,
|
|
152
|
+
grantTypes,
|
|
153
|
+
// What was asked for, narrowed to what is allowed — never the allowed
|
|
154
|
+
// set, or every client would be registered with everything.
|
|
155
|
+
scopes: requested,
|
|
156
|
+
tokenEndpointAuthMethod: readAuthMethod(request.token_endpoint_auth_method),
|
|
157
|
+
name: readName(request.client_name),
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** The 201 body for a client that was just created. */
|
|
162
|
+
export function registrationResponse(
|
|
163
|
+
client: Client,
|
|
164
|
+
issuedAt: Date,
|
|
165
|
+
secret: string | undefined,
|
|
166
|
+
options: RegistrationOptions,
|
|
167
|
+
): ClientRegistrationResponse {
|
|
168
|
+
const seconds = Math.floor(issuedAt.getTime() / 1000);
|
|
169
|
+
return {
|
|
170
|
+
client_id: client.id,
|
|
171
|
+
...(secret === undefined ? {} : { client_secret: secret }),
|
|
172
|
+
client_id_issued_at: seconds,
|
|
173
|
+
// REQUIRED when a secret was issued, and `0` is the spelling for "never"
|
|
174
|
+
// — not an omission, which would mean the field was not answered.
|
|
175
|
+
...(secret === undefined
|
|
176
|
+
? {}
|
|
177
|
+
: {
|
|
178
|
+
client_secret_expires_at:
|
|
179
|
+
options.secretTtlSeconds === undefined
|
|
180
|
+
? 0
|
|
181
|
+
: seconds + options.secretTtlSeconds,
|
|
182
|
+
}),
|
|
183
|
+
redirect_uris: client.redirectUris,
|
|
184
|
+
grant_types: client.grantTypes,
|
|
185
|
+
token_endpoint_auth_method: client.tokenEndpointAuthMethod,
|
|
186
|
+
client_name: client.name,
|
|
187
|
+
...(client.scopes.length === 0 ? {} : { scope: client.scopes.join(" ") }),
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function resolveGrants(
|
|
192
|
+
value: unknown,
|
|
193
|
+
options: RegistrationOptions,
|
|
194
|
+
): GrantType[] {
|
|
195
|
+
const allowed = options.grantTypes ?? DEFAULT_GRANTS;
|
|
196
|
+
const requested = readStringList(value);
|
|
197
|
+
if (requested.length === 0) return [...allowed];
|
|
198
|
+
const grants: GrantType[] = [];
|
|
199
|
+
for (const grant of requested) {
|
|
200
|
+
if (!isGrantType(grant) || !allowed.includes(grant)) {
|
|
201
|
+
throw new OAuthError(
|
|
202
|
+
"invalid_client_metadata",
|
|
203
|
+
`This server does not allow the ${grant} grant to a self-registered client.`,
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
if (!grants.includes(grant)) grants.push(grant);
|
|
207
|
+
}
|
|
208
|
+
return grants;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* A redirect URI a self-registered client may use.
|
|
213
|
+
*
|
|
214
|
+
* https, or http on a loopback address — a native app's callback. Anything
|
|
215
|
+
* else is refused: an authorization code sent over plain http to a host
|
|
216
|
+
* someone else controls is the code given away.
|
|
217
|
+
*/
|
|
218
|
+
function assertRedirectUri(value: string): void {
|
|
219
|
+
let url: URL;
|
|
220
|
+
try {
|
|
221
|
+
url = new URL(value);
|
|
222
|
+
} catch {
|
|
223
|
+
throw new OAuthError(
|
|
224
|
+
"invalid_redirect_uri",
|
|
225
|
+
`${value} is not an absolute URI.`,
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
if (url.hash !== "") {
|
|
229
|
+
throw new OAuthError(
|
|
230
|
+
"invalid_redirect_uri",
|
|
231
|
+
`${value} must not carry a fragment.`,
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
if (url.protocol === "https:") return;
|
|
235
|
+
const loopback =
|
|
236
|
+
url.hostname === "127.0.0.1" ||
|
|
237
|
+
url.hostname === "[::1]" ||
|
|
238
|
+
url.hostname === "localhost";
|
|
239
|
+
if (url.protocol === "http:" && loopback) return;
|
|
240
|
+
throw new OAuthError(
|
|
241
|
+
"invalid_redirect_uri",
|
|
242
|
+
`${value} must use https, or http on a loopback address.`,
|
|
243
|
+
);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function readStringList(value: unknown): string[] {
|
|
247
|
+
if (value === undefined || value === null) return [];
|
|
248
|
+
if (!Array.isArray(value)) {
|
|
249
|
+
throw new OAuthError(
|
|
250
|
+
"invalid_client_metadata",
|
|
251
|
+
"redirect_uris and grant_types must be arrays of strings.",
|
|
252
|
+
);
|
|
253
|
+
}
|
|
254
|
+
return value.filter((entry): entry is string => typeof entry === "string");
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function readScope(value: unknown): string[] {
|
|
258
|
+
if (value === undefined || value === null) return [];
|
|
259
|
+
if (typeof value !== "string") {
|
|
260
|
+
throw new OAuthError(
|
|
261
|
+
"invalid_client_metadata",
|
|
262
|
+
"scope must be a space-separated string.",
|
|
263
|
+
);
|
|
264
|
+
}
|
|
265
|
+
return value.split(/\s+/).filter((scope) => scope !== "");
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function readAuthMethod(value: unknown): ClientAuthMethod {
|
|
269
|
+
if (value === undefined || value === null) return "client_secret_basic";
|
|
270
|
+
if (
|
|
271
|
+
value === "client_secret_basic" ||
|
|
272
|
+
value === "client_secret_post" ||
|
|
273
|
+
value === "none"
|
|
274
|
+
) {
|
|
275
|
+
return value;
|
|
276
|
+
}
|
|
277
|
+
throw new OAuthError(
|
|
278
|
+
"invalid_client_metadata",
|
|
279
|
+
`token_endpoint_auth_method ${String(value)} is not supported.`,
|
|
280
|
+
);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function readName(value: unknown): string {
|
|
284
|
+
if (typeof value === "string" && value.trim() !== "") return value.trim();
|
|
285
|
+
// A client with no name shows as one on a consent screen, which is worse
|
|
286
|
+
// than a placeholder nobody mistakes for a brand.
|
|
287
|
+
return "Unnamed client";
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function isGrantType(value: string): value is GrantType {
|
|
291
|
+
return (
|
|
292
|
+
value === "authorization_code" ||
|
|
293
|
+
value === "refresh_token" ||
|
|
294
|
+
value === "client_credentials"
|
|
295
|
+
);
|
|
296
|
+
}
|