From 1ceefd7231c545880fd652943ddb7e890d72dabd Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 17:56:52 +0800 Subject: [PATCH] feat(pages): serve Custom HTML blocks from sealed frame routes Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs --- .../changes/add-custom-html-block/tasks.md | 2 +- .../app/lib/bodyLimit.pages.test.ts | 14 ++++ solvway-admin-portal/app/lib/bodyLimit.ts | 5 +- .../app/lib/frameHtml.test.ts | 57 ++++++++++++++ solvway-admin-portal/app/lib/frameHtml.ts | 65 ++++++++++++++++ .../app/lib/frameRoutes.test.ts | 76 +++++++++++++++++++ solvway-admin-portal/app/lib/routeGuard.ts | 6 +- .../p/[company]/[slug]/frame/[block]/route.ts | 15 ++++ .../pages/[id]/preview/frame/[block]/route.ts | 17 +++++ solvway-admin-portal/middleware.frame.test.ts | 30 ++++++++ solvway-admin-portal/middleware.ts | 4 +- 11 files changed, 286 insertions(+), 5 deletions(-) create mode 100644 solvway-admin-portal/app/lib/bodyLimit.pages.test.ts create mode 100644 solvway-admin-portal/app/lib/frameHtml.test.ts create mode 100644 solvway-admin-portal/app/lib/frameHtml.ts create mode 100644 solvway-admin-portal/app/lib/frameRoutes.test.ts create mode 100644 solvway-admin-portal/app/p/[company]/[slug]/frame/[block]/route.ts create mode 100644 solvway-admin-portal/app/pages/[id]/preview/frame/[block]/route.ts create mode 100644 solvway-admin-portal/middleware.frame.test.ts diff --git a/openspec/changes/add-custom-html-block/tasks.md b/openspec/changes/add-custom-html-block/tasks.md index 30a1476..a43fdf8 100644 --- a/openspec/changes/add-custom-html-block/tasks.md +++ b/openspec/changes/add-custom-html-block/tasks.md @@ -14,7 +14,7 @@ Design: `design.md` and `docs/superpowers/specs/2026-12-02-custom-html-block-des ## 2. Portal -- [ ] 2.1 Frame routes (public and preview) with the sandbox headers, the 404 rules and the height script. +- [x] 2.1 Frame routes (public and preview) with the sandbox headers, the 404 rules and the height script. - The middleware skips them; `routeGuard` admits the public frame path. - Security code: read the whole diff. - [ ] 2.2 `CmsBlocks`: diff --git a/solvway-admin-portal/app/lib/bodyLimit.pages.test.ts b/solvway-admin-portal/app/lib/bodyLimit.pages.test.ts new file mode 100644 index 0000000..415cd87 --- /dev/null +++ b/solvway-admin-portal/app/lib/bodyLimit.pages.test.ts @@ -0,0 +1,14 @@ +import { describe, it, expect } from "vitest"; +import { bodyLimit, DEFAULT_BODY_LIMIT, UPLOAD_BODY_LIMIT } from "./bodyLimit"; + +// add-custom-html-block: a page save may carry several Custom HTML blocks of up to 200,000 characters each. +describe("bodyLimit: page saves", () => { + it("gives page creates and updates the large limit", () => { + expect(bodyLimit("/api/pages")).toBe(UPLOAD_BODY_LIMIT); + expect(bodyLimit("/api/pages/12")).toBe(UPLOAD_BODY_LIMIT); + }); + + it("leaves other page-like paths on the default", () => { + for (const p of ["/api/pagesx", "/api/pages/12/other", "/api/companies/1/branding"]) expect(bodyLimit(p), p).toBe(DEFAULT_BODY_LIMIT); + }); +}); diff --git a/solvway-admin-portal/app/lib/bodyLimit.ts b/solvway-admin-portal/app/lib/bodyLimit.ts index 783fa83..acbb4dc 100644 --- a/solvway-admin-portal/app/lib/bodyLimit.ts +++ b/solvway-admin-portal/app/lib/bodyLimit.ts @@ -2,12 +2,13 @@ // front of the portal caps it (a 2 MB POST reached the login route live). The middleware refuses an API write whose // declared Content-Length exceeds its route's limit. Uploads (images, photos, documents, attachments, imports) get // room for a 5 MB file sent as base64 JSON, as do email-template saves (free HTML, which may carry inline images); -// everything else 1 MB. +// everything else 1 MB. Landing-page saves get the large limit too (add-custom-html-block): a Custom HTML block holds +// up to 200,000 characters. export const DEFAULT_BODY_LIMIT = 1024 * 1024; export const UPLOAD_BODY_LIMIT = 10 * 1024 * 1024; -const UPLOAD_PATH = /\/(?:image|images|photos|upload|attachments|doc|invoice-header|import)(?:\/|$)|^\/api\/(?:fulfilment|email-templates)(?:\/|$)/; +const UPLOAD_PATH = /\/(?:image|images|photos|upload|attachments|doc|invoice-header|import)(?:\/|$)|^\/api\/(?:fulfilment|email-templates)(?:\/|$)|^\/api\/pages(?:\/\d+)?$/; export function bodyLimit(pathname: string): number { return UPLOAD_PATH.test(pathname) ? UPLOAD_BODY_LIMIT : DEFAULT_BODY_LIMIT; diff --git a/solvway-admin-portal/app/lib/frameHtml.test.ts b/solvway-admin-portal/app/lib/frameHtml.test.ts new file mode 100644 index 0000000..def2282 --- /dev/null +++ b/solvway-admin-portal/app/lib/frameHtml.test.ts @@ -0,0 +1,57 @@ +import { describe, it, expect } from "vitest"; +import { FRAME_SANDBOX, frameDocument, frameResponse, nextFrameHeight, START_HEIGHT } from "./frameHtml"; + +// add-custom-html-block: pasted HTML runs sealed, in its own document with a sandbox policy, and reports its height. +describe("frameHtml", () => { + it("grants scripts and pop-ups only", () => { + expect(FRAME_SANDBOX.split(" ").sort()).toEqual(["allow-popups", "allow-popups-to-escape-sandbox", "allow-scripts"]); + }); + + it("adds the height script before , or at the end of a fragment", () => { + const doc = frameDocument("

Hi

"); + expect(doc).toMatch(/

Hi<\/h1>`; + +/** The pasted HTML with the height script before its last , or appended when it is a fragment. */ +export function frameDocument(html: string): string { + const at = html.toLowerCase().lastIndexOf(""); + return at < 0 ? html + HEIGHT_SCRIPT : html.slice(0, at) + HEIGHT_SCRIPT + html.slice(at); +} + +export function frameResponse(html: string, { preview }: { preview: boolean }): Response { + return new Response(frameDocument(html), { + headers: { + "Content-Type": "text/html; charset=utf-8", + "Content-Security-Policy": `sandbox ${FRAME_SANDBOX}; frame-ancestors 'self'`, + "X-Content-Type-Options": "nosniff", + "Referrer-Policy": "no-referrer", + "Cache-Control": preview ? "no-store" : "public, max-age=60", + }, + }); +} + +/** The same empty answer for every frame miss. */ +export const frameNotFound = () => new Response(null, { status: 404, headers: { "Cache-Control": "no-store" } }); + +/** The HTML of block `index` when it is an HTML block, else null. */ +export function htmlBlock(blocks: unknown, index: string): string | null { + if (!/^\d{1,2}$/.test(index) || !Array.isArray(blocks)) return null; + const block = blocks[Number(index)] as { type?: unknown; html?: unknown } | undefined; + return block?.type === "HTML" && typeof block.html === "string" ? block.html : null; +} + +export interface FrameHeight { + height: number; + /** The last growth steps, to spot content that grows with the frame. */ + steps: number[]; +} + +/** + * The frame's next height after a message from it. Junk leaves the state as it is. A section sized by the viewport + * (100vh) grows with the frame, so each report is the frame plus the same remainder: after two equal steps the + * frame stops growing. + * ponytail: equal-step heuristic; a page that grows by the same step three times for another reason stops early. + */ +export function nextFrameHeight(state: FrameHeight, data: unknown): FrameHeight { + const d = data as { type?: unknown; height?: unknown } | null; + if (!d || typeof d !== "object" || d.type !== FRAME_MESSAGE || typeof d.height !== "number" || !Number.isFinite(d.height)) return state; + const height = Math.min(MAX_HEIGHT, Math.max(MIN_HEIGHT, Math.ceil(d.height))); + if (height <= state.height) return { height, steps: [] }; + const step = height - state.height; + const [a, b] = state.steps.slice(-2); + if (a !== undefined && b !== undefined && Math.abs(a - step) <= 2 && Math.abs(b - step) <= 2) return state; + return { height, steps: [...state.steps, step].slice(-2) }; +} diff --git a/solvway-admin-portal/app/lib/frameRoutes.test.ts b/solvway-admin-portal/app/lib/frameRoutes.test.ts new file mode 100644 index 0000000..91d3ea2 --- /dev/null +++ b/solvway-admin-portal/app/lib/frameRoutes.test.ts @@ -0,0 +1,76 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); +vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); +vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); + +import * as pub from "@/app/p/[company]/[slug]/frame/[block]/route"; +import * as preview from "@/app/pages/[id]/preview/frame/[block]/route"; + +// add-custom-html-block: the frame addresses serve only an HTML block, sealed; every public miss looks the same. +const req = new Request("http://localhost/x"); +const ctx = (p: T) => ({ params: Promise.resolve(p) }); +const page = (blocks: object[]) => ({ ok: true, data: { company: { code: "INS", name: "INS" }, page: { slug: "hotel", title: "Hotel", blocks } } }); +const BLOCKS = [{ type: "HTML", html: "

Designed

" }, { type: "FORM", heading: "Join" }]; + +beforeEach(() => { + mocks.callMobileApi.mockReset(); + mocks.getToken.mockReset(); + mocks.getToken.mockResolvedValue("jwt"); + mocks.callMobileApi.mockResolvedValue(page(BLOCKS)); +}); + +describe("public frame", () => { + it("serves a published page's HTML block sealed", async () => { + const res = await pub.GET(req, ctx({ company: "INS", slug: "hotel", block: "0" })); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/public/pages/INS/hotel"); + expect(res.status).toBe(200); + expect(res.headers.get("content-security-policy")).toMatch(/^sandbox allow-scripts/); + expect(await res.text()).toContain("

Designed

"); + }); + + it("answers every miss with the same empty not-found", async () => { + // The API answers the published page; a bad index never reaches it. + for (const block of ["1", "7", "x", "-1", "100"]) { + const res = await pub.GET(req, ctx({ company: "INS", slug: "hotel", block })); + expect(res.status, block).toBe(404); + expect(await res.text()).toBe(""); + } + mocks.callMobileApi.mockResolvedValueOnce({ ok: false, status: 404 }); + const draft = await pub.GET(req, ctx({ company: "INS", slug: "draft", block: "0" })); + expect(draft.status).toBe(404); + expect(await draft.text()).toBe(""); + }); + + it("encodes the address parts", async () => { + await pub.GET(req, ctx({ company: "I/S", slug: "a b", block: "0" })); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/public/pages/I%2FS/a%20b"); + }); + + it("reports an upstream failure as 502", async () => { + mocks.callMobileApi.mockResolvedValueOnce({ ok: false, status: 500 }); + expect((await pub.GET(req, ctx({ company: "INS", slug: "hotel", block: "0" }))).status).toBe(502); + }); +}); + +describe("preview frame", () => { + it("serves a draft HTML block to staff through the admin API, uncached", async () => { + mocks.callMobileApi.mockResolvedValueOnce({ ok: true, data: { slug: "hotel", title: "Hotel", blocks: BLOCKS } }); + const res = await preview.GET(req, ctx({ id: "5", block: "0" })); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/pages/5", { token: "jwt" }); + expect(res.status).toBe(200); + expect(res.headers.get("cache-control")).toBe("no-store"); + expect(res.headers.get("content-security-policy")).toMatch(/^sandbox allow-scripts/); + }); + + it("is not found without a session, for a bad id, a refused page or a non-HTML block", async () => { + mocks.getToken.mockResolvedValueOnce(null); + expect((await preview.GET(req, ctx({ id: "5", block: "0" }))).status).toBe(404); + expect((await preview.GET(req, ctx({ id: "5x", block: "0" }))).status).toBe(404); + mocks.callMobileApi.mockResolvedValueOnce({ ok: false, status: 403 }); + expect((await preview.GET(req, ctx({ id: "5", block: "0" }))).status).toBe(404); + mocks.callMobileApi.mockResolvedValueOnce({ ok: true, data: { slug: "hotel", title: "Hotel", blocks: BLOCKS } }); + expect((await preview.GET(req, ctx({ id: "5", block: "1" }))).status).toBe(404); + expect(mocks.callMobileApi).toHaveBeenCalledTimes(2); + }); +}); diff --git a/solvway-admin-portal/app/lib/routeGuard.ts b/solvway-admin-portal/app/lib/routeGuard.ts index a1dca88..e1bf46e 100644 --- a/solvway-admin-portal/app/lib/routeGuard.ts +++ b/solvway-admin-portal/app/lib/routeGuard.ts @@ -13,9 +13,13 @@ export const PUBLIC_PATHS = new Set(["/login", "/reset-password", "/forg const VISITOR_PATH = /^\/[ric]\/[^/]+$/; // Published landing pages: /p//. const LANDING_PATH = /^\/p\/[^/]+\/[^/]+$/; +// add-custom-html-block: a published page's Custom HTML frame, /p///frame/. +export const LANDING_FRAME_PATH = /^\/p\/[^/]+\/[^/]+\/frame\/\d{1,2}$/; +// The staff preview of a draft's Custom HTML frame (signed in). +export const PREVIEW_FRAME_PATH = /^\/pages\/\d+\/preview\/frame\/\d{1,2}$/; export function isPublicPath(pathname: string): boolean { - return PUBLIC_PATHS.has(pathname) || VISITOR_PATH.test(pathname) || LANDING_PATH.test(pathname); + return PUBLIC_PATHS.has(pathname) || VISITOR_PATH.test(pathname) || LANDING_PATH.test(pathname) || LANDING_FRAME_PATH.test(pathname); } export interface SessionState { diff --git a/solvway-admin-portal/app/p/[company]/[slug]/frame/[block]/route.ts b/solvway-admin-portal/app/p/[company]/[slug]/frame/[block]/route.ts new file mode 100644 index 0000000..d73b53e --- /dev/null +++ b/solvway-admin-portal/app/p/[company]/[slug]/frame/[block]/route.ts @@ -0,0 +1,15 @@ +import { callMobileApi } from "@/app/lib/server/mobileApi"; +import { frameNotFound, frameResponse, htmlBlock } from "@/app/lib/frameHtml"; + +// add-custom-html-block: a published page's Custom HTML block as its own sealed document (see frameHtml.ts). +// Every miss (unknown company or page, draft, bad index, a block that is not HTML) is the same empty 404. +type Ctx = { params: Promise<{ company: string; slug: string; block: string }> }; + +export async function GET(_req: Request, { params }: Ctx): Promise { + const { company, slug, block } = await params; + if (!/^\d{1,2}$/.test(block)) return frameNotFound(); + const result = await callMobileApi<{ page?: { blocks?: unknown } }>(`/api/public/pages/${encodeURIComponent(company)}/${encodeURIComponent(slug)}`); + if (!result.ok) return result.status === 404 ? frameNotFound() : new Response(null, { status: 502 }); + const html = htmlBlock(result.data.page?.blocks, block); + return html === null ? frameNotFound() : frameResponse(html, { preview: false }); +} diff --git a/solvway-admin-portal/app/pages/[id]/preview/frame/[block]/route.ts b/solvway-admin-portal/app/pages/[id]/preview/frame/[block]/route.ts new file mode 100644 index 0000000..f3a91fd --- /dev/null +++ b/solvway-admin-portal/app/pages/[id]/preview/frame/[block]/route.ts @@ -0,0 +1,17 @@ +import { callMobileApi } from "@/app/lib/server/mobileApi"; +import { getToken } from "@/app/lib/server/session"; +import { frameNotFound, frameResponse, htmlBlock } from "@/app/lib/frameHtml"; + +// add-custom-html-block: a draft page's Custom HTML block for the staff preview, sealed like the public frame. +// The admin API checks BO_PAGES and the caller's company; anything it refuses is not found here. +type Ctx = { params: Promise<{ id: string; block: string }> }; + +export async function GET(_req: Request, { params }: Ctx): Promise { + const { id, block } = await params; + const token = await getToken(); + if (!token || !/^\d{1,19}$/.test(id) || !/^\d{1,2}$/.test(block)) return frameNotFound(); + const result = await callMobileApi<{ blocks?: unknown }>(`/api/admin/pages/${encodeURIComponent(id)}`, { token }); + if (!result.ok) return frameNotFound(); + const html = htmlBlock(result.data.blocks, block); + return html === null ? frameNotFound() : frameResponse(html, { preview: true }); +} diff --git a/solvway-admin-portal/middleware.frame.test.ts b/solvway-admin-portal/middleware.frame.test.ts new file mode 100644 index 0000000..5dd508b --- /dev/null +++ b/solvway-admin-portal/middleware.frame.test.ts @@ -0,0 +1,30 @@ +import { describe, it, expect } from "vitest"; +import { NextRequest } from "next/server"; +import { middleware } from "./middleware"; +import { guardDecision, isPublicPath } from "@/app/lib/routeGuard"; + +// add-custom-html-block: frame responses carry their own sandbox policy, so the middleware adds no nonce policy. +const get = (path: string) => new NextRequest(new URL(path, "https://portal.test"), { method: "GET" }); + +describe("middleware: custom HTML frames", () => { + it("lets a signed-out visitor load a public frame, without the nonce policy", async () => { + const res = await middleware(get("/p/INS/hotel-technology/frame/0")); + expect(res.status).toBe(200); + expect(res.headers.get("content-security-policy")).toBeNull(); + }); + + it("sends a signed-out preview frame request to sign in", async () => { + const res = await middleware(get("/pages/5/preview/frame/0")); + expect(res.status).toBeGreaterThanOrEqual(300); + expect(res.headers.get("location")).toContain("/login"); + }); + + it("keeps the nonce policy on the landing page itself and on look-alike paths", async () => { + expect((await middleware(get("/p/INS/hotel-technology"))).headers.get("content-security-policy")).toMatch(/nonce-/); + expect(isPublicPath("/p/INS/hotel-technology/frame/0")).toBe(true); + for (const p of ["/p/INS/hotel/frame/x", "/p/INS/hotel/frame/0/x", "/p/INS/frame/0", "/p/INS/hotel/frame/"]) { + expect(isPublicPath(p), p).toBe(false); + expect(guardDecision(p, null), p).toBe("/login"); + } + }); +}); diff --git a/solvway-admin-portal/middleware.ts b/solvway-admin-portal/middleware.ts index ac5e07b..97fd64e 100644 --- a/solvway-admin-portal/middleware.ts +++ b/solvway-admin-portal/middleware.ts @@ -2,7 +2,7 @@ import { NextResponse, type NextRequest } from "next/server"; import { sessionEnded, type SessionData } from "@/app/lib/sessionCodec"; import { openSession } from "@/app/lib/sessionSeal"; import { sessionCookieName } from "@/app/lib/sessionCookieName"; -import { guardDecision } from "@/app/lib/routeGuard"; +import { guardDecision, LANDING_FRAME_PATH, PREVIEW_FRAME_PATH } from "@/app/lib/routeGuard"; import { loginUrl } from "@/app/lib/returnTo"; import { isCrossSiteWrite } from "@/app/lib/sameOrigin"; import { bodyLimit } from "@/app/lib/bodyLimit"; @@ -44,6 +44,8 @@ function guard(req: NextRequest, session: SessionData | null): NextResponse { } return NextResponse.redirect(url); } + // add-custom-html-block: a Custom HTML frame sends its own sandbox policy; the nonce policy would block its scripts. + if (LANDING_FRAME_PATH.test(pathname) || PREVIEW_FRAME_PATH.test(pathname)) return NextResponse.next(); return withScriptPolicy(req); }