feat(pages): serve Custom HTML blocks from sealed frame routes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
This commit is contained in:
1 parent
9a7b225827
commit
1ceefd7231
11 files changed
+286
-5
No files matched your search
@@ -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`:
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
@@ -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 </body>, or at the end of a fragment", () => {
|
||||
const doc = frameDocument("<html><body><h1>Hi</h1></body></html>");
|
||||
expect(doc).toMatch(/<h1>Hi<\/h1><script>[\s\S]*colite-frame-height[\s\S]*<\/script><\/body><\/html>$/);
|
||||
expect(frameDocument("<section>x</section>")).toMatch(/^<section>x<\/section><script>[\s\S]*colite-frame-height/);
|
||||
expect(frameDocument("<BODY>x</BODY>")).toMatch(/x<script>[\s\S]*<\/script><\/BODY>$/);
|
||||
});
|
||||
|
||||
it("serves the HTML sealed: sandbox policy, own framing only, no sniffing", async () => {
|
||||
const res = frameResponse("<p>x</p>", { preview: false });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("content-type")).toBe("text/html; charset=utf-8");
|
||||
const csp = res.headers.get("content-security-policy") ?? "";
|
||||
expect(csp).toBe(`sandbox ${FRAME_SANDBOX}; frame-ancestors 'self'`);
|
||||
expect(csp).not.toContain("allow-same-origin");
|
||||
expect(csp).not.toContain("allow-forms");
|
||||
expect(csp).not.toContain("allow-top-navigation");
|
||||
expect(res.headers.get("x-content-type-options")).toBe("nosniff");
|
||||
expect(res.headers.get("referrer-policy")).toBe("no-referrer");
|
||||
expect(await res.text()).toContain("<p>x</p>");
|
||||
});
|
||||
|
||||
it("does not let a browser cache a draft", () => {
|
||||
expect(frameResponse("<p>x</p>", { preview: true }).headers.get("cache-control")).toBe("no-store");
|
||||
expect(frameResponse("<p>x</p>", { preview: false }).headers.get("cache-control")).not.toBe("no-store");
|
||||
});
|
||||
|
||||
it("clamps a reported height between 100 and 20000 pixels and ignores junk", () => {
|
||||
const start = { height: START_HEIGHT, steps: [] };
|
||||
expect(START_HEIGHT).toBe(600);
|
||||
expect(nextFrameHeight(start, { type: "colite-frame-height", height: 3000 }).height).toBe(3000);
|
||||
expect(nextFrameHeight(start, { type: "colite-frame-height", height: 10 }).height).toBe(100);
|
||||
expect(nextFrameHeight(start, { type: "colite-frame-height", height: 99999 }).height).toBe(20000);
|
||||
for (const junk of [null, "600", { type: "other", height: 900 }, { type: "colite-frame-height", height: "900" }, { type: "colite-frame-height", height: NaN }]) {
|
||||
expect(nextFrameHeight(start, junk)).toBe(start);
|
||||
}
|
||||
});
|
||||
|
||||
it("stops growing when the content grows with the frame (100vh sections)", () => {
|
||||
let s = { height: START_HEIGHT, steps: [] as number[] };
|
||||
// Each report is the frame height plus the same 400 px below a full-height section: a loop.
|
||||
for (let i = 0; i < 10; i++) s = nextFrameHeight(s, { type: "colite-frame-height", height: s.height + 400 });
|
||||
expect(s.height).toBeLessThan(START_HEIGHT + 400 * 4);
|
||||
// Ordinary growth with varying steps (images loading) keeps following the content.
|
||||
let t = { height: START_HEIGHT, steps: [] as number[] };
|
||||
for (const h of [900, 1250, 1900, 2000, 2600]) t = nextFrameHeight(t, { type: "colite-frame-height", height: h });
|
||||
expect(t.height).toBe(2600);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
// add-custom-html-block: a Custom HTML block runs sealed. It is served as its own document whose
|
||||
// Content-Security-Policy `sandbox` gives it an opaque origin, even when its address is opened directly, and it is
|
||||
// shown in an <iframe sandbox> with the same grants. No same-origin, forms, top navigation or modals.
|
||||
|
||||
export const FRAME_SANDBOX = "allow-scripts allow-popups allow-popups-to-escape-sandbox";
|
||||
export const FRAME_MESSAGE = "colite-frame-height";
|
||||
export const START_HEIGHT = 600;
|
||||
const MIN_HEIGHT = 100;
|
||||
const MAX_HEIGHT = 20000;
|
||||
|
||||
// Posts the document height to the parent page on load and whenever it changes.
|
||||
const HEIGHT_SCRIPT =
|
||||
`<script>(function(){function s(){parent.postMessage({type:"${FRAME_MESSAGE}",height:Math.ceil(document.documentElement.scrollHeight)},"*")}` +
|
||||
`addEventListener("load",s);if(window.ResizeObserver)new ResizeObserver(s).observe(document.documentElement);s()})();</script>`;
|
||||
|
||||
/** The pasted HTML with the height script before its last </body>, or appended when it is a fragment. */
|
||||
export function frameDocument(html: string): string {
|
||||
const at = html.toLowerCase().lastIndexOf("</body>");
|
||||
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) };
|
||||
}
|
||||
@@ -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 = <T,>(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: "<h1>Designed</h1>" }, { 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("<h1>Designed</h1>");
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -13,9 +13,13 @@ export const PUBLIC_PATHS = new Set<string>(["/login", "/reset-password", "/forg
|
||||
const VISITOR_PATH = /^\/[ric]\/[^/]+$/;
|
||||
// Published landing pages: /p/<company-code>/<slug>.
|
||||
const LANDING_PATH = /^\/p\/[^/]+\/[^/]+$/;
|
||||
// add-custom-html-block: a published page's Custom HTML frame, /p/<company-code>/<slug>/frame/<block>.
|
||||
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 {
|
||||
|
||||
@@ -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<Response> {
|
||||
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 });
|
||||
}
|
||||
@@ -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<Response> {
|
||||
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 });
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user