Merge pull request 'feat(pages): same-page #name links on landing pages' (#58) from add-page-anchor-links into main
CI / build-and-publish (push) Failing after 0s

This commit was merged in pull request #58.
This commit is contained in:
ngqile committed 2026-12-03 01:48:08 +00:00
commit 7229437ced
29 files changed
+515 -37

No files matched your search

+3 -1
View File
@@ -154,6 +154,7 @@ Run the three in order before the new services-system, gateway and mobile-api go
| `openspec/changes/archive/2026-12-03-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. |
| `openspec/changes/archive/2026-12-03-add-lead-notifications/sql/01-notification-columns.sql` | Turns the unused `service-system`.`notification` table into the staff bell: converts it to utf8mb4 and adds the recipient, company, type, link, collapse and read columns and two indexes. DDL. |
| `openspec/changes/archive/2026-12-03-add-lead-notifications/sql/02-notification-labels.sql` | Adds the bell's labels in English and Chinese. Same rule as `05-page-labels.sql`: only where `add-zh-cn-messages/sql/03` already ran. |
| `openspec/changes/add-page-anchor-links/sql/01-anchor-labels.sql` | Adds the "Link name" labels and updates the link hint and the bad-link message, in English and Chinese. Same rule as `05-page-labels.sql`: only where `add-zh-cn-messages/sql/03` already ran. No DDL: link names live in the page's blocks JSON. |
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.
@@ -429,7 +430,7 @@ data:
- An image removed from a page stays stored; nothing deletes unused images.
- The editor warns about unsaved edits only on reload or close, not when staff click another link in the back office.
- A standing enquiries event (section 12) appears in event lists and dashboards like any event.
- Links accept only `https://`, `mailto:`, `tel:` or a path starting with `/`. A same-page `#anchor` link (for example a hero button that jumps to the form) is refused; use the page's own path instead.
- Links accept only `https://`, `mailto:`, `tel:`, a path starting with `/`, or `#` plus a block's link name.
## 11. Connecting WhatsApp (Meta)
@@ -459,6 +460,7 @@ Marketing builds public pages under **Events → Pages**. Each page has blocks (
2. **Branding.** A super admin sets each company's logo and accent colour under **Companies → Branding**. Buttons on the company's pages use the accent colour, with black or white text, whichever is easier to read. Without them the page shows the company name and the default blue.
3. **Standing enquiries event.** A sign-up form always belongs to an event. For general enquiries, each company creates one event, for example "INS website enquiries", with a far-off end date and its sales team, and picks it in the form block. Sign-ups from a landing page are never marked as attended, so this event does not inflate attendance. Name it clearly: it shows in event lists and dashboards.
4. **The INS page.** The INS proof of concept (`ins-landing-page`, never deployed) is content, not code: rebuild it by hand in the editor after deploy. Its test leads are not imported.
- **Jump to the form.** To make a button jump to the sign-up form, give the form block a link name, for example `signup`, and link the button to `#signup`. Links inside a Custom HTML block work the same way: on the INS page, change the HTML's `#consult` links to `#signup`. A `#name` link inside the HTML that matches an `id` in that same HTML (such as `#top`) scrolls to that spot instead.
5. **Check.** Publish a page, open its address signed out, sign up through its form with `?utm_source=test` on the address, and check that the event lead shows source **Web page**, the page address and the campaign. Delete that test lead afterwards.
A form stops taking sign-ups when its event is disabled, its end date has passed (Malaysia time), or the company has no privacy notice; the page then says sign-up is closed and still shows its other blocks. Sign-ups share the QR pages' rate limits.
@@ -0,0 +1,33 @@
# Same-page anchor links on landing pages — design
Approved by the owner on 2026-12-03 (small change).
## Why
Marketing wants a button near the top of a landing page to jump to the sign-up form further down. Today the editor, the portal and services-counter all refuse a `#anchor` link, and blocks carry no `id` to jump to. On the INS "hotel-technology" page (a Custom HTML block followed by a FORM block), the pasted HTML's own `#consult` and `#top` links do nothing: the sealed frame is sized to its full height, so it never scrolls itself, and as an opaque-origin frame it may not scroll the page around it.
## Goals
- Staff can name any block and link to it with `#name` from a button, from rich text, or from inside a Custom HTML block.
- In-frame links to an `id` inside the same Custom HTML block work again.
## Non-goals
- No automatic ids (`block-3`): they break when blocks are reordered.
- No change to how the sealed frame is sandboxed. The frame gets no new grants.
## Approaches
1. **An optional link name per block (chosen).** One new optional field, unique per page, stored in the existing blocks JSON. Works for every block type and survives reordering.
2. Automatic positional ids (`block-3`). No editor change, but links break silently when blocks move.
3. A fixed `id="form"` on the FORM block only. Covers the main case, but not other blocks or `#top`.
## Design
- **Link name.** Each block has an optional "Link name": lowercase letters, digits and `-`, starting with a letter or digit and not with `reg-` (the sign-up form's field ids), at most 40 characters, unique on the page. services-counter checks it. The public page renders it as the block's `id`.
- **`#name` links.** Button links and rich-text links also accept `#` followed by a name of that pattern. The same rule is in services-counter, the portal's `isSafeLink`, the rich-text editor and the public sanitiser.
- **Frame bridge.** The frame document's injected script, which already reports its height, also catches clicks on `#name` links inside the frame and posts the name and, when the frame holds an element with that `id`, the element's offset. The page acts on such a message only from its own frame and only for a name of the pattern. It scrolls to the frame's top plus that offset when the frame has the target; otherwise to a block on the page with that link name; otherwise it does nothing. The frame link's default action is prevented, so the frame never navigates.
## Left to the builder
Field placement in the editor, label wording, and smooth vs instant scrolling.
+12 -4
View File
@@ -1607,8 +1607,8 @@ INSERT INTO message (code, content, area) SELECT 'PagesDivider', JSON_OBJECT('en
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '分隔线') WHERE LOWER(code) = LOWER('PagesDivider') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesLink', JSON_OBJECT('en_US', 'Link', 'zh_CN', '链接'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLink') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '链接') WHERE LOWER(code) = LOWER('PagesLink') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesLinkPrompt', JSON_OBJECT('en_US', 'Link address (https://, mailto:, tel: or /)', 'zh_CN', '链接地址(https://、mailto:、tel: 或 /)'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLinkPrompt') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '链接地址(https://、mailto:、tel: 或 /)') WHERE LOWER(code) = LOWER('PagesLinkPrompt') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesLinkPrompt', JSON_OBJECT('en_US', 'Link address (https://, mailto:, tel:, / or #name)', 'zh_CN', '链接地址(https://、mailto:、tel:、/ 或 #名称)'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLinkPrompt') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '链接地址(https://、mailto:、tel:、/ 或 #名称)') WHERE LOWER(code) = LOWER('PagesLinkPrompt') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesClearFormatting', JSON_OBJECT('en_US', 'Clear formatting', 'zh_CN', '清除格式'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesClearFormatting') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '清除格式') WHERE LOWER(code) = LOWER('PagesClearFormatting') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesTooManyBlocks', JSON_OBJECT('en_US', 'A page can have at most 30 blocks.', 'zh_CN', '每个网页最多 30 个区块。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTooManyBlocks') AND area = 'A');
@@ -1625,8 +1625,16 @@ INSERT INTO message (code, content, area) SELECT 'PagesFaqCount', JSON_OBJECT('e
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请添加 1 至 30 个问题。') WHERE LOWER(code) = LOWER('PagesFaqCount') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesButtonPair', JSON_OBJECT('en_US', 'Fill in both the button label and the button link, or neither.', 'zh_CN', '按钮文字和按钮链接需同时填写或同时留空。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesButtonPair') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '按钮文字和按钮链接需同时填写或同时留空。') WHERE LOWER(code) = LOWER('PagesButtonPair') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesBadLink', JSON_OBJECT('en_US', 'Use a link that starts with https://, mailto:, tel: or /.', 'zh_CN', '链接须以 https://、mailto:、tel: 或 / 开头。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBadLink') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '链接须以 https://、mailto:、tel: 或 / 开头。') WHERE LOWER(code) = LOWER('PagesBadLink') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesBadLink', JSON_OBJECT('en_US', 'Use a link that starts with https://, mailto:, tel:, / or #.', 'zh_CN', '链接须以 https://、mailto:、tel:、/ 或 # 开头。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBadLink') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '链接须以 https://、mailto:、tel:、/ 或 # 开头。') WHERE LOWER(code) = LOWER('PagesBadLink') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesAnchor', JSON_OBJECT('en_US', 'Link name (optional)', 'zh_CN', '链接名称(可选)'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAnchor') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '链接名称(可选)') WHERE LOWER(code) = LOWER('PagesAnchor') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesAnchorHint', JSON_OBJECT('en_US', 'Link to this block with #name, for example #signup. Lowercase letters, digits and - only.', 'zh_CN', '用 #名称 链接到此区块,例如 #signup。仅限小写字母、数字和 -。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAnchorHint') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '用 #名称 链接到此区块,例如 #signup。仅限小写字母、数字和 -。') WHERE LOWER(code) = LOWER('PagesAnchorHint') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesBadAnchor', JSON_OBJECT('en_US', 'Use lowercase letters, digits and - (up to 40), starting with a letter or digit and not with reg-.', 'zh_CN', '请使用小写字母、数字和 -(最多 40 个),以字母或数字开头,且不能以 reg- 开头。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBadAnchor') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请使用小写字母、数字和 -(最多 40 个),以字母或数字开头,且不能以 reg- 开头。') WHERE LOWER(code) = LOWER('PagesBadAnchor') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesAnchorTaken', JSON_OBJECT('en_US', 'Another block on this page already has this link name.', 'zh_CN', '本页已有其他区块使用此链接名称。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAnchorTaken') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '本页已有其他区块使用此链接名称。') WHERE LOWER(code) = LOWER('PagesAnchorTaken') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesScript', JSON_OBJECT('en_US', 'Scripts and event handlers are not allowed.', 'zh_CN', '不允许使用脚本或事件处理程序。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesScript') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '不允许使用脚本或事件处理程序。') WHERE LOWER(code) = LOWER('PagesScript') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesBadImage', JSON_OBJECT('en_US', 'Upload the image again.', 'zh_CN', '请重新上传图片。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBadImage') AND area = 'A');
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-12-03
@@ -0,0 +1,27 @@
## Context
See `docs/superpowers/specs/2026-12-03-page-anchor-links-design.md`. Blocks are one JSON column on `cms_page`; services-counter validates them; mobile-api passes them through as maps; the portal renders them. Custom HTML runs in an opaque-origin frame (`allow-scripts allow-popups allow-popups-to-escape-sandbox`) whose injected script already posts height reports, which `HtmlFrame` accepts only from its own `contentWindow`.
## Goals / Non-Goals
**Goals:** named block targets; `#name` links from buttons, rich text and Custom HTML.
**Non-Goals:** automatic ids; any new frame permission; scroll offsets for a sticky header (the public page has none).
## Decisions
1. **Field `anchor` on the block**, pattern `^(?!reg-)[a-z0-9][a-z0-9-]{0,39}$`, unique per page. `reg-` is reserved because the sign-up form renders its fields with literal `reg-*` ids. Stored in the blocks JSON, so no DDL. Refusal codes: `PagesBadAnchor`, `PagesAnchorTaken`.
2. **Link rule.** `#` plus the same pattern is a safe link everywhere a link is checked: `CmsBlockValidator.safeLink`, `isSafeLink`, the editor's `SAFE_LINK`, and the sanitiser (sanitize-html already keeps scheme-less hrefs; a test pins it).
3. **Ids.** The block wrapper in `CmsBlocks` gets `id={anchor}` for every type, the HTML frame included. Rendered only when the name matches the pattern, so rows written another way cannot inject odd ids.
4. **Frame bridge.** The injected script adds one click listener: for `a[href^="#"]` with a valid name it prevents the default and posts `{type:"colite-frame-anchor", name, y}`, where `y` is the in-frame element's document offset or `null`. `HtmlFrame` checks the source window as for heights, validates the message in a pure `frameAnchor()` helper, then scrolls the window to `frame top + y`, or to `document.getElementById(name)`, else ignores it. Smooth scroll.
5. **Messages are data only.** The page never navigates or evaluates anything from a frame message; it only scrolls.
## Risks / Trade-offs
- A frame script could post anchor requests at will → it can only scroll its own page, which it could already make tall. Accepted.
- A link name equal to an id the portal already uses on that page (e.g. `main`) would clash → the sign-up form's field ids all start with `reg-`, which link names may not; other ids on the page come from `useId` and cannot match the pattern. The staff preview runs inside the back-office shell, whose ids are not checked against link names.
- Pages saved by an older release lose link names → only on rollback; noted in the proposal.
## Migration Plan
Deploy services-counter and the portal; run `sql/01-anchor-labels.sql`. Rollback: previous images and `sql/99-rollback.sql`.
@@ -0,0 +1,28 @@
## Why
Landing pages cannot link within themselves. Buttons and rich-text links refuse `#anchor`, blocks have no id to jump to, and links inside a Custom HTML block do nothing because the sealed frame never scrolls and may not scroll the page. The INS page's "Get My Free Consultation" button therefore cannot take visitors to the sign-up form. Design: `docs/superpowers/specs/2026-12-03-page-anchor-links-design.md`.
## What Changes
- Each block gets an optional link name, unique on the page, rendered as the block's id.
- Button and rich-text links accept `#name`.
- The Custom HTML frame reports clicks on `#name` links to the page, which scrolls to the target inside the frame or to the named block.
- New and changed editor labels in English and Chinese.
## Capabilities
### New Capabilities
None.
### Modified Capabilities
- `landing-pages`: same-page links and block link names.
## Impact
- services-counter: `CmsBlock` gains `anchor`; `CmsBlockValidator` checks it and accepts `#name` links. No DDL: blocks are stored as JSON.
- mobile-api: none (blocks pass through as maps).
- Portal: `cmsPages.ts` (`isSafeLink`, model), `RichTextEditor.tsx`, `pageHtml.ts`, `frameHtml.ts` (script and message parsing), `HtmlFrame.tsx`, `CmsBlocks.tsx` (ids), `BlockFields.tsx` (field), labels.
- SQL: `sql/01-anchor-labels.sql` and `sql/99-rollback.sql` (labels only).
- Older releases ignore the new field on read, and a page saved by an older release loses its link names.
@@ -0,0 +1,78 @@
## MODIFIED Requirements
### Requirement: Page Content Cannot Run Scripts
A button SHALL have both a label and a link or neither. The link SHALL start with a single `/`, `https://`, `mailto:`, `tel:`, or `#` plus a valid block link name. A save SHALL be refused when RICH_TEXT or IMAGE_TEXT HTML holds a `script` element, an `on*` attribute or a `javascript:` URL. The public page SHALL also sanitise that HTML against an allow-list. HTML blocks are exempt: they only 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
#### Scenario: Same-page button link
- **WHEN** a page is saved with a HERO button link `#signup`
- **THEN** the save succeeds
#### Scenario: Malformed same-page link
- **WHEN** a page is saved with a HERO button link `#Sign Up`
- **THEN** the save is refused on field `blocks[0].buttonUrl`
## ADDED Requirements
### Requirement: Block Link Names
Any block MAY carry a link name. A link name SHALL be 1 to 40 characters of lowercase letters, digits and `-`, starting with a letter or digit, SHALL NOT start with `reg-` (the sign-up form's own field ids), and SHALL be unique within the page. A save breaking either rule SHALL be refused on that block's link-name field, writing nothing. The public page and the staff preview SHALL give the block that name as its element id, so a `#name` link scrolls to it.
#### Scenario: Hero button jumps to the form
- **GIVEN** a published page whose FORM block has the link name `signup` and whose HERO button links to `#signup`
- **WHEN** a visitor clicks the button
- **THEN** the page scrolls to the form
#### Scenario: Duplicate link name
- **WHEN** a page is saved with two blocks named `signup`
- **THEN** the save is refused on field `blocks[1].anchor` and nothing is written
#### Scenario: Reserved link name
- **WHEN** a page is saved with a block named `reg-email`
- **THEN** the save is refused on field `blocks[0].anchor` and nothing is written
#### Scenario: Bad link name
- **WHEN** a page is saved with a block named `Sign Up`
- **THEN** the save is refused on field `blocks[0].anchor` and nothing is written
### Requirement: Same-Page Links From A Custom HTML Frame
A click on a `#name` link inside a Custom HTML block SHALL scroll the page, without navigating the frame. The target SHALL be the element with that id inside the same frame when there is one, otherwise the block on the page with that link name, otherwise nothing happens. The page SHALL act only on such requests from its own frames and only for names of the link-name pattern. The frame SHALL gain no new sandbox permissions.
#### Scenario: Link to the form below the frame
- **GIVEN** a published page with an HTML block holding `<a href="#signup">` and a FORM block named `signup`
- **WHEN** a visitor clicks that link
- **THEN** the page scrolls to the form
#### Scenario: Link inside the frame
- **GIVEN** a published HTML block whose content holds `<a href="#top">` near its bottom and an element with id `top` at its start
- **WHEN** a visitor scrolls down and clicks that link
- **THEN** the page scrolls back to the start of the frame
#### Scenario: Another window asks to scroll
- **WHEN** a different window posts a same-page link request to the page
- **THEN** the page does not scroll
@@ -0,0 +1,18 @@
-- The labels added or changed by add-page-anchor-links, 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 'PagesLinkPrompt', JSON_OBJECT('en_US', 'Link address (https://, mailto:, tel:, / or #name)', 'zh_CN', '链接地址(https://、mailto:、tel:、/ 或 #名称)'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesLinkPrompt') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '链接地址(https://、mailto:、tel:、/ 或 #名称)') WHERE LOWER(code) = LOWER('PagesLinkPrompt') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesBadLink', JSON_OBJECT('en_US', 'Use a link that starts with https://, mailto:, tel:, / or #.', 'zh_CN', '链接须以 https://、mailto:、tel:、/ 或 # 开头。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBadLink') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '链接须以 https://、mailto:、tel:、/ 或 # 开头。') WHERE LOWER(code) = LOWER('PagesBadLink') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesAnchor', JSON_OBJECT('en_US', 'Link name (optional)', 'zh_CN', '链接名称(可选)'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAnchor') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '链接名称(可选)') WHERE LOWER(code) = LOWER('PagesAnchor') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesAnchorHint', JSON_OBJECT('en_US', 'Link to this block with #name, for example #signup. Lowercase letters, digits and - only.', 'zh_CN', '用 #名称 链接到此区块,例如 #signup。仅限小写字母、数字和 -。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAnchorHint') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '用 #名称 链接到此区块,例如 #signup。仅限小写字母、数字和 -。') WHERE LOWER(code) = LOWER('PagesAnchorHint') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesBadAnchor', JSON_OBJECT('en_US', 'Use lowercase letters, digits and - (up to 40), starting with a letter or digit and not with reg-.', 'zh_CN', '请使用小写字母、数字和 -(最多 40 个),以字母或数字开头,且不能以 reg- 开头。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBadAnchor') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '请使用小写字母、数字和 -(最多 40 个),以字母或数字开头,且不能以 reg- 开头。') WHERE LOWER(code) = LOWER('PagesBadAnchor') AND area = 'A';
INSERT INTO message (code, content, area) SELECT 'PagesAnchorTaken', JSON_OBJECT('en_US', 'Another block on this page already has this link name.', 'zh_CN', '本页已有其他区块使用此链接名称。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAnchorTaken') AND area = 'A');
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '本页已有其他区块使用此链接名称。') WHERE LOWER(code) = LOWER('PagesAnchorTaken') AND area = 'A';
-- PagesLinkPrompt and PagesBadLink already exist: their English changes too.
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.en_US', 'Link address (https://, mailto:, tel:, / or #name)') WHERE LOWER(code) = LOWER('PagesLinkPrompt') AND area = 'A';
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.en_US', 'Use a link that starts with https://, mailto:, tel:, / or #.') WHERE LOWER(code) = LOWER('PagesBadLink') AND area = 'A';
@@ -0,0 +1,8 @@
-- Co-Lite change add-page-anchor-links: rollback of the labels. Blocks keep their link names in the JSON; the previous
-- release ignores them on read, and a page saved by it loses them. Pages with #name links must be edited before
-- they are saved under the previous release, which refuses such links.
SET NAMES utf8mb4;
USE `service-system`;
DELETE FROM message WHERE code IN ('PagesAnchor', 'PagesAnchorHint', 'PagesBadAnchor', 'PagesAnchorTaken') AND area = 'A';
UPDATE message SET content = JSON_SET(content, '$.en_US', 'Link address (https://, mailto:, tel: or /)', '$.zh_CN', '链接地址(https://、mailto:、tel: 或 /)') WHERE LOWER(code) = LOWER('PagesLinkPrompt') AND area = 'A';
UPDATE message SET content = JSON_SET(content, '$.en_US', 'Use a link that starts with https://, mailto:, tel: or /.', '$.zh_CN', '链接须以 https://、mailto:、tel: 或 / 开头。') WHERE LOWER(code) = LOWER('PagesBadLink') AND area = 'A';
@@ -0,0 +1,20 @@
# Tasks: add-page-anchor-links
Design: `design.md`. Every task is TDD. Work is serial in the main session, with a self-review per task.
## 1. services-counter
- [x] 1.1 `CmsBlock.anchor`; `CmsBlockValidator`: link-name pattern and uniqueness (`PagesBadAnchor`, `PagesAnchorTaken` on `blocks[i].anchor`), `#name` accepted by `safeLink`.
- Verify: `mvn -T 1C -B -pl solvway-services-counter -am verify`
## 2. Portal
- [x] 2.1 Link rules: `isSafeLink`, the rich-text editor's `SAFE_LINK`, a sanitiser test that `#name` hrefs survive; block ids in `CmsBlocks` (pattern-checked).
- [x] 2.2 Frame bridge: click listener in the frame script, `frameAnchor()` message check, `HtmlFrame` scroll (own frame only).
- [x] 2.3 Editor: "Link name" field per block with field errors; label changes in `defaultMessages.ts` and `zh_CN.seed.json`, then `npm run i18n:sql`; `sql/01-anchor-labels.sql` (new labels, plus English and Chinese updates of `PagesBadLink` and `PagesLinkPrompt`) and `sql/99-rollback.sql`.
- Verify (2.1 to 2.3): `cd solvway-admin-portal && npx vitest run; echo VITEST=$? && npx tsc --noEmit && npm run lint`
## 3. Release
- [x] 3.1 `docs/deployment.md`: SQL rows, drop the `#anchor` known gap, add the INS page note (name the FORM block `signup`, change the HTML's `#consult` to `#signup`).
- [x] 3.2 Live check (Playwright) on a local portal: hero button to a named form block; Custom HTML `#name` to the form and `#top` inside the frame; refusals for a bad and a duplicate link name; 1280 and 360 px.
@@ -12,7 +12,7 @@ import { RichTextEditor } from "./RichTextEditor";
// One block of the page editor, ported from babyboo's BlockFields: a fieldset with move/remove and its type's fields.
/** Field paths (relative to the block) each type shows inline; any other error shows at the block's top. */
/** Field paths (relative to the block) each type shows inline; any other error shows at the block's top. Every type also shows "anchor". */
const INLINE: Record<string, string[]> = {
HERO: ["imageId", "heading", "text", "buttonLabel", "buttonUrl"],
RICH_TEXT: ["html"],
@@ -64,9 +64,9 @@ export function BlockFields(props: {
const t = useT();
const set = (patch: Partial<CmsBlock>) => onChange((b) => ({ ...b, ...patch }));
const fid = (name: string) => `block-${id}-${name}`;
const topErrors = Object.entries(errors).filter(([path]) => !INLINE[block.type]?.includes(path) && !LISTED.test(path));
const topErrors = Object.entries(errors).filter(([path]) => path !== "anchor" && !INLINE[block.type]?.includes(path) && !LISTED.test(path));
const text = (name: "heading" | "text" | "buttonLabel" | "buttonUrl", labelCode: string) => (
const text = (name: "heading" | "text" | "buttonLabel" | "buttonUrl" | "anchor", labelCode: string) => (
<Field id={fid(name)} label={t(labelCode)} error={errors[name]}>
<Input id={fid(name)} value={block[name] ?? ""} disabled={saving} aria-invalid={!!errors[name]} onChange={(e) => set({ [name]: e.target.value })} />
</Field>
@@ -195,6 +195,12 @@ export function BlockFields(props: {
</Field>
</>
)}
{/* add-page-anchor-links: the block's id on the page, the target of #name links. */}
<div className="space-y-1">
{text("anchor", "PagesAnchor")}
<p className="text-xs text-muted-foreground">{t("PagesAnchorHint")}</p>
</div>
</fieldset>
);
}
@@ -1,5 +1,5 @@
import { act, render, screen } from "@testing-library/react";
import { describe, it, expect } from "vitest";
import { describe, it, expect, vi } from "vitest";
import { LandingPage, type PublicBlock } from "./CmsBlocks";
import { FRAME_SANDBOX } from "@/app/lib/frameHtml";
@@ -21,6 +21,30 @@ describe("LandingPage: Custom HTML", () => {
expect(document.querySelector("script")).toBeNull();
});
it("gives a named HTML block its link name as the frame's id", () => {
render(<LandingPage company={company} page={page([{ ...HTML, anchor: "story" }])} />);
expect(frame()).toHaveAttribute("id", "story");
});
it("scrolls the page for a #name link in its own frame: to the frame's target, else to the named block", () => {
const scrollTo = vi.spyOn(window, "scrollTo").mockImplementation(() => {});
const into = vi.fn();
Element.prototype.scrollIntoView = into;
render(<LandingPage company={company} page={page([HTML, { type: "FORM", heading: "Join", closed: true, anchor: "signup" }])} />);
vi.spyOn(frame(), "getBoundingClientRect").mockReturnValue({ top: 100 } as DOMRect);
const ask = (data: unknown, source: MessageEventSource | null) => act(() => { window.dispatchEvent(new MessageEvent("message", { data, source })); });
ask({ type: "colite-frame-anchor", name: "signup", y: null }, window);
expect(into).not.toHaveBeenCalled();
ask({ type: "colite-frame-anchor", name: "signup", y: null }, frame().contentWindow);
expect(into).toHaveBeenCalledTimes(1);
expect(into.mock.contexts[0]).toBe(document.getElementById("signup"));
ask({ type: "colite-frame-anchor", name: "top", y: 300 }, frame().contentWindow);
expect(scrollTo).toHaveBeenCalledWith({ top: 400, behavior: "smooth" });
ask({ type: "colite-frame-anchor", name: "nowhere", y: null }, frame().contentWindow);
expect(into).toHaveBeenCalledTimes(1);
expect(scrollTo).toHaveBeenCalledTimes(1);
});
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");
@@ -35,6 +35,17 @@ describe("LandingPage", () => {
expect(screen.getByRole("link", { name: "Mail" })).toHaveAttribute("href", "mailto:a@b.c");
});
it("gives a named block its link name as id, so a #name button jumps to it", () => {
render(<LandingPage company={company} page={page([
{ type: "HERO", heading: "Hi", buttonLabel: "Sign up", buttonUrl: "#signup" },
{ type: "FORM", heading: "Join", closed: true, anchor: "signup" },
{ type: "RICH_TEXT", html: "<p>x</p>", anchor: 'bad" onclick="x' },
])} />);
expect(screen.getByRole("link", { name: "Sign up" })).toHaveAttribute("href", "#signup");
expect(document.getElementById("signup")).toHaveTextContent("Sign-up is closed.");
expect(document.querySelectorAll("main [id]")).toHaveLength(1);
});
it("a closed form says so; the preview shows a note instead of a form", () => {
const { unmount } = render(<LandingPage company={company} page={page([{ type: "FORM", heading: "Join", closed: true }])} />);
expect(screen.getByText("Sign-up is closed.")).toBeInTheDocument();
@@ -1,5 +1,5 @@
import type { CSSProperties, ReactNode } from "react";
import { contrastText, imageSrc, isSafeLink, type CmsBlock } from "@/app/lib/cmsPages";
import { anchorId, contrastText, imageSrc, isSafeLink, type CmsBlock } from "@/app/lib/cmsPages";
import type { RegistrationInfo } from "@/app/lib/services/publicRegistration";
import { SafeHtml } from "./SafeHtml";
import { LandingForm } from "./LandingForm";
@@ -123,8 +123,8 @@ export function LandingPage({ company, page, banner, preview, frameBase }: {
<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>)}
? <HtmlFrame key={i} id={anchorId(block.anchor)} src={`${frames}/${i}`} title={page.title} />
: <div key={i} id={anchorId(block.anchor)} className={WIDTH}><Block block={block} index={i} company={company.code} slug={page.slug} preview={preview} /></div>)}
</div>
</main>
</div>
@@ -1,19 +1,25 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { FRAME_SANDBOX, nextFrameHeight, START_HEIGHT, type FrameHeight } from "@/app/lib/frameHtml";
import { FRAME_SANDBOX, frameAnchor, 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 }) {
/** A Custom HTML block: the sealed frame, sized by height reports and scrolled to by #name requests from that frame's own window only. */
export function HtmlFrame({ id, src, title }: { id?: string; 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));
const frame = ref.current;
if (!frame || e.source !== frame.contentWindow) return;
const anchor = frameAnchor(e.data);
if (!anchor) return setSize((s) => nextFrameHeight(s, e.data));
// add-page-anchor-links: the frame's own target first, else a named block of this page.
if (anchor.y !== null) return window.scrollTo({ top: frame.getBoundingClientRect().top + window.scrollY + anchor.y, behavior: "smooth" });
const block = document.getElementById(anchor.name);
if (block?.closest("main")) block.scrollIntoView({ behavior: "smooth" });
};
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` }} />;
return <iframe ref={ref} id={id} src={src} title={title} sandbox={FRAME_SANDBOX} loading="lazy" className="block w-full border-0" style={{ height: `${size.height}px` }} />;
}
@@ -0,0 +1,59 @@
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-page-anchor-links: each block's optional link name, the target of #name links.
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>", anchor: "story" }, { type: "RICH_TEXT" as const, html: "<p>Hi</p>" }],
};
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: link names", () => {
it("shows and saves each block's link name, dropping a blank one", async () => {
const user = userEvent.setup();
render(<PageEditor pageId={5} />);
const [first, second] = await screen.findAllByLabelText("Link name (optional)");
expect(first).toHaveValue("story");
expect(screen.getAllByText(/Link to this block with #name/)).toHaveLength(2);
await user.clear(first);
await user.type(second, "signup");
await user.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(mocks.savePage).toHaveBeenCalled());
expect(mocks.savePage.mock.calls[0][1].blocks).toEqual([{ type: "HTML", html: "<h1>Designed</h1>" }, { type: "RICH_TEXT", html: "<p>Hi</p>", anchor: "signup" }]);
});
it("shows a refused link name at its field", async () => {
mocks.savePage.mockRejectedValue(new ApiError("x", 422, { code: "PagesAnchorTaken", details: { field: "blocks[1].anchor" } }));
const user = userEvent.setup();
render(<PageEditor pageId={5} />);
const second = (await screen.findAllByLabelText("Link name (optional)"))[1];
await user.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByText("Another block on this page already has this link name.")).toBeInTheDocument();
expect(second.closest("div")).toHaveTextContent("Another block on this page already has this link name.");
expect(second).toHaveAttribute("aria-invalid", "true");
});
});
@@ -79,8 +79,8 @@ describe("PageEditor", () => {
await screen.findByLabelText("Event");
await user.click(screen.getByRole("button", { name: "Save" }));
const link = screen.getAllByLabelText("Button link")[0];
expect(await screen.findByText("Use a link that starts with https://, mailto:, tel: or /.")).toBeInTheDocument();
expect(link.closest("div")).toHaveTextContent("Use a link that starts with https://, mailto:, tel: or /.");
expect(await screen.findByText("Use a link that starts with https://, mailto:, tel:, / or #.")).toBeInTheDocument();
expect(link.closest("div")).toHaveTextContent("Use a link that starts with https://, mailto:, tel:, / or #.");
});
it("uploads a chosen image on save and puts its id on the block", async () => {
@@ -7,10 +7,11 @@ import TextAlign from "@tiptap/extension-text-align";
import { AlignCenter, AlignLeft, AlignRight, Bold, Eraser, Italic, Link as LinkIcon, List, ListOrdered, Minus, Quote, Strikethrough, Underline } from "lucide-react";
import { Button } from "@/app/components/ui/button";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { isSafeLink } from "@/app/lib/cmsPages";
// Ported from babyboo's RichTextEditor, trimmed for landing pages: no YouTube, tables, inline images, emoji,
// colour or HTML source view. The public page sanitises the HTML again with an allow-list.
const SAFE_LINK = /^(https:\/\/|mailto:|tel:|\/(?!\/))/i;
// Links follow the page rule in cmsPages (isSafeLink), the same one services-counter applies to buttons.
const htmlOf = (editor: Editor) => (editor.isEmpty ? "" : editor.getHTML());
@@ -32,7 +33,7 @@ export function RichTextEditor({ id, label, value, onChange, disabled, invalid }
StarterKit.configure({
heading: { levels: [2, 3] },
trailingNode: false,
link: { openOnClick: false, protocols: ["https", "mailto", "tel"], isAllowedUri: (url) => SAFE_LINK.test(url) },
link: { openOnClick: false, protocols: ["https", "mailto", "tel"], isAllowedUri: (url) => isSafeLink(url) },
}),
TextAlign.configure({ types: ["heading", "paragraph"], alignments: ["left", "center", "right"] }),
],
@@ -75,7 +76,7 @@ export function RichTextEditor({ id, label, value, onChange, disabled, invalid }
function addLink() {
const url = window.prompt(t("PagesLinkPrompt"));
if (!url || !SAFE_LINK.test(url)) return;
if (!url || !isSafeLink(url)) return;
run((e) => e.chain().focus().extendMarkRange("link").setLink({ href: url }).run());
}
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
import { contrastText, emptyPage, isSafeLink, pageBody, slugify, withTitle } from "./cmsPages";
import { anchorId, contrastText, emptyPage, isSafeLink, pageBody, slugify, withTitle } from "./cmsPages";
describe("cmsPages helpers", () => {
it("slug follows the title until edited", () => {
@@ -29,4 +29,11 @@ describe("cmsPages helpers", () => {
for (const ok of ["/p/INS/a", "https://x.com", "mailto:a@b.c", "tel:+60123"]) expect(isSafeLink(ok), ok).toBe(true);
for (const bad of ["//evil.com", "javascript:alert(1)", "http://x.com", "https://a b", "/\\evil", undefined]) expect(isSafeLink(bad), String(bad)).toBe(false);
});
it("a same-page link is # plus a block link name", () => {
for (const ok of ["#signup", "#top", "#2-rooms", "#" + "a".repeat(40)]) expect(isSafeLink(ok), ok).toBe(true);
for (const bad of ["#", "#Sign Up", "#-x", "#signup/x", "#a\"b", "#" + "a".repeat(41), "#reg-consent"]) expect(isSafeLink(bad), bad).toBe(false);
expect(anchorId("signup")).toBe("signup");
for (const bad of [undefined, "", "Sign Up", "x\" onclick=\"y", "reg-email"]) expect(anchorId(bad), String(bad)).toBeUndefined();
});
});
+10 -1
View File
@@ -29,6 +29,8 @@ export interface CmsBlock {
html?: string;
imagePosition?: "LEFT" | "RIGHT";
items?: CmsFaqItem[];
/** Optional link name: the block's id on the page, the target of a #name link (add-page-anchor-links). */
anchor?: string;
/** The FORM block's event (a Snowflake uuid, kept as a string). */
eventUuid?: string | null;
}
@@ -131,9 +133,16 @@ export function contrastText(hex: string): "#000000" | "#FFFFFF" {
return (lum + 0.05) / 0.05 > 1.05 / (lum + 0.05) ? "#000000" : "#FFFFFF";
}
/** The counter's link rule: same-site path, https, mailto or tel. Checked again before rendering a button. */
/** A block link name, as services-counter checks it. "reg-" is reserved: the sign-up form's fields use it as ids. */
export const ANCHOR = /^(?!reg-)[a-z0-9][a-z0-9-]{0,39}$/;
/** The link name when it is valid, for use as an element id. */
export const anchorId = (name: string | undefined) => (name && ANCHOR.test(name) ? name : undefined);
/** The counter's link rule: same-site path, https, mailto, tel or #name. Checked again before rendering a button. */
export function isSafeLink(url: string | undefined): boolean {
if (!url || url.length > 1000 || /[\s\\\u0000-\u001f]/.test(url)) return false;
if (url.startsWith("#")) return ANCHOR.test(url.slice(1));
if (url.startsWith("/")) return !url.startsWith("//");
return /^(https:\/\/|mailto:|tel:)/i.test(url);
}
@@ -0,0 +1,39 @@
// @vitest-environment jsdom
import { describe, it, expect, vi, afterEach } from "vitest";
import { frameDocument } from "./frameHtml";
// add-page-anchor-links: the injected frame script turns clicks on #name links into requests to the page.
function runFrameScript(body: string) {
document.body.innerHTML = body;
const code = frameDocument("").match(/<script>([\s\S]*)<\/script>/)![1];
new Function(code)();
}
afterEach(() => vi.restoreAllMocks());
describe("frame script: same-page links", () => {
it("asks the page to scroll, with the in-frame target's offset when the frame has it, and never navigates the frame", () => {
const post = vi.spyOn(window.parent, "postMessage").mockImplementation(() => {});
runFrameScript('<div id="top">Top</div><a href="#top">Back</a><a href="#signup"><span>Join</span></a>');
const back = new MouseEvent("click", { bubbles: true, cancelable: true });
document.querySelector('a[href="#top"]')!.dispatchEvent(back);
expect(back.defaultPrevented).toBe(true);
expect(post).toHaveBeenCalledWith({ type: "colite-frame-anchor", name: "top", y: 0 }, "*");
const join = new MouseEvent("click", { bubbles: true, cancelable: true });
document.querySelector("span")!.dispatchEvent(join);
expect(join.defaultPrevented).toBe(true);
expect(post).toHaveBeenCalledWith({ type: "colite-frame-anchor", name: "signup", y: null }, "*");
});
it("leaves other links alone", () => {
const post = vi.spyOn(window.parent, "postMessage").mockImplementation(() => {});
runFrameScript('<a href="https://wa.me/1">WA</a><a href="#Bad Name">Bad</a>');
post.mockClear();
for (const a of document.querySelectorAll("a")) {
const click = new MouseEvent("click", { bubbles: true, cancelable: true });
a.dispatchEvent(click);
expect(click.defaultPrevented).toBe(false);
}
expect(post.mock.calls.filter(([d]) => (d as { type: string }).type === "colite-frame-anchor")).toHaveLength(0);
});
});
+12 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
import { FRAME_SANDBOX, frameDocument, frameResponse, nextFrameHeight, START_HEIGHT } from "./frameHtml";
import { FRAME_SANDBOX, frameAnchor, 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", () => {
@@ -54,4 +54,15 @@ describe("frameHtml", () => {
for (const h of [900, 1250, 1900, 2000, 2600]) t = nextFrameHeight(t, { type: "colite-frame-height", height: h });
expect(t.height).toBe(2600);
});
// add-page-anchor-links: a frame asks its page to scroll to a #name target.
it("reads a same-page link request: a valid name and the in-frame offset, or nothing", () => {
expect(frameAnchor({ type: "colite-frame-anchor", name: "signup", y: null })).toEqual({ name: "signup", y: null });
expect(frameAnchor({ type: "colite-frame-anchor", name: "top", y: 120.4 })).toEqual({ name: "top", y: 120 });
expect(frameAnchor({ type: "colite-frame-anchor", name: "top", y: -5 })).toEqual({ name: "top", y: 0 });
for (const junk of [null, "x", { type: "colite-frame-height", height: 5 }, { type: "colite-frame-anchor", name: "Sign Up", y: null }, { type: "colite-frame-anchor", name: "reg-email", y: null },
{ type: "colite-frame-anchor", name: "a", y: "1" }, { type: "colite-frame-anchor", name: "a", y: Infinity }, { type: "colite-frame-anchor", y: null }]) {
expect(frameAnchor(junk), JSON.stringify(junk)).toBeNull();
}
});
});
+24 -6
View File
@@ -10,15 +10,24 @@ 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>`;
export const FRAME_ANCHOR_MESSAGE = "colite-frame-anchor";
/** A block link name, as in cmsPages (kept here as a string for the frame script). */
const ANCHOR_SOURCE = "^(?!reg-)[a-z0-9][a-z0-9-]{0,39}$";
const ANCHOR = new RegExp(ANCHOR_SOURCE);
/** The pasted HTML with the height script before its last </body>, or appended when it is a fragment. */
// Posts the document height to the parent page on load and whenever it changes. A click on a #name link
// (add-page-anchor-links) asks the page to scroll instead: the frame is as tall as its content and never scrolls.
const FRAME_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();` +
`document.addEventListener("click",function(e){var a=e.target&&e.target.closest&&e.target.closest('a[href^="#"]');if(!a)return;` +
`var n=a.getAttribute("href").slice(1);if(!/${ANCHOR_SOURCE}/.test(n))return;e.preventDefault();var t=document.getElementById(n);` +
`parent.postMessage({type:"${FRAME_ANCHOR_MESSAGE}",name:n,y:t?Math.round(t.getBoundingClientRect().top+scrollY):null},"*")})})();</script>`;
/** The pasted HTML with the frame 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);
return at < 0 ? html + FRAME_SCRIPT : html.slice(0, at) + FRAME_SCRIPT + html.slice(at);
}
export function frameResponse(html: string, { preview }: { preview: boolean }): Response {
@@ -65,3 +74,12 @@ export function nextFrameHeight(state: FrameHeight, data: unknown): FrameHeight
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) };
}
/** A same-page link request from a frame: a valid link name and the target's offset in the frame (null when the frame lacks it). Junk is null. */
export function frameAnchor(data: unknown): { name: string; y: number | null } | null {
const d = data as { type?: unknown; name?: unknown; y?: unknown } | null;
if (!d || typeof d !== "object" || d.type !== FRAME_ANCHOR_MESSAGE || typeof d.name !== "string" || !ANCHOR.test(d.name)) return null;
if (d.y === null) return { name: d.name, y: null };
if (typeof d.y !== "number" || !Number.isFinite(d.y)) return null;
return { name: d.name, y: Math.min(MAX_HEIGHT, Math.max(0, Math.round(d.y))) };
}
@@ -815,7 +815,7 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
PagesQuote: "Quote",
PagesDivider: "Divider",
PagesLink: "Link",
PagesLinkPrompt: "Link address (https://, mailto:, tel: or /)",
PagesLinkPrompt: "Link address (https://, mailto:, tel:, / or #name)",
PagesClearFormatting: "Clear formatting",
// Server refusals (the code is the message key; the field says where it shows)
PagesTooManyBlocks: "A page can have at most 30 blocks.",
@@ -825,7 +825,11 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
PagesBadImagePosition: "Choose left or right.",
PagesFaqCount: "Add between 1 and 30 questions.",
PagesButtonPair: "Fill in both the button label and the button link, or neither.",
PagesBadLink: "Use a link that starts with https://, mailto:, tel: or /.",
PagesBadLink: "Use a link that starts with https://, mailto:, tel:, / or #.",
PagesAnchor: "Link name (optional)",
PagesAnchorHint: "Link to this block with #name, for example #signup. Lowercase letters, digits and - only.",
PagesBadAnchor: "Use lowercase letters, digits and - (up to 40), starting with a letter or digit and not with reg-.",
PagesAnchorTaken: "Another block on this page already has this link name.",
PagesScript: "Scripts and event handlers are not allowed.",
PagesBadImage: "Upload the image again.",
PagesBadEvent: "Choose one of this company's events.",
@@ -800,7 +800,7 @@
"PagesQuote": "引用",
"PagesDivider": "分隔线",
"PagesLink": "链接",
"PagesLinkPrompt": "链接地址(https://、mailto:、tel: 或 /)",
"PagesLinkPrompt": "链接地址(https://、mailto:、tel:、/ 或 #名称)",
"PagesClearFormatting": "清除格式",
"PagesTooManyBlocks": "每个网页最多 30 个区块。",
"PagesUnknownType": "不支持此区块类型。",
@@ -809,7 +809,11 @@
"PagesBadImagePosition": "请选择左或右。",
"PagesFaqCount": "请添加 1 至 30 个问题。",
"PagesButtonPair": "按钮文字和按钮链接需同时填写或同时留空。",
"PagesBadLink": "链接须以 https://、mailto:、tel: 或 / 开头。",
"PagesBadLink": "链接须以 https://、mailto:、tel:、/ 或 # 开头。",
"PagesAnchor": "链接名称(可选)",
"PagesAnchorHint": "用 #名称 链接到此区块,例如 #signup。仅限小写字母、数字和 -。",
"PagesBadAnchor": "请使用小写字母、数字和 -(最多 40 个),以字母或数字开头,且不能以 reg- 开头。",
"PagesAnchorTaken": "本页已有其他区块使用此链接名称。",
"PagesScript": "不允许使用脚本或事件处理程序。",
"PagesBadImage": "请重新上传图片。",
"PagesBadEvent": "请选择本公司的活动。",
@@ -23,5 +23,6 @@ describe("sanitizePageHtml (landing-page rich text allow-list)", () => {
expect(sanitizePageHtml('<a href="tel:+60123">t</a>')).toContain('href="tel:+60123"');
expect(sanitizePageHtml('<a href="/p/INS/x">s</a>')).toContain('href="/p/INS/x"');
expect(sanitizePageHtml('<a href="http://plain.com">h</a>')).not.toContain("plain.com");
expect(sanitizePageHtml('<a href="#signup">j</a>')).toBe('<a href="#signup">j</a>');
});
});
@@ -25,6 +25,8 @@ public class CmsBlock {
private String imagePosition;
private String buttonLabel;
private String buttonUrl;
/** Optional link name: the block's id on the public page, the target of a #name link (add-page-anchor-links). */
private String anchor;
private List<CmsFaqItem> items;
/** A Snowflake value beyond JavaScript number precision: written as a string, read from either. */
@JsonSerialize(using = ToStringSerializer.class)
@@ -5,7 +5,9 @@ import com.solvway.services.counter.dto.CmsFaqItem;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.LongPredicate;
import java.util.regex.Pattern;
@@ -18,6 +20,8 @@ import java.util.regex.Pattern;
*/
public final class CmsBlockValidator {
private static final int MAX_BLOCKS = 30;
/** A block link name (add-page-anchor-links); a same-page link is "#" plus one. "reg-" is the sign-up form's own ids. */
static final Pattern ANCHOR = Pattern.compile("(?!reg-)[a-z0-9][a-z0-9-]{0,39}");
private static final Pattern SCRIPT = Pattern.compile("(?i)<\\s*script|\\son[a-z]+\\s*=|javascript\\s*:");
private CmsBlockValidator() {
@@ -30,12 +34,22 @@ public final class CmsBlockValidator {
if (blocks.size() > MAX_BLOCKS) {
throw refuse("blocks", "PagesTooManyBlocks");
}
Set<String> anchors = new HashSet<>();
for (int i = 0; i < blocks.size(); i++) {
CmsBlock b = blocks.get(i);
String path = "blocks[" + i + "]";
if (b == null || b.getType() == null) {
throw refuse(path + ".type", "PagesUnknownType");
}
String anchor = b.getAnchor();
if (anchor != null && !anchor.isEmpty()) {
if (!ANCHOR.matcher(anchor).matches()) {
throw refuse(path + ".anchor", "PagesBadAnchor");
}
if (!anchors.add(anchor)) {
throw refuse(path + ".anchor", "PagesAnchorTaken");
}
}
switch (b.getType()) {
case "HERO" -> {
image(b, path, ownImage);
@@ -132,13 +146,16 @@ public final class CmsBlockValidator {
}
/**
* A same-site path, https, mailto or tel link, at most 1000 characters. Browsers turn "\" into "/" and drop
* A same-site path, https, mailto or tel link, or "#" plus a block link name; at most 1000 characters. Browsers turn "\" into "/" and drop
* whitespace inside URLs, so "/\evil" would become protocol-relative: such characters are refused outright.
*/
static boolean safeLink(String url) {
if (url.length() > 1000 || url.chars().anyMatch(c -> c == '\\' || c <= 0x20 || c == 0x7f || Character.isSpaceChar(c) || c == 0xFEFF)) {
return false;
}
if (url.startsWith("#")) {
return ANCHOR.matcher(url.substring(1)).matches();
}
if (url.startsWith("//")) {
return false;
}
@@ -166,4 +166,39 @@ class CmsBlockValidatorTest {
refused(List.of(custom("x".repeat(200_001))), "blocks[0].html", "PagesTooLong");
refused(List.of(custom(" ")), "blocks[0].html", "PagesRequired");
}
@Test
void buttonsMayLinkToANamedBlockOnTheSamePage() {
for (String good : List.of("#signup", "#top", "#a", "#2-rooms")) {
CmsBlock b = hero();
b.setButtonLabel("Go");
b.setButtonUrl(good);
assertThatCode(() -> validate(List.of(b))).as(good).doesNotThrowAnyException();
}
for (String bad : List.of("#", "#Sign Up", "#-x", "#signup/x", "#" + "a".repeat(41), "#reg-consent")) {
CmsBlock b = hero();
b.setButtonLabel("Go");
b.setButtonUrl(bad);
refused(List.of(b), "blocks[0].buttonUrl", "PagesBadLink");
}
}
@Test
void linkNamesFollowThePatternAndAreUniqueOnThePage() {
CmsBlock named = form(OWN_EVENT);
named.setAnchor("signup");
CmsBlock other = rich("<p>x</p>");
other.setAnchor("a".repeat(40));
CmsBlock blank = rich("<p>y</p>");
blank.setAnchor("");
assertThatCode(() -> validate(List.of(hero(), named, other, blank))).as("a blank name is no name").doesNotThrowAnyException();
for (String bad : List.of("Sign Up", "-x", " x", "a".repeat(41), "sign_up", "reg-email")) {
CmsBlock b = rich("<p>x</p>");
b.setAnchor(bad);
refused(List.of(b), "blocks[0].anchor", "PagesBadAnchor");
}
CmsBlock again = custom("<p>x</p>");
again.setAnchor("signup");
refused(List.of(named, again), "blocks[1].anchor", "PagesAnchorTaken");
}
}