Compare commits

...
Author SHA1 Message Date
ngqileandClaude Opus 5.5 4251d395ad docs: tick add-custom-html-block tasks
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 18:22:05 +08:00
ngqileandClaude Opus 5.5 36dbb4c949 fix(pages): keep the frame's sandbox policy past the config headers
next.config's baseline Content-Security-Policy replaced the frame route's
own header, so a frame address opened directly ran without the sandbox.
A later headers rule for the two frame paths restores it. Also drop the
gap above a header-less page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 18:18:51 +08:00
ngqileandClaude Opus 5.5 f13b2a592a docs: deployment notes for Custom HTML frames
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 18:05:10 +08:00
ngqileandClaude Opus 5.5 cfc817082d feat(pages): Custom HTML block and hide-header switch in the page editor
The iframe guard allow-lists HtmlFrame.tsx for the named FRAME_SANDBOX
only, and asserts it never grants same-origin, forms, top navigation
or modals.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 18:05:00 +08:00
ngqileandClaude Opus 5.5 6a0a6613c1 feat(pages): render Custom HTML blocks as sized sealed frames and honour hide header
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 17:58:15 +08:00
ngqileandClaude Opus 5.5 1ceefd7231 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
2026-12-02 17:56:52 +08:00
ngqileandClaude Opus 5.5 9a7b225827 feat(pages): HTML block type and hide-header option in the services
The counter accepts an HTML block (required, at most 200,000 characters, no
script check because it only runs sealed) and stores a hide-header flag on the
page. mobile-api passes the flag through on save and in the public page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 17:46:32 +08:00
ngqileandClaude Opus 5.5 dcad8cb650 docs(openspec): add-custom-html-block change
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 17:36:54 +08:00
ngqileandClaude Opus 5.5 34732ef2a5 docs: custom HTML block design
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 17:34:20 +08:00
ngqile 53f3298ded Merge pull request 'feat(pages): copy button for page addresses' (#54) from pages-copy-address into main
CI / build-and-publish (push) Failing after 0s
2026-12-02 09:30:03 +00:00
47 changed files with 995 additions and 25 deletions

No files matched your search

+4
View File
@@ -150,6 +150,8 @@ Run the three in order before the new services-system, gateway and mobile-api go
| `openspec/changes/archive/2026-12-02-add-landing-pages/sql/03-company-branding.sql` | Adds `logo_image_id` and `accent_color` to `service-system`.`company`. DDL. |
| `openspec/changes/archive/2026-12-02-add-landing-pages/sql/04-module.sql` | Adds the Pages back-office module (`BO_PAGES`) under Events. No role gets it; super admins grant it under Roles. |
| `openspec/changes/archive/2026-12-02-add-landing-pages/sql/05-page-labels.sql` | Adds the landing-page labels in English and Chinese. Run it only where `add-zh-cn-messages/sql/03` already ran before this change; the regenerated 03 already includes them. |
| `openspec/changes/add-custom-html-block/sql/01-hide-header.sql` | Adds `hide_header` to `service-counter`.`cms_page`, the "Hide page header" option. DDL. |
| `openspec/changes/add-custom-html-block/sql/02-html-block-labels.sql` | Adds the Custom HTML block labels in English and Chinese. Same rule as `05-page-labels.sql`: only where `add-zh-cn-messages/sql/03` already ran. |
Run them in order before the new services-counter, services-system and mobile-api go live: the new services read the new columns on every event lead and company query. `01` to `03` need a user that may alter tables. `99-rollback.sql` in the same folder removes the module and drops the two tables and the columns, which deletes every page, image, page address and campaign tag.
@@ -309,6 +311,8 @@ QR registration pages (`/r/<code>`) are served by the admin portal on the same h
**Landing pages.** Published pages live at `/p/<company-code>/<slug>` on the admin portal, with their images at `/api/public/page-images/<id>` and their form at `/api/public/pages/...`. They need no new route: serve them on the public-pages hostname above, so printed and shared page links survive a later move to the customer portal.
**Custom HTML frames.** A Custom HTML block loads in a sealed frame from `/p/<company-code>/<slug>/frame/<n>`, and staff preview a draft one at `/pages/<id>/preview/frame/<n>`. Both are portal routes on the same hostname as the page. Their responses carry their own `Content-Security-Policy: sandbox allow-scripts allow-popups allow-popups-to-escape-sandbox; frame-ancestors 'self'`. The proxy (Traefik or any other layer) must not replace or strip that header, and must not add `X-Frame-Options: DENY` to these paths. Without the sandbox header, pasted scripts would run as the portal's own origin when the address is opened directly. After deploy, open a frame address and check the response header.
## 9. Secret templates
There is no template yet for `service-email` (its keys wait for the email provider) or `service-system` (its Jumio keys stay unset). Kubernetes Secrets hold base64 values. Encode each one with `printf '%s' 'value' | base64 -w0`. These are templates: replace every `<…>` and never commit the filled-in files.
@@ -0,0 +1,73 @@
# Custom HTML block for landing pages — design
Date: 2026-12-02. Status: draft for owner approval.
## Intent
Marketing staff want to generate page sections with an AI tool and paste the HTML into a landing page, so a page can look like a designed site rather than only the built-in blocks. The owner chose option 1 on 2026-12-02: a "Custom HTML" block shown in a sealed frame.
## Goals
- A new block type, **Custom HTML**, holding HTML pasted by staff with `BO_PAGES`.
- The pasted HTML renders as the AI designed it: its own styles, fonts, CDN libraries and scripts.
- The pasted HTML can never act as the visitor or as a staff member on the Co-Lite site: no access to cookies, the back-office APIs, the page around it, or top-level navigation.
- Leads still come only from the built-in Sign-up form block, with consent, interests and UTM tags.
## Non-goals
- Forms inside the pasted HTML do not submit. A pasted "contact us" form is decoration; staff add the Sign-up form block for real leads.
- No HTML editor, syntax highlighting or AI generation inside Co-Lite. Staff paste text.
- No search-engine indexing of the framed content. The page title, description and the other blocks still carry the page's search text.
## Anti-goals
- Any path where pasted HTML runs with the Co-Lite origin. This includes someone opening the frame's address directly in a browser tab.
## Approaches
1. **Sealed frame (chosen).** The HTML is served from its own address with a `sandbox` Content-Security-Policy and shown in an `<iframe sandbox>`. It looks exactly as pasted, and it is isolated by the browser. Costs: weaker SEO for the framed part, and forms inside it don't work.
2. **Sanitise into the page.** It is safe and searchable, but it strips scripts, `<style>` and most classes, so AI output usually looks broken. The owner rejected it.
## Design
### Storage and validation (services-counter)
- New block type `HTML` with one field, `html` (the pasted document or fragment).
- Limit: 200,000 characters per block, refused at the field (`blocks[i].html`) when exceeded or blank.
- The script check that RICH_TEXT uses does **not** apply to `HTML`. Scripts are expected and contained by the frame.
- The existing limit of 30 blocks per page still applies. Pages keep storing blocks as JSON.
### Serving the frame (portal)
- **Public:** `GET /p/{company}/{slug}/frame/{block}` returns the block's HTML as `text/html; charset=utf-8`. It reads the published page through the existing public page API; anything else is 404 with an empty body.
- **Staff preview:** `GET /pages/{id}/preview/frame/{block}` returns a draft block's HTML for a signed-in user with `BO_PAGES`, through the admin page API.
- Both responses carry:
- `Content-Security-Policy: sandbox allow-scripts allow-popups allow-popups-to-escape-sandbox; frame-ancestors 'self'`. The `sandbox` directive gives the document an opaque origin even when opened directly. `frame-ancestors 'self'` stops other sites from embedding it.
- `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer`, and `Cache-Control: no-store` on the preview.
- They do not carry the portal's per-page nonce policy. The middleware leaves these two routes alone.
- **Not granted:** `allow-same-origin`, `allow-forms`, `allow-top-navigation` and `allow-modals`.
### Height
- On serve, the portal appends a small script to the HTML. The script posts the document height to the parent when the page loads and when the height changes (`{ type: "colite-frame-height", height }`).
- The page around it sets the frame's height from messages whose `source` is that frame's window, clamped to 100–20,000 px. Before any message arrives, the frame is 600 px tall.
### Rendering
- The public page and the staff preview render the HTML block as `<iframe sandbox="allow-scripts allow-popups allow-popups-to-escape-sandbox" src="…/frame/{index}" title="{page title}" loading="lazy">`, full width, with no border.
### Editor
- An "Add Custom HTML" button and a monospace textarea with a character counter (/200,000).
- A one-line hint that forms inside the pasted HTML don't send, and that staff should add a Sign-up form block for leads.
- New labels in English and Chinese, shipped as SQL in the change folder.
### Security review points
- The gateway is unchanged. The frame routes are portal routes that call the existing public and admin page APIs.
- A staff account with `BO_PAGES` can still publish misleading content on the company's page, for example a fake login form. That risk already exists with text blocks. The frame stops the content from reaching any Co-Lite session or data. Page saves are audited.
## Left to the builder
- How the middleware skips the two frame routes: the matcher or an early return. A test must prove that the frame response carries the sandbox policy and not the nonce policy.
- Whether the height script is injected before `</body>` or appended at the end when the paste is a fragment.
+3
View File
@@ -503,3 +503,6 @@ ALTER TABLE `company`
USE `service-system`;
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
(40250000, 'BO_PAGES', 'Pages', 'BO', 'M', 40000000, '/pages', 'PanelsTopLeft');
-- add-custom-html-block: the hide-header page option
USE `service-counter`;
ALTER TABLE `cms_page` ADD COLUMN `hide_header` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Hide the company header and the page title on the public page' AFTER `status`;
+8
View File
@@ -1489,6 +1489,14 @@ INSERT INTO message (code, content, area) SELECT 'PagesBlockFaq', JSON_OBJECT('e
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '常见问题') WHERE LOWER(code) = LOWER('PagesBlockFaq') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesBlockForm', JSON_OBJECT('en_US', 'Sign-up form', 'zh_CN', '报名表'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBlockForm') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '报名表') WHERE LOWER(code) = LOWER('PagesBlockForm') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesBlockHtml', JSON_OBJECT('en_US', 'Custom HTML', 'zh_CN', '自定义 HTML'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBlockHtml') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '自定义 HTML') WHERE LOWER(code) = LOWER('PagesBlockHtml') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesHtml', JSON_OBJECT('en_US', 'HTML', 'zh_CN', 'HTML'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHtml') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', 'HTML') WHERE LOWER(code) = LOWER('PagesHtml') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesHtmlHint', JSON_OBJECT('en_US', 'Forms inside the pasted HTML don''t send. Add a Sign-up form block to collect leads.', 'zh_CN', '粘贴的 HTML 中的表单不会发送。请添加报名表单区块来收集线索。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHtmlHint') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '粘贴的 HTML 中的表单不会发送。请添加报名表单区块来收集线索。') WHERE LOWER(code) = LOWER('PagesHtmlHint') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesHideHeader', JSON_OBJECT('en_US', 'Hide page header', 'zh_CN', '隐藏页面顶栏'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHideHeader') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '隐藏页面顶栏') WHERE LOWER(code) = LOWER('PagesHideHeader') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesMoveUp', JSON_OBJECT('en_US', 'Move up', 'zh_CN', '上移'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesMoveUp') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '上移') WHERE LOWER(code) = LOWER('PagesMoveUp') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesMoveDown', JSON_OBJECT('en_US', 'Move down', 'zh_CN', '下移'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesMoveDown') AND area = 'A');
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-12-02
@@ -0,0 +1,41 @@
# Design
The full design is `docs/superpowers/specs/2026-12-02-custom-html-block-design.md` (approved 2026-12-02). This file records the technical decisions.
## Context
- Pages store their blocks as JSON in `cms_page.blocks`. `CmsBlockValidator` in services-counter checks the blocks, and mobile-api passes them to the portal unchanged.
- The portal's `middleware.ts` gives every page and API response a per-request nonce Content-Security-Policy. An `srcdoc` frame would inherit that policy and block the pasted scripts, inline styles and CDN links. So the pasted HTML needs its own response with its own policy.
- The public page `/p/[company]/[slug]` renders on the server. `routeGuard.isPublicPath` admits only `^/p/[^/]+/[^/]+$` today.
## Goals / Non-Goals
**Goals:**
- Pasted HTML renders as designed.
- It runs with an opaque origin on every path, including a direct visit to the frame address.
**Non-Goals:**
- SEO for the framed content.
- Working forms inside it.
- An HTML editor.
## Decisions
1. **Route handlers, not pages.** `app/p/[company]/[slug]/frame/[block]/route.ts` and `app/pages/[id]/preview/frame/[block]/route.ts` return `text/html` directly. They reuse the server helpers that the public page (published read) and the preview (admin read with the session token) already use.
2. **Sandbox in two places.**
- The response header: `Content-Security-Policy: sandbox allow-scripts allow-popups allow-popups-to-escape-sandbox; frame-ancestors 'self'`. This covers a direct visit.
- The `<iframe sandbox="allow-scripts allow-popups allow-popups-to-escape-sandbox">` attribute. This covers embedding.
- There is no `default-src` restriction, so the AI's CDN scripts, fonts and images load.
3. **Middleware skips the frame routes.** It returns early, with no nonce policy, for paths ending `/frame/<n>` under `/p/` and `/pages/<id>/preview/`. The preview route still checks the session itself; the middleware's route guard still runs before the early return, so an unsigned preview request is redirected to sign in.
4. **Height script.**
- The handler inserts a fixed script before `</body>`, or appends it when there is no `</body>`. The script posts `{type: "colite-frame-height", height}` to `parent` on load, on resize and through a `ResizeObserver` on `document.documentElement`.
- The parent accepts a message only when `event.source` is that iframe's `contentWindow`. It clamps the height to 100–20,000 px, starting at 600.
5. **Not-found.** The public handler answers 404 with an empty body for every miss: unknown company or slug, a draft page, a bad index or a non-HTML block. The same rule holds on the public page.
6. **`hideHeader`.** A `cms_page.hide_header TINYINT(1) NOT NULL DEFAULT 0` column carried through the counter DTO, the mobile-api admin request and the public page response. `LandingPage` omits the header and the `<h1>` when it is on.
7. **Limits.** `HTML` blocks allow 200,000 characters, about 200 KB for a large AI page. The existing 30-block cap stands. The portal body limit for page saves is checked and raised if it is below the largest page: 30 × 200,000 characters.
## Risks / Trade-offs
- **Misleading content:** staff with `BO_PAGES` can publish misleading content, such as a fake form. The frame contains it, saves are audited, and the role is granted by super admins only.
- **Cost of each frame:** each HTML block is one more request per visit. Pages have at most 30 blocks.
- **Relative addresses:** a relative asset path in pasted HTML (such as `/logo.png`) resolves against the Co-Lite site and breaks. The editor note tells staff to use full `https://` addresses for images.
@@ -0,0 +1,54 @@
# Proposal
## Why
Marketing staff want to design a landing page with an AI tool and paste the result in, so a page can look like a designed site instead of only the built-in blocks. The INS page is the first case: rebuilt from blocks, it does not match the design of the INS proof of concept (`~/Projects/ins-landing-page`). On 2026-12-02 the owner chose to show pasted HTML in a sealed frame (option 1). Design approved 2026-12-02: `docs/superpowers/specs/2026-12-02-custom-html-block-design.md`.
## What Changes
- **New block type `HTML` (Custom HTML).**
- Staff with `BO_PAGES` paste HTML, at most 200,000 characters per block.
- Scripts are allowed in this block only. Every other block keeps refusing scripts.
- **Sealed frame.**
- The public page shows each HTML block in an `<iframe sandbox>` loaded from its own address: `/p/<company>/<slug>/frame/<block>`.
- That response carries a `sandbox` Content-Security-Policy, so the pasted HTML runs with an opaque origin even when the address is opened directly. It cannot reach cookies, Co-Lite APIs, the page around it or top-level navigation, and its forms do not submit.
- Only Co-Lite pages may frame it (`frame-ancestors 'self'`).
- Staff preview a draft through a signed-in twin: `/pages/<id>/preview/frame/<block>`.
- **Frame height:** a small script is added to the served HTML. It reports the document height, so the frame grows to fit.
- **Hide page header:** a page option that hides the company header and the page title, so a page made of pasted HTML looks exactly as designed.
- **Editor:**
- "Add Custom HTML" with a monospace text box and a character counter;
- a note that forms in the pasted HTML don't send;
- the "Hide page header" switch.
## Capabilities
### New Capabilities
None.
### Modified Capabilities
- `landing-pages`:
- the block types gain `HTML`, with its limit;
- the scripts rule exempts it;
- a new requirement covers how it is served sealed and sized;
- the page gains the "hide header" option;
- the editor gains the Custom HTML block and the switch.
## Impact
- **services-counter:**
- `CmsBlockValidator` accepts `HTML` (200,000 characters, no script check);
- `cms_page` gets a `hide_header` column and the page DTO carries it.
- **SQL:** `sql/01-hide-header.sql` (DDL), `sql/02-html-block-labels.sql` (labels) and `sql/99-rollback.sql`. Mirror 01 into `local/seed/`.
- **mobile-api:** the admin page request and the public page response carry `hideHeader`. Blocks already pass through unchanged.
- **Portal:**
- two frame route handlers;
- `middleware.ts` leaves the frame routes without the nonce policy;
- `routeGuard` admits the public frame path;
- `CmsBlocks` renders the frame and honours `hideHeader`;
- the editor;
- labels, with Chinese.
- **Gateway:** unchanged.
- **Dependencies:** none.
@@ -0,0 +1,129 @@
## MODIFIED Requirements
### Requirement: A Page Is An Ordered List Of Typed Blocks
A page SHALL belong to one company and have a slug, a title, an optional meta description, a status (Draft or Published), a "hide header" flag that defaults to off, and an ordered list of zero to 30 blocks. The block types SHALL be HERO, RICH_TEXT, IMAGE_TEXT, FAQ, FORM and HTML. Blocks SHALL be returned in the order they were saved, and a valid save SHALL replace all of a page's blocks.
#### Scenario: Blocks read back in order
- **WHEN** staff save page `hotel-technology` with blocks HERO, RICH_TEXT, FORM
- **THEN** reading the page returns those three blocks in that order with their fields
#### Scenario: A save replaces the blocks
- **GIVEN** a page whose blocks are HERO and FAQ
- **WHEN** it is saved with only a RICH_TEXT block
- **THEN** the page has only that RICH_TEXT block
#### Scenario: An HTML block and the header flag read back
- **WHEN** staff save a page with "hide header" on and blocks HTML, FORM
- **THEN** reading the page returns "hide header" on and the HTML block with its HTML unchanged
### Requirement: Block Fields Are Validated Server-Side
A page save SHALL be refused with the offending field path, writing nothing, when a block has an unknown type, a required field is blank, or a text exceeds its limit: heading 120, text and FAQ question 300, button label 40, FAQ answer 2000, rich-text HTML 100000 characters, and an HTML block's HTML 200000 characters. An HTML block's HTML SHALL NOT be blank. A FAQ SHALL have 1 to 30 items. `imagePosition` SHALL be LEFT or RIGHT.
#### Scenario: Too many blocks
- **WHEN** a page is saved with 31 blocks
- **THEN** the save is refused and nothing is written
#### Scenario: HTML block too long
- **WHEN** a page is saved with an HTML block of 200001 characters
- **THEN** the save is refused on field `blocks[0].html` and nothing is written
### Requirement: Page Content Cannot Run Scripts
A button SHALL have both a label and a link or neither. The link SHALL be a same-site path starting with a single `/`, an `https://` URL, a `mailto:` link or a `tel:` link. A save SHALL be refused when the HTML of a RICH_TEXT or IMAGE_TEXT block holds a `script` element, an `on*` attribute or a `javascript:` URL. The public page SHALL also sanitise that HTML against an allow-list before rendering it. HTML blocks are exempt, because they only ever run sealed.
#### Scenario: Script link on a button
- **WHEN** a page is saved with a HERO button link `javascript:alert(1)`
- **THEN** the save is refused on field `blocks[0].buttonUrl`
#### Scenario: Script in rich text
- **WHEN** a page is saved with rich text holding `<img src=x onerror=alert(1)>`
- **THEN** the save is refused on that block's HTML field
#### Scenario: Script in an HTML block
- **WHEN** a page is saved with an HTML block holding `<script>document.title = "x"</script>`
- **THEN** the save succeeds
## ADDED Requirements
### Requirement: Custom HTML Runs Sealed
The public page and the staff preview SHALL show each HTML block in a sandboxed frame loaded from its own address. Each frame response SHALL carry a Content-Security-Policy whose `sandbox` directive allows scripts and pop-ups only, so the HTML runs with an opaque origin even when the address is opened directly, and whose `frame-ancestors` directive allows only the Co-Lite site. The frame element SHALL NOT grant same-origin, form submission, top-level navigation or modal dialogs.
#### Scenario: Public frame is sealed
- **GIVEN** INS page `hotel-technology` is published with an HTML block at index 0
- **WHEN** a visitor's browser loads `/p/INS/hotel-technology/frame/0`
- **THEN** the response is the block's HTML with a `sandbox` policy that allows scripts and pop-ups and not same-origin
- **AND** its `frame-ancestors` allows only the Co-Lite site
#### Scenario: Pasted HTML cannot reach the visitor's session
- **GIVEN** a published HTML block whose script reads `document.cookie` and calls `/api/auth/session`
- **WHEN** the page is shown
- **THEN** the script sees no Co-Lite cookies and its call carries no Co-Lite session
### Requirement: Custom HTML Frame Addresses
The public frame address SHALL be `/p/<company>/<slug>/frame/<block index>` and SHALL answer only for an HTML block of a published page; every other request SHALL get the same not-found response. The preview frame address SHALL be `/pages/<id>/preview/frame/<block index>` and SHALL require a signed-in user with `BO_PAGES` who may see that page.
#### Scenario: No frame for a draft, a missing block or a non-HTML block
- **WHEN** a visitor loads the frame address of a draft page, of block 7 of a page with 3 blocks, or of a FORM block
- **THEN** each answers with the same not-found response
#### Scenario: Staff preview of a draft frame
- **GIVEN** a draft page with an HTML block
- **WHEN** a signed-in user with `BO_PAGES` of that page's company opens the preview
- **THEN** the frame shows the draft HTML, sealed as on the public page
- **AND** the same address without a session sends the browser to sign in
### Requirement: Custom HTML Frame Height
The frame SHALL grow to fit its content, between 100 and 20000 pixels, using height reports sent by that frame only. Before the first report it SHALL be 600 pixels tall.
#### Scenario: A tall paste grows the frame
- **GIVEN** a published HTML block whose content is 3000 pixels tall
- **WHEN** a visitor opens the page
- **THEN** the frame is 3000 pixels tall and shows no inner scroll bar
#### Scenario: Another frame cannot resize it
- **WHEN** a different window posts a height report to the page
- **THEN** the frame's height does not change
### Requirement: The Custom HTML Block In The Editor
The editor SHALL offer "Add Custom HTML", which adds an HTML block with a monospace text box, a 200000-character counter and a note that forms inside the pasted HTML do not send and the sign-up form block collects leads. The editor SHALL also offer a "hide page header" switch for the page.
#### Scenario: Adding a Custom HTML block
- **WHEN** staff add a Custom HTML block and paste HTML into it
- **THEN** the block shows the pasted HTML, the character count and the note about forms
#### Scenario: Hiding the header
- **WHEN** staff turn on "hide page header" and save
- **THEN** reading the page returns "hide header" on
### Requirement: Hide Page Header
When a page's "hide header" flag is on, its public page and its preview SHALL NOT show the company header or the page title, and SHALL still use the page title in the browser title and the page metadata.
#### Scenario: Header hidden
- **GIVEN** INS page `hotel-technology` has "hide header" on
- **WHEN** a visitor opens it
- **THEN** no company logo bar or page title heading shows above the first block
- **AND** the browser title is still the page title
@@ -0,0 +1,5 @@
-- Co-Lite change add-custom-html-block: a page option that hides the company header and the page title.
-- Target: `service-counter`. Additive only. Run once, after add-landing-pages 01.
SET NAMES utf8mb4;
USE `service-counter`;
ALTER TABLE `cms_page` ADD COLUMN `hide_header` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Hide the company header and the page title on the public page' AFTER `status`;
@@ -0,0 +1,11 @@
-- The labels added by add-custom-html-block, cut from the output of `npm run i18n:sql`. Run it only in an environment that already ran add-zh-cn-messages/sql/03-zh-cn-messages.sql; otherwise run that 03 file, which includes these labels.
SET NAMES utf8mb4;
USE `service-system`;
INSERT INTO message (code, content, area) SELECT 'PagesBlockHtml', JSON_OBJECT('en_US', 'Custom HTML', 'zh_CN', '自定义 HTML'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBlockHtml') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '自定义 HTML') WHERE LOWER(code) = LOWER('PagesBlockHtml') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesHtml', JSON_OBJECT('en_US', 'HTML', 'zh_CN', 'HTML'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHtml') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', 'HTML') WHERE LOWER(code) = LOWER('PagesHtml') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesHtmlHint', JSON_OBJECT('en_US', 'Forms inside the pasted HTML don''t send. Add a Sign-up form block to collect leads.', 'zh_CN', '粘贴的 HTML 中的表单不会发送。请添加报名表单区块来收集线索。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHtmlHint') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '粘贴的 HTML 中的表单不会发送。请添加报名表单区块来收集线索。') WHERE LOWER(code) = LOWER('PagesHtmlHint') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesHideHeader', JSON_OBJECT('en_US', 'Hide page header', 'zh_CN', '隐藏页面顶栏'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHideHeader') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '隐藏页面顶栏') WHERE LOWER(code) = LOWER('PagesHideHeader') AND area = 'A';
@@ -0,0 +1,6 @@
-- Co-Lite change add-custom-html-block: rollback. Pages with HTML blocks must be edited or deleted first,
-- because the previous release refuses the HTML block type when such a page is saved.
USE `service-counter`;
ALTER TABLE `cms_page` DROP COLUMN `hide_header`;
USE `service-system`;
DELETE FROM message WHERE code IN ('PagesBlockHtml', 'PagesHtml', 'PagesHtmlHint', 'PagesHideHeader') AND area = 'A';
@@ -0,0 +1,39 @@
# Tasks: add-custom-html-block
Design: `design.md` and `docs/superpowers/specs/2026-12-02-custom-html-block-design.md`. Every task is TDD. Work is serial in the main session, with a self-review per task.
## 1. Data and services
- [x] 1.1 SQL: `sql/01-hide-header.sql` (`cms_page.hide_header`), `sql/99-rollback.sql`; mirror 01 into `local/seed/`.
- [x] 1.2 services-counter:
- the `HTML` block type: required, at most 200,000 characters, no script check;
- `hideHeader` on the page model and DTO.
- Verify: `mvn -T 1C -B -pl solvway-services-counter -am verify`
- [x] 1.3 mobile-api: `hideHeader` on `AdminPageRequest` and in the public page response.
- Verify: `mvn -T 1C -B -pl solvway-mobile-api -am verify`
## 2. Portal
- [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.
- [x] 2.2 `CmsBlocks`:
- the sandboxed iframe with height messages from its own frame only;
- `hideHeader` hides the header and the title.
- [x] 2.3 Editor:
- "Add Custom HTML", with a monospace text box, a counter and the forms note;
- the "Hide page header" switch;
- field errors at the HTML field.
- [x] 2.4 Labels in `defaultMessages.ts` with Chinese in `zh_CN.seed.json`, then `npm run i18n:sql`. `sql/02-html-block-labels.sql` holds only the new labels.
- Verify (2.1 to 2.4): `cd solvway-admin-portal && npx vitest run; echo VITEST=$? && npx tsc --noEmit && npm run lint`
## 3. Release
- [x] 3.1 `docs/deployment.md`: the SQL rows and the frame routes. A Traefik or proxy layer must not add a CSP that overrides the frame's own policy.
- [x] 3.2 Live Playwright check on the local stack, at 1280 and 360 px:
- paste the INS proof-of-concept HTML into the INS page, with "hide page header" on and the sign-up form below it;
- it looks like the PoC signed out;
- opening the frame address directly shows no Co-Lite cookies to the frame's script;
- a draft frame is not found for visitors and previews for staff;
- an over-limit paste is refused at its field.
- [x] 3.3 Whole-branch self-review (security: the sandbox headers, the middleware skip and the message handler), then the PR to main and the merge.
@@ -19,6 +19,7 @@ const INLINE: Record<string, string[]> = {
IMAGE_TEXT: ["imageId", "imagePosition", "heading", "html", "buttonLabel", "buttonUrl"],
FAQ: ["heading", "items"],
FORM: ["heading", "eventUuid"],
HTML: ["html"],
};
const LISTED = /^items\[\d+\]\.(question|answer)$/;
const SELECT = "flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm disabled:cursor-not-allowed disabled:opacity-50";
@@ -169,6 +170,15 @@ export function BlockFields(props: {
</>
)}
{block.type === "HTML" && (
<Field id={fid("html")} label={t("PagesHtml")} error={errors.html}>
<Textarea id={fid("html")} rows={12} spellCheck={false} className="font-mono text-xs" value={block.html ?? ""} disabled={saving}
aria-invalid={!!errors.html} onChange={(e) => set({ html: e.target.value })} />
<p className="tabular text-xs text-muted-foreground">{`${(block.html ?? "").length}/200000`}</p>
<p className="text-xs text-muted-foreground">{t("PagesHtmlHint")}</p>
</Field>
)}
{block.type === "FORM" && (
<>
{text("heading", "PagesHeading")}
@@ -0,0 +1,50 @@
import { act, render, screen } from "@testing-library/react";
import { describe, it, expect } from "vitest";
import { LandingPage, type PublicBlock } from "./CmsBlocks";
import { FRAME_SANDBOX } from "@/app/lib/frameHtml";
// add-custom-html-block: an HTML block is a sealed frame sized by its own reports; "hide header" drops the header.
const company = { code: "INS", name: "INS Sdn Bhd", logoImageId: 4, accentColor: null };
const page = (blocks: PublicBlock[], hideHeader = false) => ({ slug: "hotel", title: "Hotel day", hideHeader, blocks });
const HTML: PublicBlock = { type: "HTML", html: "<h1>Designed</h1><script>x()</script>" };
const frame = () => document.querySelector("iframe") as HTMLIFrameElement;
describe("LandingPage: Custom HTML", () => {
it("shows an HTML block as a sealed frame from its own address, never inline", () => {
render(<LandingPage company={company} page={page([{ type: "FAQ", items: [{ question: "Q", answer: "A" }] }, HTML])} />);
expect(frame()).toHaveAttribute("src", "/p/INS/hotel/frame/1");
expect(frame()).toHaveAttribute("sandbox", FRAME_SANDBOX);
expect(frame()).toHaveAttribute("title", "Hotel day");
expect(frame().style.height).toBe("600px");
expect(screen.queryByText("Designed")).not.toBeInTheDocument();
expect(document.querySelector("script")).toBeNull();
});
it("uses the preview's frame address when given", () => {
render(<LandingPage company={company} page={page([HTML])} frameBase="/pages/5/preview/frame" preview />);
expect(frame()).toHaveAttribute("src", "/pages/5/preview/frame/0");
});
it("grows to its frame's reported height and ignores other windows", () => {
render(<LandingPage company={company} page={page([HTML])} />);
act(() => { window.dispatchEvent(new MessageEvent("message", { data: { type: "colite-frame-height", height: 2400 }, source: window })); });
expect(frame().style.height).toBe("600px");
act(() => { window.dispatchEvent(new MessageEvent("message", { data: { type: "colite-frame-height", height: 2400 }, source: frame().contentWindow })); });
expect(frame().style.height).toBe("2400px");
});
it("hides the company header and shows the title to screen readers only when the page says so", () => {
render(<LandingPage company={company} page={page([HTML], true)} />);
expect(screen.queryByRole("img", { name: "INS Sdn Bhd" })).not.toBeInTheDocument();
expect(document.querySelector("header")).toBeNull();
expect(screen.getByRole("heading", { level: 1, name: "Hotel day" })).toHaveClass("sr-only");
});
it("starts a header-less page flush at the top: the hidden title takes no part in block spacing", () => {
render(<LandingPage company={company} page={page([HTML], true)} />);
const title = screen.getByRole("heading", { level: 1, name: "Hotel day" });
expect(title.parentElement!.className).not.toMatch(/space-y/);
expect(frame().parentElement!.className).toMatch(/space-y/);
});
});
@@ -3,9 +3,11 @@ import { contrastText, imageSrc, isSafeLink, type CmsBlock } from "@/app/lib/cms
import type { RegistrationInfo } from "@/app/lib/services/publicRegistration";
import { SafeHtml } from "./SafeHtml";
import { LandingForm } from "./LandingForm";
import { HtmlFrame } from "./HtmlFrame";
// Landing-page blocks, ported from babyboo's CmsBlocks minus the product blocks. HTML only goes through SafeHtml;
// images are this company's uploads; buttons render only for a safe link, checked again here.
// images are this company's uploads; buttons render only for a safe link, checked again here. A Custom HTML block is
// never rendered here: it is a sealed frame loaded from its own address (add-custom-html-block).
export type PublicBlock = CmsBlock & { form?: RegistrationInfo; closed?: boolean };
@@ -86,20 +88,28 @@ function Block({ block, index, company, slug, preview }: { block: PublicBlock; i
}
}
/** A whole landing page: the company header (logo, accent), the title as the only h1, then the blocks. */
export function LandingPage({ company, page, banner, preview }: {
const WIDTH = "mx-auto w-full max-w-5xl px-4";
/**
* A whole landing page: the company header (logo, accent), the title as the only h1, then the blocks. Custom HTML
* blocks run full width; with hideHeader the header goes and the title is for screen readers only.
*/
export function LandingPage({ company, page, banner, preview, frameBase }: {
company: Branding;
page: { slug: string; title: string; blocks: PublicBlock[] };
page: { slug: string; title: string; hideHeader?: boolean; blocks: PublicBlock[] };
banner?: ReactNode;
/** The editor's draft preview: forms show a note instead of taking sign-ups. */
preview?: boolean;
/** Where block frames load from; the public page's frame address by default. */
frameBase?: string;
}) {
const frames = frameBase ?? `/p/${encodeURIComponent(company.code)}/${encodeURIComponent(page.slug)}/frame`;
const accent = company.accentColor && /^#[0-9A-Fa-f]{6}$/.test(company.accentColor) ? company.accentColor : null;
const style = accent ? ({ "--primary": accent, "--primary-foreground": contrastText(accent), "--ring": accent } as CSSProperties) : undefined;
return (
<div style={style} className="min-h-svh bg-background">
{banner}
<header className="border-b bg-card">
{page.hideHeader ? null : <header className="border-b bg-card">
<div className="mx-auto flex max-w-5xl items-center gap-3 px-4 py-3">
{company.logoImageId ? (
// eslint-disable-next-line @next/next/no-img-element -- the company's uploaded logo
@@ -108,10 +118,14 @@ export function LandingPage({ company, page, banner, preview }: {
<span className="text-lg font-semibold">{company.name}</span>
)}
</div>
</header>
<main className="mx-auto max-w-5xl space-y-10 px-4 py-8">
<h1 className="text-3xl font-semibold sm:text-4xl">{page.title}</h1>
{page.blocks.map((block, i) => <Block key={i} block={block} index={i} company={company.code} slug={page.slug} preview={preview} />)}
</header>}
<main className={page.hideHeader ? "pb-8" : "py-8"}>
<h1 className={page.hideHeader ? "sr-only" : `${WIDTH} mb-10 text-3xl font-semibold sm:text-4xl`}>{page.title}</h1>
<div className="space-y-10">
{page.blocks.map((block, i) => block.type === "HTML"
? <HtmlFrame key={i} src={`${frames}/${i}`} title={page.title} />
: <div key={i} className={WIDTH}><Block block={block} index={i} company={company.code} slug={page.slug} preview={preview} /></div>)}
</div>
</main>
</div>
);
@@ -0,0 +1,19 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { FRAME_SANDBOX, nextFrameHeight, START_HEIGHT, type FrameHeight } from "@/app/lib/frameHtml";
/** A Custom HTML block: the sealed frame, sized by height reports from that frame's own window only. */
export function HtmlFrame({ src, title }: { src: string; title: string }) {
const ref = useRef<HTMLIFrameElement>(null);
const [size, setSize] = useState<FrameHeight>({ height: START_HEIGHT, steps: [] });
useEffect(() => {
const onMessage = (e: MessageEvent) => {
if (!ref.current || e.source !== ref.current.contentWindow) return;
setSize((s) => nextFrameHeight(s, e.data));
};
window.addEventListener("message", onMessage);
return () => window.removeEventListener("message", onMessage);
}, []);
return <iframe ref={ref} src={src} title={title} sandbox={FRAME_SANDBOX} loading="lazy" className="block w-full border-0" style={{ height: `${size.height}px` }} />;
}
@@ -0,0 +1,67 @@
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { ApiError } from "@/app/lib/clientApi";
// add-custom-html-block: the editor's Custom HTML block and "Hide page header" switch.
const mocks = vi.hoisted(() => ({
getPage: vi.fn(), savePage: vi.fn(), deletePage: vi.fn(), uploadPageImage: vi.fn(),
listAdminEvents: vi.fn(), useAdminAuth: vi.fn(), useCompanyScope: vi.fn(),
}));
vi.mock("@/app/lib/services/adminPages", () => ({ getPage: mocks.getPage, savePage: mocks.savePage, deletePage: mocks.deletePage, uploadPageImage: mocks.uploadPageImage }));
vi.mock("@/app/lib/services/adminEvents", () => ({ listAdminEvents: mocks.listAdminEvents }));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
vi.mock("@/app/lib/CompanyScope", () => ({ useCompanyScope: mocks.useCompanyScope }));
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
import { memoryRouter } from "@/test/memoryRouter";
import { PageEditor } from "./PageEditor";
const stored = {
id: 5, companyId: 2, slug: "hotel", title: "Hotel", metaDescription: null, status: "PUBLISHED" as const, hideHeader: true,
blocks: [{ type: "HTML" as const, html: "<h1>Designed</h1>" }],
};
beforeEach(() => {
vi.clearAllMocks();
memoryRouter.reset("/pages/5");
mocks.useAdminAuth.mockReturnValue({ isSuper: false, companyCode: "INS" });
mocks.useCompanyScope.mockReturnValue({ companyId: undefined, companies: [{ id: 2, code: "INS", name: "INS", status: "A" }], codeOf: (id?: number) => (id === 2 ? "INS" : "") });
mocks.listAdminEvents.mockResolvedValue({ items: [], total: 0 });
mocks.getPage.mockResolvedValue(stored);
mocks.savePage.mockImplementation(async (id: number | undefined, body: object) => ({ ...stored, ...body, id: id ?? 7 }));
});
describe("PageEditor: Custom HTML", () => {
it("loads the HTML and the hide-header option, and saves both", async () => {
const user = userEvent.setup();
render(<PageEditor pageId={5} />);
const box = await screen.findByLabelText("HTML");
expect(box).toHaveValue("<h1>Designed</h1>");
expect(box).toHaveClass("font-mono");
expect(screen.getByText("17/200000")).toBeInTheDocument();
expect(screen.getByText(/Forms inside the pasted HTML don't send/)).toBeInTheDocument();
const toggle = screen.getByRole("switch", { name: "Hide page header" });
expect(toggle).toBeChecked();
await user.click(toggle);
await user.click(screen.getByRole("button", { name: "Add Custom HTML" }));
await user.type(screen.getAllByLabelText("HTML")[1], "<p>x</p>");
await user.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(mocks.savePage).toHaveBeenCalled());
const body = mocks.savePage.mock.calls[0][1];
expect(body.hideHeader).toBe(false);
expect(body.blocks).toEqual([{ type: "HTML", html: "<h1>Designed</h1>" }, { type: "HTML", html: "<p>x</p>" }]);
});
it("shows a refusal of the HTML at its field", async () => {
mocks.savePage.mockRejectedValue(new ApiError("x", 422, { code: "PagesTooLong", details: { field: "blocks[0].html" } }));
const user = userEvent.setup();
render(<PageEditor pageId={5} />);
const box = await screen.findByLabelText("HTML");
await user.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByText("Too long.")).toBeInTheDocument();
expect(box.closest("div")).toHaveTextContent("Too long.");
expect(box).toHaveAttribute("aria-invalid", "true");
});
});
@@ -8,6 +8,7 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/ca
import { ConfirmDialog } from "@/app/components/ui/confirm-dialog";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { Switch } from "@/app/components/ui/switch";
import { Textarea } from "@/app/components/ui/textarea";
import { ErrorState } from "@/app/components/ui/states";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/app/components/ui/select";
@@ -76,7 +77,7 @@ export function PageEditor({ pageId }: { pageId?: number }) {
getPage(pageId)
.then((p) => {
if (cancelled) return;
setDraft({ id: p.id, companyId: p.companyId, slug: p.slug, slugTouched: true, title: p.title, metaDescription: p.metaDescription ?? "", status: p.status, blocks: [] });
setDraft({ id: p.id, companyId: p.companyId, slug: p.slug, slugTouched: true, title: p.title, metaDescription: p.metaDescription ?? "", status: p.status, hideHeader: !!p.hideHeader, blocks: [] });
setRows(toRows(p.blocks ?? []));
setSaved({ slug: p.slug, status: p.status });
})
@@ -294,6 +295,10 @@ export function PageEditor({ pageId }: { pageId?: number }) {
</label>
))}
<FieldError message={errors.status} />
<div className="flex items-center gap-2 pt-2 text-sm">
<Switch id="page-hide-header" checked={draft.hideHeader} disabled={saving} onCheckedChange={(on) => patch({ hideHeader: on })} />
<Label htmlFor="page-hide-header">{t("PagesHideHeader")}</Label>
</div>
</CardContent>
</Card>
</div>
@@ -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);
});
});
+3 -2
View File
@@ -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;
+10 -3
View File
@@ -1,9 +1,9 @@
// Landing-page blocks and the editor's pure helpers (add-landing-pages), ported from babyboo's cmsPages.ts
// minus the product blocks. Images are page_image ids, served at /api/public/page-images/<id>.
export type BlockType = "HERO" | "RICH_TEXT" | "IMAGE_TEXT" | "FAQ" | "FORM";
export type BlockType = "HERO" | "RICH_TEXT" | "IMAGE_TEXT" | "FAQ" | "FORM" | "HTML";
export const BLOCK_TYPES: BlockType[] = ["HERO", "RICH_TEXT", "IMAGE_TEXT", "FAQ", "FORM"];
export const BLOCK_TYPES: BlockType[] = ["HERO", "RICH_TEXT", "IMAGE_TEXT", "FAQ", "FORM", "HTML"];
export const BLOCK_LABELS: Record<BlockType, string> = {
HERO: "PagesBlockHero",
@@ -11,6 +11,7 @@ export const BLOCK_LABELS: Record<BlockType, string> = {
IMAGE_TEXT: "PagesBlockImageText",
FAQ: "PagesBlockFaq",
FORM: "PagesBlockForm",
HTML: "PagesBlockHtml",
};
export interface CmsFaqItem {
@@ -41,6 +42,7 @@ export interface CmsPage {
title: string;
metaDescription: string | null;
status: PageStatus;
hideHeader?: boolean;
blocks: CmsBlock[];
updatedAt?: string | null;
}
@@ -53,6 +55,8 @@ export interface CmsPageDraft {
title: string;
metaDescription: string;
status: PageStatus;
/** Hide the company header and the page title (add-custom-html-block). */
hideHeader: boolean;
blocks: CmsBlock[];
}
@@ -61,7 +65,7 @@ export const imageSrc = (id: number) => `/api/public/page-images/${id}`;
export const pageAddress = (companyCode: string, slug: string) => `/p/${companyCode}/${slug}`;
export function emptyPage(): CmsPageDraft {
return { slug: "", slugTouched: false, title: "", metaDescription: "", status: "DRAFT", blocks: [] };
return { slug: "", slugTouched: false, title: "", metaDescription: "", status: "DRAFT", hideHeader: false, blocks: [] };
}
export function emptyBlock(type: BlockType): CmsBlock {
@@ -72,6 +76,8 @@ export function emptyBlock(type: BlockType): CmsBlock {
return { type, imageId: null, heading: "", html: "", imagePosition: "LEFT", buttonLabel: "", buttonUrl: "" };
case "FORM":
return { type, heading: "", eventUuid: null };
case "HTML":
return { type, html: "" };
default:
return { type };
}
@@ -96,6 +102,7 @@ export function pageBody(draft: CmsPageDraft) {
title: draft.title.trim(),
metaDescription: draft.metaDescription.trim() || null,
status: draft.status,
hideHeader: draft.hideHeader,
blocks: draft.blocks.map((b) => {
const out: Record<string, unknown> = { type: b.type };
for (const [key, val] of Object.entries(b)) {
@@ -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);
});
});
+67
View File
@@ -0,0 +1,67 @@
// 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";
/** The frame document's own policy. next.config sends it too: config headers replace a route's header of the same name. */
export const FRAME_CSP = `sandbox ${FRAME_SANDBOX}; frame-ancestors 'self'`;
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": FRAME_CSP,
"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);
});
});
@@ -756,6 +756,10 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
PagesBlockImageText: "Image with text",
PagesBlockFaq: "FAQ",
PagesBlockForm: "Sign-up form",
PagesBlockHtml: "Custom HTML",
PagesHtml: "HTML",
PagesHtmlHint: "Forms inside the pasted HTML don't send. Add a Sign-up form block to collect leads.",
PagesHideHeader: "Hide page header",
PagesMoveUp: "Move up",
PagesMoveDown: "Move down",
PagesRemoveBlock: "Remove block",
@@ -763,6 +763,10 @@
"PagesChooseEvent": "选择活动",
"PagesUnavailableEvent": "活动已不可用",
"PagesFormEventHint": "报名会成为此活动的线索。一般咨询请选择长期的咨询活动。",
"PagesBlockHtml": "自定义 HTML",
"PagesHtml": "HTML",
"PagesHtmlHint": "粘贴的 HTML 中的表单不会发送。请添加报名表单区块来收集线索。",
"PagesHideHeader": "隐藏页面顶栏",
"PagesFormClosed": "报名已截止。",
"PagesFormPreview": "发布后的网页会在此显示报名表。",
"PagesToolbar": "格式",
+5 -1
View File
@@ -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 {
@@ -2,6 +2,7 @@ import { describe, it, expect } from "vitest";
import fs from "node:fs";
import path from "node:path";
import ts from "typescript";
import { FRAME_SANDBOX } from "@/app/lib/frameHtml";
// Spec (admin-portal-markup-safety), security finding F09: the admin portal never injects HTML into its own origin.
// Data HTML goes into <iframe sandbox="" srcDoc>. Allow-listing a file here is a security
@@ -26,6 +27,13 @@ const SINK_ALLOWED: Record<string, Sink[]> = {
"components/pages/SafeHtml.tsx": ["dangerouslySetInnerHTML"],
};
// add-custom-html-block: a Custom HTML block's frame loads its own address, whose response carries a `sandbox` CSP
// (opaque origin), and may run scripts but never as this origin: FRAME_SANDBOX holds no allow-same-origin.
// Only this file may give an iframe that one non-empty sandbox, and only as the named constant.
const SANDBOX_ALLOWED: Record<string, string> = {
"components/pages/HtmlFrame.tsx": "FRAME_SANDBOX",
};
function sourceFiles(dir: string, out: string[] = []): string[] {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
if (entry.name === "node_modules" || entry.name === ".next") continue;
@@ -58,7 +66,9 @@ function iframeProblems(fileName: string, src: string): string[] {
(p): p is ts.JsxAttribute => ts.isJsxAttribute(p) && p.name.getText(sf) === "sandbox",
);
const value = sandbox?.initializer;
if (!value || !ts.isStringLiteral(value) || value.text !== "") {
const allowed = SANDBOX_ALLOWED[fileName];
const named = !!allowed && !!value && ts.isJsxExpression(value) && value.expression?.getText(sf) === allowed;
if (!named && (!value || !ts.isStringLiteral(value) || value.text !== "")) {
problems.push(`${fileName}:${line} iframe without sandbox=""`);
}
}
@@ -106,6 +116,13 @@ describe("admin portal never injects HTML into its own origin", () => {
}
});
it("lets the Custom HTML frame run scripts, never as this origin, submit forms or navigate the page", () => {
const grants = FRAME_SANDBOX.split(/\s+/);
for (const g of ["allow-same-origin", "allow-forms", "allow-top-navigation", "allow-top-navigation-by-user-activation", "allow-modals"]) {
expect(grants).not.toContain(g);
}
});
it("gives every iframe a literal empty sandbox", () => {
const problems = files.flatMap((f) => iframeProblems(f.rel, f.src));
expect(problems).toEqual([]);
@@ -127,6 +144,13 @@ describe("iframe checker", () => {
expect(check(`<iframe sandbox="" {...props} srcDoc={html} />`)).toHaveLength(1);
});
it("accepts the named Custom HTML sandbox only in its allow-listed file", () => {
const src = `export const X = () => <iframe title="t" sandbox={FRAME_SANDBOX} src={u} />;`;
expect(iframeProblems("components/pages/HtmlFrame.tsx", src)).toEqual([]);
expect(iframeProblems("fixture.tsx", src)).toHaveLength(1);
expect(iframeProblems("components/pages/HtmlFrame.tsx", src.replace("FRAME_SANDBOX", "mode"))).toHaveLength(1);
});
it("rejects a non-empty or computed sandbox", () => {
expect(check(`<iframe sandbox="allow-scripts" srcDoc={html} />`)).toHaveLength(1);
expect(check(`<iframe sandbox={mode} srcDoc={html} />`)).toHaveLength(1);
@@ -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 });
}
@@ -10,7 +10,7 @@ type Props = { params: Promise<{ company: string; slug: string }> };
interface PublicPage {
company: Branding;
page: { slug: string; title: string; metaDescription?: string | null; blocks: PublicBlock[] };
page: { slug: string; title: string; metaDescription?: string | null; hideHeader?: boolean; blocks: PublicBlock[] };
}
const load = cache(async (company: string, slug: string): Promise<PublicPage> => {
@@ -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 });
}
@@ -12,6 +12,7 @@ type Props = { params: Promise<{ id: string }> };
interface AdminPage {
slug: string;
title: string;
hideHeader?: boolean;
blocks: PublicBlock[];
company?: Branding;
}
@@ -27,7 +28,7 @@ export default async function PagePreview({ params }: Props) {
const banner = <p role="status" className="bg-warning/15 px-4 py-2 text-center text-sm font-medium">{t("PagesPreviewBanner")}</p>;
return (
<RequireModule pathname="/pages">
<LandingPage company={page.company ?? { code: "", name: "" }} page={page} banner={banner} preview />
<LandingPage company={page.company ?? { code: "", name: "" }} page={page} banner={banner} preview frameBase={`/pages/${encodeURIComponent(id)}/preview/frame`} />
</RequireModule>
);
}
@@ -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");
}
});
});
+3 -1
View File
@@ -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);
}
@@ -0,0 +1,21 @@
import { describe, it, expect } from "vitest";
import nextConfig from "./next.config";
import { FRAME_CSP } from "./app/lib/frameHtml";
// add-custom-html-block: config headers replace a route's own header of the same name, so the baseline
// Content-Security-Policy would strip the frame's sandbox. A later rule for the frame paths puts it back
// (Next.js: the last rule setting a key wins).
describe("Custom HTML frame headers", () => {
it("sends the sandbox policy on both frame paths, after the baseline rule", async () => {
const rules = await nextConfig.headers!();
const baseline = rules.findIndex((r) => r.source === "/:path*");
for (const source of ["/p/:company/:slug/frame/:block", "/pages/:id/preview/frame/:block"]) {
const at = rules.findIndex((r) => r.source === source);
expect(at, source).toBeGreaterThan(baseline);
const sent = Object.fromEntries(rules[at].headers.map((h) => [h.key, h.value]));
expect(sent["Content-Security-Policy"]).toBe(FRAME_CSP);
expect(sent["Referrer-Policy"]).toBe("no-referrer");
}
expect(FRAME_CSP).toMatch(/^sandbox allow-scripts allow-popups allow-popups-to-escape-sandbox; frame-ancestors 'self'/);
});
});
+10 -1
View File
@@ -1,5 +1,6 @@
import type { NextConfig } from "next";
import { SECURITY_HEADERS } from "./app/lib/securityHeaders";
import { FRAME_CSP } from "./app/lib/frameHtml";
// 2026-10-07: CI run 5545 (#731 CMS forms) failed in Docker build (a runner storage fault while run
// 5544 built at the same time), so nothing from #731 rolled out. Only a push that changes this
@@ -9,7 +10,15 @@ const nextConfig: NextConfig = {
// harden-portal-requests (F30): no X-Powered-By, baseline security headers everywhere.
poweredByHeader: false,
async headers() {
return [{ source: "/:path*", headers: [...SECURITY_HEADERS] }];
// add-custom-html-block: these headers replace a route's own, so the Custom HTML frame paths get their sandbox
// policy back from a later rule (the last rule setting a key wins). Without it, a frame address opened directly
// would run pasted scripts as this origin.
const frame = [{ key: "Content-Security-Policy", value: FRAME_CSP }, { key: "Referrer-Policy", value: "no-referrer" }];
return [
{ source: "/:path*", headers: [...SECURITY_HEADERS] },
{ source: "/p/:company/:slug/frame/:block", headers: frame },
{ source: "/pages/:id/preview/frame/:block", headers: frame },
];
},
reactStrictMode: true,
// Stop `next dev` writing AGENTS.md/CLAUDE.md into the repo; agent instructions live in the root CLAUDE.md.
@@ -5,4 +5,11 @@ import java.util.Map;
/** A landing page as the editor saves it. Blocks pass through to the counter, which validates them. companyId counts only on create. */
public record AdminPageRequest(Long companyId, String slug, String title, String metaDescription, String status,
List<Map<String, Object>> blocks) {}
boolean hideHeader, List<Map<String, Object>> blocks) {
/** A page that shows its header (the default). */
public AdminPageRequest(Long companyId, String slug, String title, String metaDescription, String status,
List<Map<String, Object>> blocks) {
this(companyId, slug, title, metaDescription, status, false, blocks);
}
}
@@ -93,6 +93,7 @@ public class AdminPageService {
page.put("title", r.title());
page.put("metaDescription", r.metaDescription());
page.put("status", r.status());
page.put("hideHeader", r.hideHeader());
page.put("blocks", r.blocks() == null ? List.of() : r.blocks());
Map<String, Object> body = new LinkedHashMap<>();
body.put("page", page);
@@ -59,6 +59,7 @@ public class PublicPageService {
page.put("slug", f.page().get("slug"));
page.put("title", f.page().get("title"));
page.put("metaDescription", f.page().get("metaDescription"));
page.put("hideHeader", Boolean.TRUE.equals(f.page().get("hideHeader")));
page.put("blocks", blocks);
return Map.of("company", f.company(), "page", page);
}
@@ -115,6 +115,17 @@ class AdminPageServiceTest {
assertThat((Map<String, Object>) sent.get("page")).containsEntry("companyId", 2L).containsEntry("slug", "hotel").containsEntry("id", null);
}
@Test
void theHideHeaderOptionIsSentToTheCounter() {
caller(2L, false);
service.create(new AdminPageRequest(null, "designed", "Designed", null, "DRAFT", true, List.of(Map.<String, Object>of("type", "HTML", "html", "<script>x()</script>"))));
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture());
Map<String, Object> page = (Map<String, Object>) ((Map<String, Object>) body.getValue()).get("page");
assertThat(page).containsEntry("hideHeader", true);
assertThat((List<Map<String, Object>>) page.get("blocks")).first().isEqualTo(Map.of("type", "HTML", "html", "<script>x()</script>"));
}
@Test
void updateKeepsTheIdAndStoredCompany() {
caller(2L, false);
@@ -123,6 +123,16 @@ class PublicPageServiceTest {
assertThat(blocks.get(1)).doesNotContainKey("closed");
}
@Test
void thePageCarriesItsHideHeaderOptionDefaultingToOff() {
assertThat((Map<String, Object>) service.page("INS", "hotel-technology").get("page")).containsEntry("hideHeader", false);
Map<String, Object> designed = page();
designed.put("hideHeader", true);
when(rest.getForEntity(eq(PUBLISHED), any(ParameterizedTypeReference.class), eq(COMPANY), eq("hotel-technology")))
.thenReturn(ResponseEntity.ok(designed));
assertThat((Map<String, Object>) service.page("INS", "hotel-technology").get("page")).containsEntry("hideHeader", true);
}
@Test
void aFormWhoseEventEndedIsClosedButThePageStillShows() {
stubEvent(LocalDateTime.of(2027, 1, 15, 23, 59));
@@ -5,4 +5,11 @@ import java.util.List;
/** A landing page as the API sends and receives it; blocks are omitted (null) in list rows. */
public record CmsPageDto(Long id, Long companyId, String slug, String title, String metaDescription, String status,
List<CmsBlock> blocks, LocalDateTime updatedAt) {}
boolean hideHeader, List<CmsBlock> blocks, LocalDateTime updatedAt) {
/** A page that shows its header (the default). */
public CmsPageDto(Long id, Long companyId, String slug, String title, String metaDescription, String status,
List<CmsBlock> blocks, LocalDateTime updatedAt) {
this(id, companyId, slug, title, metaDescription, status, false, blocks, updatedAt);
}
}
@@ -19,6 +19,7 @@ public class CmsPage {
private String title;
private String metaDescription;
private String status = "DRAFT";
private boolean hideHeader;
/** JSON array of blocks, replaced as a whole on every save. */
@Column(columnDefinition = "json")
private String blocks;
@@ -12,7 +12,8 @@ import java.util.regex.Pattern;
/**
* Landing-page block rules, ported from babyboo's CmsBlockValidator (specs/cms-pages) without the product blocks.
* Co-Lite changes: images are uploaded ids of the page's company, FORM points at an event of that company,
* buttons may also use mailto: and tel:, and HTML holding scripts is refused (the public page sanitises as well).
* buttons may also use mailto: and tel:, and rich-text HTML holding scripts is refused (the public page sanitises as well).
* The HTML block (custom HTML) is exempt from the script check: it is served only inside a sandboxed frame.
* Throws 422 on the first violation, with the reason "path|MessageCode".
*/
public final class CmsBlockValidator {
@@ -44,6 +45,11 @@ public final class CmsBlockValidator {
button(b, path);
}
case "RICH_TEXT" -> html(b.getHtml(), path + ".html");
case "HTML" -> {
// Custom HTML may hold scripts: it is only ever served in a sandboxed frame (add-custom-html-block).
required(b.getHtml(), path + ".html");
max(b.getHtml(), path + ".html", 200_000);
}
case "IMAGE_TEXT" -> {
image(b, path, ownImage);
max(b.getHeading(), path + ".heading", 120);
@@ -69,6 +69,7 @@ public class CmsPageService {
row.setTitle(dto.title().trim());
row.setMetaDescription(dto.metaDescription() == null || dto.metaDescription().isBlank() ? null : dto.metaDescription().trim());
row.setStatus(dto.status());
row.setHideHeader(dto.hideHeader());
row.setBlocks(write(dto.blocks() == null ? List.of() : dto.blocks()));
row.setUpdatedBy(user);
row.setUpdatedAt(LocalDateTime.now());
@@ -109,7 +110,7 @@ public class CmsPageService {
private CmsPageDto toDto(CmsPage p, boolean withBlocks) {
return new CmsPageDto(p.getId(), p.getCompanyId(), p.getSlug(), p.getTitle(), p.getMetaDescription(), p.getStatus(),
withBlocks ? read(p.getBlocks()) : null, p.getUpdatedAt());
p.isHideHeader(), withBlocks ? read(p.getBlocks()) : null, p.getUpdatedAt());
}
private String write(List<CmsBlock> blocks) {
@@ -150,4 +150,20 @@ class CmsBlockValidatorTest {
refused(List.of(noImage), "blocks[0].imageId", "PagesBadImage");
refused(List.of(form(901)), "blocks[0].eventUuid", "PagesBadEvent");
}
private static CmsBlock custom(String html) {
CmsBlock b = new CmsBlock();
b.setType("HTML");
b.setHtml(html);
return b;
}
@Test
void anHtmlBlockMayHoldScriptsButHasALimit() {
assertThatCode(() -> validate(List.of(custom("<style>h1{color:gold}</style><script>document.title = 'x'</script><h1 onclick=\"go()\">Hi</h1>"))))
.doesNotThrowAnyException();
assertThatCode(() -> validate(List.of(custom("x".repeat(200_000))))).doesNotThrowAnyException();
refused(List.of(custom("x".repeat(200_001))), "blocks[0].html", "PagesTooLong");
refused(List.of(custom(" ")), "blocks[0].html", "PagesRequired");
}
}
@@ -130,6 +130,22 @@ class CmsPageServiceTest {
refused(page(null, INS, "launch", List.of(hero)), HttpStatus.UNPROCESSABLE_ENTITY, "blocks[0].imageId|PagesBadImage");
}
@Test
void theHideHeaderOptionAndAnHtmlBlockReadBack() {
CmsBlock custom = new CmsBlock();
custom.setType("HTML");
custom.setHtml("<section><script>x()</script></section>");
CmsPageDto dto = new CmsPageDto(null, INS, "designed", "Designed", null, "DRAFT", true, List.of(custom), null);
service.save(dto, "staff1");
ArgumentCaptor<CmsPage> row = ArgumentCaptor.forClass(CmsPage.class);
verify(pages).saveAndFlush(row.capture());
when(pages.findById(77L)).thenReturn(Optional.of(row.getValue()));
CmsPageDto read = service.findById(77L);
assertThat(read.hideHeader()).isTrue();
assertThat(read.blocks().get(0).getHtml()).isEqualTo("<section><script>x()</script></section>");
}
@Test
void blocksReadBackInTheirSavedOrder() {
CmsBlock faq = new CmsBlock();