desearch-mcp-server 0.1.4 → 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.
Files changed (48) hide show
  1. package/CHANGELOG.md +40 -1
  2. package/README.md +209 -6
  3. package/build/http.d.ts +2 -8
  4. package/build/http.d.ts.map +1 -1
  5. package/build/http.js +126 -37
  6. package/build/oauth/client-ip.d.ts +10 -0
  7. package/build/oauth/client-ip.d.ts.map +1 -0
  8. package/build/oauth/client-ip.js +28 -0
  9. package/build/oauth/crypto.d.ts +20 -0
  10. package/build/oauth/crypto.d.ts.map +1 -0
  11. package/build/oauth/crypto.js +89 -0
  12. package/build/oauth/errors.d.ts +9 -0
  13. package/build/oauth/errors.d.ts.map +1 -0
  14. package/build/oauth/errors.js +13 -0
  15. package/build/oauth/flow.d.ts +8 -0
  16. package/build/oauth/flow.d.ts.map +1 -0
  17. package/build/oauth/flow.js +424 -0
  18. package/build/oauth/http.d.ts +24 -0
  19. package/build/oauth/http.d.ts.map +1 -0
  20. package/build/oauth/http.js +137 -0
  21. package/build/oauth/metadata.d.ts +19 -0
  22. package/build/oauth/metadata.d.ts.map +1 -0
  23. package/build/oauth/metadata.js +86 -0
  24. package/build/oauth/page.d.ts +14 -0
  25. package/build/oauth/page.d.ts.map +1 -0
  26. package/build/oauth/page.js +92 -0
  27. package/build/oauth/rate-limit.d.ts +14 -0
  28. package/build/oauth/rate-limit.d.ts.map +1 -0
  29. package/build/oauth/rate-limit.js +19 -0
  30. package/build/oauth/redirects.d.ts +14 -0
  31. package/build/oauth/redirects.d.ts.map +1 -0
  32. package/build/oauth/redirects.js +78 -0
  33. package/build/oauth/store.d.ts +139 -0
  34. package/build/oauth/store.d.ts.map +1 -0
  35. package/build/oauth/store.js +606 -0
  36. package/build/oauth/validate-key.d.ts +21 -0
  37. package/build/oauth/validate-key.d.ts.map +1 -0
  38. package/build/oauth/validate-key.js +61 -0
  39. package/build/people.d.ts +125 -0
  40. package/build/people.d.ts.map +1 -0
  41. package/build/people.js +402 -0
  42. package/build/request-key.d.ts +9 -0
  43. package/build/request-key.d.ts.map +1 -0
  44. package/build/request-key.js +24 -0
  45. package/build/server.d.ts +5 -4
  46. package/build/server.d.ts.map +1 -1
  47. package/build/server.js +404 -9
  48. package/package.json +32 -9
@@ -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"}
@@ -0,0 +1,86 @@
1
+ import { isProductionHost, OAuthConfigError } from "./errors.js";
2
+ export const SUPPORTED_SCOPES = ["mcp", "offline_access"];
3
+ /**
4
+ * Public origin of this authorization server.
5
+ * Production refuses to run without `OAUTH_ISSUER`. Forwarded host headers are
6
+ * never consulted, so a client cannot choose the issuer or the resource.
7
+ */
8
+ export function publicOrigin(request) {
9
+ const configured = process.env.OAUTH_ISSUER?.trim().replace(/\/+$/, "");
10
+ if (configured) {
11
+ return configured;
12
+ }
13
+ if (isProductionHost()) {
14
+ throw new OAuthConfigError("OAUTH_ISSUER is required in production");
15
+ }
16
+ const url = new URL(request.url);
17
+ return `${url.protocol}//${url.host}`;
18
+ }
19
+ export function canonicalResource(request) {
20
+ const configured = process.env.OAUTH_RESOURCE?.trim().replace(/\/+$/, "");
21
+ if (configured) {
22
+ return configured;
23
+ }
24
+ return `${publicOrigin(request)}/mcp`;
25
+ }
26
+ export function resourceMetadataUrl(request) {
27
+ return `${publicOrigin(request)}/.well-known/oauth-protected-resource/mcp`;
28
+ }
29
+ export function protectedResourceMetadata(request) {
30
+ const origin = publicOrigin(request);
31
+ return {
32
+ resource: canonicalResource(request),
33
+ authorization_servers: [origin],
34
+ scopes_supported: [...SUPPORTED_SCOPES],
35
+ bearer_methods_supported: ["header"],
36
+ resource_documentation: "https://www.desearch.ai/docs/guide/sdk/mcp",
37
+ };
38
+ }
39
+ export function authorizationServerMetadata(request) {
40
+ const origin = publicOrigin(request);
41
+ return {
42
+ issuer: origin,
43
+ authorization_endpoint: `${origin}/authorize`,
44
+ token_endpoint: `${origin}/token`,
45
+ registration_endpoint: `${origin}/register`,
46
+ response_types_supported: ["code"],
47
+ response_modes_supported: ["query"],
48
+ grant_types_supported: ["authorization_code", "refresh_token"],
49
+ code_challenge_methods_supported: ["S256"],
50
+ token_endpoint_auth_methods_supported: ["none"],
51
+ scopes_supported: [...SUPPORTED_SCOPES],
52
+ authorization_response_iss_parameter_supported: true,
53
+ };
54
+ }
55
+ export function wwwAuthenticate(request, challenge) {
56
+ const base = `Bearer realm="Desearch", resource_metadata="${resourceMetadataUrl(request)}", scope="mcp"`;
57
+ if (!challenge) {
58
+ return base;
59
+ }
60
+ const description = challenge.error_description.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
61
+ return `${base}, error="${challenge.error}", error_description="${description}"`;
62
+ }
63
+ export function resourcesMatch(left, right) {
64
+ return normalizeResource(left) === normalizeResource(right);
65
+ }
66
+ function normalizeResource(value) {
67
+ try {
68
+ const url = new URL(value);
69
+ const path = url.pathname.replace(/\/+$/, "") || "";
70
+ return `${url.protocol.toLowerCase()}//${url.host.toLowerCase()}${path}`;
71
+ }
72
+ catch {
73
+ return value;
74
+ }
75
+ }
76
+ export function grantedScope(requested) {
77
+ const asked = (requested ?? "")
78
+ .split(/\s+/)
79
+ .map((scope) => scope.trim())
80
+ .filter((scope) => SUPPORTED_SCOPES.includes(scope));
81
+ const unique = [...new Set(asked)];
82
+ if (unique.length === 0) {
83
+ return "mcp offline_access";
84
+ }
85
+ return unique.join(" ");
86
+ }
@@ -0,0 +1,14 @@
1
+ export interface AuthorizePageFields {
2
+ clientId: string;
3
+ redirectUri: string;
4
+ state: string;
5
+ codeChallenge: string;
6
+ codeChallengeMethod: string;
7
+ resource: string;
8
+ scope: string;
9
+ clientName: string;
10
+ error?: string;
11
+ }
12
+ export declare function authorizePage(fields: AuthorizePageFields): string;
13
+ export declare function messagePage(title: string, message: string): string;
14
+ //# sourceMappingURL=page.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"page.d.ts","sourceRoot":"","sources":["../../oauth/page.ts"],"names":[],"mappings":"AAWA,MAAM,WAAW,mBAAmB;IAChC,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,KAAK,EAAE,MAAM,CAAC;IACd,aAAa,EAAE,MAAM,CAAC;IACtB,mBAAmB,EAAE,MAAM,CAAC;IAC5B,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,wBAAgB,aAAa,CAAC,MAAM,EAAE,mBAAmB,GAAG,MAAM,CAkEjE;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAqBlE"}
@@ -0,0 +1,92 @@
1
+ import { redirectHostname } from "./redirects.js";
2
+ function escapeHtml(value) {
3
+ return value
4
+ .replace(/&/g, "&amp;")
5
+ .replace(/</g, "&lt;")
6
+ .replace(/>/g, "&gt;")
7
+ .replace(/"/g, "&quot;")
8
+ .replace(/'/g, "&#39;");
9
+ }
10
+ export function authorizePage(fields) {
11
+ const host = redirectHostname(fields.redirectUri) || "the requesting app";
12
+ const error = fields.error
13
+ ? `<p class="error" role="alert">${escapeHtml(fields.error)}</p>`
14
+ : "";
15
+ const hidden = [
16
+ ["client_id", fields.clientId],
17
+ ["redirect_uri", fields.redirectUri],
18
+ ["state", fields.state],
19
+ ["code_challenge", fields.codeChallenge],
20
+ ["code_challenge_method", fields.codeChallengeMethod],
21
+ ["resource", fields.resource],
22
+ ["scope", fields.scope],
23
+ ]
24
+ .map(([name, value]) => `<input type="hidden" name="${name}" value="${escapeHtml(value)}">`)
25
+ .join("");
26
+ return `<!DOCTYPE html>
27
+ <html lang="en">
28
+ <head>
29
+ <meta charset="utf-8">
30
+ <meta name="viewport" content="width=device-width, initial-scale=1">
31
+ <meta name="referrer" content="no-referrer">
32
+ <meta name="robots" content="noindex">
33
+ <title>Connect Desearch</title>
34
+ <style>
35
+ :root { color-scheme: light; }
36
+ body { margin: 0; background: #f3efe6; color: #1c1915; font-family: Georgia, "Iowan Old Style", serif; }
37
+ main { max-width: 28rem; margin: 10vh auto; background: #fffdf8; border: 1px solid #e3d9c6; padding: 2rem 1.75rem 1.75rem; }
38
+ h1 { font-size: 1.7rem; font-weight: 600; margin: 0 0 0.4rem; }
39
+ p, label { line-height: 1.45; }
40
+ label, button, .host { font-family: ui-sans-serif, system-ui, sans-serif; }
41
+ label { display: block; font-size: 0.85rem; margin: 1.2rem 0 0.4rem; }
42
+ input[type="password"] { width: 100%; box-sizing: border-box; font: 0.95rem ui-monospace, SFMono-Regular, Menlo, monospace; padding: 0.65rem 0.7rem; border: 1px solid #cfc4ae; background: #fff; }
43
+ .actions { display: flex; gap: 0.6rem; margin-top: 1.1rem; }
44
+ button { border: 0; padding: 0.65rem 0.95rem; cursor: pointer; }
45
+ button.primary { background: #1c1915; color: #fffdf8; }
46
+ button.secondary { background: transparent; color: #1c1915; border: 1px solid #cfc4ae; }
47
+ a { color: #1c1915; }
48
+ .error { color: #8d2a2a; font-family: ui-sans-serif, system-ui, sans-serif; }
49
+ .host { font-weight: 650; }
50
+ </style>
51
+ </head>
52
+ <body>
53
+ <main>
54
+ <h1>Desearch</h1>
55
+ <p>Paste a Desearch API key to connect. <a href="https://console.desearch.ai/api-keys">Create a key</a> in the Desearch console if you need one.</p>
56
+ <p>The key is checked before this page continues. It stays on this server and is not sent to <span class="host">${escapeHtml(host)}</span>.</p>
57
+ ${error}
58
+ <form method="post" action="/authorize" accept-charset="UTF-8">
59
+ ${hidden}
60
+ <label for="api_key">Desearch API key</label>
61
+ <input id="api_key" name="api_key" type="password" autocomplete="off" spellcheck="false" required>
62
+ <div class="actions">
63
+ <button class="primary" type="submit" name="decision" value="allow">Continue</button>
64
+ <button class="secondary" type="submit" name="decision" value="deny" formnovalidate>Cancel</button>
65
+ </div>
66
+ </form>
67
+ </main>
68
+ </body>
69
+ </html>`;
70
+ }
71
+ export function messagePage(title, message) {
72
+ return `<!DOCTYPE html>
73
+ <html lang="en">
74
+ <head>
75
+ <meta charset="utf-8">
76
+ <meta name="viewport" content="width=device-width, initial-scale=1">
77
+ <meta name="referrer" content="no-referrer">
78
+ <meta name="robots" content="noindex">
79
+ <title>${escapeHtml(title)}</title>
80
+ <style>
81
+ body { margin: 0; background: #f3efe6; color: #1c1915; font-family: Georgia, "Iowan Old Style", serif; }
82
+ main { max-width: 28rem; margin: 10vh auto; background: #fffdf8; border: 1px solid #e3d9c6; padding: 2rem 1.75rem; }
83
+ </style>
84
+ </head>
85
+ <body>
86
+ <main>
87
+ <h1>${escapeHtml(title)}</h1>
88
+ <p>${escapeHtml(message)}</p>
89
+ </main>
90
+ </body>
91
+ </html>`;
92
+ }
@@ -0,0 +1,14 @@
1
+ export interface RateLimitDecision {
2
+ allowed: boolean;
3
+ retryAfterSec: number;
4
+ }
5
+ export declare function registerRateLimitConfig(): {
6
+ limit: number;
7
+ windowSec: number;
8
+ };
9
+ export declare function authorizeKeyRateLimitConfig(): {
10
+ limit: number;
11
+ windowSec: number;
12
+ };
13
+ export declare function takeIpRateLimit(request: Request, bucket: string, limit: number, windowSec: number): Promise<RateLimitDecision>;
14
+ //# sourceMappingURL=rate-limit.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rate-limit.d.ts","sourceRoot":"","sources":["../../oauth/rate-limit.ts"],"names":[],"mappings":"AAIA,MAAM,WAAW,iBAAiB;IAC9B,OAAO,EAAE,OAAO,CAAC;IACjB,aAAa,EAAE,MAAM,CAAC;CACzB;AAED,wBAAgB,uBAAuB,IAAI;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,CAK9E;AAED,wBAAgB,2BAA2B,IAAI;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,CAKlF;AAED,wBAAsB,eAAe,CACjC,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,EACb,SAAS,EAAE,MAAM,GAClB,OAAO,CAAC,iBAAiB,CAAC,CAG5B"}
@@ -0,0 +1,19 @@
1
+ import { clientIp } from "./client-ip.js";
2
+ import { positiveInt } from "./crypto.js";
3
+ import { getOAuthStore } from "./store.js";
4
+ export function registerRateLimitConfig() {
5
+ return {
6
+ limit: positiveInt(process.env.OAUTH_REGISTER_RATE_LIMIT, 10, 1, 10_000),
7
+ windowSec: positiveInt(process.env.OAUTH_REGISTER_RATE_WINDOW_SEC, 60 * 60, 1, 60 * 60 * 24),
8
+ };
9
+ }
10
+ export function authorizeKeyRateLimitConfig() {
11
+ return {
12
+ limit: positiveInt(process.env.OAUTH_AUTHORIZE_RATE_LIMIT, 20, 1, 10_000),
13
+ windowSec: positiveInt(process.env.OAUTH_AUTHORIZE_RATE_WINDOW_SEC, 10 * 60, 1, 60 * 60 * 24),
14
+ };
15
+ }
16
+ export async function takeIpRateLimit(request, bucket, limit, windowSec) {
17
+ const store = await getOAuthStore();
18
+ return store.consumeRateLimit(bucket, clientIp(request), limit, windowSec);
19
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Redirect URIs accepted at registration and at /authorize.
3
+ * Hosted clients use fixed HTTPS callbacks. Native clients use a loopback
4
+ * redirect whose port changes every session (RFC 8252), so the port is ignored
5
+ * for localhost and 127.0.0.1.
6
+ */
7
+ export declare function isAllowedRedirectUri(value: string): boolean;
8
+ /**
9
+ * Loopback clients register one callback and then open another port.
10
+ * The host and path must match. The port does not.
11
+ */
12
+ export declare function redirectsMatch(registered: string, requested: string): boolean;
13
+ export declare function redirectHostname(value: string): string;
14
+ //# sourceMappingURL=redirects.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redirects.d.ts","sourceRoot":"","sources":["../../oauth/redirects.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAeH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAiC3D;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAqB7E;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAMtD"}
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Redirect URIs accepted at registration and at /authorize.
3
+ * Hosted clients use fixed HTTPS callbacks. Native clients use a loopback
4
+ * redirect whose port changes every session (RFC 8252), so the port is ignored
5
+ * for localhost and 127.0.0.1.
6
+ */
7
+ const EXACT_REDIRECTS = new Set([
8
+ "https://claude.ai/api/mcp/auth_callback",
9
+ "https://claude.com/api/mcp/auth_callback",
10
+ "https://chatgpt.com/connector_platform_oauth_redirect",
11
+ ]);
12
+ const CHATGPT_CALLBACK_ID = /^\/connector\/oauth\/[A-Za-z0-9._~-]{1,200}$/;
13
+ function isLoopbackHost(hostname) {
14
+ const host = hostname.toLowerCase().replace(/^\[|\]$/g, "");
15
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
16
+ }
17
+ export function isAllowedRedirectUri(value) {
18
+ let url;
19
+ try {
20
+ url = new URL(value);
21
+ }
22
+ catch {
23
+ return false;
24
+ }
25
+ if (url.username || url.password || url.hash) {
26
+ return false;
27
+ }
28
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
29
+ return false;
30
+ }
31
+ const exact = `${url.origin}${url.pathname}`;
32
+ if (EXACT_REDIRECTS.has(exact) && url.search === "") {
33
+ return true;
34
+ }
35
+ if (url.protocol === "https:" &&
36
+ url.hostname === "chatgpt.com" &&
37
+ CHATGPT_CALLBACK_ID.test(url.pathname) &&
38
+ url.search === "") {
39
+ return true;
40
+ }
41
+ if (isLoopbackHost(url.hostname)) {
42
+ return true;
43
+ }
44
+ return false;
45
+ }
46
+ /**
47
+ * Loopback clients register one callback and then open another port.
48
+ * The host and path must match. The port does not.
49
+ */
50
+ export function redirectsMatch(registered, requested) {
51
+ if (registered === requested) {
52
+ return true;
53
+ }
54
+ let left;
55
+ let right;
56
+ try {
57
+ left = new URL(registered);
58
+ right = new URL(requested);
59
+ }
60
+ catch {
61
+ return false;
62
+ }
63
+ if (!isLoopbackHost(left.hostname) || !isLoopbackHost(right.hostname)) {
64
+ return false;
65
+ }
66
+ return (left.protocol === right.protocol &&
67
+ left.hostname.toLowerCase() === right.hostname.toLowerCase() &&
68
+ left.pathname === right.pathname &&
69
+ left.search === right.search);
70
+ }
71
+ export function redirectHostname(value) {
72
+ try {
73
+ return new URL(value).hostname;
74
+ }
75
+ catch {
76
+ return "";
77
+ }
78
+ }
@@ -0,0 +1,139 @@
1
+ import { isProductionHost, OAuthConfigError } from "./errors.js";
2
+ export { OAuthConfigError, isProductionHost };
3
+ export interface ClientRecord {
4
+ clientId: string;
5
+ clientName: string;
6
+ redirectUris: string[];
7
+ tokenEndpointAuthMethod: "none";
8
+ createdAt: number;
9
+ }
10
+ export interface CodeRecord {
11
+ clientId: string;
12
+ redirectUri: string;
13
+ codeChallenge: string;
14
+ resource: string;
15
+ scope: string;
16
+ apiKeyCiphertext: string;
17
+ expiresAt: number;
18
+ }
19
+ export interface AccessRecord {
20
+ clientId: string;
21
+ resource: string;
22
+ scope: string;
23
+ apiKeyCiphertext: string;
24
+ expiresAt: number;
25
+ familyId: string;
26
+ }
27
+ export interface RefreshRecord {
28
+ clientId: string;
29
+ resource: string;
30
+ scope: string;
31
+ apiKeyCiphertext: string;
32
+ expiresAt: number;
33
+ familyId: string;
34
+ replacedBy?: string;
35
+ }
36
+ export interface ConsumeCodeResult {
37
+ status: "ok" | "missing" | "replay";
38
+ recordJson?: string;
39
+ familyId?: string;
40
+ }
41
+ export interface ClaimRefreshInput {
42
+ refreshKey: string;
43
+ tombstoneKey: string;
44
+ now: number;
45
+ expectedClientId: string;
46
+ canonicalResource: string;
47
+ presentedResource: string;
48
+ tombTtlSec: number;
49
+ familyKeyPrefix: string;
50
+ revokedKeyPrefix: string;
51
+ }
52
+ export interface ClaimRefreshResult {
53
+ status: "ok" | "invalid" | "client_mismatch" | "resource_mismatch" | "reused";
54
+ recordJson?: string;
55
+ familyId?: string;
56
+ resourceReason?: "presented" | "canonical";
57
+ }
58
+ export interface Kv {
59
+ get(key: string): Promise<string | null>;
60
+ getDel(key: string): Promise<string | null>;
61
+ set(key: string, value: string, ttlSec: number): Promise<void>;
62
+ del(key: string): Promise<void>;
63
+ consumeAuthCode(codeKey: string, tombstoneKey: string, now: number, tombTtlSec: number): Promise<ConsumeCodeResult>;
64
+ commitAuthCode(tombstoneKey: string, familyId: string, tombTtlSec: number): Promise<"committed" | "replayed">;
65
+ claimRefresh(input: ClaimRefreshInput): Promise<ClaimRefreshResult>;
66
+ /** Fixed-window counter. The count starts at 1 and the TTL is set on the first hit. */
67
+ increment(key: string, ttlSec: number): Promise<number>;
68
+ }
69
+ export declare function clientTtlSec(): number;
70
+ export declare function accessTtlSec(): number;
71
+ export declare function refreshTtlSec(): number;
72
+ export declare function codeTtlSec(): number;
73
+ export declare class KvOAuthStore {
74
+ private readonly kv;
75
+ constructor(kv: Kv);
76
+ saveClient(record: ClientRecord): Promise<void>;
77
+ getClient(clientId: string): Promise<ClientRecord | null>;
78
+ /**
79
+ * Per-subject fixed window. `bucket` separates registration from key checks.
80
+ * The subject is hashed so the stored key is not the raw address.
81
+ */
82
+ consumeRateLimit(bucket: string, subject: string, limit: number, windowSec: number): Promise<{
83
+ allowed: boolean;
84
+ retryAfterSec: number;
85
+ }>;
86
+ saveCode(code: string, record: CodeRecord): Promise<void>;
87
+ consumeCode(code: string): Promise<{
88
+ ok: true;
89
+ record: CodeRecord;
90
+ } | {
91
+ ok: false;
92
+ }>;
93
+ commitIssuedCode(code: string, familyId: string): Promise<boolean>;
94
+ saveAccess(token: string, record: AccessRecord): Promise<void>;
95
+ getAccess(token: string): Promise<AccessRecord | null>;
96
+ saveRefresh(token: string, record: RefreshRecord): Promise<void>;
97
+ /**
98
+ * Rotate a refresh token. The claim, reuse detection, and family revoke
99
+ * flag are one atomic step (in-process for memory, one Lua script for Redis)
100
+ * so two overlapping presentations cannot both mint a new grant.
101
+ */
102
+ rotateRefresh(token: string, options: {
103
+ clientId: string;
104
+ canonicalResource: string;
105
+ presentedResource: string | null;
106
+ }): Promise<{
107
+ ok: true;
108
+ accessToken: string;
109
+ refreshToken: string;
110
+ scope: string;
111
+ expiresIn: number;
112
+ } | {
113
+ ok: false;
114
+ error: "invalid_grant" | "invalid_target";
115
+ description: string;
116
+ }>;
117
+ isFamilyRevoked(familyId: string): Promise<boolean>;
118
+ readApiKey(ciphertext: string): string | null;
119
+ sealApiKey(apiKey: string): string;
120
+ private remember;
121
+ revokeFamily(familyId: string): Promise<void>;
122
+ }
123
+ interface RedisLike {
124
+ get(key: string): Promise<string | null>;
125
+ getDel(key: string): Promise<string | null>;
126
+ set(key: string, value: string, options: {
127
+ EX: number;
128
+ }): Promise<unknown>;
129
+ del(key: string): Promise<unknown>;
130
+ eval(script: string, options: {
131
+ keys: string[];
132
+ arguments: string[];
133
+ }): Promise<unknown>;
134
+ }
135
+ export declare function getOAuthStore(): Promise<KvOAuthStore>;
136
+ export declare function resetOAuthForTests(): void;
137
+ export declare function memoryStoreForTests(): KvOAuthStore;
138
+ export declare function redisKvForTests(client: RedisLike): Kv;
139
+ //# sourceMappingURL=store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../oauth/store.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAGjE,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,CAAC;AAE9C,MAAM,WAAW,YAAY;IACzB,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,YAAY,EAAE,MAAM,EAAE,CAAC;IACvB,uBAAuB,EAAE,MAAM,CAAC;IAChC,SAAS,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,UAAU;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,aAAa,EAAE,MAAM,CAAC;IACtB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,gBAAgB,EAAE,MAAM,CAAC;IACzB,SAAS,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,YAAY;IACzB,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,gBAAgB,EAAE,MAAM,CAAC;IACzB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,aAAa;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,gBAAgB,EAAE,MAAM,CA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