webcake-landing-mcp 1.16.2 → 1.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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=…`, `&api_base=…`. Hand each teammate a link with their own `jwt` →
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>` or send the `x-webcake-build-base` header per request.
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=…`, `&api_base=…`. Mỗi đồng đội một link với `jwt` riêng → mỗi người một
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
 
@@ -327,10 +327,10 @@ export function verifyPkce(verifier, challenge) {
327
327
  }
328
328
  export async function registerClient(body) {
329
329
  const uris = Array.isArray(body?.redirect_uris)
330
- ? body.redirect_uris.filter((u) => typeof u === "string" && /^https?:\/\//i.test(u))
330
+ ? body.redirect_uris.filter((u) => typeof u === "string" && isAllowedRedirect(u))
331
331
  : [];
332
332
  if (uris.length === 0) {
333
- return { ok: false, error: "invalid_redirect_uri", error_description: "redirect_uris must contain at least one absolute http(s) URI." };
333
+ 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
334
  }
335
335
  const client = {
336
336
  client_id: token(16),
@@ -347,6 +347,33 @@ export async function getClient(clientId) {
347
347
  return (await getStore()).getClient(clientId);
348
348
  }
349
349
  const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
350
+ // An open redirect target would let anyone register a client and phish a code for a victim's
351
+ // account, so DCR only accepts known MCP clients + loopback. Add hosts via WEBCAKE_OAUTH_REDIRECT_HOSTS.
352
+ const REDIRECT_HOSTS = new Set([
353
+ "claude.ai",
354
+ "claude.com",
355
+ "chatgpt.com",
356
+ "platform.openai.com",
357
+ "vscode.dev",
358
+ "insiders.vscode.dev",
359
+ ...(process.env.WEBCAKE_OAUTH_REDIRECT_HOSTS ?? "").split(",").map((h) => h.trim().toLowerCase()).filter(Boolean),
360
+ ]);
361
+ export function isAllowedRedirect(uri) {
362
+ let u;
363
+ try {
364
+ u = new URL(uri);
365
+ }
366
+ catch {
367
+ return false;
368
+ }
369
+ if (u.protocol === "http:")
370
+ return LOOPBACK_HOSTS.has(u.hostname);
371
+ return u.protocol === "https:" && REDIRECT_HOSTS.has(u.hostname);
372
+ }
373
+ /** Cookie set at /authorize and required at the callback: ties a pending request to the browser that started it. */
374
+ export function pendingCookieName(internalState) {
375
+ return `wc_oauth_${s256(internalState).slice(0, 16)}`;
376
+ }
350
377
  /**
351
378
  * Exact match, except an http loopback redirect ignores the port (RFC 8252 §7.3):
352
379
  * native clients like Claude Code register `http://localhost/callback` and then
@@ -379,7 +406,7 @@ export async function startAuthorize(p) {
379
406
  if (!client) {
380
407
  return { ok: false, error: "invalid_client", error_description: "Unknown client_id. Register first via /register.", redirectable: false };
381
408
  }
382
- if (!p.redirect_uri || !client.redirect_uris.some((r) => redirectMatches(r, p.redirect_uri))) {
409
+ if (!p.redirect_uri || !isAllowedRedirect(p.redirect_uri) || !client.redirect_uris.some((r) => redirectMatches(r, p.redirect_uri))) {
383
410
  return { ok: false, error: "invalid_request", error_description: "redirect_uri does not match a registered URI.", redirectable: false };
384
411
  }
385
412
  // From here errors CAN go back to the client's redirect_uri.
@@ -1,4 +1,18 @@
1
1
  [
2
+ {
3
+ "v": "1.17.1",
4
+ "d": "01/12/2026",
5
+ "type": "Fixed",
6
+ "en": "The hosted remote-connector OAuth flow now rejects Dynamic Client Registration and /authorize requests whose redirect_uri is not a known MCP client…",
7
+ "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…"
8
+ },
9
+ {
10
+ "v": "1.17.0",
11
+ "d": "28/11/2026",
12
+ "type": "Fixed",
13
+ "en": "clone_page and ingest_html/ingest_url with intent:'clone' now dismiss cookie/consent/newsletter banners, promo modals and chat widgets (clicking…",
14
+ "vi": "clone_page và ingest_html/ingest_url với intent:'clone' nay bỏ các lớp cookie/consent/newsletter, modal quảng cáo và widget chat (bấm nút chấp…"
15
+ },
2
16
  {
3
17
  "v": "1.16.2",
4
18
  "d": "28/11/2026",
@@ -26,19 +40,5 @@
26
40
  "type": "Added",
27
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.",
28
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…"
29
- },
30
- {
31
- "v": "1.14.0",
32
- "d": "23/11/2026",
33
- "type": "Added",
34
- "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…",
35
- "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…"
36
- },
37
- {
38
- "v": "1.13.7",
39
- "d": "22/11/2026",
40
- "type": "Fixed",
41
- "en": "install now writes the Claude Desktop config to every location Claude may read on Windows (Store/MSIX package containers, Claude-Data,…",
42
- "vi": "install nay ghi config Claude Desktop vào mọi vị trí Claude có thể đọc trên Windows (container gói Store/MSIX, Claude-Data, %APPDATA%\\Claude) thay…"
43
43
  }
44
44
  ]
package/dist/http.js CHANGED
@@ -24,7 +24,7 @@ import { searchPexels, resolvePexelsKey } from "./persistence/pexels-client.js";
24
24
  import { captureWithPlaywright, captureTilesWithPlaywright, isAllowedScreenshotUrl } from "./persistence/screenshot-playwright.js";
25
25
  import { resolveEnv, ENVIRONMENTS, stripTrailingSlash } from "./persistence/config.js";
26
26
  import { buildConnectUrl } from "./auth/login.js";
27
- import { registerClient, startAuthorize, completeAuthorize, exchangeToken, resolveAccessToken, isDeadJwt, revokeToken, authServerMetadata, protectedResourceMetadata, } from "./auth/oauth-server.js";
27
+ import { registerClient, startAuthorize, completeAuthorize, exchangeToken, resolveAccessToken, isDeadJwt, revokeToken, pendingCookieName, authServerMetadata, protectedResourceMetadata, } from "./auth/oauth-server.js";
28
28
  const MCP_PATH = "/mcp";
29
29
  const IMAGES_PATH = "/api/images/search";
30
30
  const RENDER_SCREENSHOT_PATH = "/api/render/screenshot";
@@ -112,11 +112,39 @@ const QUERY_AUTH = {
112
112
  wsid: "x-webcake-session-id",
113
113
  session_id: "x-webcake-session-id",
114
114
  env: "x-webcake-env",
115
- api_base: "x-webcake-api-base",
116
115
  org_id: "x-webcake-org-id",
117
- app_base: "x-webcake-app-base",
118
- builder_base: "x-webcake-builder-base",
119
116
  };
117
+ // The backend host receives the caller's JWT, so a remote caller must not pick it: drop
118
+ // every x-webcake-*-base header and keep the env presets / server env. Both views of the
119
+ // headers are cleaned because the transport rebuilds its Request from rawHeaders.
120
+ const BASE_HEADER = /^x-webcake-[a-z]+-base$/i;
121
+ export function stripBaseOverrides(req) {
122
+ for (const h of Object.keys(req.headers))
123
+ if (BASE_HEADER.test(h))
124
+ delete req.headers[h];
125
+ const raw = req.rawHeaders;
126
+ for (let i = raw.length - 2; i >= 0; i -= 2)
127
+ if (BASE_HEADER.test(raw[i]))
128
+ raw.splice(i, 2);
129
+ // `local` points at this server's own loopback — only when the server itself runs local.
130
+ if (/^local$/i.test(String(req.headers["x-webcake-env"] ?? "")) && !/^local$/i.test(process.env.WEBCAKE_ENV ?? "")) {
131
+ delete req.headers["x-webcake-env"];
132
+ for (let i = raw.length - 2; i >= 0; i -= 2)
133
+ if (/^x-webcake-env$/i.test(raw[i]))
134
+ raw.splice(i, 2);
135
+ }
136
+ }
137
+ // __Host- (https only) stops a sibling subdomain from planting the cookie for a known state.
138
+ function pendingCookie(issuer, state) {
139
+ const https = issuer.startsWith("https:");
140
+ return {
141
+ name: `${https ? "__Host-" : ""}${pendingCookieName(state)}`,
142
+ attrs: `; HttpOnly; SameSite=Lax${https ? "; Path=/; Secure" : `; Path=${OAUTH_CALLBACK}`}`,
143
+ };
144
+ }
145
+ function hasCookie(req, name) {
146
+ return String(req.headers.cookie ?? "").split(/;\s*/).includes(`${name}=1`);
147
+ }
120
148
  export function applyQueryAuth(req) {
121
149
  const q = (req.url ?? "").indexOf("?");
122
150
  if (q === -1)
@@ -257,12 +285,20 @@ async function handleOAuth(req, res, path) {
257
285
  // Send the user to the SPA login; it returns here with ?token=<ljwt>[&wsid=<lwsid>]&state=<internalState>.
258
286
  const callback = `${issuer}${OAUTH_CALLBACK}`;
259
287
  const loginUrl = buildConnectUrl(connectPageUrl(), callback, result.internalState);
260
- res.writeHead(302, { location: loginUrl });
288
+ const c = pendingCookie(issuer, result.internalState);
289
+ res.writeHead(302, { location: loginUrl, "set-cookie": `${c.name}=1; Max-Age=600${c.attrs}` });
261
290
  return res.end(), true;
262
291
  }
263
292
  // ---- Login callback: the SPA handed back the user's ljwt → mint a code ----
264
293
  if (req.method === "GET" && path === OAUTH_CALLBACK) {
265
294
  const sp = new URL(req.url ?? "/", "http://x").searchParams;
295
+ // Only the browser that opened /authorize may complete it — otherwise a link carrying
296
+ // someone else's state binds the victim's login to the attacker's client.
297
+ const state = sp.get("state");
298
+ const c = state ? pendingCookie(issuer, state) : undefined;
299
+ if (!c || !hasCookie(req, c.name)) {
300
+ return htmlError(res, 400, "This connection was not started in this browser — restart it from your AI app."), true;
301
+ }
266
302
  const done = await completeAuthorize(sp.get("state"), sp.get("token"), sp.get("wsid") || sp.get("session_id"));
267
303
  if (!done.ok)
268
304
  return htmlError(res, 400, done.error_description), true;
@@ -270,7 +306,7 @@ async function handleOAuth(req, res, path) {
270
306
  r.searchParams.set("code", done.code);
271
307
  if (done.state)
272
308
  r.searchParams.set("state", done.state);
273
- res.writeHead(302, { location: r.toString() });
309
+ res.writeHead(302, { location: r.toString(), "set-cookie": `${c.name}=; Max-Age=0${c.attrs}` });
274
310
  return res.end(), true;
275
311
  }
276
312
  // ---- Token ----
@@ -473,8 +509,9 @@ export async function startHttpServer(port) {
473
509
  return;
474
510
  if (path !== MCP_PATH)
475
511
  return rpcError(res, 404, `Not found. Send MCP requests to ${MCP_PATH}.`);
476
- // Accept credentials via ?jwt=/?api_base=/... (for clients that can't set headers).
512
+ // Accept credentials via ?jwt=/?env=/... (for clients that can't set headers).
477
513
  applyQueryAuth(req);
514
+ stripBaseOverrides(req);
478
515
  // OAuth access token → resolve to the user's landing JWT and inject it as the
479
516
  // normal x-webcake-jwt header, so persistence/config.ts is unchanged. It WINS over a
480
517
  // ?jwt= / x-webcake-jwt: a Bearer from our OAuth flow is what the last Connect issued,
@@ -495,7 +532,7 @@ export async function startHttpServer(port) {
495
532
  // for OAuth access tokens.
496
533
  const given = req.headers["x-webcake-jwt"];
497
534
  const dead = await isDeadJwt(Array.isArray(given) ? given[0] : given);
498
- if (OAUTH_ENFORCED && (given == null || dead)) {
535
+ if (OAUTH_ENFORCED && (!given || dead)) {
499
536
  res.writeHead(401, {
500
537
  "www-authenticate": `Bearer error="invalid_token", resource_metadata="${publicBase(req)}${WELL_KNOWN_PR}"`,
501
538
  "content-type": "application/json",
@@ -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. */
@@ -52,9 +52,12 @@ function captureInPage(opt) {
52
52
  out["font-weight"] = s.fontWeight;
53
53
  if (s.fontStyle === "italic")
54
54
  out["font-style"] = "italic";
55
- const fam = s.fontFamily.split(",")[0].trim().replace(/^['"]|['"]$/g, "");
56
- if (fam)
57
- out["font-family"] = fam;
55
+ // the family + its generic fallback ('pangea', sans-serif): a self-hosted font that has not loaded yet
56
+ // (re-hosted on save) must not fall back to the browser's serif
57
+ const stack = s.fontFamily.split(",").map((f) => f.trim().replace(/^['"]|['"]$/g, ""));
58
+ const generic = stack.find((f) => /^(sans-serif|serif|monospace|cursive|fantasy|system-ui)$/.test(f)) ?? "sans-serif";
59
+ if (stack[0])
60
+ out["font-family"] = stack[0] === generic ? generic : `'${stack[0]}', ${generic}`;
58
61
  // landing lineHeight is a multiplier of the font size
59
62
  if (s.lineHeight !== "normal" && fs)
60
63
  out["line-height"] = String(Math.round((parseFloat(s.lineHeight) / fs) * 100) / 100);
@@ -142,7 +145,9 @@ function captureInPage(opt) {
142
145
  const inlineOnly = (el) => Array.from(el.children).every((c) => {
143
146
  const d = cs(c).display;
144
147
  return (d.startsWith("inline") && !["IMG", "SVG", "svg", "BUTTON", "INPUT", "SELECT", "TEXTAREA", "VIDEO", "IFRAME"].includes(c.tagName)) || d === "none" || c.tagName === "BR" || icon(c);
145
- });
148
+ }) &&
149
+ // …and nothing inside is laid out on its own (a badge absolutely placed over a menu link): that is drawn separately
150
+ !Array.from(el.querySelectorAll("*")).some((d) => ["absolute", "fixed"].includes(cs(d).position) && shown(d));
146
151
  /** the text a visitor sees: skips screen-reader-only / hidden descendants (innerText keeps them). */
147
152
  const visibleText = (el) => {
148
153
  let out = "";
@@ -291,8 +296,8 @@ function captureInPage(opt) {
291
296
  // order → POPUP1…; the buttons/links that open them become open_popup events.
292
297
  const POPUP_SEL = 'dialog, [role="dialog"], [aria-modal="true"], .modal, .popup, [class*="popup"], [class*="modal"], [id*="popup"], [id*="modal"]';
293
298
  const popupEls = Array.from(document.querySelectorAll(POPUP_SEL)).filter((c, i, all) => {
294
- if (all.some((o) => o !== c && o.contains(c)))
295
- return false; // outermost only
299
+ if (all.some((o) => o !== c && o.contains(c)) || c.closest("[data-wc-dismissed]"))
300
+ return false; // outermost only; no dismissed cookie bar / chat
296
301
  const s = cs(c);
297
302
  // a modal overlays the page (fixed / dialog); a hidden "popup-menu" dropdown sits in the flow
298
303
  const overlay = c.tagName === "DIALOG" || s.position === "fixed" || c.getAttribute("role") === "dialog" || c.getAttribute("aria-modal") === "true" || c.classList.contains("modal");
@@ -364,12 +369,23 @@ function captureInPage(opt) {
364
369
  const byTop = (a, b) => a.getBoundingClientRect().top - b.getBoundingClientRect().top;
365
370
  // fixed / absolute layers (floating widgets, side TOCs, overlays) are not bands: each becomes a pinned
366
371
  // group inside the section where it sits.
367
- const isOverlay = (c) => ["fixed", "absolute"].includes(cs(c).position);
372
+ // A fixed bar across the top (the site header) IS a band — the section's native sticky — when the
373
+ // page keeps room for it (nothing with content starts under it); a fixed header laid over the hero stays a layer.
374
+ const contentful = (b) => !!b.innerText?.trim() || !!b.querySelector("img,svg,video,iframe,canvas,picture,input,select,textarea") || painted(cs(b));
375
+ const topBar = (c) => {
376
+ const r = c.getBoundingClientRect();
377
+ return cs(c).position === "fixed" && r.top <= 1 && r.width >= vw * 0.9 && r.height <= window.innerHeight * 0.4 &&
378
+ Array.from(root.children).every((o) => o === c || isOverlayRaw(o) || !shown(o) || !contentful(o) || o.getBoundingClientRect().top >= r.bottom - 4);
379
+ };
380
+ const isOverlayRaw = (c) => ["fixed", "absolute"].includes(cs(c).position);
381
+ const isOverlay = (c) => isOverlayRaw(c) && !(c.parentElement === root && topBar(c));
368
382
  // A tall band made of full-width blocks stacked one under another (<main> wrapping every section)
369
- // is split into those blocks, down to 3 levels.
383
+ // is split into those blocks, down to 3 levels; a lone wrapper inside it (<main><div>…) is looked through.
370
384
  const flatten = (els, depth) => els.flatMap((b) => {
371
385
  const r = b.getBoundingClientRect();
372
- const kids = sizeable(b).filter((c) => !isOverlay(c)).sort(byTop);
386
+ let kids = sizeable(b).filter((c) => !isOverlay(c)).sort(byTop);
387
+ for (let i = 0; i < 4 && kids.length === 1 && !realForm(kids[0]) && !slidesOf(kids[0]).length; i++)
388
+ kids = sizeable(kids[0]).filter((c) => !isOverlay(c)).sort(byTop);
373
389
  const stacked = kids.length >= 2 && kids.every((c, i) => {
374
390
  const q = c.getBoundingClientRect();
375
391
  // stacked: each block starts below the middle of the previous one (angled / overlapping
@@ -381,7 +397,8 @@ function captureInPage(opt) {
381
397
  });
382
398
  const topLevel = sizeable(root).sort(byTop);
383
399
  const overlayEls = topLevel.filter(isOverlay);
384
- const bandEls = flatten(topLevel.filter((c) => !isOverlay(c)), 0).sort(byTop);
400
+ // an empty band (a spacer under a fixed header) adds no section: the band above spans its room
401
+ const bandEls = flatten(topLevel.filter((c) => !isOverlay(c)), 0).filter(contentful).sort(byTop);
385
402
  // popups mode: show each hidden popup and measure its content box as its own band
386
403
  const popupContents = [];
387
404
  if (opt.popups) {
@@ -440,7 +457,12 @@ function captureInPage(opt) {
440
457
  const span = spanOf(bands.indexOf(band));
441
458
  const secTop = span.top;
442
459
  const bs = cs(band);
443
- const background = { "background-color": rgba(alpha(bs.backgroundColor) > 0 ? bs.backgroundColor : pageBg) };
460
+ // a transparent band shows the wrapper it was split from (<main class="bg-light">), else the page's background
461
+ let bgEl = band;
462
+ while (alpha(cs(bgEl).backgroundColor) === 0 && bgEl.parentElement && bgEl !== root)
463
+ bgEl = bgEl.parentElement;
464
+ const bgColor = cs(bgEl).backgroundColor;
465
+ const background = { "background-color": rgba(alpha(bgColor) > 0 ? bgColor : pageBg) };
444
466
  if (bgUrl(bs))
445
467
  background["background-image"] = bgUrl(bs);
446
468
  else if (gradient(bs))
@@ -554,8 +576,15 @@ function captureInPage(opt) {
554
576
  sink.push(raw);
555
577
  };
556
578
  const visit = (el, inForm) => {
557
- if (SKIP.has(el.tagName) || !shown(el) || count >= maxElements)
579
+ if (SKIP.has(el.tagName) || count >= maxElements)
558
580
  return;
581
+ if (!shown(el)) {
582
+ // a 0×0 wrapper that does not clip (an inline <a> around an absolute ticker item) still shows its children
583
+ const z = cs(el), zr = el.getBoundingClientRect();
584
+ if ((zr.width <= 2 || zr.height <= 2) && z.display !== "none" && z.visibility !== "hidden" && parseFloat(z.opacity) > 0.02 && z.overflowX === "visible" && z.overflowY === "visible")
585
+ Array.from(el.children).forEach((c) => visit(c, inForm));
586
+ return;
587
+ }
559
588
  const s = cs(el);
560
589
  const tag = el.tagName;
561
590
  const style = {};
@@ -727,8 +756,22 @@ function captureInPage(opt) {
727
756
  }
728
757
  if (inForm && (FIELD.has(tag) || tag === "BUTTON" || consumed.has(el)))
729
758
  return; // already a form field
730
- if (FIELD.has(tag))
731
- return; // a field outside a form cannot submit on a landing page
759
+ if (FIELD.has(tag)) {
760
+ // a field outside a form cannot submit on a landing page: its look stays (a search box) — the box + its placeholder
761
+ if (painted(s)) {
762
+ paint(s, style);
763
+ push({ __el: el, key: keyOf(el) + "~bg", kind: "box", box: boxOf(el), style });
764
+ }
765
+ const hint = String(el.placeholder || (tag === "SELECT" ? el.selectedOptions?.[0]?.text : el.value) || "").trim();
766
+ if (hint && !["checkbox", "radio", "range", "color", "file", "hidden"].includes(el.type)) {
767
+ const st = {};
768
+ typo(s, st);
769
+ if (el.placeholder && !el.value)
770
+ st.color = getComputedStyle(el, "::placeholder").color;
771
+ push({ key: keyOf(el), kind: "paragraph", text: esc(hint), box: contentBox(el, s), style: st });
772
+ }
773
+ return;
774
+ }
732
775
  const text = visibleText(el);
733
776
  const buttonish = (tag === "A" || tag === "BUTTON" || el.getAttribute("role") === "button") && painted(s) && text.length > 0 && text.length <= 60 && el.getBoundingClientRect().height <= 120;
734
777
  if (buttonish) {
@@ -972,6 +1015,72 @@ function openCollapsibles() {
972
1015
  mark(panel, t, open);
973
1016
  });
974
1017
  }
1018
+ /**
1019
+ * Runs in the page BEFORE the measurement: what floats over the page that is not its design is taken away.
1020
+ * Consent / newsletter / promo layers are dismissed the way a visitor does (their accept / close control
1021
+ * clicked: Vietnamese + English texts, aria-labels); what still floats then — cookie bars, empty
1022
+ * full-screen dim backdrops, chat widgets — is hidden and left out (data-wc-dismissed), and a promo modal
1023
+ * left open is hidden too (the popup pass measures it as a landing popup). Only position:fixed layers are touched, never the site header
1024
+ * or anything in the flow.
1025
+ */
1026
+ function dismissOverlays() {
1027
+ const vw = document.documentElement.clientWidth, vh = window.innerHeight;
1028
+ const CONSENT = /cookie|consent|gdpr|quyền riêng tư|privacy/i;
1029
+ const PROMO = /newsletter|subscribe|popup|modal|dialog|promo|đăng ký nhận/i;
1030
+ const CHAT = /chat|messenger|zalo|tawk|crisp|intercom|tidio|zopim|livechat|hubspot-messages|freshchat|drift|contact-fab|hỗ trợ|support/i;
1031
+ const CLOSE = /^(chấp nhận( tất cả)?|đồng ý( tất cả)?|tôi đồng ý|accept( all)?( cookies)?|allow( all)?( cookies)?|agree|i agree|got it|ok(ay)?|đã hiểu|đóng|close|dismiss|no,? thanks|không,? cảm ơn|bỏ qua|để sau|later|[×✕✖xX])$/i;
1032
+ const attrs = (el) => `${el.id || ""} ${typeof el.className === "string" ? el.className : ""} ${el.getAttribute("aria-label") || ""} ${el.getAttribute("role") || ""}`;
1033
+ const visible = (el) => {
1034
+ const r = el.getBoundingClientRect(), s = getComputedStyle(el);
1035
+ return r.width > 2 && r.height > 2 && s.display !== "none" && s.visibility !== "hidden" && parseFloat(s.opacity) > 0.02;
1036
+ };
1037
+ const header = (el) => el.matches("header, [role=banner]") || !!el.querySelector("nav, [role=navigation]");
1038
+ /** the outermost position:fixed ancestor-or-self (below <body>) */
1039
+ const layerOf = (el) => {
1040
+ let out = null;
1041
+ for (let n = el; n && n !== document.body; n = n.parentElement)
1042
+ if (getComputedStyle(n).position === "fixed")
1043
+ out = n;
1044
+ return out;
1045
+ };
1046
+ const kind = (el) => {
1047
+ const text = (el.innerText || "").trim();
1048
+ if (CONSENT.test(attrs(el)) || /cookie|consent|gdpr/i.test(text) || (CONSENT.test(text) && text.length < 800))
1049
+ return "consent";
1050
+ if (el.matches("dialog, [role=dialog], [aria-modal=true]") || PROMO.test(attrs(el)))
1051
+ return "promo";
1052
+ return "";
1053
+ };
1054
+ // 1. the visitor's click: accept / close inside a consent or promo layer (no navigation, no form submit)
1055
+ for (const b of Array.from(document.querySelectorAll("button, a, [role=button], input[type=button]"))) {
1056
+ const t = (b.innerText || b.value || b.getAttribute("aria-label") || b.getAttribute("title") || "").trim().replace(/\s+/g, " ");
1057
+ if (!CLOSE.test(t) || !visible(b) || (b.tagName === "A" && /^https?:|^\//.test(b.getAttribute("href") || "")) || (b.closest("form") && b.type !== "button"))
1058
+ continue;
1059
+ const layer = layerOf(b) || b.closest("dialog, [role=dialog], [aria-modal=true]");
1060
+ if (layer && !header(layer) && kind(layer)) {
1061
+ try {
1062
+ b.click();
1063
+ }
1064
+ catch { /* a handler that throws */ }
1065
+ }
1066
+ }
1067
+ // 2. what still floats
1068
+ for (const el of Array.from(document.querySelectorAll("body *"))) {
1069
+ if (!el.isConnected || getComputedStyle(el).position !== "fixed" || layerOf(el) !== el || !visible(el) || header(el))
1070
+ continue;
1071
+ const r = el.getBoundingClientRect();
1072
+ const k = kind(el);
1073
+ const text = (el.innerText || "").trim();
1074
+ const backdrop = r.width >= vw * 0.9 && r.height >= vh * 0.9 && !text && !el.querySelector("img, svg, video, iframe, picture, canvas");
1075
+ const small = r.width * r.height < vw * vh * 0.15;
1076
+ const chat = small && (CHAT.test(attrs(el)) || Array.from(el.querySelectorAll("[id], [class], [aria-label], iframe")).some((d) => CHAT.test(attrs(d)) || CHAT.test(d.src || "")) || (text.length <= 24 && CHAT.test(text)));
1077
+ // hidden, not removed: a framework (React…) that still owns the node crashes when it is gone
1078
+ if (k === "consent" || backdrop || chat)
1079
+ el.setAttribute("data-wc-dismissed", "");
1080
+ if (k || backdrop || chat)
1081
+ el.style.setProperty("display", "none", "important");
1082
+ }
1083
+ }
975
1084
  async function captureAt(target, width) {
976
1085
  const r = await withContext(width, 1, async (ctx) => {
977
1086
  // Every request the page makes (subresources, redirects, html-embedded urls) passes the same
@@ -989,6 +1098,9 @@ async function captureAt(target, width) {
989
1098
  }
990
1099
  else
991
1100
  await page.setContent(withBase(target.html, target.baseUrl), { waitUntil: "networkidle", timeout: 30000 }).catch(() => undefined);
1101
+ await page.evaluate(dismissOverlays).catch(() => undefined);
1102
+ await page.waitForTimeout(300); // the dismissed layers' close animations
1103
+ await page.evaluate(dismissOverlays).catch(() => undefined);
992
1104
  await page.evaluate(openCollapsibles).catch(() => undefined);
993
1105
  // An app shell that scrolls inside a full-height box (body = one viewport, content in a
994
1106
  // overflow:auto div): unlock it so the document is as tall as the page.
@@ -1019,6 +1131,8 @@ async function captureAt(target, width) {
1019
1131
  window.scrollTo({ top: 0, behavior: "instant" });
1020
1132
  });
1021
1133
  await page.waitForTimeout(400);
1134
+ // a layer that only appeared while scrolling (a newsletter after N seconds / % scrolled)
1135
+ await page.evaluate(dismissOverlays).catch(() => undefined);
1022
1136
  const main = await page.evaluate(captureInPage, { max: MAX_ELEMENTS, popups: false });
1023
1137
  // second pass reveals the hidden popups (mutates the page: after the main capture)
1024
1138
  const pop = await page.evaluate(captureInPage, { max: 200, popups: true }).catch(() => null);
@@ -1149,7 +1263,7 @@ export function mergeCaptures(desk, mob) {
1149
1263
  // element is placed by its absolute page position; each desktop section gets a mobile FRAME — from its
1150
1264
  // matched elements down to the next section's frame — and its mobile boxes are relative to that frame.
1151
1265
  // Matching is by DOM path, else by what the element shows (text / picture / icon); a section that
1152
- // barely matches hides nothing on mobile (scaled fallback) and gets no mobile-only additions.
1266
+ // barely matches (and is not the same band there) hides nothing on mobile (scaled fallback) and gets no mobile-only additions.
1153
1267
  const sigOf = (e) => (e.text ? `t:${e.text.replace(/<[^>]+>/g, "").replace(/\s+/g, " ").trim().slice(0, 80)}` : e.src ? `s:${e.src}` : e.svg ? `v:${e.svg.slice(0, 120)}` : "");
1154
1268
  const mobAll = (mob?.sections ?? []).flatMap((ms) => ms.elements.map((e) => ({ e, abs: ms.top + e.box.top, sec: ms })));
1155
1269
  const byKey = new Map(mobAll.map((r) => [r.e.key, r]));
@@ -1212,9 +1326,12 @@ export function mergeCaptures(desk, mob) {
1212
1326
  s.elements.forEach((e, j) => (matchesOf[i][j] ??= bySigPick(e, (r) => r.abs >= frames[i] && r.abs < end)));
1213
1327
  });
1214
1328
  const relative = (r, frameTop) => ({ ...r.e, box: { ...r.e.box, top: Math.round(r.abs - frameTop) } });
1329
+ // the mobile layout of a section is known when the same band exists there (a header whose desktop nav
1330
+ // collapses into a burger matches little, yet what is missing IS hidden) or enough of it matched
1331
+ const reliableAt = (i) => !!mob && ((keysHold && mobSec.has(desk.sections[i].key)) || desk.sections[i].elements.length === 0 || matchesOf[i].filter(Boolean).length / desk.sections[i].elements.length >= 0.3);
1215
1332
  const sections = desk.sections.map((s, i) => {
1216
1333
  const hits = matchesOf[i];
1217
- const reliable = !!mob && (s.elements.length === 0 || hits.filter(Boolean).length / s.elements.length >= 0.3);
1334
+ const reliable = reliableAt(i);
1218
1335
  const fTop = frames[i];
1219
1336
  const fEnd = i + 1 < frames.length ? frames[i + 1] : mobEnd;
1220
1337
  const sec = {
@@ -1234,8 +1351,7 @@ export function mergeCaptures(desk, mob) {
1234
1351
  if (used.has(r))
1235
1352
  continue;
1236
1353
  const i = frameOf(r.abs);
1237
- const hits = matchesOf[i] ?? [];
1238
- if (!desk.sections[i] || (desk.sections[i].elements.length && hits.filter(Boolean).length / desk.sections[i].elements.length < 0.3))
1354
+ if (!desk.sections[i] || !reliableAt(i))
1239
1355
  continue;
1240
1356
  const el = toEl(relative(r, frames[i]), undefined, km);
1241
1357
  mobileOnly(el, true);
package/dist/smoke.js CHANGED
@@ -19,7 +19,7 @@ import { matchAccountDomain, normalizeDomain } from "./persistence/domain-match.
19
19
  import { normalizePhoto, resolvePexelsKey, pexelsKeyFromHeaders, resolvePexelsProxyBase, buildSearchQuery, PEXELS_PROXY_DEFAULT, variantPixels, annotateVariantSizes } from "./persistence/pexels-client.js";
20
20
  import { putDraft, getDraft, updateDraft, deleteDraft } from "./persistence/draft-cache.js";
21
21
  import { buildConnectUrl, parseCallback } from "./auth/login.js";
22
- import { redirectMatches, isDeadJwt, markJwtDead } from "./auth/oauth-server.js";
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
25
  import { isLocalPath, resolveLocalPath, sniffMime, localContentType } from "./tools/media.js";
@@ -130,6 +130,8 @@ check("good page valid", r1.valid, r1.errors);
130
130
  check("oauth redirect: exact claude.ai match", redirectMatches("https://claude.ai/api/mcp/auth_callback", "https://claude.ai/api/mcp/auth_callback"));
131
131
  check("oauth redirect: loopback any port (Claude Code)", redirectMatches("http://localhost/callback", "http://localhost:3118/callback") && redirectMatches("http://127.0.0.1/callback", "http://127.0.0.1:51234/callback"));
132
132
  check("oauth redirect: rejects other path/host/https port drift", !redirectMatches("http://localhost/callback", "http://localhost:3118/evil") && !redirectMatches("http://localhost/callback", "http://127.0.0.1:3118/callback") && !redirectMatches("https://claude.ai/api/mcp/auth_callback", "https://claude.ai:8443/api/mcp/auth_callback") && !redirectMatches("http://evil.com/callback", "http://evil.com:1/callback"));
133
+ check("oauth DCR: allows known clients + loopback", isAllowedRedirect("https://claude.ai/api/mcp/auth_callback") && isAllowedRedirect("https://chatgpt.com/connector_platform_oauth_redirect") && isAllowedRedirect("http://localhost:3118/callback") && isAllowedRedirect("http://[::1]/cb"));
134
+ check("oauth DCR: rejects foreign hosts / http non-loopback / other schemes", !isAllowedRedirect("https://evil.tld/cb") && !isAllowedRedirect("https://claude.ai.evil.tld/cb") && !isAllowedRedirect("http://claude.ai/cb") && !isAllowedRedirect("javascript:alert(1)") && !isAllowedRedirect("nope"));
133
135
  check("good page has no dangling-target warnings", r1.warnings.length === 0, r1.warnings);
134
136
  check("good page stats", r1.stats.sections === 2 && r1.stats.ids === 3, r1.stats);
135
137
  console.log("== validate: catches problems ==");
@@ -239,8 +239,8 @@ export function registerApiGatewayTools(server) {
239
239
  id: z.string().optional().describe("Operation id from api_find (preferred)"),
240
240
  method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]).optional().describe("With path, when id is not given"),
241
241
  path: z.string().optional().describe("Catalog path with :params, e.g. /api/datasets/records"),
242
- path_params: z.record(z.string()).optional().describe("Values for :params in the path (page_id, org_id…); org_id defaults to the selected organization"),
243
- query: z.record(z.any()).optional().describe("Query-string values"),
242
+ path_params: z.record(z.string(), z.string()).optional().describe("Values for :params in the path (page_id, org_id…); org_id defaults to the selected organization"),
243
+ query: z.record(z.string(), z.any()).optional().describe("Query-string values"),
244
244
  org_id: z.string().optional().describe("Organization sent as x-org-id ('personal' = none); default: the configured org. Many routes need it."),
245
245
  pick: z.array(z.string()).optional().describe("Keep only these fields on each item of a list result (or on a single object)"),
246
246
  max_items: z.number().int().min(1).max(500).optional().describe("Cap list results (default 50)"),
@@ -58,7 +58,7 @@ export async function cloneToDraft(domain, target, name) {
58
58
  };
59
59
  }
60
60
  export function registerCloneTools(server, domain) {
61
- server.tool("clone_page", "Clones any web page into a Webcake landing page by MEASURING it in a real browser (headless Chrome via Playwright, JavaScript executed — works for React/Vue/Next sites too). The page is loaded at 1200 px and at 420 px; every visible text, image, button, painted box, divider, svg icon and form is recorded with its box, rotation and typography and placed on the landing canvas: desktop boxes scaled onto 960, mobile boxes as measured on 420 (elements the mobile layout hides get config.hide on mobile; mobile-only ones are hidden on desktop). Links become open_link events; fixed elements are pinned; a sticky header becomes the section's native sticky (a-t). Effects, native first: gradients (also gradient text), filters/backdrop blur, rotation and AOS / animate.css / WOW entrance animations map onto native settings; an overflow:hidden box whose content spills out becomes a clipping group (custom_css overflow:hidden); the page's own :hover rules (also ancestor rules like .card:hover img, applied on the element itself) + transitions and its looping CSS animations (@keyframes) become settings.extra_css scoped to #w-<id> (the one thing no native setting covers); icon-font stylesheets go to settings.bhet; self-hosted @font-face fonts to settings.fontGroups. Forms keep every control as its native field (select with options, radio, checkbox-group, textarea, date, file), also forms without a <form> tag. Interactive parts stay interactive, natively: accordions / FAQs (<details>, Bootstrap collapse, aria-expanded panels) become a click→collapse on the question that collapses the answer on load; tab sets ([role=tabpanel], .tab-pane) become a carousel switched by its tab buttons (change_tab); modals hidden on load (.modal, <dialog>, [role=dialog], .popup…) become landing popups, and the buttons/links that open them get open_popup; #anchor links get scroll_to; sliders (Swiper, Slick, Splide, Owl, Bootstrap carousel, Glide, Flickity, Keen, Embla) become a carousel of slides (hidden slides measured too, library clones skipped); YouTube / Vimeo / <video> become the video element. Multi-colour svgs (logos, illustrations, gradients) become images of themselves; single-colour icons stay native svg masks. The source is validated like a save and cached: the result carries `draft_id` — save it with create_page({ draft_id, dry_run:false }). Robust to real sites: app shells that scroll inside a full-height box are unlocked, reveal-on-scroll content is scrolled into its shown state, a tall <main> is split into its sections, overlapping (angled) sections keep their stacking, content clipped by overflow:hidden is cropped (images keep a crop), measured text heights are kept (config.virtualHeight), every colour is rgba(), and desktop/mobile elements are matched by DOM path, else by their text / picture. Approximations: an ancestor :hover fires when the element itself is hovered, other iframes become html-box embeds, content a site renders differently on each load may shift. Needs Playwright on the host (playwright-core + Chrome, or CHROME_BIN). No credentials, no writes.", {
61
+ server.tool("clone_page", "Clones any web page into a Webcake landing page by MEASURING it in a real browser (headless Chrome via Playwright, JavaScript executed — works for React/Vue/Next sites too). The page is loaded at 1200 px and at 420 px; every visible text, image, button, painted box, divider, svg icon and form is recorded with its box, rotation and typography and placed on the landing canvas: desktop boxes scaled onto 960, mobile boxes as measured on 420 (elements the mobile layout hides get config.hide on mobile; mobile-only ones are hidden on desktop). Links become open_link events; fixed elements are pinned; a sticky header becomes the section's native sticky (a-t). Effects, native first: gradients (also gradient text), filters/backdrop blur, rotation and AOS / animate.css / WOW entrance animations map onto native settings; an overflow:hidden box whose content spills out becomes a clipping group (custom_css overflow:hidden); the page's own :hover rules (also ancestor rules like .card:hover img, applied on the element itself) + transitions and its looping CSS animations (@keyframes) become settings.extra_css scoped to #w-<id> (the one thing no native setting covers); icon-font stylesheets go to settings.bhet; self-hosted @font-face fonts to settings.fontGroups. Forms keep every control as its native field (select with options, radio, checkbox-group, textarea, date, file), also forms without a <form> tag. Interactive parts stay interactive, natively: accordions / FAQs (<details>, Bootstrap collapse, aria-expanded panels) become a click→collapse on the question that collapses the answer on load; tab sets ([role=tabpanel], .tab-pane) become a carousel switched by its tab buttons (change_tab); modals hidden on load (.modal, <dialog>, [role=dialog], .popup…) become landing popups, and the buttons/links that open them get open_popup; #anchor links get scroll_to; sliders (Swiper, Slick, Splide, Owl, Bootstrap carousel, Glide, Flickity, Keen, Embla) become a carousel of slides (hidden slides measured too, library clones skipped); YouTube / Vimeo / <video> become the video element. Multi-colour svgs (logos, illustrations, gradients) become images of themselves; single-colour icons stay native svg masks. The source is validated like a save and cached: the result carries `draft_id` — save it with create_page({ draft_id, dry_run:false }). Robust to real sites: cookie / consent / newsletter overlays are dismissed (their accept / close clicked) and chat widgets left out before measuring, a fixed site header becomes the sticky first section, app shells that scroll inside a full-height box are unlocked, reveal-on-scroll content is scrolled into its shown state, a tall <main> (also through a lone wrapper div) is split into its sections, overlapping (angled) sections keep their stacking, content clipped by overflow:hidden is cropped (images keep a crop), measured text heights are kept (config.virtualHeight), every colour is rgba(), and desktop/mobile elements are matched by DOM path, else by their text / picture. Approximations: an ancestor :hover fires when the element itself is hovered, other iframes become html-box embeds, content a site renders differently on each load may shift. Needs Playwright on the host (playwright-core + Chrome, or CHROME_BIN). No credentials, no writes.", {
62
62
  url: z.string().optional().describe("Public http(s) URL of the page to clone."),
63
63
  html: z.string().optional().describe("Raw HTML instead of a URL (a saved page / an exported file). Pass base_url so its relative images, stylesheets and fonts load."),
64
64
  base_url: z.string().optional().describe("With html: the page's original URL — relative assets (images, CSS, fonts) resolve against it, as if the page were loaded from there."),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webcake-landing-mcp",
3
- "version": "1.16.2",
3
+ "version": "1.17.1",
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",
@@ -50,7 +50,7 @@
50
50
  "@modelcontextprotocol/sdk": "^1.12.0",
51
51
  "ajv": "^8.17.1",
52
52
  "node-html-parser": "^7.1.0",
53
- "zod": "^3.23.8"
53
+ "zod": "^4.6.7"
54
54
  },
55
55
  "devDependencies": {
56
56
  "@types/node": "^22.0.0",