webcake-landing-mcp 1.17.0 → 1.18.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 +2 -2
- package/README.vi.md +1 -1
- package/dist/auth/login.js +6 -2
- package/dist/auth/oauth-server.js +40 -9
- package/dist/changelog.json +14 -14
- package/dist/http.js +191 -38
- package/dist/mcp/params.js +1 -1
- package/dist/persistence/html-ingest.js +31 -69
- package/dist/persistence/ingest/browser-capture.js +4 -14
- package/dist/persistence/rehost.js +41 -0
- package/dist/persistence/screenshot-playwright.js +129 -19
- package/dist/persistence/webcake-client.js +14 -31
- package/dist/smoke.js +60 -5
- package/dist/tools/api-gateway.js +2 -2
- package/dist/tools/media.js +10 -48
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -149,7 +149,7 @@ Two ways to get the link:
|
|
|
149
149
|
- **Easiest** — open **<https://webcake.io/mcp-remote>** in your Webcake dashboard → it builds & copies the link for you.
|
|
150
150
|
- **By hand** — see the step-by-step guide: **[docs/connect-mcp.md](docs/connect-mcp.md)**.
|
|
151
151
|
|
|
152
|
-
Optional extras: `&env=prod`, `&org_id
|
|
152
|
+
Optional extras: `&env=prod`, `&org_id=…`. Hand each teammate a link with their own `jwt` →
|
|
153
153
|
per-user, no OAuth. Clients that support headers should send the token as **`x-webcake-jwt`** instead of
|
|
154
154
|
putting it in the URL — the full header ↔ env mapping is in **[docs/configuration.md](docs/configuration.md#per-request-headers-hosted--remote-server)**.
|
|
155
155
|
|
|
@@ -171,7 +171,7 @@ npx -y webcake-landing-mcp login # opens the browser once, saves the token to
|
|
|
171
171
|
For `publish_page` to actually put a page **live**, a build host is needed (it renders the
|
|
172
172
|
`app`/`app_css` that the live `publish_html` route requires):
|
|
173
173
|
- `prod` preset auto-configures `https://build.webcake.io` — no extra setup (the preset applies when the env resolves to `prod`: `WEBCAKE_ENV=prod`, `--env prod`, or `x-webcake-env: prod`).
|
|
174
|
-
- For staging/local, set `WEBCAKE_BUILD_BASE=<url>`
|
|
174
|
+
- For staging/local, set `WEBCAKE_BUILD_BASE=<url>` on the server (per-request `x-webcake-*-base` headers are ignored over HTTP).
|
|
175
175
|
- Without it, `publish_page` falls back to a legacy source-only save with `rendered:false, live:false` + a warning — nothing goes live.
|
|
176
176
|
- A page is only **permanently** live with a `custom_domain`; without one the returned `/preview/<page_id>` link expires ~10 minutes after the publish.
|
|
177
177
|
|
package/README.vi.md
CHANGED
|
@@ -148,7 +148,7 @@ Hai cách lấy link:
|
|
|
148
148
|
- **Dễ nhất** — mở **<https://webcake.io/mcp-remote>** trong dashboard Webcake → nó tự tạo & copy link cho bạn.
|
|
149
149
|
- **Thủ công** — xem hướng dẫn từng bước: **[docs/ket-noi-mcp.md](docs/ket-noi-mcp.md)**.
|
|
150
150
|
|
|
151
|
-
Tham số thêm: `&env=prod`, `&org_id
|
|
151
|
+
Tham số thêm: `&env=prod`, `&org_id=…`. Mỗi đồng đội một link với `jwt` riêng → mỗi người một
|
|
152
152
|
tài khoản, không cần OAuth. Client nào set được header thì nên gửi token qua header **`x-webcake-jwt`** thay vì
|
|
153
153
|
nhét vào URL — bảng header ↔ env đầy đủ ở **[docs/configuration.vi.md](docs/configuration.vi.md#header-mỗi-request-server-hosted--remote)**.
|
|
154
154
|
|
package/dist/auth/login.js
CHANGED
|
@@ -145,9 +145,13 @@ function resolveConnectUrl(opts, appBase) {
|
|
|
145
145
|
* openBrowser's Windows note) the state is what goes missing, and parseCallback
|
|
146
146
|
* rejects the round-trip. Pure + exported so smoke can pin the contract.
|
|
147
147
|
*/
|
|
148
|
-
export function buildConnectUrl(connectUrl, redirectUri, state) {
|
|
148
|
+
export function buildConnectUrl(connectUrl, redirectUri, state, extra = {}) {
|
|
149
149
|
const sep = connectUrl.includes("?") ? "&" : "?";
|
|
150
|
-
|
|
150
|
+
let url = `${connectUrl}${sep}redirect_uri=${encodeURIComponent(redirectUri)}&state=${state}`;
|
|
151
|
+
for (const [k, v] of Object.entries(extra))
|
|
152
|
+
if (v)
|
|
153
|
+
url += `&${k}=${encodeURIComponent(v)}`;
|
|
154
|
+
return url;
|
|
151
155
|
}
|
|
152
156
|
/** Decide what a loopback request means. Pure + exported so smoke can test it. */
|
|
153
157
|
export function parseCallback(reqUrl, expectedState) {
|
|
@@ -171,9 +171,11 @@ class MemoryStore {
|
|
|
171
171
|
async putRefresh(t, r) {
|
|
172
172
|
this.refresh.set(t, r);
|
|
173
173
|
}
|
|
174
|
-
async takeRefresh(t) {
|
|
174
|
+
async takeRefresh(t, clientId) {
|
|
175
175
|
this.sweep();
|
|
176
176
|
const r = this.refresh.get(t);
|
|
177
|
+
if (r && clientId && r.client_id !== clientId)
|
|
178
|
+
return undefined;
|
|
177
179
|
this.refresh.delete(t);
|
|
178
180
|
return r && r.expiresAt >= now() ? r : undefined;
|
|
179
181
|
}
|
|
@@ -267,8 +269,8 @@ class PgStore {
|
|
|
267
269
|
async putRefresh(t, r) {
|
|
268
270
|
await this.pool.query(`INSERT INTO oauth_refresh_tokens (token, ljwt, wsid, client_id, scope, expires_at) VALUES ($1,$2,$3,$4,$5,$6)`, [t, r.ljwt, r.wsid, r.client_id, r.scope ?? null, r.expiresAt]);
|
|
269
271
|
}
|
|
270
|
-
async takeRefresh(t) {
|
|
271
|
-
const { rows } = await this.pool.query(`DELETE FROM oauth_refresh_tokens WHERE token=$1 RETURNING ljwt, wsid, client_id, scope, expires_at`, [t]);
|
|
272
|
+
async takeRefresh(t, clientId) {
|
|
273
|
+
const { rows } = await this.pool.query(`DELETE FROM oauth_refresh_tokens WHERE token=$1 AND ($2::text IS NULL OR client_id=$2) RETURNING ljwt, wsid, client_id, scope, expires_at`, [t, clientId || null]);
|
|
272
274
|
const r = rows[0];
|
|
273
275
|
if (!r || Number(r.expires_at) < now())
|
|
274
276
|
return undefined;
|
|
@@ -327,10 +329,10 @@ export function verifyPkce(verifier, challenge) {
|
|
|
327
329
|
}
|
|
328
330
|
export async function registerClient(body) {
|
|
329
331
|
const uris = Array.isArray(body?.redirect_uris)
|
|
330
|
-
? body.redirect_uris.filter((u) => typeof u === "string" &&
|
|
332
|
+
? body.redirect_uris.filter((u) => typeof u === "string" && isAllowedRedirect(u))
|
|
331
333
|
: [];
|
|
332
334
|
if (uris.length === 0) {
|
|
333
|
-
return { ok: false, error: "invalid_redirect_uri", error_description: "redirect_uris must
|
|
335
|
+
return { ok: false, error: "invalid_redirect_uri", error_description: "redirect_uris must be a known MCP client callback (claude.ai, chatgpt.com, …) or an http loopback URI." };
|
|
334
336
|
}
|
|
335
337
|
const client = {
|
|
336
338
|
client_id: token(16),
|
|
@@ -347,6 +349,33 @@ export async function getClient(clientId) {
|
|
|
347
349
|
return (await getStore()).getClient(clientId);
|
|
348
350
|
}
|
|
349
351
|
const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
352
|
+
// An open redirect target would let anyone register a client and phish a code for a victim's
|
|
353
|
+
// account, so DCR only accepts known MCP clients + loopback. Add hosts via WEBCAKE_OAUTH_REDIRECT_HOSTS.
|
|
354
|
+
const REDIRECT_HOSTS = new Set([
|
|
355
|
+
"claude.ai",
|
|
356
|
+
"claude.com",
|
|
357
|
+
"chatgpt.com",
|
|
358
|
+
"platform.openai.com",
|
|
359
|
+
"vscode.dev",
|
|
360
|
+
"insiders.vscode.dev",
|
|
361
|
+
...(process.env.WEBCAKE_OAUTH_REDIRECT_HOSTS ?? "").split(",").map((h) => h.trim().toLowerCase()).filter(Boolean),
|
|
362
|
+
]);
|
|
363
|
+
export function isAllowedRedirect(uri) {
|
|
364
|
+
let u;
|
|
365
|
+
try {
|
|
366
|
+
u = new URL(uri);
|
|
367
|
+
}
|
|
368
|
+
catch {
|
|
369
|
+
return false;
|
|
370
|
+
}
|
|
371
|
+
if (u.protocol === "http:")
|
|
372
|
+
return LOOPBACK_HOSTS.has(u.hostname);
|
|
373
|
+
return u.protocol === "https:" && REDIRECT_HOSTS.has(u.hostname);
|
|
374
|
+
}
|
|
375
|
+
/** Cookie set at /authorize and required at the callback: ties a pending request to the browser that started it. */
|
|
376
|
+
export function pendingCookieName(internalState) {
|
|
377
|
+
return `wc_oauth_${s256(internalState).slice(0, 16)}`;
|
|
378
|
+
}
|
|
350
379
|
/**
|
|
351
380
|
* Exact match, except an http loopback redirect ignores the port (RFC 8252 §7.3):
|
|
352
381
|
* native clients like Claude Code register `http://localhost/callback` and then
|
|
@@ -379,7 +408,7 @@ export async function startAuthorize(p) {
|
|
|
379
408
|
if (!client) {
|
|
380
409
|
return { ok: false, error: "invalid_client", error_description: "Unknown client_id. Register first via /register.", redirectable: false };
|
|
381
410
|
}
|
|
382
|
-
if (!p.redirect_uri || !client.redirect_uris.some((r) => redirectMatches(r, p.redirect_uri))) {
|
|
411
|
+
if (!p.redirect_uri || !isAllowedRedirect(p.redirect_uri) || !client.redirect_uris.some((r) => redirectMatches(r, p.redirect_uri))) {
|
|
383
412
|
return { ok: false, error: "invalid_request", error_description: "redirect_uri does not match a registered URI.", redirectable: false };
|
|
384
413
|
}
|
|
385
414
|
// From here errors CAN go back to the client's redirect_uri.
|
|
@@ -398,7 +427,7 @@ export async function startAuthorize(p) {
|
|
|
398
427
|
scope: p.scope ?? undefined,
|
|
399
428
|
expiresAt: now() + PENDING_TTL,
|
|
400
429
|
});
|
|
401
|
-
return { ok: true, internalState };
|
|
430
|
+
return { ok: true, internalState, clientName: client.client_name };
|
|
402
431
|
}
|
|
403
432
|
/**
|
|
404
433
|
* The login page (/mcp-connect) bounced back with the user's `ljwt` (+ optional
|
|
@@ -453,9 +482,11 @@ export async function exchangeToken(p) {
|
|
|
453
482
|
return { ok: true, body: await issueTokens(store, c.ljwt, c.wsid, c.client_id, c.scope) };
|
|
454
483
|
}
|
|
455
484
|
if (p.grant_type === "refresh_token") {
|
|
456
|
-
|
|
485
|
+
// Rotate — but only for the client the token was issued to: another client_id finds nothing (and
|
|
486
|
+
// burns nothing); a request without client_id keeps the binding it already has.
|
|
487
|
+
const r = p.refresh_token ? await store.takeRefresh(p.refresh_token, p.client_id) : undefined;
|
|
457
488
|
if (!r) {
|
|
458
|
-
return { ok: false, status: 400, error: "invalid_grant", error_description: "Unknown or expired refresh token." };
|
|
489
|
+
return { ok: false, status: 400, error: "invalid_grant", error_description: "Unknown or expired refresh token, or not issued to this client_id." };
|
|
459
490
|
}
|
|
460
491
|
if (await isDeadJwt(r.ljwt)) {
|
|
461
492
|
return { ok: false, status: 400, error: "invalid_grant", error_description: "Webcake session expired — sign in again (Connect)." };
|
package/dist/changelog.json
CHANGED
|
@@ -1,4 +1,18 @@
|
|
|
1
1
|
[
|
|
2
|
+
{
|
|
3
|
+
"v": "1.18.0",
|
|
4
|
+
"d": "01/12/2026",
|
|
5
|
+
"type": "Fixed",
|
|
6
|
+
"en": "The remote HTTP server (serve) now blocks render_preview, ingest_url, clone_page, and image/font re-hosting (upload_images and the automatic re-host…",
|
|
7
|
+
"vi": "Remote HTTP server (serve) nay chặn render_preview, ingest_url, clone_page, và việc re-host ảnh/font (upload_images cùng lượt re-host tự động khi…"
|
|
8
|
+
},
|
|
9
|
+
{
|
|
10
|
+
"v": "1.17.1",
|
|
11
|
+
"d": "01/12/2026",
|
|
12
|
+
"type": "Fixed",
|
|
13
|
+
"en": "The hosted remote-connector OAuth flow now rejects Dynamic Client Registration and /authorize requests whose redirect_uri is not a known MCP client…",
|
|
14
|
+
"vi": "Luồng OAuth của remote connector đã hosted nay từ chối các yêu cầu Dynamic Client Registration và /authorize có redirect_uri không phải callback của…"
|
|
15
|
+
},
|
|
2
16
|
{
|
|
3
17
|
"v": "1.17.0",
|
|
4
18
|
"d": "28/11/2026",
|
|
@@ -26,19 +40,5 @@
|
|
|
26
40
|
"type": "Added",
|
|
27
41
|
"en": "list_pages, find_pages, get_page, update_page, add_section, patch_page, and publish_page now accept an organization_id argument (an organization id,…",
|
|
28
42
|
"vi": "list_pages, find_pages, get_page, update_page, add_section, patch_page và publish_page nay nhận thêm tham số organization_id (một id tổ chức, hoặc…"
|
|
29
|
-
},
|
|
30
|
-
{
|
|
31
|
-
"v": "1.15.0",
|
|
32
|
-
"d": "23/11/2026",
|
|
33
|
-
"type": "Added",
|
|
34
|
-
"en": "api_find/api_get/api_call's route catalog now includes get:/api/v1/pages/options, a slim, filterable page list endpoint on the Webcake backend.",
|
|
35
|
-
"vi": "Danh mục route của api_find/api_get/api_call nay có thêm get:/api/v1/pages/options, một endpoint lấy danh sách trang dạng gọn, lọc được, trên…"
|
|
36
|
-
},
|
|
37
|
-
{
|
|
38
|
-
"v": "1.14.0",
|
|
39
|
-
"d": "23/11/2026",
|
|
40
|
-
"type": "Added",
|
|
41
|
-
"en": "ingest_html and ingest_url with intent:'clone' now measure a page that is not an absolute-canvas export in a real browser, the same way clone_page…",
|
|
42
|
-
"vi": "ingest_html và ingest_url với intent:'clone' nay đo trang không phải export dạng canvas tuyệt đối bằng một trình duyệt thật, giống cách clone_page…"
|
|
43
43
|
}
|
|
44
44
|
]
|
package/dist/http.js
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
*
|
|
12
12
|
* All logging stays on stderr (console.error), same as stdio mode.
|
|
13
13
|
*/
|
|
14
|
-
import { randomUUID } from "node:crypto";
|
|
14
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
15
15
|
import { readFileSync } from "node:fs";
|
|
16
16
|
import { createServer as createHttpServer } from "node:http";
|
|
17
17
|
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
@@ -21,10 +21,11 @@ import { ICON_SVG, ICON_MIME } from "./branding.js";
|
|
|
21
21
|
import { guideHtml, ogImageSvg, normalizeLang } from "./web-guide.js";
|
|
22
22
|
import { privacyHtml, termsHtml } from "./legal.js";
|
|
23
23
|
import { searchPexels, resolvePexelsKey } from "./persistence/pexels-client.js";
|
|
24
|
-
import { captureWithPlaywright, captureTilesWithPlaywright,
|
|
25
|
-
import { resolveEnv, ENVIRONMENTS, stripTrailingSlash } from "./persistence/config.js";
|
|
24
|
+
import { captureWithPlaywright, captureTilesWithPlaywright, assertPublicUrl, setSsrfGuard } from "./persistence/screenshot-playwright.js";
|
|
25
|
+
import { resolveEnv, ENVIRONMENTS, stripTrailingSlash, readConfig, configFromHeaders } from "./persistence/config.js";
|
|
26
|
+
import { listOrganizations } from "./persistence/webcake-client.js";
|
|
26
27
|
import { buildConnectUrl } from "./auth/login.js";
|
|
27
|
-
import { registerClient, startAuthorize, completeAuthorize, exchangeToken, resolveAccessToken, isDeadJwt, revokeToken, authServerMetadata, protectedResourceMetadata, } from "./auth/oauth-server.js";
|
|
28
|
+
import { registerClient, startAuthorize, completeAuthorize, exchangeToken, resolveAccessToken, isDeadJwt, markJwtDead, revokeToken, pendingCookieName, authServerMetadata, protectedResourceMetadata, } from "./auth/oauth-server.js";
|
|
28
29
|
const MCP_PATH = "/mcp";
|
|
29
30
|
const IMAGES_PATH = "/api/images/search";
|
|
30
31
|
const RENDER_SCREENSHOT_PATH = "/api/render/screenshot";
|
|
@@ -94,11 +95,13 @@ function sendJson(res, status, body) {
|
|
|
94
95
|
function rpcError(res, status, message) {
|
|
95
96
|
sendJson(res, status, { jsonrpc: "2.0", error: { code: -32000, message }, id: null });
|
|
96
97
|
}
|
|
98
|
+
// Bodies are buffered whole, so cap them: create_page payloads are big (nginx allows 20m), OAuth forms tiny.
|
|
99
|
+
const MCP_BODY_MAX = 20 * 1024 * 1024;
|
|
100
|
+
const OAUTH_BODY_MAX = 64 * 1024;
|
|
101
|
+
class BodyTooLarge extends Error {
|
|
102
|
+
}
|
|
97
103
|
async function readBody(req) {
|
|
98
|
-
const
|
|
99
|
-
for await (const c of req)
|
|
100
|
-
chunks.push(c);
|
|
101
|
-
const raw = Buffer.concat(chunks).toString("utf8").trim();
|
|
104
|
+
const raw = await readRawBody(req, MCP_BODY_MAX);
|
|
102
105
|
return raw ? JSON.parse(raw) : undefined;
|
|
103
106
|
}
|
|
104
107
|
// Map credentials passed in the URL query (e.g. .../mcp?jwt=<token>) onto the
|
|
@@ -112,11 +115,39 @@ const QUERY_AUTH = {
|
|
|
112
115
|
wsid: "x-webcake-session-id",
|
|
113
116
|
session_id: "x-webcake-session-id",
|
|
114
117
|
env: "x-webcake-env",
|
|
115
|
-
api_base: "x-webcake-api-base",
|
|
116
118
|
org_id: "x-webcake-org-id",
|
|
117
|
-
app_base: "x-webcake-app-base",
|
|
118
|
-
builder_base: "x-webcake-builder-base",
|
|
119
119
|
};
|
|
120
|
+
// The backend host receives the caller's JWT, so a remote caller must not pick it: drop
|
|
121
|
+
// every x-webcake-*-base header and keep the env presets / server env. Both views of the
|
|
122
|
+
// headers are cleaned because the transport rebuilds its Request from rawHeaders.
|
|
123
|
+
const BASE_HEADER = /^x-webcake-[a-z]+-base$/i;
|
|
124
|
+
export function stripBaseOverrides(req) {
|
|
125
|
+
for (const h of Object.keys(req.headers))
|
|
126
|
+
if (BASE_HEADER.test(h))
|
|
127
|
+
delete req.headers[h];
|
|
128
|
+
const raw = req.rawHeaders;
|
|
129
|
+
for (let i = raw.length - 2; i >= 0; i -= 2)
|
|
130
|
+
if (BASE_HEADER.test(raw[i]))
|
|
131
|
+
raw.splice(i, 2);
|
|
132
|
+
// `local` points at this server's own loopback — only when the server itself runs local.
|
|
133
|
+
if (/^local$/i.test(String(req.headers["x-webcake-env"] ?? "")) && !/^local$/i.test(process.env.WEBCAKE_ENV ?? "")) {
|
|
134
|
+
delete req.headers["x-webcake-env"];
|
|
135
|
+
for (let i = raw.length - 2; i >= 0; i -= 2)
|
|
136
|
+
if (/^x-webcake-env$/i.test(raw[i]))
|
|
137
|
+
raw.splice(i, 2);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
// __Host- (https only) stops a sibling subdomain from planting the cookie for a known state.
|
|
141
|
+
function pendingCookie(issuer, state) {
|
|
142
|
+
const https = issuer.startsWith("https:");
|
|
143
|
+
return {
|
|
144
|
+
name: `${https ? "__Host-" : ""}${pendingCookieName(state)}`,
|
|
145
|
+
attrs: `; HttpOnly; SameSite=Lax${https ? "; Path=/; Secure" : `; Path=${OAUTH_CALLBACK}`}`,
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
function hasCookie(req, name) {
|
|
149
|
+
return String(req.headers.cookie ?? "").split(/;\s*/).includes(`${name}=1`);
|
|
150
|
+
}
|
|
120
151
|
export function applyQueryAuth(req) {
|
|
121
152
|
const q = (req.url ?? "").indexOf("?");
|
|
122
153
|
if (q === -1)
|
|
@@ -155,11 +186,33 @@ function connectPageUrl() {
|
|
|
155
186
|
const appBase = stripTrailingSlash(process.env.WEBCAKE_APP_BASE || preset.appBase);
|
|
156
187
|
return `${appBase}/mcp-connect`;
|
|
157
188
|
}
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
189
|
+
function readRawBody(req, max = OAUTH_BODY_MAX) {
|
|
190
|
+
return new Promise((resolve, reject) => {
|
|
191
|
+
// Over the cap: stop buffering but keep draining (resume) — destroying the stream resets the
|
|
192
|
+
// socket and the client never sees the 413.
|
|
193
|
+
const overflow = () => {
|
|
194
|
+
req.removeAllListeners("data");
|
|
195
|
+
req.resume();
|
|
196
|
+
reject(new BodyTooLarge());
|
|
197
|
+
};
|
|
198
|
+
if (Number(req.headers["content-length"]) > max)
|
|
199
|
+
return overflow();
|
|
200
|
+
const chunks = [];
|
|
201
|
+
let total = 0;
|
|
202
|
+
req.on("data", (c) => {
|
|
203
|
+
total += c.length;
|
|
204
|
+
if (total > max)
|
|
205
|
+
overflow();
|
|
206
|
+
else
|
|
207
|
+
chunks.push(c);
|
|
208
|
+
});
|
|
209
|
+
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8").trim()));
|
|
210
|
+
req.on("error", reject);
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
function tooLarge(res) {
|
|
214
|
+
res.writeHead(413, { "content-type": "application/json" });
|
|
215
|
+
res.end(JSON.stringify({ error: "payload_too_large" }));
|
|
163
216
|
}
|
|
164
217
|
/** Parse a request body that may be JSON or application/x-www-form-urlencoded. */
|
|
165
218
|
function parseBodyParams(raw, contentType) {
|
|
@@ -187,6 +240,11 @@ function htmlError(res, status, message) {
|
|
|
187
240
|
res.writeHead(status, { "content-type": "text/html; charset=utf-8" });
|
|
188
241
|
res.end(`<!doctype html><meta charset="utf-8"><body style="font-family:system-ui;padding:40px;max-width:520px;margin:auto"><h2>Webcake connector</h2><p>${message}</p></body>`);
|
|
189
242
|
}
|
|
243
|
+
// Moves token/wsid/state from the #fragment (query as fallback) into a same-origin POST form, so
|
|
244
|
+
// the SameSite=Lax pending cookie rides along, and wipes them from the address bar first.
|
|
245
|
+
const CALLBACK_SCRIPT = `var h=new URLSearchParams(location.hash.slice(1)),q=new URLSearchParams(location.search),f=document.forms[0];["token","wsid","state"].forEach(function(k){f.elements[k].value=h.get(k)||q.get(k)||""});history.replaceState(null,"",location.pathname);f.submit();`;
|
|
246
|
+
const CALLBACK_CSP = `default-src 'none'; script-src 'sha256-${createHash("sha256").update(CALLBACK_SCRIPT).digest("base64")}'; base-uri 'none'; frame-ancestors 'none'`;
|
|
247
|
+
const CALLBACK_PAGE = `<!doctype html><meta charset="utf-8"><title>Webcake connector</title><form method="post" action="${OAUTH_CALLBACK}"><input type="hidden" name="token"><input type="hidden" name="wsid"><input type="hidden" name="state"><noscript>Enable JavaScript to finish connecting.</noscript></form><script>${CALLBACK_SCRIPT}</script>`;
|
|
190
248
|
/**
|
|
191
249
|
* Handle every OAuth 2.1 endpoint. Returns true when the request was an OAuth
|
|
192
250
|
* route (and a response was sent), false to let the caller continue routing.
|
|
@@ -256,13 +314,36 @@ async function handleOAuth(req, res, path) {
|
|
|
256
314
|
}
|
|
257
315
|
// Send the user to the SPA login; it returns here with ?token=<ljwt>[&wsid=<lwsid>]&state=<internalState>.
|
|
258
316
|
const callback = `${issuer}${OAUTH_CALLBACK}`;
|
|
259
|
-
|
|
260
|
-
|
|
317
|
+
// client_host + client_name let the consent page show who is asking and where the code goes.
|
|
318
|
+
const loginUrl = buildConnectUrl(connectPageUrl(), callback, result.internalState, {
|
|
319
|
+
client_host: new URL(sp.get("redirect_uri")).hostname,
|
|
320
|
+
client_name: result.clientName ? Array.from(result.clientName).slice(0, 60).join("") : undefined,
|
|
321
|
+
});
|
|
322
|
+
const c = pendingCookie(issuer, result.internalState);
|
|
323
|
+
res.writeHead(302, { location: loginUrl, "set-cookie": `${c.name}=1; Max-Age=600${c.attrs}` });
|
|
261
324
|
return res.end(), true;
|
|
262
325
|
}
|
|
263
326
|
// ---- Login callback: the SPA handed back the user's ljwt → mint a code ----
|
|
264
|
-
|
|
265
|
-
|
|
327
|
+
// Legacy: GET ?token=&wsid=&state=. Preferred: the SPA puts them in the #fragment (never sent to a
|
|
328
|
+
// server or logged); GET then serves CALLBACK_PAGE, which re-POSTs them here from the same origin.
|
|
329
|
+
if (path === OAUTH_CALLBACK && (req.method === "GET" || req.method === "POST")) {
|
|
330
|
+
const sp = req.method === "POST" ? new URLSearchParams(await readRawBody(req)) : new URL(req.url ?? "/", "http://x").searchParams;
|
|
331
|
+
if (req.method === "GET" && !sp.get("token")) {
|
|
332
|
+
res.writeHead(200, {
|
|
333
|
+
"content-type": "text/html; charset=utf-8",
|
|
334
|
+
"cache-control": "no-store",
|
|
335
|
+
"referrer-policy": "no-referrer",
|
|
336
|
+
"content-security-policy": CALLBACK_CSP,
|
|
337
|
+
});
|
|
338
|
+
return res.end(CALLBACK_PAGE), true;
|
|
339
|
+
}
|
|
340
|
+
// Only the browser that opened /authorize may complete it — otherwise a link carrying
|
|
341
|
+
// someone else's state binds the victim's login to the attacker's client.
|
|
342
|
+
const state = sp.get("state");
|
|
343
|
+
const c = state ? pendingCookie(issuer, state) : undefined;
|
|
344
|
+
if (!c || !hasCookie(req, c.name)) {
|
|
345
|
+
return htmlError(res, 400, "This connection was not started in this browser — restart it from your AI app."), true;
|
|
346
|
+
}
|
|
266
347
|
const done = await completeAuthorize(sp.get("state"), sp.get("token"), sp.get("wsid") || sp.get("session_id"));
|
|
267
348
|
if (!done.ok)
|
|
268
349
|
return htmlError(res, 400, done.error_description), true;
|
|
@@ -270,7 +351,7 @@ async function handleOAuth(req, res, path) {
|
|
|
270
351
|
r.searchParams.set("code", done.code);
|
|
271
352
|
if (done.state)
|
|
272
353
|
r.searchParams.set("state", done.state);
|
|
273
|
-
res.writeHead(302, { location: r.toString() });
|
|
354
|
+
res.writeHead(302, { location: r.toString(), "set-cookie": `${c.name}=; Max-Age=0${c.attrs}`, "referrer-policy": "no-referrer" });
|
|
274
355
|
return res.end(), true;
|
|
275
356
|
}
|
|
276
357
|
// ---- Token ----
|
|
@@ -368,15 +449,20 @@ async function handleRenderScreenshot(req, res) {
|
|
|
368
449
|
const target = sp.get("url")?.trim();
|
|
369
450
|
if (!target)
|
|
370
451
|
return sendErr(400, { ok: false, error: "Pass ?url=<public http(s) URL>." });
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
452
|
+
try {
|
|
453
|
+
await assertPublicUrl(target);
|
|
454
|
+
}
|
|
455
|
+
catch (e) {
|
|
456
|
+
return sendErr(400, { ok: false, error: e.message });
|
|
457
|
+
}
|
|
374
458
|
const fullPage = sp.get("full_page") !== "false";
|
|
375
|
-
|
|
459
|
+
// Clamped: a huge viewport / band is a cheap way to exhaust the host's memory.
|
|
460
|
+
const clamp = (v, lo, hi) => (v && Number.isFinite(Number(v)) ? Math.min(hi, Math.max(lo, Number(v))) : undefined);
|
|
461
|
+
const width = clamp(sp.get("width"), 320, 1920);
|
|
376
462
|
// Tiles mode: split a tall page into horizontal bands, returned as a JSON array
|
|
377
463
|
// of base64 images (top→bottom) so the model reads each slice at a readable size.
|
|
378
464
|
if (sp.get("tiles") === "1" || sp.get("tiles") === "true") {
|
|
379
|
-
const bandHeight = sp.get("band_height")
|
|
465
|
+
const bandHeight = clamp(sp.get("band_height"), 200, 4000);
|
|
380
466
|
const t = await captureTilesWithPlaywright(target, { width, bandHeight });
|
|
381
467
|
if (!t.ok)
|
|
382
468
|
return sendErr(t.reason === "not_installed" ? 503 : 502, { ok: false, error: t.error });
|
|
@@ -398,9 +484,36 @@ async function handleRenderScreenshot(req, res) {
|
|
|
398
484
|
res.writeHead(200, { "content-type": r.mimeType, "cache-control": "no-store", ...cors });
|
|
399
485
|
return res.end(r.data);
|
|
400
486
|
}
|
|
487
|
+
// Each session holds a whole McpServer in memory: close idle ones, cap the total, and cap each
|
|
488
|
+
// credential so one caller can't evict everyone else's sessions.
|
|
489
|
+
const SESSION_IDLE_MS = 30 * 60_000;
|
|
490
|
+
const MAX_SESSIONS = 500;
|
|
491
|
+
const MAX_SESSIONS_PER_CRED = 20;
|
|
401
492
|
export async function startHttpServer(port) {
|
|
402
|
-
//
|
|
493
|
+
setSsrfGuard(true); // hosted: caller-chosen URLs must not reach this host's private network
|
|
494
|
+
// mcp-session-id -> live session (each bound to its own McpServer instance), in least-recently-used
|
|
495
|
+
// order: a request re-inserts its session at the end, so the oldest idle ones sit first. `busy`
|
|
496
|
+
// counts open responses (incl. SSE streams); a busy session is never evicted.
|
|
403
497
|
const transports = new Map();
|
|
498
|
+
const evict = (id) => {
|
|
499
|
+
const s = transports.get(id);
|
|
500
|
+
transports.delete(id);
|
|
501
|
+
s?.transport.close().catch(() => { });
|
|
502
|
+
};
|
|
503
|
+
/** Oldest session that is not mid-request (of `cred` when given); undefined when all are busy. */
|
|
504
|
+
const oldestIdle = (cred) => {
|
|
505
|
+
for (const [id, s] of transports)
|
|
506
|
+
if (!s.busy && (cred === undefined || s.cred === cred))
|
|
507
|
+
return id;
|
|
508
|
+
};
|
|
509
|
+
setInterval(() => {
|
|
510
|
+
for (const [id, s] of transports) {
|
|
511
|
+
if (Date.now() - s.seen < SESSION_IDLE_MS)
|
|
512
|
+
break;
|
|
513
|
+
if (!s.busy)
|
|
514
|
+
evict(id);
|
|
515
|
+
}
|
|
516
|
+
}, 60_000).unref();
|
|
404
517
|
const httpServer = createHttpServer(async (req, res) => {
|
|
405
518
|
const path = (req.url ?? "").split("?")[0];
|
|
406
519
|
// Brand icon — clients (e.g. the claude.ai connector) fetch a favicon from the
|
|
@@ -469,12 +582,20 @@ export async function startHttpServer(port) {
|
|
|
469
582
|
if (path === RENDER_SCREENSHOT_PATH)
|
|
470
583
|
return handleRenderScreenshot(req, res);
|
|
471
584
|
// OAuth 2.1 endpoints (always served; see handleOAuth). Returns true if handled.
|
|
472
|
-
|
|
473
|
-
|
|
585
|
+
try {
|
|
586
|
+
if (await handleOAuth(req, res, path))
|
|
587
|
+
return;
|
|
588
|
+
}
|
|
589
|
+
catch (err) {
|
|
590
|
+
if (err instanceof BodyTooLarge)
|
|
591
|
+
return tooLarge(res);
|
|
592
|
+
throw err;
|
|
593
|
+
}
|
|
474
594
|
if (path !== MCP_PATH)
|
|
475
595
|
return rpcError(res, 404, `Not found. Send MCP requests to ${MCP_PATH}.`);
|
|
476
|
-
// Accept credentials via ?jwt=/?
|
|
596
|
+
// Accept credentials via ?jwt=/?env=/... (for clients that can't set headers).
|
|
477
597
|
applyQueryAuth(req);
|
|
598
|
+
stripBaseOverrides(req);
|
|
478
599
|
// OAuth access token → resolve to the user's landing JWT and inject it as the
|
|
479
600
|
// normal x-webcake-jwt header, so persistence/config.ts is unchanged. It WINS over a
|
|
480
601
|
// ?jwt= / x-webcake-jwt: a Bearer from our OAuth flow is what the last Connect issued,
|
|
@@ -493,24 +614,35 @@ export async function startHttpServer(port) {
|
|
|
493
614
|
// WWW-Authenticate so Claude/ChatGPT (re)open the Connect page by themselves. In
|
|
494
615
|
// enforced mode a raw JWT must use x-webcake-jwt / ?jwt=, since Bearer is reserved
|
|
495
616
|
// for OAuth access tokens.
|
|
496
|
-
const
|
|
497
|
-
const
|
|
498
|
-
|
|
617
|
+
const givenRaw = req.headers["x-webcake-jwt"];
|
|
618
|
+
const given = Array.isArray(givenRaw) ? givenRaw[0] : givenRaw;
|
|
619
|
+
const unauthorized = (why) => {
|
|
499
620
|
res.writeHead(401, {
|
|
500
621
|
"www-authenticate": `Bearer error="invalid_token", resource_metadata="${publicBase(req)}${WELL_KNOWN_PR}"`,
|
|
501
622
|
"content-type": "application/json",
|
|
502
623
|
});
|
|
503
|
-
|
|
504
|
-
|
|
624
|
+
res.end(JSON.stringify({ error: "invalid_token", error_description: why }));
|
|
625
|
+
};
|
|
626
|
+
const dead = await isDeadJwt(given);
|
|
627
|
+
if (OAUTH_ENFORCED && (!given || dead)) {
|
|
628
|
+
return unauthorized(dead ? "Webcake session expired — reconnect (Connect) to renew it." : "Authentication required — connect via OAuth.");
|
|
505
629
|
}
|
|
630
|
+
const cred = createHash("sha256").update(given ?? "").digest("hex");
|
|
506
631
|
const sidHeader = req.headers["mcp-session-id"];
|
|
507
632
|
const sessionId = Array.isArray(sidHeader) ? sidHeader[0] : sidHeader;
|
|
508
633
|
try {
|
|
509
634
|
// Existing session: delegate any method (POST/GET/DELETE) to its transport.
|
|
510
635
|
if (sessionId && transports.has(sessionId)) {
|
|
511
|
-
const
|
|
636
|
+
const s = transports.get(sessionId);
|
|
637
|
+
transports.delete(sessionId);
|
|
638
|
+
transports.set(sessionId, s);
|
|
639
|
+
s.busy++;
|
|
640
|
+
res.on("close", () => {
|
|
641
|
+
s.busy--;
|
|
642
|
+
s.seen = Date.now();
|
|
643
|
+
});
|
|
512
644
|
const body = req.method === "POST" ? await readBody(req) : undefined;
|
|
513
|
-
await transport.handleRequest(req, res, body);
|
|
645
|
+
await s.transport.handleRequest(req, res, body);
|
|
514
646
|
return;
|
|
515
647
|
}
|
|
516
648
|
// Unknown session (e.g. sessions are in-memory and the server restarted):
|
|
@@ -522,10 +654,29 @@ export async function startHttpServer(port) {
|
|
|
522
654
|
if (req.method === "POST") {
|
|
523
655
|
const body = await readBody(req);
|
|
524
656
|
if (!sessionId && isInitializeRequest(body)) {
|
|
657
|
+
// Presence is not proof: a made-up JWT must not open sessions (and evict real ones). Ask the
|
|
658
|
+
// backend once per credential — a live session of the same credential already proved it.
|
|
659
|
+
// Only a 401 refuses; a timeout / 5xx lets it through as before.
|
|
660
|
+
if (OAUTH_ENFORCED && ![...transports.values()].some((t) => t.cred === cred)) {
|
|
661
|
+
const { config } = readConfig(configFromHeaders(req.headers));
|
|
662
|
+
if (config && (await listOrganizations(config)).status === 401) {
|
|
663
|
+
await markJwtDead(given);
|
|
664
|
+
return unauthorized("Webcake rejected this token — reconnect (Connect) to renew it.");
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
let mine = 0;
|
|
668
|
+
for (const t of transports.values())
|
|
669
|
+
if (t.cred === cred)
|
|
670
|
+
mine++;
|
|
671
|
+
const victim = mine >= MAX_SESSIONS_PER_CRED ? oldestIdle(cred) : transports.size >= MAX_SESSIONS ? oldestIdle() : null;
|
|
672
|
+
if (victim === undefined)
|
|
673
|
+
return rpcError(res, 429, "Too many open sessions — close one and retry.");
|
|
674
|
+
if (victim)
|
|
675
|
+
evict(victim);
|
|
525
676
|
const transport = new StreamableHTTPServerTransport({
|
|
526
677
|
sessionIdGenerator: () => randomUUID(),
|
|
527
678
|
onsessioninitialized: (id) => {
|
|
528
|
-
transports.set(id, transport);
|
|
679
|
+
transports.set(id, { transport, seen: Date.now(), cred, busy: 0 });
|
|
529
680
|
},
|
|
530
681
|
});
|
|
531
682
|
transport.onclose = () => {
|
|
@@ -542,6 +693,8 @@ export async function startHttpServer(port) {
|
|
|
542
693
|
return rpcError(res, 400, "Bad Request: missing or unknown mcp-session-id.");
|
|
543
694
|
}
|
|
544
695
|
catch (err) {
|
|
696
|
+
if (err instanceof BodyTooLarge)
|
|
697
|
+
return tooLarge(res);
|
|
545
698
|
console.error("[webcake-http] request error:", err);
|
|
546
699
|
if (!res.headersSent)
|
|
547
700
|
rpcError(res, 500, "Internal server error.");
|
package/dist/mcp/params.js
CHANGED
|
@@ -2,7 +2,7 @@ import { z } from "zod";
|
|
|
2
2
|
// Typed stand-ins for z.any(): directory reviewers (and some clients) reject
|
|
3
3
|
// params whose JSON Schema has no `type`. Handlers still parse JSON strings.
|
|
4
4
|
// Fresh instance per use: a shared one makes zod-to-json-schema emit a `$ref`.
|
|
5
|
-
const jsonObject = () => z.record(z.any());
|
|
5
|
+
const jsonObject = () => z.record(z.string(), z.any());
|
|
6
6
|
/** A JSON object, or a JSON string of one. */
|
|
7
7
|
export const objectOrJson = () => z.union([jsonObject(), z.string()]);
|
|
8
8
|
/** A JSON object, an array of them, or a JSON string of either. */
|