desearch-mcp-server 0.2.0 → 0.2.1
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/CHANGELOG.md +13 -1
- package/README.md +58 -4
- package/build/http.d.ts +2 -8
- package/build/http.d.ts.map +1 -1
- package/build/http.js +126 -37
- package/build/oauth/client-ip.d.ts +10 -0
- package/build/oauth/client-ip.d.ts.map +1 -0
- package/build/oauth/client-ip.js +28 -0
- package/build/oauth/crypto.d.ts +20 -0
- package/build/oauth/crypto.d.ts.map +1 -0
- package/build/oauth/crypto.js +89 -0
- package/build/oauth/errors.d.ts +9 -0
- package/build/oauth/errors.d.ts.map +1 -0
- package/build/oauth/errors.js +13 -0
- package/build/oauth/flow.d.ts +8 -0
- package/build/oauth/flow.d.ts.map +1 -0
- package/build/oauth/flow.js +424 -0
- package/build/oauth/http.d.ts +24 -0
- package/build/oauth/http.d.ts.map +1 -0
- package/build/oauth/http.js +137 -0
- package/build/oauth/metadata.d.ts +19 -0
- package/build/oauth/metadata.d.ts.map +1 -0
- package/build/oauth/metadata.js +86 -0
- package/build/oauth/page.d.ts +14 -0
- package/build/oauth/page.d.ts.map +1 -0
- package/build/oauth/page.js +92 -0
- package/build/oauth/rate-limit.d.ts +14 -0
- package/build/oauth/rate-limit.d.ts.map +1 -0
- package/build/oauth/rate-limit.js +19 -0
- package/build/oauth/redirects.d.ts +14 -0
- package/build/oauth/redirects.d.ts.map +1 -0
- package/build/oauth/redirects.js +78 -0
- package/build/oauth/store.d.ts +139 -0
- package/build/oauth/store.d.ts.map +1 -0
- package/build/oauth/store.js +606 -0
- package/build/oauth/validate-key.d.ts +21 -0
- package/build/oauth/validate-key.d.ts.map +1 -0
- package/build/oauth/validate-key.js +61 -0
- package/build/request-key.d.ts +9 -0
- package/build/request-key.d.ts.map +1 -0
- package/build/request-key.js +24 -0
- package/build/server.d.ts +1 -1
- package/build/server.d.ts.map +1 -1
- package/build/server.js +151 -5
- package/package.json +2 -1
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
import { ACCESS_TOKEN_PREFIX, AUTH_CODE_PREFIX, CLIENT_ID_PREFIX, REFRESH_TOKEN_PREFIX, challengesMatch, randomToken, s256Challenge, } from "./crypto.js";
|
|
2
|
+
import { canonicalResource, grantedScope, publicOrigin, resourcesMatch, } from "./metadata.js";
|
|
3
|
+
import { authorizePage, messagePage } from "./page.js";
|
|
4
|
+
import { authorizeKeyRateLimitConfig, registerRateLimitConfig, takeIpRateLimit } from "./rate-limit.js";
|
|
5
|
+
import { isAllowedRedirectUri, redirectsMatch } from "./redirects.js";
|
|
6
|
+
import { accessTtlSec, codeTtlSec, getOAuthStore, refreshTtlSec, } from "./store.js";
|
|
7
|
+
import { checkDesearchApiKey } from "./validate-key.js";
|
|
8
|
+
const VERIFIER_PATTERN = /^[A-Za-z0-9\-._~]{43,128}$/;
|
|
9
|
+
const HTML_HEADERS = {
|
|
10
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
11
|
+
"Cache-Control": "no-store",
|
|
12
|
+
"Referrer-Policy": "no-referrer",
|
|
13
|
+
"X-Frame-Options": "DENY",
|
|
14
|
+
"Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'",
|
|
15
|
+
};
|
|
16
|
+
export function htmlResponse(status, html) {
|
|
17
|
+
return new Response(html, { status, headers: HTML_HEADERS });
|
|
18
|
+
}
|
|
19
|
+
export function oauthError(status, error, description) {
|
|
20
|
+
return new Response(JSON.stringify({ error, error_description: description }), {
|
|
21
|
+
status,
|
|
22
|
+
headers: {
|
|
23
|
+
"Content-Type": "application/json",
|
|
24
|
+
"Cache-Control": "no-store",
|
|
25
|
+
},
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
function withRetryAfter(response, retryAfterSec) {
|
|
29
|
+
const headers = new Headers(response.headers);
|
|
30
|
+
headers.set("Retry-After", String(retryAfterSec));
|
|
31
|
+
return new Response(response.body, { status: response.status, headers });
|
|
32
|
+
}
|
|
33
|
+
function tooManyJson(retryAfterSec, description) {
|
|
34
|
+
return withRetryAfter(oauthError(429, "temporarily_unavailable", description), retryAfterSec);
|
|
35
|
+
}
|
|
36
|
+
function redirectBack(redirectUri, issuer, params) {
|
|
37
|
+
const url = new URL(redirectUri);
|
|
38
|
+
for (const [key, value] of Object.entries(params)) {
|
|
39
|
+
if (value) {
|
|
40
|
+
url.searchParams.set(key, value);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
url.searchParams.set("iss", issuer);
|
|
44
|
+
return new Response(null, {
|
|
45
|
+
status: 302,
|
|
46
|
+
headers: {
|
|
47
|
+
Location: url.toString(),
|
|
48
|
+
"Cache-Control": "no-store",
|
|
49
|
+
"Referrer-Policy": "no-referrer",
|
|
50
|
+
},
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
async function readJsonBody(request) {
|
|
54
|
+
const text = await request.text();
|
|
55
|
+
if (text.length > 32_000) {
|
|
56
|
+
throw new Error("body too large");
|
|
57
|
+
}
|
|
58
|
+
return JSON.parse(text);
|
|
59
|
+
}
|
|
60
|
+
async function readFormBody(request) {
|
|
61
|
+
const text = await request.text();
|
|
62
|
+
if (text.length > 32_000) {
|
|
63
|
+
throw new Error("body too large");
|
|
64
|
+
}
|
|
65
|
+
return new URLSearchParams(text);
|
|
66
|
+
}
|
|
67
|
+
function clientName(value) {
|
|
68
|
+
if (typeof value !== "string") {
|
|
69
|
+
return "MCP client";
|
|
70
|
+
}
|
|
71
|
+
const cleaned = value.replace(/[\u0000-\u001f\u007f]/g, "").trim().slice(0, 80);
|
|
72
|
+
return cleaned || "MCP client";
|
|
73
|
+
}
|
|
74
|
+
export async function registerClient(request) {
|
|
75
|
+
const registerLimit = registerRateLimitConfig();
|
|
76
|
+
const registration = await takeIpRateLimit(request, "register", registerLimit.limit, registerLimit.windowSec);
|
|
77
|
+
if (!registration.allowed) {
|
|
78
|
+
return tooManyJson(registration.retryAfterSec, "Too many registration attempts from this address. Try again later.");
|
|
79
|
+
}
|
|
80
|
+
const contentType = request.headers.get("content-type") ?? "";
|
|
81
|
+
if (!contentType.toLowerCase().includes("application/json")) {
|
|
82
|
+
return oauthError(400, "invalid_client_metadata", "Dynamic client registration requires application/json.");
|
|
83
|
+
}
|
|
84
|
+
let body;
|
|
85
|
+
try {
|
|
86
|
+
body = await readJsonBody(request);
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
return oauthError(400, "invalid_client_metadata", "Registration body must be JSON.");
|
|
90
|
+
}
|
|
91
|
+
if (!body || typeof body !== "object") {
|
|
92
|
+
return oauthError(400, "invalid_client_metadata", "Registration body must be a JSON object.");
|
|
93
|
+
}
|
|
94
|
+
const record = body;
|
|
95
|
+
const redirects = record.redirect_uris;
|
|
96
|
+
if (!Array.isArray(redirects) || redirects.length === 0 || redirects.length > 10) {
|
|
97
|
+
return oauthError(400, "invalid_redirect_uri", "redirect_uris must list 1 to 10 callback URLs.");
|
|
98
|
+
}
|
|
99
|
+
const redirectUris = [];
|
|
100
|
+
for (const entry of redirects) {
|
|
101
|
+
if (typeof entry !== "string" || !isAllowedRedirectUri(entry)) {
|
|
102
|
+
return oauthError(400, "invalid_redirect_uri", "One or more redirect_uris are not allowed.");
|
|
103
|
+
}
|
|
104
|
+
redirectUris.push(entry);
|
|
105
|
+
}
|
|
106
|
+
if (record.token_endpoint_auth_method && record.token_endpoint_auth_method !== "none") {
|
|
107
|
+
return oauthError(400, "invalid_client_metadata", "This server registers public clients. Use token_endpoint_auth_method none.");
|
|
108
|
+
}
|
|
109
|
+
const responseTypes = record.response_types;
|
|
110
|
+
if (responseTypes !== undefined) {
|
|
111
|
+
if (!Array.isArray(responseTypes) || responseTypes.some((entry) => entry !== "code")) {
|
|
112
|
+
return oauthError(400, "invalid_client_metadata", "Only response type code is supported.");
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
const grantTypes = record.grant_types;
|
|
116
|
+
if (grantTypes !== undefined) {
|
|
117
|
+
if (!Array.isArray(grantTypes) || grantTypes.some((entry) => entry !== "authorization_code" && entry !== "refresh_token")) {
|
|
118
|
+
return oauthError(400, "invalid_client_metadata", "Only authorization_code and refresh_token grants are supported.");
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
const client = {
|
|
122
|
+
clientId: randomToken(CLIENT_ID_PREFIX, 24),
|
|
123
|
+
clientName: clientName(record.client_name),
|
|
124
|
+
redirectUris,
|
|
125
|
+
tokenEndpointAuthMethod: "none",
|
|
126
|
+
createdAt: Date.now(),
|
|
127
|
+
};
|
|
128
|
+
const store = await getOAuthStore();
|
|
129
|
+
await store.saveClient(client);
|
|
130
|
+
return new Response(JSON.stringify({
|
|
131
|
+
client_id: client.clientId,
|
|
132
|
+
client_name: client.clientName,
|
|
133
|
+
redirect_uris: client.redirectUris,
|
|
134
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
135
|
+
response_types: ["code"],
|
|
136
|
+
token_endpoint_auth_method: "none",
|
|
137
|
+
}), {
|
|
138
|
+
status: 201,
|
|
139
|
+
headers: {
|
|
140
|
+
"Content-Type": "application/json",
|
|
141
|
+
"Cache-Control": "no-store",
|
|
142
|
+
},
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
function readAuthorizeQuery(params) {
|
|
146
|
+
return {
|
|
147
|
+
clientId: params.get("client_id") ?? "",
|
|
148
|
+
redirectUri: params.get("redirect_uri") ?? "",
|
|
149
|
+
state: params.get("state") ?? "",
|
|
150
|
+
codeChallenge: params.get("code_challenge") ?? "",
|
|
151
|
+
codeChallengeMethod: params.get("code_challenge_method") ?? "",
|
|
152
|
+
resource: params.get("resource") ?? "",
|
|
153
|
+
scope: params.get("scope") ?? "",
|
|
154
|
+
responseType: params.get("response_type") ?? "",
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
async function authorizeContext(request, query) {
|
|
158
|
+
if (!query.clientId || !query.redirectUri) {
|
|
159
|
+
return htmlResponse(400, messagePage("Connect Desearch", "This sign-in link is missing a client or callback."));
|
|
160
|
+
}
|
|
161
|
+
if (!isAllowedRedirectUri(query.redirectUri)) {
|
|
162
|
+
return htmlResponse(400, messagePage("Connect Desearch", "This callback URL is not allowed."));
|
|
163
|
+
}
|
|
164
|
+
const store = await getOAuthStore();
|
|
165
|
+
const client = await store.getClient(query.clientId);
|
|
166
|
+
if (!client || !client.redirectUris.some((uri) => redirectsMatch(uri, query.redirectUri))) {
|
|
167
|
+
return htmlResponse(400, messagePage("Connect Desearch", "This application is not registered for that callback."));
|
|
168
|
+
}
|
|
169
|
+
const fields = {
|
|
170
|
+
clientId: query.clientId,
|
|
171
|
+
redirectUri: query.redirectUri,
|
|
172
|
+
state: query.state,
|
|
173
|
+
codeChallenge: query.codeChallenge,
|
|
174
|
+
codeChallengeMethod: query.codeChallengeMethod,
|
|
175
|
+
resource: query.resource,
|
|
176
|
+
scope: query.scope,
|
|
177
|
+
clientName: client.clientName,
|
|
178
|
+
};
|
|
179
|
+
if (query.responseType !== "code") {
|
|
180
|
+
return failAuthorize(request, client, fields, "unsupported_response_type", "Only authorization code is supported.");
|
|
181
|
+
}
|
|
182
|
+
if (!query.state || query.state.length > 512) {
|
|
183
|
+
return failAuthorize(request, client, fields, "invalid_request", "A state value is required.");
|
|
184
|
+
}
|
|
185
|
+
if (query.codeChallengeMethod !== "S256" || !VERIFIER_PATTERN.test(query.codeChallenge)) {
|
|
186
|
+
return failAuthorize(request, client, fields, "invalid_request", "PKCE S256 is required.");
|
|
187
|
+
}
|
|
188
|
+
const resource = query.resource || canonicalResource(request);
|
|
189
|
+
if (!resourcesMatch(resource, canonicalResource(request))) {
|
|
190
|
+
return failAuthorize(request, client, fields, "invalid_target", "The requested resource does not match this server.");
|
|
191
|
+
}
|
|
192
|
+
fields.resource = canonicalResource(request);
|
|
193
|
+
return { client, fields };
|
|
194
|
+
}
|
|
195
|
+
function failAuthorize(request, client, fields, error, description) {
|
|
196
|
+
if (client.redirectUris.some((uri) => redirectsMatch(uri, fields.redirectUri)) &&
|
|
197
|
+
isAllowedRedirectUri(fields.redirectUri)) {
|
|
198
|
+
return redirectBack(fields.redirectUri, publicOrigin(request), {
|
|
199
|
+
error,
|
|
200
|
+
error_description: description,
|
|
201
|
+
state: fields.state,
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
return htmlResponse(400, messagePage("Connect Desearch", description));
|
|
205
|
+
}
|
|
206
|
+
export async function showAuthorize(request) {
|
|
207
|
+
const query = readAuthorizeQuery(new URL(request.url).searchParams);
|
|
208
|
+
const context = await authorizeContext(request, query);
|
|
209
|
+
if (context instanceof Response) {
|
|
210
|
+
return context;
|
|
211
|
+
}
|
|
212
|
+
return htmlResponse(200, authorizePage(context.fields));
|
|
213
|
+
}
|
|
214
|
+
function authorizePostForbidden(request) {
|
|
215
|
+
const fetchSite = request.headers.get("sec-fetch-site")?.trim().toLowerCase() ?? "";
|
|
216
|
+
if (fetchSite === "cross-site") {
|
|
217
|
+
return htmlResponse(400, messagePage("Connect Desearch", "This sign-in form was sent from another site."));
|
|
218
|
+
}
|
|
219
|
+
const expected = publicOrigin(request);
|
|
220
|
+
const origin = request.headers.get("origin")?.trim();
|
|
221
|
+
if (origin) {
|
|
222
|
+
if (origin.replace(/\/+$/, "") !== expected) {
|
|
223
|
+
return htmlResponse(400, messagePage("Connect Desearch", "This sign-in form was sent from another site."));
|
|
224
|
+
}
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
const referer = request.headers.get("referer")?.trim() ?? "";
|
|
228
|
+
if (referer) {
|
|
229
|
+
try {
|
|
230
|
+
if (new URL(referer).origin !== expected) {
|
|
231
|
+
return htmlResponse(400, messagePage("Connect Desearch", "This sign-in form was sent from another site."));
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
catch {
|
|
235
|
+
return htmlResponse(400, messagePage("Connect Desearch", "This sign-in form was sent from another site."));
|
|
236
|
+
}
|
|
237
|
+
return null;
|
|
238
|
+
}
|
|
239
|
+
if (!fetchSite) {
|
|
240
|
+
return htmlResponse(403, messagePage("Connect Desearch", "This sign-in form did not come from this site."));
|
|
241
|
+
}
|
|
242
|
+
return null;
|
|
243
|
+
}
|
|
244
|
+
export async function submitAuthorize(request) {
|
|
245
|
+
const forbidden = authorizePostForbidden(request);
|
|
246
|
+
if (forbidden) {
|
|
247
|
+
return forbidden;
|
|
248
|
+
}
|
|
249
|
+
let form;
|
|
250
|
+
try {
|
|
251
|
+
form = await readFormBody(request);
|
|
252
|
+
}
|
|
253
|
+
catch {
|
|
254
|
+
return htmlResponse(400, messagePage("Connect Desearch", "The sign-in form could not be read."));
|
|
255
|
+
}
|
|
256
|
+
const query = readAuthorizeQuery(form);
|
|
257
|
+
const context = await authorizeContext(request, query);
|
|
258
|
+
if (context instanceof Response) {
|
|
259
|
+
return context;
|
|
260
|
+
}
|
|
261
|
+
const { fields } = context;
|
|
262
|
+
if (form.get("decision") === "deny") {
|
|
263
|
+
return redirectBack(fields.redirectUri, publicOrigin(request), {
|
|
264
|
+
error: "access_denied",
|
|
265
|
+
error_description: "The sign-in was cancelled.",
|
|
266
|
+
state: fields.state,
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
const keyLimit = authorizeKeyRateLimitConfig();
|
|
270
|
+
const keyAttempts = await takeIpRateLimit(request, "authorize-key", keyLimit.limit, keyLimit.windowSec);
|
|
271
|
+
if (!keyAttempts.allowed) {
|
|
272
|
+
return withRetryAfter(htmlResponse(429, messagePage("Connect Desearch", "Too many sign-in attempts from this address. Try again in a moment.")), keyAttempts.retryAfterSec);
|
|
273
|
+
}
|
|
274
|
+
const apiKey = (form.get("api_key") ?? "").trim();
|
|
275
|
+
const checked = await checkDesearchApiKey(apiKey);
|
|
276
|
+
if (!checked.ok) {
|
|
277
|
+
return htmlResponse(400, authorizePage({ ...fields, error: checked.message }));
|
|
278
|
+
}
|
|
279
|
+
const code = randomToken(AUTH_CODE_PREFIX, 32);
|
|
280
|
+
const store = await getOAuthStore();
|
|
281
|
+
await store.saveCode(code, {
|
|
282
|
+
clientId: fields.clientId,
|
|
283
|
+
redirectUri: fields.redirectUri,
|
|
284
|
+
codeChallenge: fields.codeChallenge,
|
|
285
|
+
resource: fields.resource,
|
|
286
|
+
scope: grantedScope(fields.scope),
|
|
287
|
+
apiKeyCiphertext: store.sealApiKey(apiKey),
|
|
288
|
+
expiresAt: Date.now() + codeTtlSec() * 1000,
|
|
289
|
+
});
|
|
290
|
+
return redirectBack(fields.redirectUri, publicOrigin(request), {
|
|
291
|
+
code,
|
|
292
|
+
state: fields.state,
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
function tokenResponse(accessToken, refreshToken, scope, expiresIn) {
|
|
296
|
+
return new Response(JSON.stringify({
|
|
297
|
+
access_token: accessToken,
|
|
298
|
+
token_type: "Bearer",
|
|
299
|
+
expires_in: expiresIn,
|
|
300
|
+
refresh_token: refreshToken,
|
|
301
|
+
scope,
|
|
302
|
+
}), {
|
|
303
|
+
status: 200,
|
|
304
|
+
headers: {
|
|
305
|
+
"Content-Type": "application/json",
|
|
306
|
+
"Cache-Control": "no-store",
|
|
307
|
+
},
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
async function issueTokens(clientId, resource, scope, apiKeyCiphertext, familyId, issuedCode) {
|
|
311
|
+
const store = await getOAuthStore();
|
|
312
|
+
const family = familyId ?? randomToken("", 16);
|
|
313
|
+
if (issuedCode) {
|
|
314
|
+
const committed = await store.commitIssuedCode(issuedCode, family);
|
|
315
|
+
if (!committed) {
|
|
316
|
+
return oauthError(400, "invalid_grant", "The authorization code is invalid or was already used.");
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
const accessToken = randomToken(ACCESS_TOKEN_PREFIX, 32);
|
|
320
|
+
const refreshToken = randomToken(REFRESH_TOKEN_PREFIX, 32);
|
|
321
|
+
const accessExpires = Date.now() + accessTtlSec() * 1000;
|
|
322
|
+
const refreshExpires = Date.now() + refreshTtlSec() * 1000;
|
|
323
|
+
await store.saveAccess(accessToken, {
|
|
324
|
+
clientId,
|
|
325
|
+
resource,
|
|
326
|
+
scope,
|
|
327
|
+
apiKeyCiphertext,
|
|
328
|
+
expiresAt: accessExpires,
|
|
329
|
+
familyId: family,
|
|
330
|
+
});
|
|
331
|
+
await store.saveRefresh(refreshToken, {
|
|
332
|
+
clientId,
|
|
333
|
+
resource,
|
|
334
|
+
scope,
|
|
335
|
+
apiKeyCiphertext,
|
|
336
|
+
expiresAt: refreshExpires,
|
|
337
|
+
familyId: family,
|
|
338
|
+
});
|
|
339
|
+
if (await store.isFamilyRevoked(family)) {
|
|
340
|
+
await store.revokeFamily(family);
|
|
341
|
+
return oauthError(400, "invalid_grant", "The authorization code is invalid or was already used.");
|
|
342
|
+
}
|
|
343
|
+
return tokenResponse(accessToken, refreshToken, scope, accessTtlSec());
|
|
344
|
+
}
|
|
345
|
+
export async function exchangeToken(request) {
|
|
346
|
+
const contentType = request.headers.get("content-type") ?? "";
|
|
347
|
+
if (contentType.toLowerCase().includes("application/json")) {
|
|
348
|
+
return oauthError(400, "invalid_request", "The token endpoint expects application/x-www-form-urlencoded.");
|
|
349
|
+
}
|
|
350
|
+
let form;
|
|
351
|
+
try {
|
|
352
|
+
form = await readFormBody(request);
|
|
353
|
+
}
|
|
354
|
+
catch {
|
|
355
|
+
return oauthError(400, "invalid_request", "The token request could not be read.");
|
|
356
|
+
}
|
|
357
|
+
const grant = form.get("grant_type");
|
|
358
|
+
if (grant === "authorization_code") {
|
|
359
|
+
return exchangeCode(request, form);
|
|
360
|
+
}
|
|
361
|
+
if (grant === "refresh_token") {
|
|
362
|
+
return exchangeRefresh(request, form);
|
|
363
|
+
}
|
|
364
|
+
return oauthError(400, "unsupported_grant_type", "Supported grants are authorization_code and refresh_token.");
|
|
365
|
+
}
|
|
366
|
+
async function exchangeCode(request, form) {
|
|
367
|
+
const code = form.get("code") ?? "";
|
|
368
|
+
const clientId = form.get("client_id") ?? "";
|
|
369
|
+
const redirectUri = form.get("redirect_uri") ?? "";
|
|
370
|
+
const verifier = form.get("code_verifier") ?? "";
|
|
371
|
+
const resource = form.get("resource");
|
|
372
|
+
if (!code || !clientId || !redirectUri || !verifier) {
|
|
373
|
+
return oauthError(400, "invalid_request", "code, client_id, redirect_uri, and code_verifier are required.");
|
|
374
|
+
}
|
|
375
|
+
if (!VERIFIER_PATTERN.test(verifier)) {
|
|
376
|
+
return oauthError(400, "invalid_grant", "code_verifier is not valid.");
|
|
377
|
+
}
|
|
378
|
+
const store = await getOAuthStore();
|
|
379
|
+
const consumed = await store.consumeCode(code);
|
|
380
|
+
if (!consumed.ok || consumed.record.clientId !== clientId || consumed.record.redirectUri !== redirectUri) {
|
|
381
|
+
return oauthError(400, "invalid_grant", "The authorization code is invalid or was already used.");
|
|
382
|
+
}
|
|
383
|
+
const pending = consumed.record;
|
|
384
|
+
if (resource && !resourcesMatch(resource, pending.resource)) {
|
|
385
|
+
return oauthError(400, "invalid_target", "The resource does not match the authorization request.");
|
|
386
|
+
}
|
|
387
|
+
if (!resourcesMatch(pending.resource, canonicalResource(request))) {
|
|
388
|
+
return oauthError(400, "invalid_target", "The authorization code was issued for a different resource.");
|
|
389
|
+
}
|
|
390
|
+
const expected = s256Challenge(verifier);
|
|
391
|
+
if (!challengesMatch(expected, pending.codeChallenge)) {
|
|
392
|
+
return oauthError(400, "invalid_grant", "PKCE verification failed.");
|
|
393
|
+
}
|
|
394
|
+
return issueTokens(pending.clientId, pending.resource, pending.scope, pending.apiKeyCiphertext, undefined, code);
|
|
395
|
+
}
|
|
396
|
+
async function exchangeRefresh(request, form) {
|
|
397
|
+
const refreshToken = form.get("refresh_token") ?? "";
|
|
398
|
+
const clientId = form.get("client_id") ?? "";
|
|
399
|
+
const resource = form.get("resource");
|
|
400
|
+
if (!refreshToken || !clientId) {
|
|
401
|
+
return oauthError(400, "invalid_request", "refresh_token and client_id are required.");
|
|
402
|
+
}
|
|
403
|
+
const store = await getOAuthStore();
|
|
404
|
+
const rotated = await store.rotateRefresh(refreshToken, {
|
|
405
|
+
clientId,
|
|
406
|
+
canonicalResource: canonicalResource(request),
|
|
407
|
+
presentedResource: resource,
|
|
408
|
+
});
|
|
409
|
+
if (!rotated.ok) {
|
|
410
|
+
return oauthError(400, rotated.error, rotated.description);
|
|
411
|
+
}
|
|
412
|
+
return tokenResponse(rotated.accessToken, rotated.refreshToken, rotated.scope, rotated.expiresIn);
|
|
413
|
+
}
|
|
414
|
+
export async function lookupAccessApiKey(token, request) {
|
|
415
|
+
const store = await getOAuthStore();
|
|
416
|
+
const record = await store.getAccess(token);
|
|
417
|
+
if (!record) {
|
|
418
|
+
return null;
|
|
419
|
+
}
|
|
420
|
+
if (!resourcesMatch(record.resource, canonicalResource(request))) {
|
|
421
|
+
return null;
|
|
422
|
+
}
|
|
423
|
+
return store.readApiKey(record.apiKeyCiphertext);
|
|
424
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { wwwAuthenticate } from "./metadata.js";
|
|
2
|
+
export { resetOAuthForTests } from "./store.js";
|
|
3
|
+
export { setApiKeyCheckerForTests, validateDesearchApiKey } from "./validate-key.js";
|
|
4
|
+
export { wwwAuthenticate };
|
|
5
|
+
export declare function isOAuthPath(pathname: string): boolean;
|
|
6
|
+
export declare function isOAuthMaterial(value: string): boolean;
|
|
7
|
+
export type RequestCredential = {
|
|
8
|
+
kind: "anonymous";
|
|
9
|
+
} | {
|
|
10
|
+
kind: "key";
|
|
11
|
+
apiKey: string;
|
|
12
|
+
} | {
|
|
13
|
+
kind: "unauthorized";
|
|
14
|
+
} | {
|
|
15
|
+
kind: "unavailable";
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* A raw Desearch API key is returned as-is. An OAuth access token is exchanged
|
|
19
|
+
* for the key stored at grant time. Other OAuth material is never forwarded
|
|
20
|
+
* to the Desearch API.
|
|
21
|
+
*/
|
|
22
|
+
export declare function resolveRequestCredential(request: Request): Promise<RequestCredential>;
|
|
23
|
+
export declare function handleOAuthHttp(request: Request): Promise<Response | null>;
|
|
24
|
+
//# sourceMappingURL=http.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../../oauth/http.ts"],"names":[],"mappings":"AAEA,OAAO,EAA0D,eAAe,EAAE,MAAM,eAAe,CAAC;AAKxG,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAChD,OAAO,EAAE,wBAAwB,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AACrF,OAAO,EAAE,eAAe,EAAE,CAAC;AAY3B,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAErD;AAED,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAMtD;AAED,MAAM,MAAM,iBAAiB,GACvB;IAAE,IAAI,EAAE,WAAW,CAAA;CAAE,GACrB;IAAE,IAAI,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAC/B;IAAE,IAAI,EAAE,cAAc,CAAA;CAAE,GACxB;IAAE,IAAI,EAAE,aAAa,CAAA;CAAE,CAAC;AAE9B;;;;GAIG;AACH,wBAAsB,wBAAwB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,iBAAiB,CAAC,CA0B3F;AAuBD,wBAAsB,eAAe,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CA8DhF"}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { ACCESS_TOKEN_PREFIX, REFRESH_TOKEN_PREFIX, AUTH_CODE_PREFIX } from "./crypto.js";
|
|
2
|
+
import { exchangeToken, htmlResponse, registerClient, showAuthorize, submitAuthorize, lookupAccessApiKey } from "./flow.js";
|
|
3
|
+
import { authorizationServerMetadata, protectedResourceMetadata, wwwAuthenticate } from "./metadata.js";
|
|
4
|
+
import { messagePage } from "./page.js";
|
|
5
|
+
import { OAuthConfigError } from "./store.js";
|
|
6
|
+
import { extractDesearchApiKey } from "../request-key.js";
|
|
7
|
+
export { resetOAuthForTests } from "./store.js";
|
|
8
|
+
export { setApiKeyCheckerForTests, validateDesearchApiKey } from "./validate-key.js";
|
|
9
|
+
export { wwwAuthenticate };
|
|
10
|
+
const OAUTH_PATHS = new Set([
|
|
11
|
+
"/.well-known/oauth-protected-resource",
|
|
12
|
+
"/.well-known/oauth-protected-resource/mcp",
|
|
13
|
+
"/.well-known/oauth-authorization-server",
|
|
14
|
+
"/.well-known/openid-configuration",
|
|
15
|
+
"/register",
|
|
16
|
+
"/authorize",
|
|
17
|
+
"/token",
|
|
18
|
+
]);
|
|
19
|
+
export function isOAuthPath(pathname) {
|
|
20
|
+
return OAUTH_PATHS.has(pathname);
|
|
21
|
+
}
|
|
22
|
+
export function isOAuthMaterial(value) {
|
|
23
|
+
return (value.startsWith(ACCESS_TOKEN_PREFIX) ||
|
|
24
|
+
value.startsWith(REFRESH_TOKEN_PREFIX) ||
|
|
25
|
+
value.startsWith(AUTH_CODE_PREFIX));
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* A raw Desearch API key is returned as-is. An OAuth access token is exchanged
|
|
29
|
+
* for the key stored at grant time. Other OAuth material is never forwarded
|
|
30
|
+
* to the Desearch API.
|
|
31
|
+
*/
|
|
32
|
+
export async function resolveRequestCredential(request) {
|
|
33
|
+
const presented = extractDesearchApiKey(request);
|
|
34
|
+
if (!presented) {
|
|
35
|
+
return { kind: "anonymous" };
|
|
36
|
+
}
|
|
37
|
+
if (!isOAuthMaterial(presented)) {
|
|
38
|
+
return { kind: "key", apiKey: presented };
|
|
39
|
+
}
|
|
40
|
+
if (!presented.startsWith(ACCESS_TOKEN_PREFIX)) {
|
|
41
|
+
return { kind: "unauthorized" };
|
|
42
|
+
}
|
|
43
|
+
try {
|
|
44
|
+
const apiKey = await lookupAccessApiKey(presented, request);
|
|
45
|
+
if (!apiKey) {
|
|
46
|
+
return { kind: "unauthorized" };
|
|
47
|
+
}
|
|
48
|
+
return { kind: "key", apiKey };
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
if (error instanceof OAuthConfigError) {
|
|
52
|
+
return { kind: "unavailable" };
|
|
53
|
+
}
|
|
54
|
+
console.error(`OAuth token lookup failed: ${error instanceof Error ? error.message : "unknown error"}`);
|
|
55
|
+
return { kind: "unavailable" };
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function json(body) {
|
|
59
|
+
return new Response(JSON.stringify(body), {
|
|
60
|
+
status: 200,
|
|
61
|
+
headers: {
|
|
62
|
+
"Content-Type": "application/json",
|
|
63
|
+
"Cache-Control": "public, max-age=300",
|
|
64
|
+
},
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
function methodNotAllowed(allow) {
|
|
68
|
+
return new Response(JSON.stringify({ error: "invalid_request", error_description: "Method not allowed." }), {
|
|
69
|
+
status: 405,
|
|
70
|
+
headers: {
|
|
71
|
+
Allow: allow,
|
|
72
|
+
"Content-Type": "application/json",
|
|
73
|
+
"Cache-Control": "no-store",
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
export async function handleOAuthHttp(request) {
|
|
78
|
+
const pathname = new URL(request.url).pathname.replace(/\/+$/, "") || "/";
|
|
79
|
+
if (!isOAuthPath(pathname)) {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
try {
|
|
83
|
+
if (pathname === "/.well-known/oauth-protected-resource" || pathname === "/.well-known/oauth-protected-resource/mcp") {
|
|
84
|
+
if (request.method !== "GET" && request.method !== "HEAD") {
|
|
85
|
+
return methodNotAllowed("GET");
|
|
86
|
+
}
|
|
87
|
+
return json(protectedResourceMetadata(request));
|
|
88
|
+
}
|
|
89
|
+
if (pathname === "/.well-known/oauth-authorization-server" || pathname === "/.well-known/openid-configuration") {
|
|
90
|
+
if (request.method !== "GET" && request.method !== "HEAD") {
|
|
91
|
+
return methodNotAllowed("GET");
|
|
92
|
+
}
|
|
93
|
+
return json(authorizationServerMetadata(request));
|
|
94
|
+
}
|
|
95
|
+
if (pathname === "/register") {
|
|
96
|
+
if (request.method !== "POST") {
|
|
97
|
+
return methodNotAllowed("POST");
|
|
98
|
+
}
|
|
99
|
+
return await registerClient(request);
|
|
100
|
+
}
|
|
101
|
+
if (pathname === "/authorize") {
|
|
102
|
+
if (request.method === "GET" || request.method === "HEAD") {
|
|
103
|
+
return await showAuthorize(request);
|
|
104
|
+
}
|
|
105
|
+
if (request.method === "POST") {
|
|
106
|
+
return await submitAuthorize(request);
|
|
107
|
+
}
|
|
108
|
+
return methodNotAllowed("GET, POST");
|
|
109
|
+
}
|
|
110
|
+
if (pathname === "/token") {
|
|
111
|
+
if (request.method !== "POST") {
|
|
112
|
+
return methodNotAllowed("POST");
|
|
113
|
+
}
|
|
114
|
+
return await exchangeToken(request);
|
|
115
|
+
}
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
if (error instanceof OAuthConfigError) {
|
|
120
|
+
if (pathname === "/authorize") {
|
|
121
|
+
return htmlResponse(500, messagePage("Connect Desearch", "OAuth storage is not configured on this server."));
|
|
122
|
+
}
|
|
123
|
+
return new Response(JSON.stringify({
|
|
124
|
+
error: "server_error",
|
|
125
|
+
error_description: "OAuth storage is not configured on this server.",
|
|
126
|
+
}), {
|
|
127
|
+
status: 500,
|
|
128
|
+
headers: { "Content-Type": "application/json", "Cache-Control": "no-store" },
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
console.error(`OAuth error: ${error instanceof Error ? error.message : "unknown error"}`);
|
|
132
|
+
return new Response(JSON.stringify({ error: "server_error", error_description: "OAuth request failed." }), {
|
|
133
|
+
status: 500,
|
|
134
|
+
headers: { "Content-Type": "application/json", "Cache-Control": "no-store" },
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export declare const SUPPORTED_SCOPES: readonly ["mcp", "offline_access"];
|
|
2
|
+
export interface WwwChallenge {
|
|
3
|
+
error: string;
|
|
4
|
+
error_description: string;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Public origin of this authorization server.
|
|
8
|
+
* Production refuses to run without `OAUTH_ISSUER`. Forwarded host headers are
|
|
9
|
+
* never consulted, so a client cannot choose the issuer or the resource.
|
|
10
|
+
*/
|
|
11
|
+
export declare function publicOrigin(request: Request): string;
|
|
12
|
+
export declare function canonicalResource(request: Request): string;
|
|
13
|
+
export declare function resourceMetadataUrl(request: Request): string;
|
|
14
|
+
export declare function protectedResourceMetadata(request: Request): Record<string, unknown>;
|
|
15
|
+
export declare function authorizationServerMetadata(request: Request): Record<string, unknown>;
|
|
16
|
+
export declare function wwwAuthenticate(request: Request, challenge?: WwwChallenge): string;
|
|
17
|
+
export declare function resourcesMatch(left: string, right: string): boolean;
|
|
18
|
+
export declare function grantedScope(requested: string | null | undefined): string;
|
|
19
|
+
//# sourceMappingURL=metadata.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"metadata.d.ts","sourceRoot":"","sources":["../../oauth/metadata.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,gBAAgB,oCAAqC,CAAC;AAEnE,MAAM,WAAW,YAAY;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,iBAAiB,EAAE,MAAM,CAAC;CAC7B;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,CAUrD;AAED,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,CAM1D;AAED,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,CAE5D;AAED,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CASnF;AAED,wBAAgB,2BAA2B,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAerF;AAED,wBAAgB,eAAe,CAAC,OAAO,EAAE,OAAO,EAAE,SAAS,CAAC,EAAE,YAAY,GAAG,MAAM,CAOlF;AAED,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAEnE;AAYD,wBAAgB,YAAY,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,MAAM,CAUzE"}
|