webcake-landing-mcp 1.17.1 → 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/dist/auth/login.js +6 -2
- package/dist/auth/oauth-server.js +10 -6
- package/dist/changelog.json +7 -7
- package/dist/http.js +149 -33
- 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 +57 -4
- package/dist/tools/media.js +10 -48
- package/package.json +1 -1
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;
|
|
@@ -425,7 +427,7 @@ export async function startAuthorize(p) {
|
|
|
425
427
|
scope: p.scope ?? undefined,
|
|
426
428
|
expiresAt: now() + PENDING_TTL,
|
|
427
429
|
});
|
|
428
|
-
return { ok: true, internalState };
|
|
430
|
+
return { ok: true, internalState, clientName: client.client_name };
|
|
429
431
|
}
|
|
430
432
|
/**
|
|
431
433
|
* The login page (/mcp-connect) bounced back with the user's `ljwt` (+ optional
|
|
@@ -480,9 +482,11 @@ export async function exchangeToken(p) {
|
|
|
480
482
|
return { ok: true, body: await issueTokens(store, c.ljwt, c.wsid, c.client_id, c.scope) };
|
|
481
483
|
}
|
|
482
484
|
if (p.grant_type === "refresh_token") {
|
|
483
|
-
|
|
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;
|
|
484
488
|
if (!r) {
|
|
485
|
-
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." };
|
|
486
490
|
}
|
|
487
491
|
if (await isDeadJwt(r.ljwt)) {
|
|
488
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,11 @@
|
|
|
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
|
+
},
|
|
2
9
|
{
|
|
3
10
|
"v": "1.17.1",
|
|
4
11
|
"d": "01/12/2026",
|
|
@@ -33,12 +40,5 @@
|
|
|
33
40
|
"type": "Added",
|
|
34
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,…",
|
|
35
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…"
|
|
36
|
-
},
|
|
37
|
-
{
|
|
38
|
-
"v": "1.15.0",
|
|
39
|
-
"d": "23/11/2026",
|
|
40
|
-
"type": "Added",
|
|
41
|
-
"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.",
|
|
42
|
-
"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…"
|
|
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, pendingCookieName, 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
|
|
@@ -183,11 +186,33 @@ function connectPageUrl() {
|
|
|
183
186
|
const appBase = stripTrailingSlash(process.env.WEBCAKE_APP_BASE || preset.appBase);
|
|
184
187
|
return `${appBase}/mcp-connect`;
|
|
185
188
|
}
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
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" }));
|
|
191
216
|
}
|
|
192
217
|
/** Parse a request body that may be JSON or application/x-www-form-urlencoded. */
|
|
193
218
|
function parseBodyParams(raw, contentType) {
|
|
@@ -215,6 +240,11 @@ function htmlError(res, status, message) {
|
|
|
215
240
|
res.writeHead(status, { "content-type": "text/html; charset=utf-8" });
|
|
216
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>`);
|
|
217
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>`;
|
|
218
248
|
/**
|
|
219
249
|
* Handle every OAuth 2.1 endpoint. Returns true when the request was an OAuth
|
|
220
250
|
* route (and a response was sent), false to let the caller continue routing.
|
|
@@ -284,14 +314,29 @@ async function handleOAuth(req, res, path) {
|
|
|
284
314
|
}
|
|
285
315
|
// Send the user to the SPA login; it returns here with ?token=<ljwt>[&wsid=<lwsid>]&state=<internalState>.
|
|
286
316
|
const callback = `${issuer}${OAUTH_CALLBACK}`;
|
|
287
|
-
|
|
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
|
+
});
|
|
288
322
|
const c = pendingCookie(issuer, result.internalState);
|
|
289
323
|
res.writeHead(302, { location: loginUrl, "set-cookie": `${c.name}=1; Max-Age=600${c.attrs}` });
|
|
290
324
|
return res.end(), true;
|
|
291
325
|
}
|
|
292
326
|
// ---- Login callback: the SPA handed back the user's ljwt → mint a code ----
|
|
293
|
-
|
|
294
|
-
|
|
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
|
+
}
|
|
295
340
|
// Only the browser that opened /authorize may complete it — otherwise a link carrying
|
|
296
341
|
// someone else's state binds the victim's login to the attacker's client.
|
|
297
342
|
const state = sp.get("state");
|
|
@@ -306,7 +351,7 @@ async function handleOAuth(req, res, path) {
|
|
|
306
351
|
r.searchParams.set("code", done.code);
|
|
307
352
|
if (done.state)
|
|
308
353
|
r.searchParams.set("state", done.state);
|
|
309
|
-
res.writeHead(302, { location: r.toString(), "set-cookie": `${c.name}=; Max-Age=0${c.attrs}
|
|
354
|
+
res.writeHead(302, { location: r.toString(), "set-cookie": `${c.name}=; Max-Age=0${c.attrs}`, "referrer-policy": "no-referrer" });
|
|
310
355
|
return res.end(), true;
|
|
311
356
|
}
|
|
312
357
|
// ---- Token ----
|
|
@@ -404,15 +449,20 @@ async function handleRenderScreenshot(req, res) {
|
|
|
404
449
|
const target = sp.get("url")?.trim();
|
|
405
450
|
if (!target)
|
|
406
451
|
return sendErr(400, { ok: false, error: "Pass ?url=<public http(s) URL>." });
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
452
|
+
try {
|
|
453
|
+
await assertPublicUrl(target);
|
|
454
|
+
}
|
|
455
|
+
catch (e) {
|
|
456
|
+
return sendErr(400, { ok: false, error: e.message });
|
|
457
|
+
}
|
|
410
458
|
const fullPage = sp.get("full_page") !== "false";
|
|
411
|
-
|
|
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);
|
|
412
462
|
// Tiles mode: split a tall page into horizontal bands, returned as a JSON array
|
|
413
463
|
// of base64 images (top→bottom) so the model reads each slice at a readable size.
|
|
414
464
|
if (sp.get("tiles") === "1" || sp.get("tiles") === "true") {
|
|
415
|
-
const bandHeight = sp.get("band_height")
|
|
465
|
+
const bandHeight = clamp(sp.get("band_height"), 200, 4000);
|
|
416
466
|
const t = await captureTilesWithPlaywright(target, { width, bandHeight });
|
|
417
467
|
if (!t.ok)
|
|
418
468
|
return sendErr(t.reason === "not_installed" ? 503 : 502, { ok: false, error: t.error });
|
|
@@ -434,9 +484,36 @@ async function handleRenderScreenshot(req, res) {
|
|
|
434
484
|
res.writeHead(200, { "content-type": r.mimeType, "cache-control": "no-store", ...cors });
|
|
435
485
|
return res.end(r.data);
|
|
436
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;
|
|
437
492
|
export async function startHttpServer(port) {
|
|
438
|
-
//
|
|
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.
|
|
439
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();
|
|
440
517
|
const httpServer = createHttpServer(async (req, res) => {
|
|
441
518
|
const path = (req.url ?? "").split("?")[0];
|
|
442
519
|
// Brand icon — clients (e.g. the claude.ai connector) fetch a favicon from the
|
|
@@ -505,8 +582,15 @@ export async function startHttpServer(port) {
|
|
|
505
582
|
if (path === RENDER_SCREENSHOT_PATH)
|
|
506
583
|
return handleRenderScreenshot(req, res);
|
|
507
584
|
// OAuth 2.1 endpoints (always served; see handleOAuth). Returns true if handled.
|
|
508
|
-
|
|
509
|
-
|
|
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
|
+
}
|
|
510
594
|
if (path !== MCP_PATH)
|
|
511
595
|
return rpcError(res, 404, `Not found. Send MCP requests to ${MCP_PATH}.`);
|
|
512
596
|
// Accept credentials via ?jwt=/?env=/... (for clients that can't set headers).
|
|
@@ -530,24 +614,35 @@ export async function startHttpServer(port) {
|
|
|
530
614
|
// WWW-Authenticate so Claude/ChatGPT (re)open the Connect page by themselves. In
|
|
531
615
|
// enforced mode a raw JWT must use x-webcake-jwt / ?jwt=, since Bearer is reserved
|
|
532
616
|
// for OAuth access tokens.
|
|
533
|
-
const
|
|
534
|
-
const
|
|
535
|
-
|
|
617
|
+
const givenRaw = req.headers["x-webcake-jwt"];
|
|
618
|
+
const given = Array.isArray(givenRaw) ? givenRaw[0] : givenRaw;
|
|
619
|
+
const unauthorized = (why) => {
|
|
536
620
|
res.writeHead(401, {
|
|
537
621
|
"www-authenticate": `Bearer error="invalid_token", resource_metadata="${publicBase(req)}${WELL_KNOWN_PR}"`,
|
|
538
622
|
"content-type": "application/json",
|
|
539
623
|
});
|
|
540
|
-
|
|
541
|
-
|
|
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.");
|
|
542
629
|
}
|
|
630
|
+
const cred = createHash("sha256").update(given ?? "").digest("hex");
|
|
543
631
|
const sidHeader = req.headers["mcp-session-id"];
|
|
544
632
|
const sessionId = Array.isArray(sidHeader) ? sidHeader[0] : sidHeader;
|
|
545
633
|
try {
|
|
546
634
|
// Existing session: delegate any method (POST/GET/DELETE) to its transport.
|
|
547
635
|
if (sessionId && transports.has(sessionId)) {
|
|
548
|
-
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
|
+
});
|
|
549
644
|
const body = req.method === "POST" ? await readBody(req) : undefined;
|
|
550
|
-
await transport.handleRequest(req, res, body);
|
|
645
|
+
await s.transport.handleRequest(req, res, body);
|
|
551
646
|
return;
|
|
552
647
|
}
|
|
553
648
|
// Unknown session (e.g. sessions are in-memory and the server restarted):
|
|
@@ -559,10 +654,29 @@ export async function startHttpServer(port) {
|
|
|
559
654
|
if (req.method === "POST") {
|
|
560
655
|
const body = await readBody(req);
|
|
561
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);
|
|
562
676
|
const transport = new StreamableHTTPServerTransport({
|
|
563
677
|
sessionIdGenerator: () => randomUUID(),
|
|
564
678
|
onsessioninitialized: (id) => {
|
|
565
|
-
transports.set(id, transport);
|
|
679
|
+
transports.set(id, { transport, seen: Date.now(), cred, busy: 0 });
|
|
566
680
|
},
|
|
567
681
|
});
|
|
568
682
|
transport.onclose = () => {
|
|
@@ -579,6 +693,8 @@ export async function startHttpServer(port) {
|
|
|
579
693
|
return rpcError(res, 400, "Bad Request: missing or unknown mcp-session-id.");
|
|
580
694
|
}
|
|
581
695
|
catch (err) {
|
|
696
|
+
if (err instanceof BodyTooLarge)
|
|
697
|
+
return tooLarge(res);
|
|
582
698
|
console.error("[webcake-http] request error:", err);
|
|
583
699
|
if (!res.headersSent)
|
|
584
700
|
rpcError(res, 500, "Internal server error.");
|
|
@@ -19,7 +19,7 @@ import { extractTailwindConfig } from "./ingest/tailwind.js";
|
|
|
19
19
|
import { findSections, classifySection, computeSizeHint, detectWidgets, detectHoverEffects, brandHints, pickHeading } from "./ingest/semantic.js";
|
|
20
20
|
import { parseAbsoluteCanvas, canvasRoleSections, stripCdnSizePrefix } from "./ingest/canvas.js";
|
|
21
21
|
import { extractFontFaces, toFontGroups, extractTypography, parseCssRules, makeTypeResolver, resolveCssVars, rootFontPx, stripComments } from "./ingest/fonts.js";
|
|
22
|
-
import {
|
|
22
|
+
import { fetchPublic } from "./screenshot-playwright.js";
|
|
23
23
|
// Re-export the public surface so existing imports of "./persistence/html-ingest.js"
|
|
24
24
|
// (parseHtml, fetchHtml, and the IngestedAst/IngestedCanvas/CanvasElement/CanvasSection
|
|
25
25
|
// types) keep resolving unchanged.
|
|
@@ -194,33 +194,15 @@ export async function fetchHtml(url, opts = {}) {
|
|
|
194
194
|
const ctrl = new AbortController();
|
|
195
195
|
const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs ?? FETCH_TIMEOUT_MS);
|
|
196
196
|
try {
|
|
197
|
-
//
|
|
198
|
-
//
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
res = await fetch(target, {
|
|
207
|
-
headers: {
|
|
208
|
-
"User-Agent": opts.userAgent ?? "Mozilla/5.0 (compatible; webcake-landing-mcp/ingest_url)",
|
|
209
|
-
Accept: "text/html,application/xhtml+xml,text/plain;q=0.9,*/*;q=0.5",
|
|
210
|
-
},
|
|
211
|
-
signal: ctrl.signal,
|
|
212
|
-
redirect: "manual",
|
|
213
|
-
});
|
|
214
|
-
if (res.status < 300 || res.status >= 400)
|
|
215
|
-
break;
|
|
216
|
-
const loc = res.headers.get("location");
|
|
217
|
-
if (!loc)
|
|
218
|
-
return { ok: false, status: res.status, error: `Redirect ${res.status} without a Location header` };
|
|
219
|
-
target = new URL(loc, target).href;
|
|
220
|
-
res = undefined;
|
|
221
|
-
}
|
|
222
|
-
if (!res)
|
|
223
|
-
return { ok: false, error: `Too many redirects (> ${MAX_REDIRECTS})` };
|
|
197
|
+
// fetchPublic blocks private/loopback/link-local targets and re-checks every redirect hop; in
|
|
198
|
+
// stdio the user's own URL host is exempt (a localhost dev page), never in serve.
|
|
199
|
+
const res = await fetchPublic(url, {
|
|
200
|
+
headers: {
|
|
201
|
+
"User-Agent": opts.userAgent ?? "Mozilla/5.0 (compatible; webcake-landing-mcp/ingest_url)",
|
|
202
|
+
Accept: "text/html,application/xhtml+xml,text/plain;q=0.9,*/*;q=0.5",
|
|
203
|
+
},
|
|
204
|
+
signal: ctrl.signal,
|
|
205
|
+
}, url);
|
|
224
206
|
if (!res.ok)
|
|
225
207
|
return { ok: false, status: res.status, error: `Server returned ${res.status}` };
|
|
226
208
|
const ctype = res.headers.get("content-type") ?? "";
|
|
@@ -265,7 +247,6 @@ async function readCapped(res, max) {
|
|
|
265
247
|
}
|
|
266
248
|
const MAX_STYLESHEETS = 12;
|
|
267
249
|
const MAX_CSS_BYTES = 1_000_000;
|
|
268
|
-
const MAX_REDIRECTS = 3;
|
|
269
250
|
/** One attribute of a raw tag (quoted or bare); `data-href` never matches `href`. */
|
|
270
251
|
function tagAttr(tag, name) {
|
|
271
252
|
const m = new RegExp(`[\\s"']${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'>]+))`, "i").exec(tag);
|
|
@@ -309,46 +290,27 @@ function cssImports(css) {
|
|
|
309
290
|
* followed MANUALLY so each hop is re-checked, CSS/text content-type only, and the
|
|
310
291
|
* body streamed with a byte cap.
|
|
311
292
|
*/
|
|
312
|
-
async function fetchCss(url) {
|
|
313
|
-
let
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
try {
|
|
333
|
-
target = new URL(loc, target).href;
|
|
334
|
-
}
|
|
335
|
-
catch {
|
|
336
|
-
return null;
|
|
337
|
-
}
|
|
338
|
-
continue;
|
|
339
|
-
}
|
|
340
|
-
const ctype = (res.headers.get("content-type") ?? "").toLowerCase();
|
|
341
|
-
if (!res.ok || (ctype && !/css|text\/plain|octet-stream/.test(ctype)))
|
|
342
|
-
return null;
|
|
343
|
-
try {
|
|
344
|
-
const buf = await readCapped(res, MAX_CSS_BYTES);
|
|
345
|
-
return buf && buf !== "too-large" ? buf.toString("utf-8") : null;
|
|
346
|
-
}
|
|
347
|
-
catch {
|
|
348
|
-
return null;
|
|
349
|
-
}
|
|
293
|
+
async function fetchCss(url, pageUrl) {
|
|
294
|
+
let res;
|
|
295
|
+
try {
|
|
296
|
+
res = await fetchPublic(url, {
|
|
297
|
+
signal: AbortSignal.timeout(8_000),
|
|
298
|
+
headers: { "User-Agent": "Mozilla/5.0 (compatible; webcake-landing-mcp/ingest_url)", Accept: "text/css,*/*;q=0.1" },
|
|
299
|
+
}, pageUrl);
|
|
300
|
+
}
|
|
301
|
+
catch {
|
|
302
|
+
return null;
|
|
303
|
+
}
|
|
304
|
+
const ctype = (res.headers.get("content-type") ?? "").toLowerCase();
|
|
305
|
+
if (!res.ok || (ctype && !/css|text\/plain|octet-stream/.test(ctype)))
|
|
306
|
+
return null;
|
|
307
|
+
try {
|
|
308
|
+
const buf = await readCapped(res, MAX_CSS_BYTES);
|
|
309
|
+
return buf && buf !== "too-large" ? buf.toString("utf-8") : null;
|
|
310
|
+
}
|
|
311
|
+
catch {
|
|
312
|
+
return null;
|
|
350
313
|
}
|
|
351
|
-
return null;
|
|
352
314
|
}
|
|
353
315
|
/**
|
|
354
316
|
* Fetch the page's external stylesheets — and what they (or inline <style> blocks)
|
|
@@ -374,7 +336,7 @@ export async function fetchStylesheets(html, pageUrl) {
|
|
|
374
336
|
};
|
|
375
337
|
// One sheet → [its imports' sheets (recursively, in order)…, itself].
|
|
376
338
|
const load = async (abs, owner, depth) => {
|
|
377
|
-
const css = await fetchCss(abs);
|
|
339
|
+
const css = await fetchCss(abs, pageUrl);
|
|
378
340
|
if (css === null)
|
|
379
341
|
return [];
|
|
380
342
|
const imports = depth < 2 ? cssImports(css).map((h) => claim(h, abs)).filter((h) => !!h) : [];
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { withContext,
|
|
1
|
+
import { withContext, assertPublicUrl, guardContext } from "../screenshot-playwright.js";
|
|
2
2
|
export const DESKTOP_VIEWPORT = 1200;
|
|
3
3
|
const DESKTOP_CANVAS = 960;
|
|
4
4
|
const MOBILE_CANVAS = 420;
|
|
@@ -1085,12 +1085,7 @@ async function captureAt(target, width) {
|
|
|
1085
1085
|
const r = await withContext(width, 1, async (ctx) => {
|
|
1086
1086
|
// Every request the page makes (subresources, redirects, html-embedded urls) passes the same
|
|
1087
1087
|
// public-host guard as the url itself: no SSRF into the host's private network.
|
|
1088
|
-
await ctx
|
|
1089
|
-
const u = route.request().url();
|
|
1090
|
-
return /^(data|blob|about):/.test(u) || (await isPublicUrl(u)) ? route.continue() : route.abort();
|
|
1091
|
-
});
|
|
1092
|
-
// WebSockets bypass ctx.route: refuse them outright (a measurement needs none)
|
|
1093
|
-
await ctx.routeWebSocket?.("**/*", (ws) => ws.close()).catch?.(() => undefined);
|
|
1088
|
+
await guardContext(ctx, target.url ?? target.baseUrl); // stdio: the user's own page host stays reachable
|
|
1094
1089
|
const page = await ctx.newPage();
|
|
1095
1090
|
try {
|
|
1096
1091
|
if (target.url) {
|
|
@@ -1383,13 +1378,8 @@ export function mergeCaptures(desk, mob) {
|
|
|
1383
1378
|
}
|
|
1384
1379
|
/** Load the page in Chrome at DESKTOP_VIEWPORT and at the mobile canvas width; measure; merge. */
|
|
1385
1380
|
export async function captureLayout(target) {
|
|
1386
|
-
if (target.url)
|
|
1387
|
-
|
|
1388
|
-
if (!ok.ok)
|
|
1389
|
-
throw new Error(ok.error);
|
|
1390
|
-
if (!(await isPublicUrl(target.url)))
|
|
1391
|
-
throw new Error("the url resolves to a private / loopback address");
|
|
1392
|
-
}
|
|
1381
|
+
if (target.url)
|
|
1382
|
+
await assertPublicUrl(target.url, target.url);
|
|
1393
1383
|
const desk = await captureAt(target, DESKTOP_VIEWPORT);
|
|
1394
1384
|
const mob = await captureAt(target, MOBILE_CANVAS).catch(() => null);
|
|
1395
1385
|
return mergeCaptures(desk, mob);
|
|
@@ -36,6 +36,47 @@ const SKIP_HOSTS = [
|
|
|
36
36
|
const IMAGE_EXT_RE = /\.(jpe?g|png|gif|webp|svg|bmp|avif|ico|tiff?)(?:[?#]|$)/i;
|
|
37
37
|
/** Self-hosted font files (a clone's settings.fontGroups[].fonts[].url) ride the same re-host pass. */
|
|
38
38
|
export const FONT_EXT_RE = /\.(woff2?|ttf|otf)(?:[?#]|$)/i;
|
|
39
|
+
/**
|
|
40
|
+
* Sniff the MIME type of a Buffer from its magic bytes.
|
|
41
|
+
* Returns undefined when the signature isn't recognised.
|
|
42
|
+
* Exported for smoke-test coverage.
|
|
43
|
+
*/
|
|
44
|
+
export function sniffMime(buf) {
|
|
45
|
+
if (buf.length < 4)
|
|
46
|
+
return undefined;
|
|
47
|
+
// JPEG: FF D8 FF
|
|
48
|
+
if (buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff)
|
|
49
|
+
return "image/jpeg";
|
|
50
|
+
// PNG: 89 50 4E 47
|
|
51
|
+
if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47)
|
|
52
|
+
return "image/png";
|
|
53
|
+
// GIF: 47 49 46 38 (GIF87a / GIF89a)
|
|
54
|
+
if (buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x38)
|
|
55
|
+
return "image/gif";
|
|
56
|
+
// BMP: 42 4D
|
|
57
|
+
if (buf[0] === 0x42 && buf[1] === 0x4d)
|
|
58
|
+
return "image/bmp";
|
|
59
|
+
// WEBP: RIFF????WEBP (bytes 0-3 = RIFF, bytes 8-11 = WEBP)
|
|
60
|
+
if (buf.length >= 12 &&
|
|
61
|
+
buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 &&
|
|
62
|
+
buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50) {
|
|
63
|
+
return "image/webp";
|
|
64
|
+
}
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
/** A font file's extension from its magic bytes, else undefined — the bytes decide, never the URL. */
|
|
68
|
+
export function fontExtFromBytes(b) {
|
|
69
|
+
const sig = Buffer.from(b.subarray(0, 4)).toString("latin1");
|
|
70
|
+
if (sig === "wOF2")
|
|
71
|
+
return "woff2";
|
|
72
|
+
if (sig === "wOFF")
|
|
73
|
+
return "woff";
|
|
74
|
+
if (sig === "OTTO")
|
|
75
|
+
return "otf";
|
|
76
|
+
if (sig === "\x00\x01\x00\x00" || sig === "true")
|
|
77
|
+
return "ttf";
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
39
80
|
/** All `url( … )` tokens in a CSS value (handles optional quotes; stops at `)`). */
|
|
40
81
|
const CSS_URL_RE = /url\(\s*(['"]?)([^'")]+)\1\s*\)/gi;
|
|
41
82
|
/**
|
|
@@ -168,7 +168,7 @@ async function withContextUnlimited(width, scale, fn) {
|
|
|
168
168
|
}
|
|
169
169
|
let ctx;
|
|
170
170
|
try {
|
|
171
|
-
ctx = await browser.newContext({ viewport: { width, height: 900 }, deviceScaleFactor: scale });
|
|
171
|
+
ctx = await browser.newContext({ viewport: { width, height: 900 }, deviceScaleFactor: scale, serviceWorkers: "block" });
|
|
172
172
|
const value = await fn(ctx);
|
|
173
173
|
return { ok: true, value };
|
|
174
174
|
}
|
|
@@ -190,6 +190,7 @@ async function withContextUnlimited(width, scale, fn) {
|
|
|
190
190
|
}
|
|
191
191
|
/** Load a page in `ctx`, wait for it to settle, return the page handle. */
|
|
192
192
|
async function openSettledPage(ctx, url) {
|
|
193
|
+
await guardContext(ctx); // redirects + subresources must not reach the private network either
|
|
193
194
|
const page = await ctx.newPage();
|
|
194
195
|
await page.goto(url, { waitUntil: "load", timeout: 30_000 });
|
|
195
196
|
await page.waitForTimeout(1200); // let webfonts/lazy images settle
|
|
@@ -260,17 +261,46 @@ export async function captureTilesWithPlaywright(url, opts = {}) {
|
|
|
260
261
|
// targets (someone could otherwise screenshot internal services). Pure + exported
|
|
261
262
|
// for smoke coverage. Opt out with RENDER_ALLOW_PRIVATE=1 (e.g. local dev).
|
|
262
263
|
// ---------------------------------------------------------------------------
|
|
264
|
+
/** The eight 16-bit groups of an IPv6 literal (a trailing dotted quad allowed), else undefined. */
|
|
265
|
+
function v6Groups(h) {
|
|
266
|
+
if (!h.includes(":"))
|
|
267
|
+
return undefined;
|
|
268
|
+
const quad = /(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(h);
|
|
269
|
+
if (quad)
|
|
270
|
+
h = `${h.slice(0, quad.index)}${((+quad[1] << 8) | +quad[2]).toString(16)}:${((+quad[3] << 8) | +quad[4]).toString(16)}`;
|
|
271
|
+
const [head, tail, extra] = h.split("::");
|
|
272
|
+
if (extra !== undefined)
|
|
273
|
+
return undefined;
|
|
274
|
+
const a = head ? head.split(":") : [];
|
|
275
|
+
const b = tail ? tail.split(":") : [];
|
|
276
|
+
const g = [...a, ...Array(tail === undefined ? 0 : Math.max(0, 8 - a.length - b.length)).fill("0"), ...b].map((x) => parseInt(x, 16));
|
|
277
|
+
return g.length === 8 && g.every((x) => x >= 0 && x <= 0xffff) ? g : undefined;
|
|
278
|
+
}
|
|
263
279
|
/** True when `hostname` resolves to a loopback / link-local / RFC-1918 private host. */
|
|
264
280
|
export function isPrivateHost(hostname) {
|
|
265
281
|
let h = hostname.toLowerCase().replace(/^\[|\]$/g, ""); // strip IPv6 brackets
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
282
|
+
const g = v6Groups(h);
|
|
283
|
+
if (g) {
|
|
284
|
+
// IPv6 forms that carry an IPv4 are judged by that IPv4 (else ::ffff:127.0.0.1 walks past).
|
|
285
|
+
const zero = (from, to) => g.slice(from, to).every((x) => x === 0);
|
|
286
|
+
const v4 = (hi, lo) => [hi >> 8, hi & 255, lo >> 8, lo & 255].join(".");
|
|
287
|
+
if (zero(0, 5) && (g[5] === 0 || g[5] === 0xffff))
|
|
288
|
+
h = v4(g[6], g[7]); // ::/96 (incl. :: and ::1), ::ffff:0:0/96
|
|
289
|
+
else if (zero(0, 4) && g[4] === 0xffff && g[5] === 0)
|
|
290
|
+
h = v4(g[6], g[7]); // ::ffff:0:a.b.c.d (translated)
|
|
291
|
+
else if (g[0] === 0x64 && g[1] === 0xff9b && zero(2, 6))
|
|
292
|
+
h = v4(g[6], g[7]); // NAT64 64:ff9b::/96
|
|
293
|
+
else if (g[0] === 0x2002)
|
|
294
|
+
h = v4(g[1], g[2]); // 6to4 2002::/16
|
|
295
|
+
else {
|
|
296
|
+
return ((g[0] & 0xfe00) === 0xfc00 || // ULA fc00::/7
|
|
297
|
+
(g[0] & 0xffc0) === 0xfe80 || // link-local fe80::/10
|
|
298
|
+
(g[0] & 0xffc0) === 0xfec0 || // site-local fec0::/10
|
|
299
|
+
(g[0] & 0xff00) === 0xff00 // multicast
|
|
300
|
+
);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
if (h === "localhost" || h.endsWith(".localhost"))
|
|
274
304
|
return true;
|
|
275
305
|
if (/^127\./.test(h))
|
|
276
306
|
return true; // loopback
|
|
@@ -286,14 +316,18 @@ export function isPrivateHost(hostname) {
|
|
|
286
316
|
return true; // CGNAT 100.64/10 (Alibaba metadata 100.100.100.200)
|
|
287
317
|
if (/^0\./.test(h))
|
|
288
318
|
return true; // "this" network
|
|
289
|
-
if (/^(
|
|
290
|
-
return true; //
|
|
291
|
-
if (h.
|
|
292
|
-
return true; //
|
|
319
|
+
if (/^2(2[4-9]|[3-5]\d)\./.test(h))
|
|
320
|
+
return true; // multicast 224/4, reserved 240/4, broadcast
|
|
321
|
+
if (h === "168.63.129.16" || h === "192.0.0.192")
|
|
322
|
+
return true; // Azure wireserver / Oracle metadata
|
|
293
323
|
return false;
|
|
294
324
|
}
|
|
295
325
|
/** Like isAllowedScreenshotUrl, plus DNS: rejects a public-looking name that resolves to a private
|
|
296
|
-
* address (localtest.me → 127.0.0.1)
|
|
326
|
+
* address (localtest.me → 127.0.0.1), or that does not resolve at all. */
|
|
327
|
+
// ponytail: 30 s per-host cache, so one page's subresources don't each re-resolve. The fetcher
|
|
328
|
+
// (Chromium / undici) resolves again after this check — a DNS-rebinding TOCTOU; pin the resolved
|
|
329
|
+
// IP via an undici Agent `lookup` if that window ever matters.
|
|
330
|
+
const DNS_TTL_MS = 30_000;
|
|
297
331
|
const resolvedPrivate = new Map();
|
|
298
332
|
export async function isPublicUrl(raw) {
|
|
299
333
|
if (!isAllowedScreenshotUrl(raw).ok)
|
|
@@ -303,12 +337,88 @@ export async function isPublicUrl(raw) {
|
|
|
303
337
|
const host = new URL(raw).hostname.replace(/^\[|\]$/g, "");
|
|
304
338
|
if (/^[\d.]+$/.test(host) || host.includes(":"))
|
|
305
339
|
return true; // an IP literal: already checked above
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
340
|
+
const hit = resolvedPrivate.get(host);
|
|
341
|
+
if (hit && Date.now() - hit.at < DNS_TTL_MS)
|
|
342
|
+
return !hit.priv;
|
|
343
|
+
const { lookup } = await import("node:dns/promises");
|
|
344
|
+
const addrs = await lookup(host, { all: true }).catch(() => []);
|
|
345
|
+
const priv = addrs.length === 0 || addrs.some((a) => isPrivateHost(a.address));
|
|
346
|
+
if (resolvedPrivate.size > 1000)
|
|
347
|
+
resolvedPrivate.clear();
|
|
348
|
+
resolvedPrivate.set(host, { priv, at: Date.now() });
|
|
349
|
+
return !priv;
|
|
350
|
+
}
|
|
351
|
+
// serve (hosted, next to a private network): every URL must be public. stdio (the user's own
|
|
352
|
+
// machine): the same, except the host of the URL the user handed in (`trust`) — so a localhost dev
|
|
353
|
+
// page still ingests, while a PUBLIC page can't steer this machine into its LAN.
|
|
354
|
+
let ssrfGuard = false;
|
|
355
|
+
export function setSsrfGuard(on) {
|
|
356
|
+
ssrfGuard = on;
|
|
357
|
+
}
|
|
358
|
+
/** Throw unless `raw` is http(s) and public — or, in stdio only, on the same host as `trust`. */
|
|
359
|
+
export async function assertPublicUrl(raw, trust) {
|
|
360
|
+
let u;
|
|
361
|
+
try {
|
|
362
|
+
u = new URL(raw);
|
|
363
|
+
}
|
|
364
|
+
catch {
|
|
365
|
+
throw new Error("URL not allowed: invalid url");
|
|
366
|
+
}
|
|
367
|
+
if (u.protocol !== "http:" && u.protocol !== "https:")
|
|
368
|
+
throw new Error("URL not allowed: only http(s) urls are allowed");
|
|
369
|
+
if (!ssrfGuard && trust && (() => { try {
|
|
370
|
+
return new URL(trust).hostname;
|
|
371
|
+
}
|
|
372
|
+
catch {
|
|
373
|
+
return "";
|
|
374
|
+
} })() === u.hostname)
|
|
375
|
+
return;
|
|
376
|
+
if (!(await isPublicUrl(raw)))
|
|
377
|
+
throw new Error("URL not allowed: private, loopback or link-local address");
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* Guard a Playwright context: WebSockets are refused, and every request is fetched here with
|
|
381
|
+
* its redirect chain walked by hand (Chromium follows a redirect without routing the next hop),
|
|
382
|
+
* each hop checked by assertPublicUrl, at most 5; the final answer is served under the first URL.
|
|
383
|
+
* ponytail: a redirected document keeps its first URL as base (relative links resolve there).
|
|
384
|
+
*/
|
|
385
|
+
export async function guardContext(ctx, trust) {
|
|
386
|
+
if (ctx.routeWebSocket)
|
|
387
|
+
await ctx.routeWebSocket("**/*", (ws) => ws.close()).catch(() => { });
|
|
388
|
+
await ctx.route("**/*", async (route) => {
|
|
389
|
+
let u = route.request().url();
|
|
390
|
+
if (/^(data|blob|about):/.test(u))
|
|
391
|
+
return route.continue();
|
|
392
|
+
try {
|
|
393
|
+
for (let hop = 0;; hop++) {
|
|
394
|
+
await assertPublicUrl(u, trust);
|
|
395
|
+
const res = await route.fetch({ url: u, maxRedirects: 0 });
|
|
396
|
+
const loc = res.headers()["location"];
|
|
397
|
+
if (res.status() < 300 || res.status() > 399 || !loc)
|
|
398
|
+
return await route.fulfill({ response: res });
|
|
399
|
+
if (hop >= 5)
|
|
400
|
+
throw new Error("Too many redirects");
|
|
401
|
+
u = new URL(loc, u).href;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
catch {
|
|
405
|
+
await route.abort("blockedbyclient").catch(() => { });
|
|
406
|
+
}
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
/** fetch() with redirects followed by hand (max 5), each hop re-checked by assertPublicUrl. */
|
|
410
|
+
export async function fetchPublic(url, init = {}, trust) {
|
|
411
|
+
let target = url;
|
|
412
|
+
for (let hop = 0; hop <= 5; hop++) {
|
|
413
|
+
await assertPublicUrl(target, trust);
|
|
414
|
+
const res = await fetch(target, { ...init, redirect: "manual" });
|
|
415
|
+
const loc = res.status >= 300 && res.status < 400 ? res.headers.get("location") : null;
|
|
416
|
+
if (!loc)
|
|
417
|
+
return res;
|
|
418
|
+
await res.body?.cancel().catch(() => { });
|
|
419
|
+
target = new URL(loc, target).href;
|
|
310
420
|
}
|
|
311
|
-
|
|
421
|
+
throw new Error("Too many redirects (> 5)");
|
|
312
422
|
}
|
|
313
423
|
/** Validate a screenshot target URL: http(s) only, no private host (unless RENDER_ALLOW_PRIVATE). */
|
|
314
424
|
export function isAllowedScreenshotUrl(raw) {
|
|
@@ -12,8 +12,9 @@
|
|
|
12
12
|
*/
|
|
13
13
|
import { createHash } from "node:crypto";
|
|
14
14
|
import { withGoogleWeightLinks, googleWeightLinks } from "./ingest/fonts.js";
|
|
15
|
-
import { collectExternalImageUrls, rewriteImageUrls, parseInlineBase64Image, MAX_REHOST_PER_SAVE,
|
|
15
|
+
import { collectExternalImageUrls, rewriteImageUrls, parseInlineBase64Image, MAX_REHOST_PER_SAVE, fontExtFromBytes, sniffMime } from "./rehost.js";
|
|
16
16
|
import { rehostGet, rehostSet } from "./rehost-cache.js";
|
|
17
|
+
import { fetchPublic } from "./screenshot-playwright.js";
|
|
17
18
|
/** Default fetch timeout in ms. Override via WEBCAKE_HTTP_TIMEOUT_MS env. */
|
|
18
19
|
const HTTP_TIMEOUT_MS = (() => {
|
|
19
20
|
const v = parseInt(process.env.WEBCAKE_HTTP_TIMEOUT_MS ?? "", 10);
|
|
@@ -1194,7 +1195,7 @@ async function fetchAndHostOne(config, src) {
|
|
|
1194
1195
|
}
|
|
1195
1196
|
let res;
|
|
1196
1197
|
try {
|
|
1197
|
-
res = await
|
|
1198
|
+
res = await fetchPublic(src, {
|
|
1198
1199
|
signal: timeoutSignal(REHOST_FETCH_TIMEOUT_MS),
|
|
1199
1200
|
headers: { "User-Agent": "Mozilla/5.0 (compatible; webcake-landing-mcp/1.0; +https://webcake.io)" },
|
|
1200
1201
|
});
|
|
@@ -1207,35 +1208,12 @@ async function fetchAndHostOne(config, src) {
|
|
|
1207
1208
|
const cl = res.headers.get("content-length");
|
|
1208
1209
|
if (cl && parseInt(cl, 10) > REHOST_MAX_BYTES)
|
|
1209
1210
|
return null;
|
|
1210
|
-
|
|
1211
|
-
//
|
|
1212
|
-
//
|
|
1213
|
-
const
|
|
1214
|
-
|
|
1215
|
-
return
|
|
1216
|
-
}
|
|
1217
|
-
catch {
|
|
1218
|
-
return undefined;
|
|
1219
|
-
} })();
|
|
1220
|
-
if (fontExt) {
|
|
1221
|
-
if (/html|json|xml/.test(contentType))
|
|
1222
|
-
return null; // an error/login page served at a .woff2 URL
|
|
1223
|
-
contentType = `font/${fontExt}`;
|
|
1224
|
-
}
|
|
1225
|
-
else if (!contentType.startsWith("image/")) {
|
|
1226
|
-
// Some CDNs send octet-stream for images — trust the URL extension instead of rejecting.
|
|
1227
|
-
const extGuess = (() => { try {
|
|
1228
|
-
const p = new URL(src).pathname;
|
|
1229
|
-
const d = p.lastIndexOf(".");
|
|
1230
|
-
return d >= 0 ? p.slice(d + 1).split(/[?#]/)[0].toLowerCase() : "";
|
|
1231
|
-
}
|
|
1232
|
-
catch {
|
|
1233
|
-
return "";
|
|
1234
|
-
} })();
|
|
1235
|
-
if (!extGuess)
|
|
1236
|
-
return null;
|
|
1237
|
-
contentType = `image/${extGuess === "jpg" ? "jpeg" : extGuess}`;
|
|
1238
|
-
}
|
|
1211
|
+
// Label by what the server sent, never by the URL: a `#.woff2` or `.png` suffix must not turn an
|
|
1212
|
+
// arbitrary response into an upload. A definite non-image/font type is refused unread; fonts and
|
|
1213
|
+
// octet-stream / untyped bodies are decided by their magic bytes.
|
|
1214
|
+
const ct = (res.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();
|
|
1215
|
+
if (ct && !/^image\/|font|octet-stream$/.test(ct))
|
|
1216
|
+
return null;
|
|
1239
1217
|
let buf;
|
|
1240
1218
|
try {
|
|
1241
1219
|
buf = await res.arrayBuffer();
|
|
@@ -1243,6 +1221,11 @@ async function fetchAndHostOne(config, src) {
|
|
|
1243
1221
|
catch {
|
|
1244
1222
|
return null;
|
|
1245
1223
|
}
|
|
1224
|
+
const bytes = new Uint8Array(buf);
|
|
1225
|
+
const fontExt = fontExtFromBytes(bytes);
|
|
1226
|
+
const contentType = fontExt ? `font/${fontExt}` : ct.startsWith("image/") ? ct : sniffMime(bytes);
|
|
1227
|
+
if (!contentType)
|
|
1228
|
+
return null;
|
|
1246
1229
|
if (buf.byteLength > REHOST_MAX_BYTES)
|
|
1247
1230
|
return null;
|
|
1248
1231
|
const ext = rehostExtFromContentType(contentType);
|
package/dist/smoke.js
CHANGED
|
@@ -22,12 +22,13 @@ import { buildConnectUrl, parseCallback } from "./auth/login.js";
|
|
|
22
22
|
import { redirectMatches, isDeadJwt, markJwtDead, isAllowedRedirect } from "./auth/oauth-server.js";
|
|
23
23
|
import { isUnauthorized, renewAuthOnExpiry } from "./auth/renew.js";
|
|
24
24
|
import { jwtExpired } from "./persistence/config.js";
|
|
25
|
-
import { isLocalPath, resolveLocalPath,
|
|
25
|
+
import { isLocalPath, resolveLocalPath, localContentType } from "./tools/media.js";
|
|
26
26
|
import { buildMicrolinkUrl } from "./persistence/screenshot-client.js";
|
|
27
|
-
import { isPrivateHost, isAllowedScreenshotUrl, acquireSlot, releaseSlot, slotStats } from "./persistence/screenshot-playwright.js";
|
|
27
|
+
import { isPrivateHost, isAllowedScreenshotUrl, acquireSlot, releaseSlot, slotStats, setSsrfGuard, fetchPublic, assertPublicUrl } from "./persistence/screenshot-playwright.js";
|
|
28
28
|
import { iconifyCandidates } from "./persistence/icon-client.js";
|
|
29
29
|
import { withBase } from "./persistence/ingest/browser-capture.js";
|
|
30
|
-
import { collectExternalImageUrls, rewriteImageUrls, isRehostableImageUrl, isInlineBase64Image, parseInlineBase64Image, healBrokenResizeUrls } from "./persistence/rehost.js";
|
|
30
|
+
import { collectExternalImageUrls, rewriteImageUrls, isRehostableImageUrl, isInlineBase64Image, parseInlineBase64Image, healBrokenResizeUrls, fontExtFromBytes, sniffMime } from "./persistence/rehost.js";
|
|
31
|
+
import { rehostSourceImages } from "./persistence/webcake-client.js";
|
|
31
32
|
import { key as rehostCacheKey } from "./persistence/rehost-cache.js";
|
|
32
33
|
import { sourceFingerprint, collectElementIds, decideOverwrite, rememberPageVersion, forgetPageVersion, lastKnownPageVersion, resetPageVersions, sourceCacheKey, cachePageSource, cachedPageSource, cachedPageSourceVersion, dropCachedPageSource, resetPageSourceCache, } from "./persistence/page-version.js";
|
|
33
34
|
let failures = 0;
|
|
@@ -782,11 +783,13 @@ console.log("== fonts: review hardening (cascade order, media, rem root, UA, Tai
|
|
|
782
783
|
t0 = Date.now();
|
|
783
784
|
resolveCssVars([{ selector: ":root", decls: "--a:1px", media: "all" }, { selector: "h1", decls: "font-size:var(--x," + "a ".repeat(9_000), media: "all" }]);
|
|
784
785
|
check("perf: unclosed var() fallback resolves fast", Date.now() - t0 < 500, Date.now() - t0);
|
|
785
|
-
// SSRF: stylesheet hrefs chosen by the crawled page never reach private hosts.
|
|
786
|
+
// SSRF: stylesheet hrefs chosen by the crawled page never reach private hosts (hosted guard on).
|
|
787
|
+
setSsrfGuard(true);
|
|
786
788
|
const priv = await fetchStylesheets(`<link rel="stylesheet" href="http://169.254.169.254/latest/meta-data"><link rel="stylesheet" href="http://127.0.0.1:1/a.css"><style>@import url(http://10.0.0.1/x.css);</style>`, "https://example.com/");
|
|
787
789
|
check("ssrf: private/link-local stylesheet + @import targets are not fetched", priv.length === 0, priv);
|
|
788
790
|
const privPage = await Promise.all(["http://169.254.169.254/latest/meta-data", "http://127.0.0.1:1/", "http://10.0.0.1/"].map((u) => fetchHtml(u)));
|
|
789
791
|
check("ingest_url SSRF: private/loopback/link-local page fetch blocked before any request", privPage.every((r) => !r.ok && /not allowed/.test(r.error ?? "")), privPage);
|
|
792
|
+
setSsrfGuard(false);
|
|
790
793
|
}
|
|
791
794
|
console.log("== settings: width_section defaulted (build host crashes without it) ==");
|
|
792
795
|
{
|
|
@@ -1535,6 +1538,7 @@ console.log("== login: connect URL + loopback callback parsing (offline) ==");
|
|
|
1535
1538
|
const url = buildConnectUrl("https://webcake.io/mcp-connect", "http://127.0.0.1:51234/callback", "abc123");
|
|
1536
1539
|
check("connect url keeps the state param", url.endsWith("&state=abc123"), url);
|
|
1537
1540
|
check("connect url percent-encodes redirect_uri", url.includes("redirect_uri=http%3A%2F%2F127.0.0.1%3A51234%2Fcallback"), url);
|
|
1541
|
+
check("connect url carries client_host/client_name, encoded", buildConnectUrl("https://x.test/c", "https://m/cb", "s", { client_host: "claude.ai", client_name: "A&B", x: undefined }).endsWith("&state=s&client_host=claude.ai&client_name=A%26B"));
|
|
1538
1542
|
check("connect url joins with & when a query already exists", buildConnectUrl("https://x.test/c?a=1", "http://127.0.0.1:1/callback", "s").includes("?a=1&redirect_uri="));
|
|
1539
1543
|
const okCb = parseCallback("/callback?token=tok&state=abc", "abc");
|
|
1540
1544
|
check("callback with token+state accepted", okCb.ok && okCb.token === "tok", okCb);
|
|
@@ -2445,6 +2449,55 @@ console.log("== upload_images: localContentType (ext + magic, pure offline) ==")
|
|
|
2445
2449
|
check("isAllowedScreenshotUrl: ftp rejected", !isAllowedScreenshotUrl("ftp://x.test/a").ok);
|
|
2446
2450
|
check("isAllowedScreenshotUrl: localhost rejected", !isAllowedScreenshotUrl("http://localhost:5800/preview/1").ok);
|
|
2447
2451
|
check("isAllowedScreenshotUrl: garbage rejected", !isAllowedScreenshotUrl("not a url").ok);
|
|
2452
|
+
check("isPrivateHost: CGNAT / 0.0.0.0/8 / multicast / broadcast", ["100.64.0.1", "100.100.100.200", "0.1.2.3", "224.0.0.1", "239.255.255.250", "255.255.255.255"].every(isPrivateHost));
|
|
2453
|
+
check("isPrivateHost: metadata IPs", ["169.254.169.254", "168.63.129.16", "192.0.0.192", "fd00:ec2::254"].every(isPrivateHost));
|
|
2454
|
+
check("isPrivateHost: IPv6 link-local / multicast / unspecified", ["fe80::1", "febf::1", "ff02::1", "::", "fc00::1"].every(isPrivateHost));
|
|
2455
|
+
check("isPrivateHost: IPv4-mapped / -compatible IPv6", ["::ffff:127.0.0.1", "::ffff:7f00:1", "::ffff:a9fe:a9fe", "::ffff:10.0.0.5", "::7f00:1", "[::ffff:c0a8:1]"].every(isPrivateHost));
|
|
2456
|
+
check("isPrivateHost: public v4/v6 stay public", !["1.1.1.1", "100.63.255.255", "100.128.0.1", "223.255.255.255", "2606:4700::1111", "::ffff:8.8.8.8", "::ffff:808:808"].some(isPrivateHost));
|
|
2457
|
+
// fetchPublic: every redirect hop is re-checked, and hops are capped (fetch stubbed — offline).
|
|
2458
|
+
const realFetch = globalThis.fetch;
|
|
2459
|
+
const hops = [];
|
|
2460
|
+
const redirectTo = (loc) => (async (u) => (hops.push(String(u)), new Response(null, { status: 302, headers: { location: loc } })));
|
|
2461
|
+
setSsrfGuard(true);
|
|
2462
|
+
globalThis.fetch = redirectTo("http://127.0.0.1:8788/health");
|
|
2463
|
+
const hopErr = await fetchPublic("http://93.184.216.34/").then(() => "", (e) => String(e.message));
|
|
2464
|
+
check("fetchPublic: a 302 to loopback is refused before the second request", /not allowed/.test(hopErr) && hops.length === 1, { hopErr, hops });
|
|
2465
|
+
hops.length = 0;
|
|
2466
|
+
globalThis.fetch = redirectTo("http://93.184.216.34/next");
|
|
2467
|
+
const loopErr = await fetchPublic("http://93.184.216.34/").then(() => "", (e) => String(e.message));
|
|
2468
|
+
check("fetchPublic: at most 5 redirects followed", /Too many redirects/.test(loopErr) && hops.length === 6, { loopErr, n: hops.length });
|
|
2469
|
+
check("assertPublicUrl: serve blocks localhost (even as the given url) + non-http", !(await assertPublicUrl("http://localhost:3000/", "http://localhost:3000/").then(() => true, () => false)) && !(await assertPublicUrl("http://localhost:3000/").then(() => true, () => false)) && !(await assertPublicUrl("file:///etc/passwd").then(() => true, () => false)));
|
|
2470
|
+
setSsrfGuard(false);
|
|
2471
|
+
const allowed = (u, trust) => assertPublicUrl(u, trust).then(() => true, () => false);
|
|
2472
|
+
check("assertPublicUrl: stdio exempts only the user's own url host", (await allowed("http://localhost:3000/", "http://localhost:3000/")) && (await allowed("http://localhost:5173/api", "http://localhost:3000/")));
|
|
2473
|
+
check("assertPublicUrl: stdio still blocks private hosts a PUBLIC page points at", !(await allowed("http://127.0.0.1:3000/", "https://example.com/")) && !(await allowed("http://localhost:3000/")) && !(await allowed("http://10.0.0.5/", "http://localhost:3000/")));
|
|
2474
|
+
hops.length = 0;
|
|
2475
|
+
globalThis.fetch = redirectTo("http://127.0.0.1:8788/health");
|
|
2476
|
+
const stdioHop = await fetchPublic("http://93.184.216.34/", {}, "http://93.184.216.34/").then(() => "", (e) => String(e.message));
|
|
2477
|
+
check("fetchPublic (stdio): a public page's 302 to loopback is refused", /not allowed/.test(stdioHop) && hops.length === 1, { stdioHop, hops });
|
|
2478
|
+
// Re-host labels by content-type, octet-stream / untyped by magic bytes, never by the url.
|
|
2479
|
+
const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0]);
|
|
2480
|
+
const jpg = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0, 0, 0, 0]);
|
|
2481
|
+
const uploaded = [];
|
|
2482
|
+
const served = {
|
|
2483
|
+
"http://93.184.216.34/oct.png": () => new Response(png, { headers: { "content-type": "application/octet-stream" } }),
|
|
2484
|
+
"http://93.184.216.34/none.jpg": () => new Response(jpg),
|
|
2485
|
+
"http://93.184.216.34/meta.png": () => new Response("ami-id", { headers: { "content-type": "text/plain" } }),
|
|
2486
|
+
"http://93.184.216.34/junk.png": () => new Response("not an image", { headers: { "content-type": "binary/octet-stream" } }),
|
|
2487
|
+
};
|
|
2488
|
+
globalThis.fetch = (async (u, init) => {
|
|
2489
|
+
if (init?.method === "POST") {
|
|
2490
|
+
uploaded.push(init.body.get("file") instanceof Blob ? init.body.get("file").type : "?");
|
|
2491
|
+
return new Response(JSON.stringify({ success: true, data: `https://statics.pancake.vn/h${uploaded.length}.png` }), { headers: { "content-type": "application/json" } });
|
|
2492
|
+
}
|
|
2493
|
+
return served[String(u)]?.() ?? new Response(null, { status: 404 });
|
|
2494
|
+
});
|
|
2495
|
+
const rh = await rehostSourceImages({ base: "http://upload.test", jwt: "" }, { page: Object.keys(served).map((src, i) => ({ id: `i${i}`, type: "image", specials: { src } })) });
|
|
2496
|
+
check("rehost: octet-stream / untyped images sniffed and hosted; text and junk octet-stream skipped", rh.report?.rehosted === 2 && uploaded.sort().join() === "image/jpeg,image/png", { report: rh.report, uploaded });
|
|
2497
|
+
globalThis.fetch = realFetch;
|
|
2498
|
+
check("isPrivateHost: NAT64 / IPv4-translated / 6to4 carrying private IPv4s, site-local", ["64:ff9b::7f00:1", "64:ff9b::10.0.0.1", "::ffff:0:7f00:1", "::ffff:0:169.254.169.254", "2002:7f00:1::", "2002:a9fe:a9fe::1", "fec0::1"].every(isPrivateHost));
|
|
2499
|
+
check("isPrivateHost: NAT64 / 6to4 of a public IPv4 stay public", !["64:ff9b::808:808", "2002:808:808::1"].some(isPrivateHost));
|
|
2500
|
+
check("fontExtFromBytes: magic bytes, not the url", fontExtFromBytes(Buffer.from("wOF2xxxx")) === "woff2" && fontExtFromBytes(Buffer.from([0, 1, 0, 0, 9])) === "ttf" && fontExtFromBytes(Buffer.from("ami-id\n")) === undefined);
|
|
2448
2501
|
}
|
|
2449
2502
|
console.log("== autofix-layout: clamps off-canvas + reflows wrapped-text overlap (reported, idempotent) ==");
|
|
2450
2503
|
{
|
package/dist/tools/media.js
CHANGED
|
@@ -31,6 +31,8 @@ import { searchPexels, searchImagesViaProxy, resolvePexelsKey, resolvePexelsProx
|
|
|
31
31
|
import { captureScreenshot, captureScreenshotTiles, resolveScreenshotProxyBase, screenshotProxyBaseFromHeaders, resolveMicrolinkKey, microlinkKeyFromHeaders, } from "../persistence/screenshot-client.js";
|
|
32
32
|
import { uploadImageMultipart, uploadImagePreferCollection, resolveCollectionOrgId, listOrganizations, } from "../persistence/webcake-client.js";
|
|
33
33
|
import { resolveIconSvg } from "../persistence/icon-client.js";
|
|
34
|
+
import { sniffMime } from "../persistence/rehost.js";
|
|
35
|
+
import { fetchPublic } from "../persistence/screenshot-playwright.js";
|
|
34
36
|
import { configFromHeaders, ENVIRONMENTS, readConfig, stripTrailingSlash } from "../persistence/config.js";
|
|
35
37
|
/**
|
|
36
38
|
* Name the uploaded asset after its source file so the collection lists
|
|
@@ -99,19 +101,6 @@ function extFromContentType(ct) {
|
|
|
99
101
|
};
|
|
100
102
|
return map[sub] ?? (sub.replace("image/", "") || "jpg");
|
|
101
103
|
}
|
|
102
|
-
/** Derive file extension from a URL path when content-type is unavailable. */
|
|
103
|
-
function extFromUrl(url) {
|
|
104
|
-
try {
|
|
105
|
-
const pathname = new URL(url).pathname;
|
|
106
|
-
const dot = pathname.lastIndexOf(".");
|
|
107
|
-
if (dot >= 0)
|
|
108
|
-
return pathname.slice(dot + 1).split("?")[0].toLowerCase();
|
|
109
|
-
}
|
|
110
|
-
catch {
|
|
111
|
-
/* ignore */
|
|
112
|
-
}
|
|
113
|
-
return "jpg";
|
|
114
|
-
}
|
|
115
104
|
// ---------------------------------------------------------------------------
|
|
116
105
|
// Local-path helpers (exported for smoke-test coverage)
|
|
117
106
|
// ---------------------------------------------------------------------------
|
|
@@ -155,34 +144,6 @@ const EXT_TO_MIME = {
|
|
|
155
144
|
tiff: "image/tiff",
|
|
156
145
|
tif: "image/tiff",
|
|
157
146
|
};
|
|
158
|
-
/**
|
|
159
|
-
* Sniff the MIME type of a Buffer from its magic bytes.
|
|
160
|
-
* Returns undefined when the signature isn't recognised.
|
|
161
|
-
* Exported for smoke-test coverage.
|
|
162
|
-
*/
|
|
163
|
-
export function sniffMime(buf) {
|
|
164
|
-
if (buf.length < 4)
|
|
165
|
-
return undefined;
|
|
166
|
-
// JPEG: FF D8 FF
|
|
167
|
-
if (buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff)
|
|
168
|
-
return "image/jpeg";
|
|
169
|
-
// PNG: 89 50 4E 47
|
|
170
|
-
if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47)
|
|
171
|
-
return "image/png";
|
|
172
|
-
// GIF: 47 49 46 38 (GIF87a / GIF89a)
|
|
173
|
-
if (buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x38)
|
|
174
|
-
return "image/gif";
|
|
175
|
-
// BMP: 42 4D
|
|
176
|
-
if (buf[0] === 0x42 && buf[1] === 0x4d)
|
|
177
|
-
return "image/bmp";
|
|
178
|
-
// WEBP: RIFF????WEBP (bytes 0-3 = RIFF, bytes 8-11 = WEBP)
|
|
179
|
-
if (buf.length >= 12 &&
|
|
180
|
-
buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 &&
|
|
181
|
-
buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50) {
|
|
182
|
-
return "image/webp";
|
|
183
|
-
}
|
|
184
|
-
return undefined;
|
|
185
|
-
}
|
|
186
147
|
/**
|
|
187
148
|
* Derive the content-type for a local file: sniff magic bytes first, then fall
|
|
188
149
|
* back to the extension. Returns undefined when both fail (unrecognised format).
|
|
@@ -492,12 +453,12 @@ export function registerMediaTools(server, allowLocalFiles = true) {
|
|
|
492
453
|
// --- REMOTE HTTP(S) URL ---
|
|
493
454
|
let res;
|
|
494
455
|
try {
|
|
495
|
-
res = await
|
|
456
|
+
res = await fetchPublic(originalEntry, {
|
|
496
457
|
signal: AbortSignal.timeout(UPLOAD_FETCH_TIMEOUT_MS),
|
|
497
458
|
headers: {
|
|
498
459
|
"User-Agent": "Mozilla/5.0 (compatible; webcake-landing-mcp/1.0; +https://webcake.io)",
|
|
499
460
|
},
|
|
500
|
-
});
|
|
461
|
+
}, originalEntry); // stdio: the given url's own host may be private (localhost); no other private host
|
|
501
462
|
}
|
|
502
463
|
catch (e) {
|
|
503
464
|
return [originalEntry, { ok: false, error: `Fetch failed: ${e?.message ?? e}` }];
|
|
@@ -510,17 +471,18 @@ export function registerMediaTools(server, allowLocalFiles = true) {
|
|
|
510
471
|
if (cl && parseInt(cl, 10) > UPLOAD_MAX_BYTES) {
|
|
511
472
|
return [originalEntry, { ok: false, error: `Image exceeds the 200 MB backend limit (Content-Length: ${cl})` }];
|
|
512
473
|
}
|
|
513
|
-
//
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
if (!
|
|
517
|
-
return [originalEntry, { ok: false, error: `Not an image — content-type: ${
|
|
474
|
+
// Never the URL's extension: an image/* content-type, or octet-stream / none proven by
|
|
475
|
+
// magic bytes. A definite other type is refused before the body is read.
|
|
476
|
+
const ct = (res.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();
|
|
477
|
+
if (ct && !ct.startsWith("image/") && !ct.endsWith("octet-stream")) {
|
|
478
|
+
return [originalEntry, { ok: false, error: `Not an image — content-type: ${ct}` }];
|
|
518
479
|
}
|
|
519
480
|
const buf = await res.arrayBuffer();
|
|
520
481
|
if (buf.byteLength > UPLOAD_MAX_BYTES) {
|
|
521
482
|
return [originalEntry, { ok: false, error: `Image exceeds the 200 MB backend limit (actual: ${buf.byteLength} bytes)` }];
|
|
522
483
|
}
|
|
523
484
|
bytes = Buffer.from(buf);
|
|
485
|
+
contentType = ct.startsWith("image/") ? ct : sniffMime(bytes) ?? (ct || "(empty)");
|
|
524
486
|
}
|
|
525
487
|
if (!contentType.startsWith("image/")) {
|
|
526
488
|
return [originalEntry, { ok: false, error: `Not an image — content-type: ${contentType}` }];
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "webcake-landing-mcp",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.18.0",
|
|
4
4
|
"description": "MCP server exposing Webcake landing-page element schemas + AI usage hints, and persisting LLM-generated page sources to a Webcake backend.",
|
|
5
5
|
"mcpName": "io.github.vuluu2k/webcake-landing-mcp",
|
|
6
6
|
"type": "module",
|