encarapi-mcp 1.0.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +97 -6
- package/package.json +6 -4
- package/src/app.js +183 -0
- package/src/brand.js +41 -0
- package/src/http.js +6 -90
- package/src/oauth.js +657 -0
- package/src/server.js +234 -162
package/src/oauth.js
ADDED
|
@@ -0,0 +1,657 @@
|
|
|
1
|
+
// OAuth 2.1 authorization server + protected resource metadata for the hosted
|
|
2
|
+
// endpoint, per the MCP authorization spec. Enabled only when MCP_OAUTH_SECRET
|
|
3
|
+
// is set.
|
|
4
|
+
//
|
|
5
|
+
// Stateless by design (single container, no database): client ids,
|
|
6
|
+
// authorization codes, access tokens and refresh tokens are AES-256-GCM sealed
|
|
7
|
+
// blobs. The API key the user pasted on /authorize travels inside the code and
|
|
8
|
+
// the tokens and is only readable by this server. The only in-memory state is
|
|
9
|
+
// best-effort and lost on restart: the used-code set, the used-refresh-token
|
|
10
|
+
// set and the rate-limit counters.
|
|
11
|
+
//
|
|
12
|
+
// Protocol plumbing (parameter validation, redirect_uri matching, PKCE check,
|
|
13
|
+
// client authentication, metadata documents, CORS, bearer check) comes from
|
|
14
|
+
// the MCP SDK's server/auth handlers; this file supplies the stateless provider
|
|
15
|
+
// and the key form.
|
|
16
|
+
import crypto from "node:crypto";
|
|
17
|
+
import express from "express";
|
|
18
|
+
import encarapi from "encarapi";
|
|
19
|
+
import { authorizationHandler } from "@modelcontextprotocol/sdk/server/auth/handlers/authorize.js";
|
|
20
|
+
import { tokenHandler } from "@modelcontextprotocol/sdk/server/auth/handlers/token.js";
|
|
21
|
+
import { clientRegistrationHandler } from "@modelcontextprotocol/sdk/server/auth/handlers/register.js";
|
|
22
|
+
import { metadataHandler } from "@modelcontextprotocol/sdk/server/auth/handlers/metadata.js";
|
|
23
|
+
import { requireBearerAuth } from "@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js";
|
|
24
|
+
import {
|
|
25
|
+
createOAuthMetadata,
|
|
26
|
+
mcpAuthMetadataRouter,
|
|
27
|
+
getOAuthProtectedResourceMetadataUrl,
|
|
28
|
+
} from "@modelcontextprotocol/sdk/server/auth/router.js";
|
|
29
|
+
import {
|
|
30
|
+
InvalidClientMetadataError,
|
|
31
|
+
InvalidGrantError,
|
|
32
|
+
InvalidTargetError,
|
|
33
|
+
InvalidTokenError,
|
|
34
|
+
} from "@modelcontextprotocol/sdk/server/auth/errors.js";
|
|
35
|
+
import { brandFor } from "./brand.js";
|
|
36
|
+
|
|
37
|
+
const { KoreaClient, ChinaClient } = encarapi;
|
|
38
|
+
|
|
39
|
+
export const ACCESS_TOKEN_PREFIX = "emat_";
|
|
40
|
+
const REFRESH_TOKEN_PREFIX = "emrt_";
|
|
41
|
+
const CODE_PREFIX = "emac_";
|
|
42
|
+
const CLIENT_PREFIX = "emc_";
|
|
43
|
+
|
|
44
|
+
const CODE_TTL = 5 * 60;
|
|
45
|
+
const ACCESS_TTL = 60 * 60;
|
|
46
|
+
const REFRESH_TTL = 90 * 24 * 60 * 60;
|
|
47
|
+
const CSRF_TTL = 30 * 60;
|
|
48
|
+
// A rotated refresh token stays usable for this long, so a client that lost the
|
|
49
|
+
// response (or refreshes from two workers at once) is not logged out.
|
|
50
|
+
const REFRESH_REUSE_GRACE = 60;
|
|
51
|
+
|
|
52
|
+
const KEY_CHECK_MAX = 10;
|
|
53
|
+
const KEY_CHECK_WINDOW = 10 * 60;
|
|
54
|
+
const KEY_CHECK_TIMEOUT_MS = 10000;
|
|
55
|
+
const CHINA_API = "https://api.chinacarapi.com";
|
|
56
|
+
|
|
57
|
+
const MAX_REDIRECT_URIS = 10;
|
|
58
|
+
const MAX_REDIRECT_URI_LENGTH = 500;
|
|
59
|
+
const MAX_KEY_LENGTH = 256;
|
|
60
|
+
const MAX_TRACKED = 50000;
|
|
61
|
+
|
|
62
|
+
const CSRF_COOKIE = "encarapi_mcp_csrf";
|
|
63
|
+
const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
64
|
+
|
|
65
|
+
const b64 = (buf) => Buffer.from(buf).toString("base64url");
|
|
66
|
+
const sha = (text) => crypto.createHash("sha256").update(text).digest();
|
|
67
|
+
const stripSlash = (s) => String(s).replace(/#.*$/, "").replace(/\/$/, "");
|
|
68
|
+
|
|
69
|
+
/** AES-256-GCM with one HKDF-derived key per purpose, so blobs cannot be swapped between roles. */
|
|
70
|
+
function makeSealer(secret) {
|
|
71
|
+
const keys = new Map();
|
|
72
|
+
const keyFor = (purpose) => {
|
|
73
|
+
if (!keys.has(purpose)) {
|
|
74
|
+
keys.set(purpose, Buffer.from(crypto.hkdfSync("sha256", secret, "encarapi-mcp-oauth", purpose, 32)));
|
|
75
|
+
}
|
|
76
|
+
return keys.get(purpose);
|
|
77
|
+
};
|
|
78
|
+
return {
|
|
79
|
+
seal(purpose, data) {
|
|
80
|
+
const iv = crypto.randomBytes(12);
|
|
81
|
+
const cipher = crypto.createCipheriv("aes-256-gcm", keyFor(purpose), iv);
|
|
82
|
+
const ct = Buffer.concat([cipher.update(JSON.stringify(data), "utf8"), cipher.final()]);
|
|
83
|
+
return b64(Buffer.concat([iv, ct, cipher.getAuthTag()]));
|
|
84
|
+
},
|
|
85
|
+
open(purpose, blob) {
|
|
86
|
+
try {
|
|
87
|
+
const raw = Buffer.from(String(blob), "base64url");
|
|
88
|
+
if (raw.length < 29) return null;
|
|
89
|
+
const decipher = crypto.createDecipheriv("aes-256-gcm", keyFor(purpose), raw.subarray(0, 12));
|
|
90
|
+
decipher.setAuthTag(raw.subarray(raw.length - 16));
|
|
91
|
+
const pt = Buffer.concat([decipher.update(raw.subarray(12, raw.length - 16)), decipher.final()]);
|
|
92
|
+
return JSON.parse(pt.toString("utf8"));
|
|
93
|
+
} catch {
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
},
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Map of id -> expiry (seconds) that forgets expired entries and stays bounded. */
|
|
101
|
+
function makeTtlMap(now) {
|
|
102
|
+
const map = new Map();
|
|
103
|
+
const prune = () => {
|
|
104
|
+
const t = now();
|
|
105
|
+
for (const [k, v] of map) if (v.exp <= t) map.delete(k);
|
|
106
|
+
while (map.size > MAX_TRACKED) map.delete(map.keys().next().value);
|
|
107
|
+
};
|
|
108
|
+
return {
|
|
109
|
+
get: (k) => {
|
|
110
|
+
const v = map.get(k);
|
|
111
|
+
return v && v.exp > now() ? v : undefined;
|
|
112
|
+
},
|
|
113
|
+
set: (k, v) => {
|
|
114
|
+
if (map.size >= 1000) prune();
|
|
115
|
+
map.set(k, v);
|
|
116
|
+
},
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Caller IP: Cloudflare's header first, then the proxy chain, then the socket. */
|
|
121
|
+
export function clientIp(req) {
|
|
122
|
+
const cf = req.headers["cf-connecting-ip"];
|
|
123
|
+
if (cf) return String(cf).trim();
|
|
124
|
+
const xff = req.headers["x-forwarded-for"];
|
|
125
|
+
if (xff) return String(xff).split(",")[0].trim();
|
|
126
|
+
return req.socket?.remoteAddress || "unknown";
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const esc = (s) =>
|
|
130
|
+
String(s).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
|
|
131
|
+
|
|
132
|
+
function redirectHost(uri) {
|
|
133
|
+
try {
|
|
134
|
+
const u = new URL(uri);
|
|
135
|
+
return u.host || u.protocol.replace(/:$/, "");
|
|
136
|
+
} catch {
|
|
137
|
+
return "the client";
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function renderPage({ brand, nonce, clientName, host, hidden, error }) {
|
|
142
|
+
const fields = Object.entries(hidden)
|
|
143
|
+
.filter(([, v]) => v !== undefined && v !== null)
|
|
144
|
+
.map(([k, v]) => `<input type="hidden" name="${esc(k)}" value="${esc(v)}">`)
|
|
145
|
+
.join("\n ");
|
|
146
|
+
return `<!doctype html>
|
|
147
|
+
<html lang="en">
|
|
148
|
+
<head>
|
|
149
|
+
<meta charset="utf-8">
|
|
150
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
151
|
+
<meta name="robots" content="noindex, nofollow">
|
|
152
|
+
<meta name="color-scheme" content="dark">
|
|
153
|
+
<title>Connect ${brand.product}</title>
|
|
154
|
+
<style nonce="${nonce}">
|
|
155
|
+
*, *::before, *::after { box-sizing: border-box; }
|
|
156
|
+
html { background: #030712; }
|
|
157
|
+
body {
|
|
158
|
+
margin: 0; min-height: 100vh; display: flex; align-items: center; justify-content: center;
|
|
159
|
+
padding: 24px 16px; background: #030712; color: #f8fafc;
|
|
160
|
+
font: 15px/1.55 ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
|
161
|
+
-webkit-font-smoothing: antialiased;
|
|
162
|
+
}
|
|
163
|
+
main { width: 100%; max-width: 420px; background: #0a0f1a; border: 1px solid #1d283a; border-radius: 14px; padding: 32px 28px; }
|
|
164
|
+
.brand { font-size: 13px; font-weight: 600; letter-spacing: .08em; text-transform: uppercase; color: #94a3b8; margin: 0 0 20px; }
|
|
165
|
+
h1 { font-size: 22px; line-height: 1.25; font-weight: 600; letter-spacing: -.01em; margin: 0 0 10px; }
|
|
166
|
+
p { margin: 0; }
|
|
167
|
+
.who { color: #94a3b8; margin-bottom: 24px; overflow-wrap: anywhere; }
|
|
168
|
+
.who strong { color: #f8fafc; font-weight: 600; }
|
|
169
|
+
label { display: block; font-size: 13px; font-weight: 500; margin: 0 0 6px; }
|
|
170
|
+
label span { color: #94a3b8; font-weight: 400; }
|
|
171
|
+
input[type=password] {
|
|
172
|
+
display: block; width: 100%; height: 44px; padding: 0 12px; margin: 0 0 18px;
|
|
173
|
+
background: #030712; color: #f8fafc; border: 1px solid #1d283a; border-radius: 10px;
|
|
174
|
+
font: inherit; font-size: 16px; outline: none;
|
|
175
|
+
}
|
|
176
|
+
input[type=password]:focus-visible { border-color: #f8fafc; box-shadow: 0 0 0 3px rgba(248, 250, 252, .14); }
|
|
177
|
+
button {
|
|
178
|
+
display: block; width: 100%; height: 44px; margin: 6px 0 0; border: 0; border-radius: 10px;
|
|
179
|
+
background: #ffffff; color: #030712; font: inherit; font-weight: 600; cursor: pointer;
|
|
180
|
+
}
|
|
181
|
+
button:hover { background: #e2e8f0; }
|
|
182
|
+
button:focus-visible { outline: 2px solid #f8fafc; outline-offset: 3px; }
|
|
183
|
+
.error { border: 1px solid #f87171; border-radius: 10px; padding: 10px 12px; margin: 0 0 20px; color: #fca5a5; font-size: 14px; }
|
|
184
|
+
.error strong { display: block; color: #f87171; font-weight: 600; }
|
|
185
|
+
.hint { color: #94a3b8; font-size: 14px; margin-top: 20px; }
|
|
186
|
+
.note { color: #64748b; font-size: 12.5px; margin-top: 14px; }
|
|
187
|
+
a { color: #f8fafc; text-underline-offset: 3px; }
|
|
188
|
+
</style>
|
|
189
|
+
</head>
|
|
190
|
+
<body>
|
|
191
|
+
<main>
|
|
192
|
+
<p class="brand">${brand.product}</p>
|
|
193
|
+
<h1>Connect ${brand.product}</h1>
|
|
194
|
+
<p class="who"><strong>${esc(clientName)}</strong> wants to use ${brand.product} with your key. After connecting you return to <strong>${esc(host)}</strong>.</p>
|
|
195
|
+
${error ? `<div class="error" role="alert"><strong>${esc(error.title)}</strong>${esc(error.text)}</div>` : ""}
|
|
196
|
+
<form method="post" action="/authorize" autocomplete="off">
|
|
197
|
+
${fields}
|
|
198
|
+
<label for="${brand.mainField}">${brand.product} key</label>
|
|
199
|
+
<input type="password" id="${brand.mainField}" name="${brand.mainField}" maxlength="${MAX_KEY_LENGTH}" autocomplete="off" autocapitalize="off" spellcheck="false" autofocus>
|
|
200
|
+
<label for="${brand.secondField}">${brand.otherProduct} key <span>(optional)</span></label>
|
|
201
|
+
<input type="password" id="${brand.secondField}" name="${brand.secondField}" maxlength="${MAX_KEY_LENGTH}" autocomplete="off" autocapitalize="off" spellcheck="false">
|
|
202
|
+
<button type="submit">Connect</button>
|
|
203
|
+
</form>
|
|
204
|
+
<p class="hint">No key yet? Get one at <a href="${brand.signupUrl}" target="_blank" rel="noopener noreferrer">${brand.signupText}</a></p>
|
|
205
|
+
<p class="note">The second field is only needed for a separate ${brand.otherProduct} key. Keys are checked once and are not stored on this server: they are encrypted into the access token issued to this client.</p>
|
|
206
|
+
</main>
|
|
207
|
+
</body>
|
|
208
|
+
</html>`;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const PRODUCT = { k: "EnCarAPI", c: "ChinaCarAPI" };
|
|
212
|
+
const SLOT = { korea: "k", china: "c" };
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Checks one key against one product with a cheap request. Returns
|
|
216
|
+
* { result: "ok", slot } | { result: "rejected" | "unavailable" }. `slot` is where the
|
|
217
|
+
* key goes in the token: "k" (EnCarAPI key) or "c" (ChinaCarAPI key).
|
|
218
|
+
*/
|
|
219
|
+
async function probeKey(slot, key, fetchImpl) {
|
|
220
|
+
const base = fetchImpl || fetch;
|
|
221
|
+
const timed = (url, init) => base(url, { ...init, signal: AbortSignal.timeout(KEY_CHECK_TIMEOUT_MS) });
|
|
222
|
+
const fail = (e) => ({ result: e?.status === 401 || e?.status === 403 ? "rejected" : "unavailable" });
|
|
223
|
+
if (slot === "k") {
|
|
224
|
+
try {
|
|
225
|
+
await new KoreaClient(key, { fetch: timed }).modelSearch("k5", { limit: 1 });
|
|
226
|
+
return { result: "ok", slot: "k" };
|
|
227
|
+
} catch (e) {
|
|
228
|
+
return fail(e);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
// China: GET /api/me does not count against any request budget. 200 { product, plan, ... }
|
|
232
|
+
// with product "chinacarapi" or "encarapi-addon"; an add-on key is kept as an
|
|
233
|
+
// EnCarAPI key, so the Korean tools work with it as well.
|
|
234
|
+
try {
|
|
235
|
+
const res = await timed(`${CHINA_API}/api/me`, { headers: { "x-api-key": key, Accept: "application/json" } });
|
|
236
|
+
if (res.status === 200) {
|
|
237
|
+
let me = null;
|
|
238
|
+
try {
|
|
239
|
+
me = JSON.parse(await res.text());
|
|
240
|
+
} catch {}
|
|
241
|
+
const product = String(me?.product || "chinacarapi").toLowerCase();
|
|
242
|
+
return { result: "ok", slot: product === "chinacarapi" ? "c" : "k" };
|
|
243
|
+
}
|
|
244
|
+
if (res.status !== 404) return fail(res);
|
|
245
|
+
} catch (e) {
|
|
246
|
+
return fail(e);
|
|
247
|
+
}
|
|
248
|
+
// Older API without /api/me.
|
|
249
|
+
try {
|
|
250
|
+
await new ChinaClient(key, { fetch: timed }).catalog({ limit: 1 });
|
|
251
|
+
return { result: "ok", slot: "c" };
|
|
252
|
+
} catch (e) {
|
|
253
|
+
return fail(e);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Checks the pasted keys. The main key is tried against the products in the
|
|
259
|
+
* brand's order (the first that accepts it wins), the optional second key against
|
|
260
|
+
* the other product. Returns { ok: true, k, c } |
|
|
261
|
+
* { ok: false, reason: "rejected" | "unavailable", product }.
|
|
262
|
+
*/
|
|
263
|
+
async function checkKeys({ main, second, brand }, fetchImpl) {
|
|
264
|
+
const keys = {};
|
|
265
|
+
let taken = null;
|
|
266
|
+
if (main) {
|
|
267
|
+
let unavailable = null;
|
|
268
|
+
for (const product of brand.probeOrder) {
|
|
269
|
+
const r = await probeKey(SLOT[product], main, fetchImpl);
|
|
270
|
+
if (r.result === "ok") {
|
|
271
|
+
taken = SLOT[product];
|
|
272
|
+
keys[r.slot] = main;
|
|
273
|
+
break;
|
|
274
|
+
}
|
|
275
|
+
if (r.result === "unavailable" && !unavailable) unavailable = PRODUCT[SLOT[product]];
|
|
276
|
+
}
|
|
277
|
+
if (!taken) return { ok: false, reason: unavailable ? "unavailable" : "rejected", product: unavailable || brand.product };
|
|
278
|
+
}
|
|
279
|
+
if (second) {
|
|
280
|
+
const slot = taken ? (taken === "k" ? "c" : "k") : SLOT[brand.probeOrder[1]];
|
|
281
|
+
const r = await probeKey(slot, second, fetchImpl);
|
|
282
|
+
if (r.result !== "ok") return { ok: false, reason: r.result, product: PRODUCT[slot] };
|
|
283
|
+
keys[slot] = second;
|
|
284
|
+
}
|
|
285
|
+
return { ok: true, ...keys };
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* @param {object} o
|
|
290
|
+
* @param {string} o.secret MCP_OAUTH_SECRET (at least 32 characters)
|
|
291
|
+
* @param {string} o.publicUrl public origin, e.g. https://mcp.encarapi.com
|
|
292
|
+
* @param {object} [o.brand] page texts and key order (src/brand.js), default from publicUrl
|
|
293
|
+
* @param {Function} o.handleMcp (req, res, { apiKey, chinaKey }) for an authenticated /mcp request
|
|
294
|
+
* @param {Function} [o.fetchImpl] fetch used for the key check (tests)
|
|
295
|
+
* @param {Function} [o.now] clock in ms (tests)
|
|
296
|
+
*/
|
|
297
|
+
export function createOAuth({ secret, publicUrl, brand, handleMcp, fetchImpl, now: nowMs = Date.now }) {
|
|
298
|
+
if (typeof secret !== "string" || secret.length < 32) {
|
|
299
|
+
throw new Error("MCP_OAUTH_SECRET must be at least 32 characters (e.g. openssl rand -base64 48)");
|
|
300
|
+
}
|
|
301
|
+
const issuerUrl = new URL(publicUrl);
|
|
302
|
+
if (issuerUrl.pathname !== "/" || issuerUrl.search || issuerUrl.hash) {
|
|
303
|
+
throw new Error("MCP_PUBLIC_URL must be an origin without path, e.g. https://mcp.encarapi.com");
|
|
304
|
+
}
|
|
305
|
+
brand = brand || brandFor(issuerUrl.href);
|
|
306
|
+
const resourceUrl = new URL("/mcp", issuerUrl);
|
|
307
|
+
const resource = resourceUrl.href;
|
|
308
|
+
const secure = issuerUrl.protocol === "https:";
|
|
309
|
+
const now = () => Math.floor(nowMs() / 1000);
|
|
310
|
+
const { seal, open } = makeSealer(secret);
|
|
311
|
+
|
|
312
|
+
const usedCodes = makeTtlMap(now);
|
|
313
|
+
const usedRefresh = makeTtlMap(now);
|
|
314
|
+
const keyChecks = new Map(); // ip -> [timestamps]
|
|
315
|
+
|
|
316
|
+
const clientRef = (clientId) => b64(sha(clientId).subarray(0, 16));
|
|
317
|
+
const unwrap = (purpose, prefix, value) =>
|
|
318
|
+
typeof value === "string" && value.startsWith(prefix) ? open(purpose, value.slice(prefix.length)) : null;
|
|
319
|
+
|
|
320
|
+
const assertResource = (requested) => {
|
|
321
|
+
if (requested && stripSlash(requested.href ?? requested) !== stripSlash(resource)) {
|
|
322
|
+
throw new InvalidTargetError(`Unknown resource. This server issues tokens for ${resource} only`);
|
|
323
|
+
}
|
|
324
|
+
};
|
|
325
|
+
|
|
326
|
+
const clientsStore = {
|
|
327
|
+
getClient(clientId) {
|
|
328
|
+
const c = unwrap("client", CLIENT_PREFIX, clientId);
|
|
329
|
+
// Clients registered before 1.2.0 carry no resource and stay valid.
|
|
330
|
+
if (!c || !Array.isArray(c.r) || (c.a && c.a !== resource)) return undefined;
|
|
331
|
+
return {
|
|
332
|
+
client_id: clientId,
|
|
333
|
+
client_id_issued_at: c.t,
|
|
334
|
+
redirect_uris: c.r,
|
|
335
|
+
client_name: c.n,
|
|
336
|
+
client_uri: c.u,
|
|
337
|
+
token_endpoint_auth_method: c.m,
|
|
338
|
+
client_secret: c.s,
|
|
339
|
+
client_secret_expires_at: c.s ? 0 : undefined,
|
|
340
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
341
|
+
response_types: ["code"],
|
|
342
|
+
};
|
|
343
|
+
},
|
|
344
|
+
registerClient(meta) {
|
|
345
|
+
const uris = meta.redirect_uris || [];
|
|
346
|
+
if (!uris.length || uris.length > MAX_REDIRECT_URIS) {
|
|
347
|
+
throw new InvalidClientMetadataError(`redirect_uris must contain 1 to ${MAX_REDIRECT_URIS} entries`);
|
|
348
|
+
}
|
|
349
|
+
for (const uri of uris) {
|
|
350
|
+
const u = new URL(uri);
|
|
351
|
+
if (uri.length > MAX_REDIRECT_URI_LENGTH || u.hash) {
|
|
352
|
+
throw new InvalidClientMetadataError("redirect_uris must be short and must not contain a fragment");
|
|
353
|
+
}
|
|
354
|
+
if (u.protocol === "http:" && !LOOPBACK.has(u.hostname)) {
|
|
355
|
+
throw new InvalidClientMetadataError("redirect_uris must use https (http is allowed for localhost only)");
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
const issuedAt = now();
|
|
359
|
+
const method = meta.token_endpoint_auth_method === "none" ? "none" : "client_secret_post";
|
|
360
|
+
const clientId =
|
|
361
|
+
CLIENT_PREFIX +
|
|
362
|
+
seal("client", {
|
|
363
|
+
r: uris,
|
|
364
|
+
n: meta.client_name ? String(meta.client_name).slice(0, 80) : undefined,
|
|
365
|
+
u: meta.client_uri ? String(meta.client_uri).slice(0, 200) : undefined,
|
|
366
|
+
m: method,
|
|
367
|
+
s: method === "none" ? undefined : meta.client_secret,
|
|
368
|
+
t: issuedAt,
|
|
369
|
+
a: resource,
|
|
370
|
+
});
|
|
371
|
+
return {
|
|
372
|
+
...meta,
|
|
373
|
+
client_id: clientId,
|
|
374
|
+
client_id_issued_at: issuedAt,
|
|
375
|
+
token_endpoint_auth_method: method,
|
|
376
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
377
|
+
response_types: ["code"],
|
|
378
|
+
};
|
|
379
|
+
},
|
|
380
|
+
};
|
|
381
|
+
|
|
382
|
+
function issueTokens(grant) {
|
|
383
|
+
const t = now();
|
|
384
|
+
const base = { k: grant.k, c: grant.c, cid: grant.cid, aud: resource, iat: t };
|
|
385
|
+
return {
|
|
386
|
+
access_token: ACCESS_TOKEN_PREFIX + seal("access", { ...base, exp: t + ACCESS_TTL }),
|
|
387
|
+
token_type: "Bearer",
|
|
388
|
+
expires_in: ACCESS_TTL,
|
|
389
|
+
refresh_token:
|
|
390
|
+
REFRESH_TOKEN_PREFIX + seal("refresh", { ...base, exp: t + REFRESH_TTL, jti: b64(crypto.randomBytes(12)) }),
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function openCode(client, code) {
|
|
395
|
+
const c = unwrap("code", CODE_PREFIX, code);
|
|
396
|
+
if (!c || c.exp <= now() || c.cid !== clientRef(client.client_id) || c.aud !== resource) {
|
|
397
|
+
throw new InvalidGrantError("Invalid or expired authorization code");
|
|
398
|
+
}
|
|
399
|
+
return c;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
function keyCheckAllowed(ip) {
|
|
403
|
+
const t = now();
|
|
404
|
+
if (keyChecks.size > MAX_TRACKED) keyChecks.clear();
|
|
405
|
+
const recent = (keyChecks.get(ip) || []).filter((x) => x > t - KEY_CHECK_WINDOW);
|
|
406
|
+
if (recent.length >= KEY_CHECK_MAX) {
|
|
407
|
+
keyChecks.set(ip, recent);
|
|
408
|
+
return false;
|
|
409
|
+
}
|
|
410
|
+
recent.push(t);
|
|
411
|
+
keyChecks.set(ip, recent);
|
|
412
|
+
return true;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// Binds the form to the authorization request it was rendered for.
|
|
416
|
+
const csrfBinding = (client, params) =>
|
|
417
|
+
b64(sha([client.client_id, params.redirectUri, params.codeChallenge, params.state ?? ""].join("\n")));
|
|
418
|
+
|
|
419
|
+
function sendForm(res, client, params, { status = 200, error } = {}) {
|
|
420
|
+
const req = res.req;
|
|
421
|
+
const src = req.method === "POST" ? req.body || {} : req.query || {};
|
|
422
|
+
const cookieNonce = b64(crypto.randomBytes(18));
|
|
423
|
+
const styleNonce = b64(crypto.randomBytes(16));
|
|
424
|
+
const csrf = seal("csrf", { n: cookieNonce, b: csrfBinding(client, params), exp: now() + CSRF_TTL });
|
|
425
|
+
res.status(status);
|
|
426
|
+
res.setHeader(
|
|
427
|
+
"Set-Cookie",
|
|
428
|
+
`${CSRF_COOKIE}=${cookieNonce}; Path=/authorize; Max-Age=${CSRF_TTL}; HttpOnly; SameSite=Lax${secure ? "; Secure" : ""}`
|
|
429
|
+
);
|
|
430
|
+
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
431
|
+
res.setHeader("Cache-Control", "no-store");
|
|
432
|
+
res.setHeader("Referrer-Policy", "no-referrer");
|
|
433
|
+
res.setHeader("X-Frame-Options", "DENY");
|
|
434
|
+
res.setHeader(
|
|
435
|
+
"Content-Security-Policy",
|
|
436
|
+
`default-src 'none'; style-src 'nonce-${styleNonce}'; base-uri 'none'; frame-ancestors 'none'`
|
|
437
|
+
);
|
|
438
|
+
res.end(
|
|
439
|
+
renderPage({
|
|
440
|
+
brand,
|
|
441
|
+
nonce: styleNonce,
|
|
442
|
+
clientName: client.client_name || "An MCP client",
|
|
443
|
+
host: redirectHost(params.redirectUri),
|
|
444
|
+
error,
|
|
445
|
+
hidden: {
|
|
446
|
+
csrf,
|
|
447
|
+
client_id: client.client_id,
|
|
448
|
+
redirect_uri: params.redirectUri,
|
|
449
|
+
response_type: "code",
|
|
450
|
+
code_challenge: params.codeChallenge,
|
|
451
|
+
code_challenge_method: "S256",
|
|
452
|
+
state: params.state,
|
|
453
|
+
scope: typeof src.scope === "string" ? src.scope : undefined,
|
|
454
|
+
resource: params.resource?.href,
|
|
455
|
+
},
|
|
456
|
+
})
|
|
457
|
+
);
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
function csrfValid(req, client, params) {
|
|
461
|
+
const token = open("csrf", req.body.csrf);
|
|
462
|
+
if (!token || token.exp <= now() || token.b !== csrfBinding(client, params)) return false;
|
|
463
|
+
const cookie = String(req.headers.cookie || "")
|
|
464
|
+
.split(";")
|
|
465
|
+
.map((p) => p.trim())
|
|
466
|
+
.find((p) => p.startsWith(CSRF_COOKIE + "="));
|
|
467
|
+
const value = Buffer.from(cookie ? cookie.slice(CSRF_COOKIE.length + 1) : "");
|
|
468
|
+
const expected = Buffer.from(String(token.n));
|
|
469
|
+
return value.length === expected.length && crypto.timingSafeEqual(value, expected);
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
const provider = {
|
|
473
|
+
clientsStore,
|
|
474
|
+
|
|
475
|
+
// Called by the SDK handler after client_id, redirect_uri and the PKCE
|
|
476
|
+
// parameters are validated - for the initial GET and for the form POST
|
|
477
|
+
// (the form carries the original parameters, so they are validated again).
|
|
478
|
+
async authorize(client, params, res) {
|
|
479
|
+
assertResource(params.resource);
|
|
480
|
+
const req = res.req;
|
|
481
|
+
const body = req.method === "POST" ? req.body || {} : null;
|
|
482
|
+
if (!body || typeof body.csrf !== "string") return sendForm(res, client, params);
|
|
483
|
+
|
|
484
|
+
if (!csrfValid(req, client, params)) {
|
|
485
|
+
return sendForm(res, client, params, {
|
|
486
|
+
status: 400,
|
|
487
|
+
error: { title: "This form expired.", text: "Please enter your key again." },
|
|
488
|
+
});
|
|
489
|
+
}
|
|
490
|
+
const clean = (v) => (typeof v === "string" ? v.trim().slice(0, MAX_KEY_LENGTH) : "");
|
|
491
|
+
const main = clean(body[brand.mainField]);
|
|
492
|
+
const second = clean(body[brand.secondField]);
|
|
493
|
+
if (!main && !second) {
|
|
494
|
+
return sendForm(res, client, params, {
|
|
495
|
+
status: 400,
|
|
496
|
+
error: { title: "A key is required.", text: `Paste your ${brand.product} key to connect.` },
|
|
497
|
+
});
|
|
498
|
+
}
|
|
499
|
+
if (!keyCheckAllowed(clientIp(req))) {
|
|
500
|
+
return sendForm(res, client, params, {
|
|
501
|
+
status: 429,
|
|
502
|
+
error: { title: "Too many attempts.", text: "Please wait a few minutes and try again." },
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
const check = await checkKeys({ main, second, brand }, fetchImpl);
|
|
506
|
+
if (!check.ok) {
|
|
507
|
+
return sendForm(res, client, params, {
|
|
508
|
+
status: check.reason === "rejected" ? 400 : 503,
|
|
509
|
+
error:
|
|
510
|
+
check.reason === "rejected"
|
|
511
|
+
? { title: `This ${check.product} key was not accepted.`, text: "Check the key and that your plan is active." }
|
|
512
|
+
: { title: `${check.product} could not be reached.`, text: "The key was not checked. Please try again in a moment." },
|
|
513
|
+
});
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
const code =
|
|
517
|
+
CODE_PREFIX +
|
|
518
|
+
seal("code", {
|
|
519
|
+
k: check.k,
|
|
520
|
+
c: check.c,
|
|
521
|
+
cid: clientRef(client.client_id),
|
|
522
|
+
aud: resource,
|
|
523
|
+
ru: params.redirectUri,
|
|
524
|
+
cc: params.codeChallenge,
|
|
525
|
+
exp: now() + CODE_TTL,
|
|
526
|
+
jti: b64(crypto.randomBytes(12)),
|
|
527
|
+
});
|
|
528
|
+
const target = new URL(params.redirectUri);
|
|
529
|
+
target.searchParams.set("code", code);
|
|
530
|
+
if (params.state !== undefined) target.searchParams.set("state", params.state);
|
|
531
|
+
target.searchParams.set("iss", oauthMetadata.issuer);
|
|
532
|
+
res.setHeader("Set-Cookie", `${CSRF_COOKIE}=; Path=/authorize; Max-Age=0; HttpOnly; SameSite=Lax${secure ? "; Secure" : ""}`);
|
|
533
|
+
res.setHeader("Referrer-Policy", "no-referrer");
|
|
534
|
+
res.redirect(302, target.href);
|
|
535
|
+
},
|
|
536
|
+
|
|
537
|
+
async challengeForAuthorizationCode(client, code) {
|
|
538
|
+
return openCode(client, code).cc;
|
|
539
|
+
},
|
|
540
|
+
|
|
541
|
+
// The SDK handler has verified the PKCE code_verifier against the challenge before this runs.
|
|
542
|
+
async exchangeAuthorizationCode(client, code, _verifier, redirectUri, requestedResource) {
|
|
543
|
+
const c = openCode(client, code);
|
|
544
|
+
if (redirectUri !== undefined && redirectUri !== c.ru) {
|
|
545
|
+
throw new InvalidGrantError("redirect_uri does not match the authorization request");
|
|
546
|
+
}
|
|
547
|
+
assertResource(requestedResource);
|
|
548
|
+
if (usedCodes.get(c.jti)) throw new InvalidGrantError("Authorization code was already used");
|
|
549
|
+
usedCodes.set(c.jti, { exp: c.exp });
|
|
550
|
+
return issueTokens(c);
|
|
551
|
+
},
|
|
552
|
+
|
|
553
|
+
async exchangeRefreshToken(client, refreshToken, _scopes, requestedResource) {
|
|
554
|
+
const r = unwrap("refresh", REFRESH_TOKEN_PREFIX, refreshToken);
|
|
555
|
+
if (!r || r.exp <= now() || r.cid !== clientRef(client.client_id) || r.aud !== resource) {
|
|
556
|
+
throw new InvalidGrantError("Invalid or expired refresh token");
|
|
557
|
+
}
|
|
558
|
+
assertResource(requestedResource);
|
|
559
|
+
const used = usedRefresh.get(r.jti);
|
|
560
|
+
if (used && now() - used.at > REFRESH_REUSE_GRACE) {
|
|
561
|
+
throw new InvalidGrantError("Refresh token was already used");
|
|
562
|
+
}
|
|
563
|
+
if (!used) usedRefresh.set(r.jti, { exp: r.exp, at: now() });
|
|
564
|
+
return issueTokens(r);
|
|
565
|
+
},
|
|
566
|
+
|
|
567
|
+
async verifyAccessToken(token) {
|
|
568
|
+
const a = unwrap("access", ACCESS_TOKEN_PREFIX, token);
|
|
569
|
+
if (!a) throw new InvalidTokenError("Invalid access token");
|
|
570
|
+
if (a.exp <= now()) throw new InvalidTokenError("Token has expired");
|
|
571
|
+
return {
|
|
572
|
+
token,
|
|
573
|
+
clientId: a.cid,
|
|
574
|
+
scopes: [],
|
|
575
|
+
expiresAt: a.exp,
|
|
576
|
+
resource: new URL(a.aud),
|
|
577
|
+
extra: { apiKey: a.k, chinaKey: a.c },
|
|
578
|
+
};
|
|
579
|
+
},
|
|
580
|
+
};
|
|
581
|
+
|
|
582
|
+
const oauthMetadata = {
|
|
583
|
+
...createOAuthMetadata({
|
|
584
|
+
provider,
|
|
585
|
+
issuerUrl,
|
|
586
|
+
serviceDocumentationUrl: new URL("https://github.com/ThatMojo/encarapi-mcp"),
|
|
587
|
+
}),
|
|
588
|
+
authorization_response_iss_parameter_supported: true,
|
|
589
|
+
};
|
|
590
|
+
const resourceName = brand.resourceName;
|
|
591
|
+
const resourceMetadataUrl = getOAuthProtectedResourceMetadataUrl(resourceUrl);
|
|
592
|
+
const wwwAuthenticate = `Bearer resource_metadata="${resourceMetadataUrl}"`;
|
|
593
|
+
|
|
594
|
+
// The SDK's per-IP limits, keyed by the real caller instead of the proxy. Token and
|
|
595
|
+
// registration limits are generous because hosted clients share egress addresses.
|
|
596
|
+
const limit = (max) => ({ max, keyGenerator: (req) => clientIp(req), validate: false });
|
|
597
|
+
|
|
598
|
+
const app = express();
|
|
599
|
+
app.disable("x-powered-by");
|
|
600
|
+
app.use((_req, res, next) => {
|
|
601
|
+
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
602
|
+
next();
|
|
603
|
+
});
|
|
604
|
+
app.use("/authorize", authorizationHandler({ provider, rateLimit: limit(100) }));
|
|
605
|
+
app.use("/token", tokenHandler({ provider, rateLimit: limit(600) }));
|
|
606
|
+
app.use(
|
|
607
|
+
"/register",
|
|
608
|
+
clientRegistrationHandler({ clientsStore, clientSecretExpirySeconds: 0, clientIdGeneration: false, rateLimit: limit(300) })
|
|
609
|
+
);
|
|
610
|
+
app.use("/.well-known", (_req, res, next) => {
|
|
611
|
+
res.setHeader("Cache-Control", "public, max-age=300");
|
|
612
|
+
next();
|
|
613
|
+
});
|
|
614
|
+
// /.well-known/oauth-authorization-server and /.well-known/oauth-protected-resource/mcp
|
|
615
|
+
app.use(
|
|
616
|
+
mcpAuthMetadataRouter({
|
|
617
|
+
oauthMetadata,
|
|
618
|
+
resourceServerUrl: resourceUrl,
|
|
619
|
+
resourceName,
|
|
620
|
+
serviceDocumentationUrl: new URL("https://github.com/ThatMojo/encarapi-mcp"),
|
|
621
|
+
})
|
|
622
|
+
);
|
|
623
|
+
// Root variant for clients that do not append the resource path.
|
|
624
|
+
app.use(
|
|
625
|
+
"/.well-known/oauth-protected-resource",
|
|
626
|
+
metadataHandler({
|
|
627
|
+
resource,
|
|
628
|
+
authorization_servers: [oauthMetadata.issuer],
|
|
629
|
+
resource_name: resourceName,
|
|
630
|
+
resource_documentation: "https://github.com/ThatMojo/encarapi-mcp",
|
|
631
|
+
})
|
|
632
|
+
);
|
|
633
|
+
app.post(
|
|
634
|
+
"/mcp",
|
|
635
|
+
requireBearerAuth({ verifier: provider, resourceMetadataUrl, expectedResource: resourceUrl }),
|
|
636
|
+
(req, res) => handleMcp(req, res, { apiKey: req.auth.extra.apiKey, chinaKey: req.auth.extra.chinaKey })
|
|
637
|
+
);
|
|
638
|
+
app.use((_req, res) => {
|
|
639
|
+
res.setHeader("Cache-Control", "no-store");
|
|
640
|
+
res.status(404).json({ error: "Not found. MCP endpoint: /mcp" });
|
|
641
|
+
});
|
|
642
|
+
app.use((err, _req, res, _next) => {
|
|
643
|
+
const status = err?.status >= 400 && err?.status < 500 ? err.status : 500;
|
|
644
|
+
if (!res.headersSent) res.status(status).json({ error: status === 500 ? "server_error" : "invalid_request" });
|
|
645
|
+
});
|
|
646
|
+
|
|
647
|
+
return {
|
|
648
|
+
app,
|
|
649
|
+
brand,
|
|
650
|
+
provider,
|
|
651
|
+
resource,
|
|
652
|
+
resourceMetadataUrl,
|
|
653
|
+
wwwAuthenticate,
|
|
654
|
+
owns: (pathname) =>
|
|
655
|
+
pathname === "/authorize" || pathname === "/token" || pathname === "/register" || pathname.startsWith("/.well-known/oauth-"),
|
|
656
|
+
};
|
|
657
|
+
}
|