Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4251d395ad | ||
|
|
36dbb4c949 | ||
|
|
f13b2a592a | ||
|
|
cfc817082d | ||
|
|
6a0a6613c1 | ||
|
|
1ceefd7231 | ||
|
|
9a7b225827 | ||
|
|
dcad8cb650 | ||
|
|
34732ef2a5 | ||
|
|
53f3298ded | ||
|
|
1e09b652dc | ||
|
|
26b39283e6 | ||
|
|
4d291c6150 | ||
|
|
2c6a4dc8ce | ||
|
|
e70e1084d9 |
No files matched your search
+15
-11
@@ -129,27 +129,29 @@ Run both, in order, before the new images go live: the new services-counter read
|
||||
|
||||
| File | What it does |
|
||||
|---|---|
|
||||
| `openspec/changes/archive/<date>-add-whatsapp-inbox/sql/01-whatsapp-schema.sql` | Creates the schema `service-whatsapp` with the conversation, message, read-marker and template tables. DDL: run it with a user that may create databases and tables. |
|
||||
| `openspec/changes/archive/<date>-add-whatsapp-inbox/sql/02-whatsapp-modules.sql` | Adds the WhatsApp modules `BO_WHATSAPP` (the inbox) and `BO_WHATSAPP_ADMIN` (every chat of the company, assigning owners, template sync). No role gets them; super admins grant them under Roles. |
|
||||
| `openspec/changes/archive/2026-12-02-add-whatsapp-inbox/sql/01-whatsapp-schema.sql` | Creates the schema `service-whatsapp` with the conversation, message, read-marker and template tables. DDL: run it with a user that may create databases and tables. |
|
||||
| `openspec/changes/archive/2026-12-02-add-whatsapp-inbox/sql/02-whatsapp-modules.sql` | Adds the WhatsApp modules `BO_WHATSAPP` (the inbox) and `BO_WHATSAPP_ADMIN` (every chat of the company, assigning owners, template sync). No role gets them; super admins grant them under Roles. |
|
||||
|
||||
Run both before `service-whatsapp` starts. Give the services' database user the same rights on `service-whatsapp` as on the other schemas. `99-rollback.sql` in the same folder removes the modules and drops the schema with every stored chat.
|
||||
|
||||
| File | What it does |
|
||||
|---|---|
|
||||
| `openspec/changes/archive/<date>-add-zh-cn-messages/sql/01-locales.sql` | Creates `service-system`.`supported_locale` (the languages staff can pick: English and 简体中文 on; Malay, Traditional Chinese and Indonesian off) and `catalog_meta` (the label catalog version). DDL. |
|
||||
| `openspec/changes/archive/<date>-add-zh-cn-messages/sql/02-modules.sql` | Adds the back-office modules `BO_MESSAGES` (Translations) and `BO_LOCALES` (Languages) under System. No role gets them; super admins grant them under Roles. |
|
||||
| `openspec/changes/archive/<date>-add-zh-cn-messages/sql/03-zh-cn-messages.sql` | Loads the first-pass Chinese for every back-office label into `service-system`.`message`: inserts the labels that are missing, sets their Chinese, gives four rows (`LogIn`, `Member`, `Tree`, `Wallet`) the back office's English, and bumps the catalog version. Generated; run it once. |
|
||||
| `openspec/changes/archive/<date>-add-messages-colite-filter/sql/01-colite-filter-labels.sql` | Adds the "Co-Lite labels only" label. Run it only where the 03 file above already ran before this change; the regenerated 03 already includes it. |
|
||||
| `openspec/changes/archive/2026-12-02-add-zh-cn-messages/sql/01-locales.sql` | Creates `service-system`.`supported_locale` (the languages staff can pick: English and 简体中文 on; Malay, Traditional Chinese and Indonesian off) and `catalog_meta` (the label catalog version). DDL. |
|
||||
| `openspec/changes/archive/2026-12-02-add-zh-cn-messages/sql/02-modules.sql` | Adds the back-office modules `BO_MESSAGES` (Translations) and `BO_LOCALES` (Languages) under System. No role gets them; super admins grant them under Roles. |
|
||||
| `openspec/changes/archive/2026-12-02-add-zh-cn-messages/sql/03-zh-cn-messages.sql` | Loads the first-pass Chinese for every back-office label into `service-system`.`message`: inserts the labels that are missing, sets their Chinese, gives four rows (`LogIn`, `Member`, `Tree`, `Wallet`) the back office's English, and bumps the catalog version. Generated; run it once. |
|
||||
| `openspec/changes/archive/2026-12-02-add-messages-colite-filter/sql/01-colite-filter-labels.sql` | Adds the "Co-Lite labels only" label. Run it only where the 03 file above already ran before this change; the regenerated 03 already includes it. |
|
||||
|
||||
Run the three in order before the new services-system, gateway and mobile-api go live. `01` needs a user that may create tables. Run `03` once only: it overwrites the Chinese of every back-office label, so running it again after staff have edited translations undoes their edits. `99-rollback.sql` in the same folder drops the two tables and removes the modules; the Chinese stays in `message`, which the previous images never read.
|
||||
|
||||
| File | What it does |
|
||||
|---|---|
|
||||
| `openspec/changes/archive/<date>-add-landing-pages/sql/01-pages.sql` | Creates `service-counter`.`cms_page` (landing pages, blocks as JSON, slug unique per company) and `page_image` (uploaded images, at most 2 MB each). DDL. |
|
||||
| `openspec/changes/archive/<date>-add-landing-pages/sql/02-event-lead-web.sql` | Adds `page_path`, `utm_source`, `utm_medium` and `utm_campaign` to `event_lead`, for sign-ups from a landing page (source `WEB`). DDL. |
|
||||
| `openspec/changes/archive/<date>-add-landing-pages/sql/03-company-branding.sql` | Adds `logo_image_id` and `accent_color` to `service-system`.`company`. DDL. |
|
||||
| `openspec/changes/archive/<date>-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/<date>-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/archive/2026-12-02-add-landing-pages/sql/01-pages.sql` | Creates `service-counter`.`cms_page` (landing pages, blocks as JSON, slug unique per company) and `page_image` (uploaded images, at most 2 MB each). DDL. |
|
||||
| `openspec/changes/archive/2026-12-02-add-landing-pages/sql/02-event-lead-web.sql` | Adds `page_path`, `utm_source`, `utm_medium` and `utm_campaign` to `event_lead`, for sign-ups from a landing page (source `WEB`). DDL. |
|
||||
| `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.
|
||||
@@ -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`;
|
||||
@@ -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');
|
||||
|
||||
File renamed without changes.
@@ -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.
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+1
@@ -108,3 +108,4 @@ Verify commands:
|
||||
- the unread badge.
|
||||
- Earlier in 5.1: media, ticks and the 360 px layout. The staff-only view (Mine only, no owner select) is covered by tests only: no staff password was available, and staff passwords were not reset for it. The test rows were removed.
|
||||
- [ ] 6.3 The owner's manual click-every-button e2e on a production build covers the inbox too (record the result here).
|
||||
- Deferred by the owner on 2026-12-02: the WhatsApp business account cannot be linked yet, so the change is archived with this check open. Run it once the account is linked; any fix goes in a new change.
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-12-02
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -129,10 +129,15 @@ A table wider than its container SHALL show a fade on each edge where more colum
|
||||
|
||||
The sidebar SHALL show Dashboard first, then the labelled sections Events, Leads, Access and System, each with a fixed set and order of pages. A page not in any section SHALL appear in a final section without a label. A section SHALL be marked by a divider and a small muted label, with only the divider in the collapsed rail, and SHALL NOT show when it has no page the user may open. Every page SHALL have a distinct icon.
|
||||
|
||||
#### Scenario: WhatsApp inbox in the Leads section
|
||||
|
||||
- **WHEN** a user with `BO_WHATSAPP` and two unread conversations opens the portal
|
||||
- **THEN** the Leads section lists Leads, WhatsApp and Interests, with a badge showing 2
|
||||
|
||||
#### Scenario: Super admin sidebar
|
||||
|
||||
- **WHEN** a super admin opens the portal
|
||||
- **THEN** the sidebar shows Dashboard, then "Events" with Events and Event leads, "Leads" with Leads and Interests, "Access" with Users, Roles and Login security, and "System" with Companies, Emails and Audit log
|
||||
- **THEN** the sidebar shows Dashboard, then "Events" with Events, Event leads and Pages, "Leads" with Leads, WhatsApp and Interests, "Access" with Users, Roles and Login security, and "System" with Companies, Emails, Audit log, Translations and Languages
|
||||
|
||||
#### Scenario: Staff without admin pages
|
||||
|
||||
|
||||
@@ -70,7 +70,7 @@ On the event days, a registered guest's invite link SHALL show a "Check in" butt
|
||||
|
||||
### Requirement: Attendance at capture
|
||||
|
||||
Each event lead SHALL have an attended time. A staff capture, a walk-in code registration or a check-in-page capture made during the event days SHALL set it. A registration made before the event days SHALL NOT set it. Event leads that exist before this change SHALL count as not attended.
|
||||
Each event lead SHALL have an attended time. A staff capture, a walk-in code registration or a check-in-page capture made during the event days SHALL set it. A registration made before the event days SHALL NOT set it. A web page sign-up SHALL NOT set it, whenever it is made. Event leads that exist before this change SHALL count as not attended.
|
||||
|
||||
#### Scenario: Walk-in on the day
|
||||
|
||||
@@ -84,15 +84,27 @@ Each event lead SHALL have an attended time. A staff capture, a walk-in code reg
|
||||
- **WHEN** a visitor registers through the event's walk-in code
|
||||
- **THEN** the event lead is registered but not attended
|
||||
|
||||
#### Scenario: Web enquiry during a standing event
|
||||
|
||||
- **GIVEN** the running event `INS website enquiries`
|
||||
- **WHEN** a visitor submits the form on a landing page that points at it
|
||||
- **THEN** the event lead is registered but not attended
|
||||
|
||||
### Requirement: Attendance in staff screens
|
||||
|
||||
Users who can edit event leads SHALL tick or untick Attended. The event leads listing SHALL show an Attended column and filter, and each event lead's source (Staff, QR, Invite).
|
||||
Users who can edit event leads SHALL tick or untick Attended. The event leads listing SHALL show an Attended column and filter, and each event lead's source (Staff, QR, Invite, Web page).
|
||||
|
||||
#### Scenario: Staff untick
|
||||
|
||||
- **WHEN** staff untick Attended on an event lead linked to a guest
|
||||
- **THEN** the guest list shows that guest as Registered
|
||||
|
||||
#### Scenario: Web page source
|
||||
|
||||
- **GIVEN** an event lead created by a landing-page form
|
||||
- **WHEN** staff open the event leads listing
|
||||
- **THEN** its source shows "Web page"
|
||||
|
||||
### Requirement: Guest linking across routes
|
||||
|
||||
A guest's status SHALL be derived from the event lead it is linked to: Registered when linked, Attended when that event lead is attended. Whenever a capture for an event creates or finds an event lead, by staff, walk-in code, invite or check-in, an unlinked guest of the same event SHALL be linked to it. The guest is matched by mobile first, else by email. The guest then SHALL count as a guest, not as a walk-in.
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
# landing-pages Specification
|
||||
|
||||
## Purpose
|
||||
|
||||
Public landing pages per company, built by staff from blocks in the back office without a developer. A page's sign-up form registers visitors into an event as web sign-ups, with the page address and campaign tags, so they enter the lead pipeline. Each page shows its company's logo and accent colour.
|
||||
|
||||
## 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) and an ordered list of zero to 30 blocks. The block types SHALL be HERO, RICH_TEXT, IMAGE_TEXT, FAQ and FORM. 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
|
||||
|
||||
### Requirement: Page Fields Are Validated Server-Side
|
||||
|
||||
A page save SHALL be refused with the offending field path, writing nothing, when the slug does not match `^[a-z0-9]+(-[a-z0-9]+)*$`, is longer than 80 characters or is used by another page of the same company, ignoring case; or when the title is blank or longer than 120 characters; or when the meta description is longer than 160 characters.
|
||||
|
||||
#### Scenario: Duplicate slug in one company
|
||||
|
||||
- **GIVEN** INS has a page `hotel-technology`
|
||||
- **WHEN** INS staff save another page with slug `hotel-technology`
|
||||
- **THEN** the save is refused on field `slug`
|
||||
|
||||
#### Scenario: Same slug in two companies
|
||||
|
||||
- **GIVEN** INS has a page `about`
|
||||
- **WHEN** CV staff save a page with slug `about`
|
||||
- **THEN** the save succeeds
|
||||
|
||||
### 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, HTML 100000 characters. 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
|
||||
|
||||
### Requirement: Block References Stay Inside The Company
|
||||
|
||||
A block's image SHALL be an image of the page's company, and a FORM block's event SHALL be an event of the page's company. Otherwise the save SHALL be refused on that field.
|
||||
|
||||
#### Scenario: Another company's event
|
||||
|
||||
- **GIVEN** event `CV Roadshow` belongs to CV
|
||||
- **WHEN** INS staff save a FORM block pointing at `CV Roadshow`
|
||||
- **THEN** the save is refused on that block's event field
|
||||
|
||||
### 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 any HTML holds a `script` element, an `on*` attribute or a `javascript:` URL. The public page SHALL also sanitise all HTML against an allow-list before rendering it.
|
||||
|
||||
#### 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
|
||||
|
||||
### Requirement: Page Images
|
||||
|
||||
Staff with `BO_PAGES` SHALL upload images for their company in PNG, JPEG or WebP, each at most 2 MB, checked by the file's content and not by its name. Anyone SHALL be able to read an image by its id, so that public pages can show it.
|
||||
|
||||
#### Scenario: Wrong file type
|
||||
|
||||
- **WHEN** staff upload a PDF renamed to `banner.png`
|
||||
- **THEN** the upload is refused and nothing is stored
|
||||
|
||||
#### Scenario: Too large
|
||||
|
||||
- **WHEN** staff upload a 3 MB JPEG
|
||||
- **THEN** the upload is refused and nothing is stored
|
||||
|
||||
### Requirement: Company Branding
|
||||
|
||||
Each company SHALL have an optional logo, an image of that company, and an optional accent colour in `#RRGGBB` form. These SHALL be edited on the Companies screen. Its public pages SHALL show the logo in the header and use the accent colour on buttons, with black or white button text, whichever contrasts more. Without these, the pages SHALL use the neutral Co-Lite look.
|
||||
|
||||
#### Scenario: Accent colour
|
||||
|
||||
- **GIVEN** INS has accent colour `#0B5FFF`
|
||||
- **WHEN** a visitor opens an INS page
|
||||
- **THEN** its buttons are `#0B5FFF` with white text
|
||||
|
||||
#### Scenario: Invalid colour
|
||||
|
||||
- **WHEN** a super admin saves the accent colour `blue`
|
||||
- **THEN** the save is refused on that field
|
||||
|
||||
### Requirement: Public Page Address
|
||||
|
||||
A published page SHALL be public at `/p/<company-code>/<slug>`, matching the company code and the slug ignoring case. It SHALL be rendered on the server with the page title, the meta description and Open Graph tags. An unknown company, an unknown slug or a draft SHALL show the same not-found page to a visitor.
|
||||
|
||||
#### Scenario: Draft hidden from visitors
|
||||
|
||||
- **GIVEN** INS page `launch` is a draft
|
||||
- **WHEN** a signed-out visitor opens `/p/INS/launch`
|
||||
- **THEN** they see the not-found page
|
||||
|
||||
#### Scenario: Staff preview a draft
|
||||
|
||||
- **GIVEN** INS page `launch` is a draft
|
||||
- **WHEN** INS staff with `BO_PAGES` open its preview from the editor
|
||||
- **THEN** they see the page as it would be published, marked as a preview
|
||||
|
||||
### Requirement: The Form Block Registers For An Event
|
||||
|
||||
A FORM block SHALL show Co-Lite's sign-up form for its event, with that event's interests and the company's privacy notice. A submit SHALL follow the QR registration rules for matching, the existing-lead notes, consent and abuse limits. It SHALL create the event lead with source Web page and no salesperson, and SHALL record the page address and the `utm_source`, `utm_medium` and `utm_campaign` values from the page URL, each cut to 100 characters.
|
||||
|
||||
#### Scenario: New enquiry
|
||||
|
||||
- **GIVEN** page `/p/INS/hotel-technology` has a FORM block for `INS website enquiries`
|
||||
- **WHEN** a new visitor submits it from a URL with `utm_source=facebook`
|
||||
- **THEN** a new lead and an event lead with source Web page, no salesperson and UTM source `facebook` are created
|
||||
|
||||
#### Scenario: Known visitor
|
||||
|
||||
- **GIVEN** a lead with the same mobile exists in INS
|
||||
- **WHEN** they submit the form with a different email
|
||||
- **THEN** the lead is not edited, and the new email is written into the event lead's notes
|
||||
|
||||
### Requirement: The Form Block Closes With Its Event
|
||||
|
||||
A FORM block SHALL accept a submit only while its event is enabled, the event's end date in Malaysia time has not passed and the company has a privacy notice. Otherwise the page SHALL still show its other blocks, and the form area SHALL say that sign-up is closed.
|
||||
|
||||
#### Scenario: Ended event
|
||||
|
||||
- **GIVEN** the FORM block's event ended yesterday
|
||||
- **WHEN** a visitor opens the page
|
||||
- **THEN** the other blocks show and the form area says sign-up is closed
|
||||
|
||||
### Requirement: Web Sign-Up Details For Staff
|
||||
|
||||
The event lead detail SHALL show the page address and the UTM values of a Web page sign-up.
|
||||
|
||||
#### Scenario: Campaign shown
|
||||
|
||||
- **GIVEN** an event lead from a page opened with `utm_campaign=jan-launch`
|
||||
- **WHEN** staff open the event lead
|
||||
- **THEN** its detail shows the page address and campaign `jan-launch`
|
||||
|
||||
### Requirement: Pages Are Company-Scoped
|
||||
|
||||
Pages and page images SHALL follow the company scoping rules: staff see, edit and delete only their own company's pages, and a super admin sees every company's pages with their company. The Pages screens SHALL need `BO_PAGES`, which no role has at first. Page saves and deletes SHALL be audited.
|
||||
|
||||
#### Scenario: Another company's page
|
||||
|
||||
- **GIVEN** page 12 belongs to CV
|
||||
- **WHEN** INS staff ask for page 12
|
||||
- **THEN** they get not found
|
||||
|
||||
### Requirement: The Pages List
|
||||
|
||||
`/pages` SHALL list the pages in scope with their title, public address, status and last update, with a search by title or slug and an Add page action. Each row SHALL open its editor. Pages SHALL appear in the sidebar for users with `BO_PAGES`.
|
||||
|
||||
#### Scenario: Draft in the list
|
||||
|
||||
- **GIVEN** INS page `launch` is a draft
|
||||
- **WHEN** INS staff open `/pages`
|
||||
- **THEN** its row shows status Draft and address `/p/INS/launch`
|
||||
|
||||
### Requirement: The Page Editor
|
||||
|
||||
The editor SHALL offer the title, a slug filled from the title until edited, a meta description with a 160-character counter, the status and the block list. Blocks SHALL be added, moved up or down and removed. A chosen image SHALL be uploaded only when the page is saved. A FORM block SHALL pick from the company's enabled events that have not ended.
|
||||
|
||||
#### Scenario: Slug follows the title until edited
|
||||
|
||||
- **GIVEN** a new page
|
||||
- **WHEN** staff type the title "Hotel Technology"
|
||||
- **THEN** the slug becomes `hotel-technology`
|
||||
|
||||
### Requirement: Saving And Deleting In The Editor
|
||||
|
||||
Server field errors SHALL show next to their fields, keeping all entered values. After a save the editor SHALL offer a link to view the page. Deleting a page SHALL ask first, and unsaved edits SHALL be guarded.
|
||||
|
||||
#### Scenario: Server error at its field
|
||||
|
||||
- **WHEN** staff save a HERO button link `javascript:alert(1)`
|
||||
- **THEN** the error shows next to that button link and every entered value stays
|
||||
@@ -0,0 +1,286 @@
|
||||
# ui-translations Specification
|
||||
|
||||
## Purpose
|
||||
|
||||
Back-office labels load from a database message catalog per language, with English built in as the fallback. Staff can correct wording and add Chinese (zh_CN) translations on the Translations and Languages screens without a release.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: The Portal Shows Labels In The Chosen Language
|
||||
|
||||
The admin portal SHALL show every label in the language the user picked, read from the back-office message catalog. A label with no text in that language SHALL fall back to its English text, then to the portal's built-in English, and never show blank. The catalog read SHALL need no session, because the sign-in page shows labels too, and it SHALL return label text only.
|
||||
|
||||
#### Scenario: Chinese picked
|
||||
|
||||
- **GIVEN** the catalog has Chinese text for the label `Leads`
|
||||
- **WHEN** a signed-in user picks 简体中文
|
||||
- **THEN** the sidebar shows the Chinese text instead of "Leads"
|
||||
|
||||
#### Scenario: A label without Chinese
|
||||
|
||||
- **GIVEN** a label has English text in the catalog and no Chinese text
|
||||
- **WHEN** a user who picked 简体中文 opens a page with that label
|
||||
- **THEN** the label shows its English text
|
||||
|
||||
#### Scenario: Catalog unavailable
|
||||
|
||||
- **WHEN** the catalog cannot be read
|
||||
- **THEN** the portal shows the last catalog it loaded, or its built-in English if it has none
|
||||
- **AND** no label is blank
|
||||
|
||||
### Requirement: A Wording Change Shows On The Next Page Load
|
||||
|
||||
The system SHALL keep a catalog version that increases with every saved or imported label and every language change, within the same write. The portal SHALL check the version on each page load and reload the catalog when it has changed, on every portal instance, with no fixed waiting time.
|
||||
|
||||
#### Scenario: A label is edited
|
||||
|
||||
- **GIVEN** a user sees a label's Chinese text
|
||||
- **WHEN** a translator saves new Chinese text for that label
|
||||
- **THEN** the next page load shows the new text
|
||||
|
||||
#### Scenario: A refused save
|
||||
|
||||
- **WHEN** a label save or language change is refused
|
||||
- **THEN** the catalog version does not change
|
||||
|
||||
### Requirement: Supported Languages Are Kept In A Registry
|
||||
|
||||
The system SHALL keep the supported languages in a registry, each with a code that matches the catalog's language keys, a label, an enabled flag and an order. It SHALL start with English (`en_US`) and 简体中文 (`zh_CN`) enabled, and Bahasa Melayu (`ms_MY`), 繁體中文 (`zh_TW`) and Bahasa Indonesia (`in_ID`) disabled. The language picker SHALL list only enabled languages in their order, before and after sign-in. If the registry cannot be read, the picker SHALL offer English and 简体中文.
|
||||
|
||||
#### Scenario: Picker after rollout
|
||||
|
||||
- **WHEN** a user opens the language picker
|
||||
- **THEN** it lists English and 简体中文 only
|
||||
|
||||
#### Scenario: A language is enabled
|
||||
|
||||
- **WHEN** an admin enables Bahasa Melayu on the Languages page
|
||||
- **THEN** the picker lists it on the next page load, with no redeploy
|
||||
|
||||
#### Scenario: Registry unavailable
|
||||
|
||||
- **WHEN** the language list cannot be read
|
||||
- **THEN** the picker lists English and 简体中文
|
||||
|
||||
### Requirement: A Language Change Cannot Break The Registry
|
||||
|
||||
The system SHALL refuse:
|
||||
- a new language whose code already exists;
|
||||
- a change of a language's code;
|
||||
- switching English off;
|
||||
- switching off the last enabled language.
|
||||
|
||||
Each refusal SHALL leave the registry unchanged and SHALL reach the user as a named reason, not a generic error.
|
||||
|
||||
#### Scenario: Duplicate code
|
||||
|
||||
- **WHEN** an admin adds a language with the code `zh_CN`
|
||||
- **THEN** it is refused and the page says the code already exists
|
||||
|
||||
#### Scenario: English cannot be switched off
|
||||
|
||||
- **WHEN** the Languages page lists English
|
||||
- **THEN** its switch is disabled and the page says why
|
||||
- **AND** a direct request to disable English is refused
|
||||
|
||||
#### Scenario: Last enabled language
|
||||
|
||||
- **GIVEN** only one language is enabled
|
||||
- **WHEN** a request disables it
|
||||
- **THEN** it is refused
|
||||
|
||||
### Requirement: The Languages Page
|
||||
|
||||
The portal SHALL provide a Languages page at `/locales` that lists every language with its code, label, order and an enabled switch. It SHALL let the user add a language and edit a label and order. The code SHALL be editable only when adding. Switching a language off SHALL ask for confirmation first. Refusals SHALL show on the page.
|
||||
|
||||
#### Scenario: Switching a language off asks first
|
||||
|
||||
- **WHEN** a user switches 简体中文 off
|
||||
- **THEN** a confirmation is shown
|
||||
- **AND** nothing changes unless the user confirms
|
||||
|
||||
#### Scenario: Code read-only when editing
|
||||
|
||||
- **WHEN** a user edits an existing language
|
||||
- **THEN** its code is shown read-only
|
||||
|
||||
### Requirement: The Translations Page Lists And Finds Back-Office Labels
|
||||
|
||||
The portal SHALL provide a Translations page at `/messages` listing the back-office labels in pages, each with its code, English text and Chinese text. The search SHALL match the code, the English text or the Chinese text, ignoring case. A "Missing Chinese" filter SHALL list labels whose Chinese text is absent, blank or the same as the English text. Each such label SHALL be marked with a text badge, not colour alone. The page SHALL offer no way to add or delete a label.
|
||||
|
||||
#### Scenario: Search by Chinese wording
|
||||
|
||||
- **GIVEN** a label whose Chinese text contains "线索"
|
||||
- **WHEN** the user searches "线索"
|
||||
- **THEN** that label is listed
|
||||
|
||||
#### Scenario: Copied English counts as missing
|
||||
|
||||
- **GIVEN** a label whose English and Chinese text are both "WhatsApp"
|
||||
- **WHEN** the user turns on "Missing Chinese"
|
||||
- **THEN** that label is listed with a badge that says why
|
||||
|
||||
#### Scenario: No add or delete
|
||||
|
||||
- **WHEN** the Translations page and its row actions are inspected
|
||||
- **THEN** there is no add and no delete action
|
||||
|
||||
### Requirement: Editing A Translation
|
||||
|
||||
Opening a label SHALL show an edit panel with one multi-line field per enabled language and the code read-only. Closing it with unsaved changes SHALL ask before discarding them. The server SHALL refuse a save that changes a label's code, or that creates a label whose code already exists ignoring case. Label text SHALL always be shown as text, never as markup.
|
||||
|
||||
#### Scenario: Unsaved edits
|
||||
|
||||
- **WHEN** the user changes a field and closes the panel
|
||||
- **THEN** the panel asks before discarding the change
|
||||
|
||||
#### Scenario: Code change refused
|
||||
|
||||
- **WHEN** a save request changes an existing label's code
|
||||
- **THEN** it is refused and the label is unchanged
|
||||
|
||||
#### Scenario: Markup is shown as text
|
||||
|
||||
- **GIVEN** a translator saves `<b>Leads</b>` as a label's Chinese text
|
||||
- **WHEN** a page shows that label
|
||||
- **THEN** the angle brackets show as text and nothing is bold
|
||||
|
||||
### Requirement: Placeholders Are Kept In Translations
|
||||
|
||||
Each non-English text SHALL keep the same placeholders as the English text, in the `{name}` and `{0}` forms. When an edit creates a mismatch, the edit panel SHALL name the missing or extra placeholders and block Save. When the label was mismatched before the edit, it SHALL warn without blocking.
|
||||
|
||||
#### Scenario: A new placeholder mismatch blocks Save
|
||||
|
||||
- **GIVEN** a label whose English is "{n} unread" and Chinese is "{n} 条未读"
|
||||
- **WHEN** the user changes the Chinese to "条未读"
|
||||
- **THEN** the panel names `{n}` as missing
|
||||
- **AND** Save is disabled
|
||||
|
||||
#### Scenario: An old mismatch only warns
|
||||
|
||||
- **GIVEN** a label whose English is "{n} unread" and Chinese is "未读"
|
||||
- **WHEN** the user edits the English
|
||||
- **THEN** the panel warns that `{n}` is missing in Chinese
|
||||
- **AND** Save stays enabled
|
||||
|
||||
### Requirement: Translations Export
|
||||
|
||||
The Translations page SHALL export every back-office label, with the text in every language, as a JSON file download, without leaving the page.
|
||||
|
||||
#### Scenario: Export downloads
|
||||
|
||||
- **WHEN** the user clicks Export
|
||||
- **THEN** the browser offers a JSON file with every back-office label
|
||||
- **AND** the page stays on `/messages`
|
||||
|
||||
### Requirement: Translations Import With A Preview
|
||||
|
||||
The Translations page SHALL import a file in the export shape. It SHALL first show a preview that marks each row as an update, matched by code ignoring case and never by an id in the file, or as a new label. It SHALL apply nothing until the user confirms. A file that is not a JSON list SHALL be rejected on the page without sending anything. Each row SHALL be saved on its own, and a summary SHALL show the counts created and updated and name the failed rows.
|
||||
|
||||
#### Scenario: Preview before import
|
||||
|
||||
- **WHEN** the user picks an export file
|
||||
- **THEN** the page lists every row as an update or a new label
|
||||
- **AND** nothing is saved until the user confirms
|
||||
|
||||
#### Scenario: Matched by code
|
||||
|
||||
- **GIVEN** a file row with code `leads` and the id of another label
|
||||
- **AND** the catalog holds the label `Leads`
|
||||
- **WHEN** the file is imported
|
||||
- **THEN** the `Leads` label is updated
|
||||
|
||||
#### Scenario: Not a list
|
||||
|
||||
- **WHEN** the user picks a file that is not a JSON list
|
||||
- **THEN** the page shows an error and sends nothing
|
||||
|
||||
#### Scenario: One bad row
|
||||
|
||||
- **WHEN** an import has one row that fails and others that succeed
|
||||
- **THEN** the other rows are saved
|
||||
- **AND** the summary names the failed row
|
||||
|
||||
### Requirement: Access To Translations And Languages
|
||||
|
||||
The Translations page SHALL require `BO_MESSAGES` and the Languages page `BO_LOCALES`, checked on the server for every list, detail, export and write, with a signed-in admin. Both modules SHALL be granted to no role, so only super admins have them until a super admin grants them. Saves, imports, exports and language changes SHALL be audited.
|
||||
|
||||
#### Scenario: Without the module
|
||||
|
||||
- **WHEN** a staff user without `BO_MESSAGES` opens `/messages`
|
||||
- **THEN** the not-authorised page is shown
|
||||
- **AND** a direct save request is refused
|
||||
|
||||
#### Scenario: A save is audited
|
||||
|
||||
- **WHEN** a super admin saves a translation
|
||||
- **THEN** the audit log records who saved which label
|
||||
|
||||
### Requirement: Internal Catalog Writes Need A Token
|
||||
|
||||
Inside the system, message and language writes and full listings SHALL need a user token. Only the catalog, its version and the enabled-language list SHALL be readable without one.
|
||||
|
||||
#### Scenario: Internal write without a token
|
||||
|
||||
- **WHEN** a request without a user token tries to save a message or language inside the system
|
||||
- **THEN** it is refused
|
||||
|
||||
#### Scenario: Catalog read without a token
|
||||
|
||||
- **WHEN** the sign-in page loads the catalog without a session
|
||||
- **THEN** the catalog is returned
|
||||
|
||||
### Requirement: Every Back-Office Label Has Chinese
|
||||
|
||||
Every back-office label SHALL have Simplified Chinese text with the same placeholders as its English, using one consistent glossary, as a first pass for a native speaker to review. Every new back-office label SHALL ship with its Chinese text.
|
||||
|
||||
#### Scenario: Back office in Chinese
|
||||
|
||||
- **WHEN** a user picks 简体中文 and opens any back-office page
|
||||
- **THEN** every label on it shows Chinese text
|
||||
|
||||
#### Scenario: A new label without Chinese
|
||||
|
||||
- **WHEN** a developer adds a back-office label with no Chinese text
|
||||
- **THEN** the portal's tests fail and name the label
|
||||
|
||||
### Requirement: Loading The Chinese Keeps English Unchanged
|
||||
|
||||
Loading the Chinese SHALL replace earlier Chinese for the back-office labels, leave other languages unchanged, and add missing labels with their English. It SHALL reset the English of any label whose old database text differs from the portal's English, so nobody who keeps English sees a change.
|
||||
|
||||
#### Scenario: English unchanged
|
||||
|
||||
- **GIVEN** the old database English for the sign-in button is "Login"
|
||||
- **WHEN** the Chinese is loaded and a user who keeps English opens the sign-in page
|
||||
- **THEN** the button reads "Log in"
|
||||
|
||||
### Requirement: Translations Can Be Limited To Co-Lite Labels
|
||||
|
||||
The Translations page SHALL offer a "Co-Lite labels only" checkbox, on by default, that limits the list, the search and the "Missing Chinese" filter to the labels in the portal's built-in English list. Codes SHALL match ignoring case. Turning the checkbox off SHALL list every back-office label.
|
||||
|
||||
#### Scenario: Inherited labels hidden by default
|
||||
|
||||
- **GIVEN** a back-office label "OrderPayment" that is not in the portal's built-in list, and a label "Leads" that is
|
||||
- **WHEN** the user opens the Translations page
|
||||
- **THEN** "Leads" is listed and "OrderPayment" is not
|
||||
- **AND** "Co-Lite labels only" is checked
|
||||
|
||||
#### Scenario: Missing Chinese counts only Co-Lite labels
|
||||
|
||||
- **GIVEN** every label in the built-in list has Chinese and some inherited labels have none
|
||||
- **WHEN** the user turns on "Missing Chinese" with "Co-Lite labels only" checked
|
||||
- **THEN** no label is listed
|
||||
|
||||
#### Scenario: Every label on request
|
||||
|
||||
- **WHEN** the user unchecks "Co-Lite labels only"
|
||||
- **THEN** "OrderPayment" is listed too
|
||||
|
||||
### Requirement: The Co-Lite Code List Comes From The Portal Server
|
||||
|
||||
The portal's server SHALL build the Co-Lite code list from its built-in list and SHALL NOT take codes from the browser. mobile-api SHALL refuse with 400 a code list that is not a list of strings or holds more than 5,000 entries. Export and import SHALL keep covering every back-office label.
|
||||
|
||||
#### Scenario: Code list too long
|
||||
|
||||
- **WHEN** mobile-api receives a search with 5,001 codes
|
||||
- **THEN** it answers 400 and does not call services-system
|
||||
@@ -0,0 +1,211 @@
|
||||
# whatsapp-inbox Specification
|
||||
|
||||
## Purpose
|
||||
|
||||
A two-way WhatsApp inbox inside Co-Lite on each company's business number. Sales staff follow up leads from the back office, every message is recorded, and any colleague with access can pick up a chat.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: Company WhatsApp settings
|
||||
|
||||
The system SHALL read each company's WhatsApp number id, business account id, access token and app secret from the environment, and SHALL never store or log them. A company without complete settings SHALL have WhatsApp switched off. Its inbox SHALL say "WhatsApp is not configured", and the rest of the system SHALL keep working.
|
||||
|
||||
#### Scenario: Company not configured
|
||||
|
||||
- **GIVEN** CV has no WhatsApp settings
|
||||
- **WHEN** a CV admin with `BO_WHATSAPP` opens the inbox
|
||||
- **THEN** the page says "WhatsApp is not configured" and offers no composer
|
||||
|
||||
### Requirement: Webhook handshake
|
||||
|
||||
The public webhook SHALL answer Meta's subscription check with the given challenge only when the verify token matches the configured one. Otherwise it SHALL answer 403.
|
||||
|
||||
#### Scenario: Wrong verify token
|
||||
|
||||
- **WHEN** a subscription check arrives with a verify token that does not match
|
||||
- **THEN** the webhook answers 403 and does not echo the challenge
|
||||
|
||||
### Requirement: Webhook signature
|
||||
|
||||
The webhook SHALL accept an event only when its `X-Hub-Signature-256` header is a valid HMAC-SHA256 of the raw body under the app secret of the company the event's number belongs to. A missing or invalid signature SHALL get 401, and nothing SHALL be stored.
|
||||
|
||||
#### Scenario: Forged event
|
||||
|
||||
- **WHEN** an event for INS's number arrives without a valid signature
|
||||
- **THEN** the webhook answers 401 and no message is stored
|
||||
|
||||
#### Scenario: Signed with the other company's secret
|
||||
|
||||
- **GIVEN** INS and CV have different app secrets
|
||||
- **WHEN** an event for INS's number is signed with CV's app secret
|
||||
- **THEN** the event is rejected and no message is stored
|
||||
|
||||
### Requirement: Inbound messages
|
||||
|
||||
An accepted inbound message SHALL be stored once, in the conversation of the company that owns the receiving number, for the sender's WhatsApp number. Meta redelivering the same message id SHALL NOT create a second message. An event for a number no company owns SHALL be dropped. An event the inbox cannot take yet (the service is down, or the company of a configured number is not known yet) SHALL be refused, so that Meta redelivers it. Receiving a message SHALL open the 24-hour reply window.
|
||||
|
||||
#### Scenario: Lead writes to INS
|
||||
|
||||
- **GIVEN** INS lead Aisyah has mobile `+60123456701`
|
||||
- **WHEN** she sends "Hi, about the expo" to INS's number
|
||||
- **THEN** an INS conversation for `60123456701` holds the message, linked to Aisyah's lead
|
||||
- **AND** no CV user can see it
|
||||
|
||||
#### Scenario: Redelivery
|
||||
|
||||
- **WHEN** Meta delivers the same message id twice
|
||||
- **THEN** the conversation holds the message once
|
||||
|
||||
#### Scenario: Inbox not ready
|
||||
|
||||
- **GIVEN** the WhatsApp service has just started and cannot reach the system service yet
|
||||
- **WHEN** Meta delivers a message to INS's number
|
||||
- **THEN** the webhook answers 503 and stores nothing
|
||||
- **AND** when Meta redelivers after the service has resolved INS, the message is stored once
|
||||
|
||||
### Requirement: Delivery status
|
||||
|
||||
The status of a sent message SHALL move only forward, from pending to sent to delivered to read, except that failed SHALL be recorded at any point, together with Meta's error code and title. The thread SHALL show the status as ticks, or as a failure with its reason.
|
||||
|
||||
#### Scenario: Late delivered after read
|
||||
|
||||
- **WHEN** a "read" status arrives and then a "delivered" status arrives for the same message
|
||||
- **THEN** the message stays "read"
|
||||
|
||||
#### Scenario: Send failed
|
||||
|
||||
- **WHEN** Meta rejects a sent message
|
||||
- **THEN** the thread shows the message as failed with Meta's error title
|
||||
|
||||
### Requirement: Automatic ownership
|
||||
|
||||
A conversation without a manual owner SHALL be owned by the lead's latest salesperson (the salesperson of its most recently captured event lead that has one) when that user is active and holds `BO_WHATSAPP`. Otherwise the current owner SHALL be kept while still active with `BO_WHATSAPP`, and the conversation SHALL be unassigned when not. Ownership SHALL be recomputed when the conversation is created and when an event lead of that lead is captured or changes salesperson.
|
||||
|
||||
#### Scenario: Chat follows the latest salesperson
|
||||
|
||||
- **GIVEN** Aisyah's latest event lead has salesperson `sales1`, who holds `BO_WHATSAPP`
|
||||
- **WHEN** Aisyah writes for the first time
|
||||
- **THEN** the conversation is owned by `sales1`
|
||||
|
||||
#### Scenario: Latest event has no salesperson
|
||||
|
||||
- **GIVEN** a conversation owned by `sales1`
|
||||
- **WHEN** Aisyah is captured at a new event without a salesperson
|
||||
- **THEN** the conversation stays with `sales1`
|
||||
|
||||
#### Scenario: Salesperson without WhatsApp access
|
||||
|
||||
- **GIVEN** Aisyah's latest salesperson `sales2` does not hold `BO_WHATSAPP` and the conversation has no owner
|
||||
- **WHEN** ownership is recomputed
|
||||
- **THEN** the conversation is unassigned
|
||||
|
||||
#### Scenario: Unknown sender
|
||||
|
||||
- **WHEN** a number with no lead in INS writes to INS
|
||||
- **THEN** an unassigned conversation without a lead link is created
|
||||
|
||||
### Requirement: Manual assignment
|
||||
|
||||
A WhatsApp Admin SHALL be able to assign a conversation of their company to any active user of that company who holds `BO_WHATSAPP`, including themselves. A manual owner SHALL NOT change when event leads change. "Return to automatic" SHALL clear the manual owner and recompute it.
|
||||
|
||||
#### Scenario: Manual owner sticks
|
||||
|
||||
- **GIVEN** a WhatsApp Admin assigned Aisyah's conversation to `sales3`
|
||||
- **WHEN** Aisyah is captured at a new event with salesperson `sales1`
|
||||
- **THEN** the conversation stays with `sales3`
|
||||
|
||||
#### Scenario: Owner outside WhatsApp
|
||||
|
||||
- **WHEN** a WhatsApp Admin tries to assign a conversation to a user without `BO_WHATSAPP`
|
||||
- **THEN** the request is refused and the owner does not change
|
||||
|
||||
### Requirement: Owner loses access
|
||||
|
||||
When a user is disabled, or their roles no longer grant `BO_WHATSAPP`, the system SHALL make their conversations unassigned and clear any manual assignment. A user locked out by failed logins SHALL keep their conversations.
|
||||
|
||||
#### Scenario: Owner disabled
|
||||
|
||||
- **GIVEN** `sales1` owns three conversations
|
||||
- **WHEN** an admin disables `sales1`
|
||||
- **THEN** the three conversations are unassigned
|
||||
|
||||
### Requirement: Inbox access
|
||||
|
||||
A user with `BO_WHATSAPP` SHALL see, read and reply only in conversations they own. A user with `BO_WHATSAPP_ADMIN` SHALL see every conversation of their company, including unassigned ones, and SHALL be able to read and reply in any of them. A super admin SHALL see the conversations of every company. Every request SHALL be limited to the caller's company, and SHALL fail closed when the caller's company cannot be determined.
|
||||
|
||||
#### Scenario: Staff opens someone else's chat
|
||||
|
||||
- **WHEN** `sales1` requests a conversation owned by `sales3`
|
||||
- **THEN** the request answers 404
|
||||
|
||||
#### Scenario: WhatsApp Admin sees the queue
|
||||
|
||||
- **WHEN** an INS WhatsApp Admin opens the Unassigned tab
|
||||
- **THEN** it lists INS's unassigned conversations and none of CV's
|
||||
|
||||
### Requirement: Replies inside the 24-hour window
|
||||
|
||||
A user SHALL be able to send a text message only while less than 24 hours have passed since the contact's last inbound message. Outside the window a text send SHALL be refused with "The 24-hour window has closed. Send a template." The composer SHALL show the window's state and offer only templates when the window is closed.
|
||||
|
||||
#### Scenario: Window closed
|
||||
|
||||
- **GIVEN** Aisyah last wrote 25 hours ago
|
||||
- **WHEN** `sales1` sends a text reply
|
||||
- **THEN** it is refused and nothing is sent to Meta
|
||||
|
||||
### Requirement: Templates
|
||||
|
||||
A WhatsApp Admin SHALL be able to sync a company's approved templates from that company's business account, and the system SHALL also sync them nightly. Staff SHALL be able to send a synced template with every body parameter filled, inside or outside the window. Templates whose header or buttons need parameters SHALL be listed as not supported and SHALL NOT be sendable.
|
||||
|
||||
#### Scenario: Missing parameter
|
||||
|
||||
- **WHEN** a user sends template `expo_followup` with one of its two parameters empty
|
||||
- **THEN** it is refused and nothing is sent to Meta
|
||||
|
||||
### Requirement: Starting a chat from a lead
|
||||
|
||||
A user with `BO_WHATSAPP` SHALL be able to start a chat from a lead or event lead that has a mobile number, in that lead's company. If the conversation has no owner it SHALL become the starter's as a manual assignment. If another user owns it, the starter SHALL be told who owns it. Until the contact replies, only templates SHALL be offered.
|
||||
|
||||
#### Scenario: Start an unowned chat
|
||||
|
||||
- **GIVEN** Aisyah has no conversation yet and no salesperson with WhatsApp
|
||||
- **WHEN** `sales1` presses WhatsApp on her event lead
|
||||
- **THEN** a conversation owned by `sales1` opens with the template composer
|
||||
|
||||
### Requirement: Incoming media
|
||||
|
||||
Incoming images, documents, audio, video, stickers and locations SHALL be shown in the thread. Media SHALL be fetched from Meta only when a user with access opens it. Media that Meta no longer holds SHALL show "Media expired".
|
||||
|
||||
#### Scenario: Image opened by someone without access
|
||||
|
||||
- **WHEN** a user who cannot see the conversation requests one of its images
|
||||
- **THEN** the request answers 404
|
||||
|
||||
### Requirement: Unread counts
|
||||
|
||||
The system SHALL track, per user, the last message they read in each conversation they can see. It SHALL show unread conversations in the list and the number of unread conversations as a badge on the sidebar's inbox item.
|
||||
|
||||
#### Scenario: Reading clears the badge
|
||||
|
||||
- **GIVEN** `sales1` has one unread conversation
|
||||
- **WHEN** `sales1` opens it
|
||||
- **THEN** the sidebar badge clears
|
||||
|
||||
### Requirement: WhatsApp audit and privacy
|
||||
|
||||
Sending a message, reassigning a conversation and syncing templates SHALL be recorded in the audit log with the conversation and template names but not the message text. Message text, phone numbers, media, tokens and signatures SHALL NOT be written to application logs.
|
||||
|
||||
#### Scenario: Template send audited
|
||||
|
||||
- **WHEN** `sales1` sends template `expo_followup`
|
||||
- **THEN** the audit log records the send by `sales1` with the conversation and template name
|
||||
- **AND** not the filled-in text
|
||||
|
||||
### Requirement: Local Meta stand-in
|
||||
|
||||
The local stack SHALL include a test-only stand-in for Meta's API. It SHALL accept sends, serve templates and media, and post signed inbound events to the webhook on request, so the inbox can be developed and tested without a Meta account. The stand-in SHALL NOT be part of any release.
|
||||
|
||||
#### Scenario: Simulated inbound message
|
||||
|
||||
- **WHEN** a developer asks the stand-in to deliver "Hello" from `+60123456701` to INS's number
|
||||
- **THEN** the INS inbox shows the message within one polling interval
|
||||
@@ -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,36 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Check, Copy } from "lucide-react";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
/** A page address with a button that copies its full URL (this site's origin plus the path). */
|
||||
export function CopyAddress({ address }: { address: string }) {
|
||||
const t = useT();
|
||||
const [state, setState] = useState<"idle" | "copied" | "failed">("idle");
|
||||
|
||||
async function copy() {
|
||||
try {
|
||||
await navigator.clipboard.writeText(`${window.location.origin}${address}`);
|
||||
setState("copied");
|
||||
setTimeout(() => setState("idle"), 2000);
|
||||
} catch {
|
||||
setState("failed");
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<span className="font-mono text-xs">{address}</span>
|
||||
<Button type="button" variant="ghost" size="icon" className="size-7" aria-label={`${t("QrCopy")} ${address}`} title={t("QrCopy")} onClick={copy}>
|
||||
{state === "copied" ? <Check className="size-3.5" aria-hidden /> : <Copy className="size-3.5" aria-hidden />}
|
||||
</Button>
|
||||
{state !== "idle" ? (
|
||||
<span role="status" className={state === "failed" ? "text-xs text-destructive" : "text-xs text-muted-foreground"}>
|
||||
{t(state === "copied" ? "QrCopied" : "CopyFailed")}
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -35,6 +35,15 @@ beforeEach(() => {
|
||||
});
|
||||
|
||||
describe("PageEditor", () => {
|
||||
it("copies the saved page's full address", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<PageEditor pageId={5} />);
|
||||
await screen.findByLabelText("Event");
|
||||
const write = vi.spyOn(navigator.clipboard, "writeText");
|
||||
await user.click(screen.getByRole("button", { name: "Copy link /p/INS/hotel" }));
|
||||
expect(write).toHaveBeenCalledWith(`${window.location.origin}/p/INS/hotel`);
|
||||
});
|
||||
|
||||
it("names the rich text box after its field label", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<PageEditor pageId={5} />);
|
||||
|
||||
@@ -8,12 +8,14 @@ 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";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { useCompanyScope } from "@/app/lib/CompanyScope";
|
||||
import { CopyAddress } from "./CopyAddress";
|
||||
import { BLOCK_LABELS, BLOCK_TYPES, emptyBlock, emptyPage, pageAddress, pageBody, withTitle, type CmsBlock, type CmsPageDraft, type PageStatus } from "@/app/lib/cmsPages";
|
||||
import { deletePage, getPage, savePage, uploadPageImage } from "@/app/lib/services/adminPages";
|
||||
import { listAdminEvents } from "@/app/lib/services/adminEvents";
|
||||
@@ -75,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 });
|
||||
})
|
||||
@@ -198,7 +200,8 @@ export function PageEditor({ pageId }: { pageId?: number }) {
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-wrap justify-end gap-2">
|
||||
<div className="flex flex-wrap items-center justify-end gap-2">
|
||||
{saved && code ? <span className="mr-auto"><CopyAddress address={pageAddress(code, saved.slug)} /></span> : null}
|
||||
{draft.id != null ? (
|
||||
<Button variant="outline" asChild>
|
||||
<Link href={`/pages/${draft.id}/preview`}>{t("PagesPreview")}</Link>
|
||||
@@ -292,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);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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": "格式",
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -17,6 +17,23 @@ beforeEach(() => {
|
||||
});
|
||||
|
||||
describe("PagesPage", () => {
|
||||
it("copies a page's full address and reports a clipboard failure", async () => {
|
||||
const user = userEvent.setup();
|
||||
mocks.listPages.mockResolvedValue({
|
||||
items: [{ id: 5, companyId: 2, slug: "hotel-tech", title: "Hotel tech", status: "PUBLISHED", metaDescription: null, blocks: [], updatedAt: "2026-12-02T10:15:00" }],
|
||||
total: 1,
|
||||
});
|
||||
render(<PagesPage />);
|
||||
const write = vi.spyOn(navigator.clipboard, "writeText");
|
||||
await user.click(await screen.findByRole("button", { name: "Copy link /p/INS/hotel-tech" }));
|
||||
expect(write).toHaveBeenCalledWith(`${window.location.origin}/p/INS/hotel-tech`);
|
||||
expect(await screen.findByText("Link copied")).toBeInTheDocument();
|
||||
|
||||
write.mockRejectedValueOnce(new Error("denied"));
|
||||
await user.click(screen.getByRole("button", { name: "Copy link /p/INS/hotel-tech" }));
|
||||
expect(await screen.findByText("Could not copy.")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("lists title, address, status and update time", async () => {
|
||||
mocks.listPages.mockResolvedValue({
|
||||
items: [{ id: 5, companyId: 2, slug: "hotel-tech", title: "Hotel tech", status: "PUBLISHED", metaDescription: null, blocks: [], updatedAt: "2026-12-02T10:15:00" }],
|
||||
|
||||
@@ -18,6 +18,7 @@ import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize";
|
||||
import { useCompanyScope } from "@/app/lib/CompanyScope";
|
||||
import { listPages } from "@/app/lib/services/adminPages";
|
||||
import { formatEmailDate } from "@/app/lib/services/adminEmails";
|
||||
import { CopyAddress } from "@/app/components/pages/CopyAddress";
|
||||
import { pageAddress, type CmsPage } from "@/app/lib/cmsPages";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
@@ -63,7 +64,7 @@ function PagesPageContent() {
|
||||
{
|
||||
id: "address",
|
||||
header: t("PagesAddress"),
|
||||
cell: ({ row }) => <span className="font-mono text-xs">{pageAddress(codeOf(row.original.companyId) || companyCode || "", row.original.slug)}</span>,
|
||||
cell: ({ row }) => <CopyAddress address={pageAddress(codeOf(row.original.companyId) || companyCode || "", row.original.slug)} />,
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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'/);
|
||||
});
|
||||
});
|
||||
@@ -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.
|
||||
|
||||
+8
-1
@@ -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);
|
||||
}
|
||||
|
||||
+11
@@ -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);
|
||||
|
||||
+10
@@ -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));
|
||||
|
||||
+8
-1
@@ -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;
|
||||
|
||||
+7
-1
@@ -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);
|
||||
|
||||
+2
-1
@@ -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) {
|
||||
|
||||
+16
@@ -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");
|
||||
}
|
||||
}
|
||||
+16
@@ -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();
|
||||
|
||||
Reference in new issue
Block a user