diff --git a/.agents/skills/formweb-harness/SKILL.md b/.agents/skills/formweb-harness/SKILL.md index 157868a7..fe25e017 100644 --- a/.agents/skills/formweb-harness/SKILL.md +++ b/.agents/skills/formweb-harness/SKILL.md @@ -5,7 +5,7 @@ license: Apache-2.0 compatibility: "Project skill for Claude Code and other clients with the FormWeb MCP server connected. Requires a running local FormWeb FastAPI service and explicit Agents enablement." metadata: author: "nodemode-ai" - version: "0.34.0" + version: "0.36.0" --- # FormWeb Harness diff --git a/.claude/skills/formweb-harness/SKILL.md b/.claude/skills/formweb-harness/SKILL.md index 157868a7..fe25e017 100644 --- a/.claude/skills/formweb-harness/SKILL.md +++ b/.claude/skills/formweb-harness/SKILL.md @@ -5,7 +5,7 @@ license: Apache-2.0 compatibility: "Project skill for Claude Code and other clients with the FormWeb MCP server connected. Requires a running local FormWeb FastAPI service and explicit Agents enablement." metadata: author: "nodemode-ai" - version: "0.34.0" + version: "0.36.0" --- # FormWeb Harness diff --git a/.docs/wiki/Architecture.md b/.docs/wiki/Architecture.md index 0a4f7c81..67e2f790 100644 --- a/.docs/wiki/Architecture.md +++ b/.docs/wiki/Architecture.md @@ -14,7 +14,7 @@ The Rust engine is the single owner of site state. The editor, MCP tools and HTT | Agent substrate | `backend/app/substrate.py` | One command surface (catalogue, dispatch, attributed events) behind REST, MCP, `./formweb run` and the terminal; approvals; the external-substrate adapter | | Live terminal | `backend/app/terminal.py`, `frontend/src/features/terminal.ts` | Pseudo-terminal in the FormWeb folder over a loopback WebSocket, opened only by the FormWeb window, while Agents is on | | GPU renderer | `native/crates/formweb-render/` | Family wgpu renderer (own workspace and lockfile): area-averaged thumbnails, minimap with a viewport outline, release pixel diffs, a CPU path with identical results, `./formweb render` | -| Desktop shell | `src-tauri/` | Tauri 2 window around the editor on 127.0.0.1:8240; adopts a service there only when its `/api/health` reply names `formweb` and this version, otherwise starts `./formweb serve` (on the first free port from 8241 to 8279 if something else holds 8240) and stops it on exit; one running copy per login (`tauri-plugin-single-instance`), which opens a `.fweb` or `.fpub` handed to it; exposes the renderer as `render_probe`, `render_thumbnail` and `render_diff`; handles every download (the web views save to Downloads without a prompt on all three systems; WebKitGTK picks the folder itself and, with no Downloads entry in `~/.config/user-dirs.dirs`, saves into the working folder, so the shell moves such a file to `~/Downloads`), sends every link that opens a new window to the system browser through `on_new_window` (it loads no shell plugin, whose page script would catch those links first), tells the page where each was saved with a `formweb-download` event and shows the last one in the file manager through `reveal_download`; `./formweb desktop`; builds and runs on Linux with WebKitGTK (see the manual's Desktop shell on Linux) | +| Desktop shell | `src-tauri/` | Tauri 2 window around the editor on 127.0.0.1:8240; adopts a service there only when its `/api/health` reply names `formweb` and this version, otherwise starts `./formweb serve` (on the first free port from 8241 to 8279 if something else holds 8240) and stops it on exit; one running copy per login (`tauri-plugin-single-instance`), which opens a `.fweb` or `.fpub` handed to it; exposes the renderer as `render_probe`, `render_thumbnail` and `render_diff`; handles every download (the web views save to Downloads without a prompt on all three systems; WebKitGTK picks the folder itself and, with no Downloads entry in `~/.config/user-dirs.dirs`, saves into the working folder, so the shell moves such a file to `~/Downloads`; since 0.35.0 `downloads.rs` sets the destination in `DownloadEvent::Requested` from the person's choice, Downloads, a folder recorded only by its own folder dialog in `export-folder.json` in the app config folder, or the answer of a save dialog opened before the download, with a cleaned name, " (1)" numbering and a Downloads fallback named in the event's `unusable`, through the commands `set_export_place`, `choose_export_folder` and `ask_export_place`), sends every link that opens a new window to the system browser through `on_new_window` (it loads no shell plugin, whose page script would catch those links first), tells the page where each was saved with a `formweb-download` event and shows the last one in the file manager through `reveal_download`; `./formweb desktop`; builds and runs on Linux with WebKitGTK (see the manual's Desktop shell on Linux) | | Agent Connect | `frontend/src/features/agent-connect.ts`, `backend/app/clients.py` | MCP switch, client cards, approvals, identity and the attributed activity feed | | Agent dock | `frontend/src/features/terminal.ts`, `chat-pane.ts`, `backend/app/claude_code.py`, `chat.py` | Session tabs, in-app Claude Code and streamed Chat, both launched with an in-app MCP token | | Command registry | `frontend/src/commands/`, `backend/app/commands_mirror.py` | One list of commands behind menus, buttons, shortcuts, search and agents | @@ -63,7 +63,9 @@ New features are modules at the existing layer seams. Read `frontend/HASHOUT_LOG **Design field controls (0.33.0).** `features/inspector/controls/` puts a control beside a style field made by `addStyle()` in `main.ts`, by CSS key, without owning its value: the text input stays visible and is the one stored value, and a control writes through `field.commit()`, which goes through the same `setStyle()` as typing (breakpoint scope, undo, brand check). `index.ts` is the kit: `registerControl(keys, factory)`, `installControls()` (called once after the inspector is built), three slots per field (`lead`, `trail`, `below`, mounted once; a field's state is `data-ctl` `off`, `on` or `raw` and never changes its height), the raw CSS switch in each label, and the default in `localStorage['formweb.design-controls']`, never in the site. `slider.ts` with the fixed range table in `number.ts`, `color.ts` with one picker popover in `color-picker.ts` (`color-area.ts`, `color-math.ts`), the picker's Gradient tab in `gradient.ts` and `gradient-model.ts` through `registerPickerTab`, and `grid.ts` with `grid-tracks.ts`. Controls that use plain keys carry `data-own-keys`, which `commands/keymap.ts` reads to leave plain keys to them while still running Ctrl/Cmd shortcuts. `view.design-controls` (View > Show controls in Design fields) flips the default. `frontend/HASHOUT_LOG.md` (0.33.0) has the contract and the traps. -**Try a choice (0.34.0).** A trial is canvas-only: no engine command, no `/api` call and no stored value changes until Keep. `ui/canvas.ts` `Canvas.setLayer(name, frame)` draws two named layers over the stored styles, `play` then `trial` (after the scene scrubber's motion frame; later wins), restyling only the named properties of the named nodes and never calling `render()`; a `null` value shows what the element inherits at the picked breakpoint. `features/try/` holds the contract (`types.ts`) and the kit (`index.ts`, `installTry()`, called once from `main.ts` before `installControls`): one trial at most, `begin(owner)`, `put`, `keep` (one `setStyle`, one undo step), `revert`, and `sync()` from `update()`, which drops a trial when the selection, breakpoint or page changes, design is left, or another writer changes the same property. `bar.ts` is the one Keep and Revert bar in `#overlay-root`; `segments.ts` takes over the Design segment groups with a capture-phase click; `choice-list.ts` opens one `listbox` popover for the eight `select[data-style]` fields while the select keeps the stored value. `commands/registry.ts` asks `Commands.intercept` before every `run()` and `call()`: a command reverts a trial first, a person's Undo during a trial is used up, and an agent's call always runs. The control kit hands drag values to the canvas through its `trial` option (`live`, `settled`). `features/motion/play.ts` plays a motion preset once through the `play` layer, frame by frame in the editor, with nothing added to the canvas document. `view.try-choices` and Preferences > Interface > Design fields turn trying off, stored only in `localStorage['formweb.try-choices']`. `frontend/HASHOUT_LOG.md` (0.34.0) has every way a trial ends and the traps. +**Try a choice (0.34.0).** A trial is canvas-only: no engine command, no `/api` call and no stored value changes until Keep. `ui/canvas.ts` `Canvas.setLayer(name, frame)` draws two named layers over the stored styles, `play` then `trial` (after the scene scrubber's motion frame; later wins), restyling only the named properties of the named nodes and never calling `render()`; a `null` value shows what the element inherits at the picked breakpoint. `features/try/` holds the contract (`types.ts`) and the kit (`index.ts`, `installTry()`, called once from `main.ts` before `installControls`): one trial at most, `begin(owner)`, `put`, `keep` (one `setStyle`, one undo step), `revert`, and `sync()` from `update()`, which drops a trial when the selection, breakpoint or page changes, design is left, or another writer changes the same property. `bar.ts` is the one Keep and Revert bar in `#overlay-root`; `segments.ts` takes over the Design segment groups with a capture-phase click; `choice-list.ts` opens one `listbox` popover for the eight `select[data-style]` fields while the select keeps the stored value. `commands/registry.ts` asks `Commands.intercept` before every `run()` and `call()`: a command reverts a trial first, a person's Undo during a trial is used up, and an agent's call always runs. Since 0.35.0 focus moving into the menu bar or one of its menus parks a trial instead of ending it: a command in the kit's `PASS` set keeps it and focus returns to the trial's control, `edit.undo` reverts it and is used up, any other command reverts it first; `choice-list.ts` leaves an open list alone while a trial is on and the press is in the menus. The control kit hands drag values to the canvas through its `trial` option (`live`, `settled`). `features/motion/play.ts` plays a motion preset once through the `play` layer, frame by frame in the editor, with nothing added to the canvas document. `view.try-choices` and Preferences > Interface > Design fields turn trying off, stored only in `localStorage['formweb.try-choices']`. `frontend/HASHOUT_LOG.md` (0.34.0) has every way a trial ends and the traps. + +**Audit markers (0.35.0).** `features/audit-markers.ts` (styles in `styles/audit-markers.css`), installed once from `main.ts`, keeps the last good `/api/audit` answer stamped with the site id and revision it was asked for and filters it by the open page on every `update()`. With the switch on (`view.audit-markers`, View > Show audit markers, and a row in the Audit dialog; `localStorage['formweb.audit-markers']` is `'1'`) one timer asks the audit again after a change: at least 150 ms after it, 600 ms after the last start, never while a request is out; an answer for an older site, revision or page is thrown away, and a failure hides the dots and is not asked again until the revision moves. Dots are pooled buttons in `#overlay-root`, updated with `keyed()`, at most 200, each centred on its element's top right corner through `FrameMap` and hidden (never clamped) when that corner is out of view, placed in at most one animation frame when an event asks and in the same frame on a resize, with all reads before all writes; nothing is added to the canvas document. They carry `data-own-keys`, hide in either preview, during drags, trials and text editing and under a dialog, and move the focus to the active inspector tab or the Audit button before they hide. A click selects the element as the dialog's Select does, with a small list when it has several issues. The command is in the try kit's `PASS` set. `frontend/HASHOUT_LOG.md` (0.35.0) has the rules and the traps. **Touch, pen and Select several.** `features/hold.ts` holds what both drags share for touch: a 350 ms hold with an 8 px slop, `startsDrag` (left button only, and for a pen only `buttons === 1`, so the barrel or eraser button never starts a drag), a permanent non-passive `touchmove` listener on the list and on the canvas document that calls `preventDefault` only while a drag is armed (setting `touch-action` after `touchstart` does not affect the running gesture, so this is what keeps the list or canvas still), a capture `contextmenu` blocker on the top window and the canvas window for the length of a held gesture, and a synthetic `contextmenu` at the release point when a hold ends without moving, so the existing menus open by touch on every platform, including those that never fire `contextmenu` on a long press. `installRowDrag` and `installCanvasDrag` keep the mouse path as it was (4 px and 6 px thresholds, immediate) and run pens through it; a touch press arms a timer instead, and moving past the slop first gives the gesture back to the browser, so it scrolls. When the hold takes, the row gets `is-lifted` or the element `data-fw-lifted` (on the canvas an unselected element is selected first), the drag then follows the finger with pointer capture, and listeners filter by `pointerId`: a `pointerdown` of any other pointer or a `pointercancel` ends it with no command. A touch lift outside the list or the canvas finds no target. `features/select-mode.ts` adds the header toggles (one shared state, `picking()` in `features/selection.ts`, which makes `layerClick`, `pageClick` and `canvasClick` toggle as Ctrl+click does), the count and Done bar laid over the heading's first grid column so nothing moves, the `edit.select-mode` command, Escape on the window, and a capture `dblclick` blocker on the lists and the canvas window while the mode is on; `main.ts` repaints it from `update()`. @@ -78,7 +80,7 @@ New features are modules at the existing layer seams. Read `frontend/HASHOUT_LOG **Site background.** The link between pages is a design token, not a model field, so `.fweb` files stay readable by older engines (FormPublisher's among them) that refuse unknown fields: the site background is the token `--page-background` (stored as `page-background`, a valid token identifier), and a page is on it when its root's `background` is exactly `var(--page-background)`. The exporter already writes every token into `:root` and the other theme's values into `html[data-theme]`, and the canvas already sets the site tokens on its document, so the canvas and the export agree with no Rust change. `page-background.ts` derives everything from the site: `siteBackgroundKey`, `backgroundMode` (site, own), `siteBackgroundPages`, and `pageColorToken`, which offers the token the home page's background already uses (or one named `paper`, `bg`, `background`) on a site without `--page-background`; adopting it stores `page-background: var(--paper)` and `siteBackgroundTarget` then edits `--paper`, so there is one color. The group's three choices are radio inputs; Same as another page and This page only only change which part shows until a value is written. `useSiteBackgroundCommands` sends `token.set` (the first time) and every page's `node.update` in one batch. The other theme's value is written by `otherThemeValueCommand` from `inspector/theme.ts`, the helper the Themes block uses. `startCommands` gives a new page `var(--page-background)` when the token exists. `readableTextPatch` (contrast from `features/contrast.ts`) adds `color: #ffffff` to a root with no text color when its new background needs light text, and removes exactly that value when a light background or no background follows, inside the same `node.update`. It judges only an opaque hex color after tokens are resolved (a gradient, an image or a see-through color leaves the text alone), and it never runs on a site with themes, where one fixed text color cannot suit both themes. A new page started on a dark site background gets the white text in its first batch. The editor shows each change in a notice whose Undo sends the root's earlier `color` back as a step of its own, so the background stays. Nothing runs on load. A `--page-background` token whose value, resolved, is neither a `background-color` nor a `background-image` (`siteBackgroundTaken`) belongs to the site for something else: `siteBackgroundKey` then reports no site background, so new pages start white, and every path that would create or set it refuses with the reason instead of overwriting it. Commands: `page.background-site {color?}`, `page.background-site-all`, `page.background-site-color {color, theme?}`, `page.background-site-theme`. **Starter styles.** `frontend/src/features/starter-elements.ts` holds the styles `insertElement` in `main.ts` gives new elements: no fill on Section, Grid cards, Form fields or Embed, translucent grey lines (`LINE` and `MUTED` from `features/sections.ts`, the built-in sections' own neutrals), text that inherits the page color, and filled buttons whose text color `inkOn` picks against the resolved `--accent`. Sections, starter pages and library sections are not touched. The engine's `a11y.contrast` audit rule walks up the ancestors for both the text color and the background, so it does see inherited backgrounds, but it checks only when some element on that path sets a `color` it can parse: it does not assume the browser's default black text (or white page), and it does not read `var(--x, fallback)`, so black text on a dark section with no colour set anywhere is not reported. -**Inspector search.** `frontend/src/features/inspector/search.ts` indexes the mounted inspector instead of keeping a field list: every `.inspector-section` (its `data-section` id and title) in the four tab panes, and in each the `.field`, `.checkbox-field` and direct buttons with their visible label, the CSS property from `data-style` or `data-field` (attribute fields carry `data-attr`) and the synonym groups in `search-terms.ts`. Anything under a `hidden` ancestor is left out, so a control the inspector hides for the selection never shows; a disabled control is listed as unavailable. A MutationObserver on the panes only marks the index stale; it is rebuilt on the next keystroke or, while results are open, once per frame. The list is a `keyed()` list in a sibling of `.inspector-scroll`; the two swap with `hidden`, so the panes keep their state and scroll position. The command is `inspector.search`. +**Inspector search.** `frontend/src/features/inspector/search.ts` indexes the mounted inspector instead of keeping a field list: every `.inspector-section` (its `data-section` id and title) in the four tab panes, and in each the `.field`, `.checkbox-field` and direct buttons with their visible label, the CSS property from `data-style` or `data-field` (attribute fields carry `data-attr`) and the synonym groups in `search-terms.ts`. Since 0.35.0 it also indexes choices: each `.fw-seg-btn` of a segment group, each option of a `select[data-style]` but the empty Inherit one, and segment groups outside any field (Motion presets, named by a `.field-label` just before them); a choice matches only by its own name or value. The list is text only: each `role="listitem"` row reads "{name} · {tab} > {section}" (a choice adds " > {field}"), and nothing in the module switches a tab, unfolds a section, scrolls, focuses a control or marks one; a click, Enter and the arrows do nothing, a mousedown in the results is prevented so focus stays in the box, and Escape on an empty box moves focus to the active tab button. Bounds: 4,000 entries, 64 choices per group or select, names and the query at most 120 characters, 120 rows shown. Anything under a `hidden` ancestor is left out, so a control the inspector hides for the selection never shows; a disabled control is listed as unavailable. A MutationObserver on the panes only marks the index stale; it is rebuilt on the next keystroke or, while results are open, once per frame. The list is a `keyed()` list in a sibling of `.inspector-scroll`; the two swap with `hidden`, so the panes keep their state and scroll position. The command is `inspector.search`. **Frozen desktop engine.** `./build_app` builds the editor and Rust core, freezes `backend/formweb_engine.py` with PyInstaller (`setup/freeze_backend`, `requirements_desktop.txt`) and runs the Tauri build. Inside the bundle (`config.FROZEN`) the core binary and editor come from the bundle and data lives in `~/FormWeb` (or `FORMWEB_HOME`); `formweb_engine.py --selfcheck` names anything missing, and the Tauri shell spawns the frozen engine as a sidecar. diff --git a/.docs/wiki/Guide.md b/.docs/wiki/Guide.md index 4b657390..4ff35c67 100644 --- a/.docs/wiki/Guide.md +++ b/.docs/wiki/Guide.md @@ -9,9 +9,9 @@ The user guide teaches FormWeb to a person who has never used it: plain words, n - [The right panel](https://github.com/nodemode-dev/formweb/blob/main/docs/guide/04-right-panel.md): tabs, trying a choice before keeping it, sliders, the color picker and gradients, the grid layout chooser, motion presets, Search properties and breakpoints. - [Page background and theme colors](https://github.com/nodemode-dev/formweb/blob/main/docs/guide/05-background-and-theme-colors.md) - [Preview](https://github.com/nodemode-dev/formweb/blob/main/docs/guide/06-preview.md) -- [Audit](https://github.com/nodemode-dev/formweb/blob/main/docs/guide/07-audit.md) -- [Export and publishing](https://github.com/nodemode-dev/formweb/blob/main/docs/guide/08-export-and-publish.md) -- [Importing](https://github.com/nodemode-dev/formweb/blob/main/docs/guide/09-importing.md) +- [Audit](https://github.com/nodemode-dev/formweb/blob/main/docs/guide/07-audit.md): the audit, Select, and audit markers on the page. +- [Export and publishing](https://github.com/nodemode-dev/formweb/blob/main/docs/guide/08-export-and-publish.md): the zip, and where the desktop app saves exports. +- [Importing](https://github.com/nodemode-dev/formweb/blob/main/docs/guide/09-importing.md): the review names files a page loads from the web; a converted page keeps the style rules its script needs. - [Components and the Library](https://github.com/nodemode-dev/formweb/blob/main/docs/guide/10-components-and-library.md) - [Keyboard shortcuts](https://github.com/nodemode-dev/formweb/blob/main/docs/guide/11-keyboard-shortcuts.md) - [Coming from Dreamweaver or another visual builder](https://github.com/nodemode-dev/formweb/blob/main/docs/guide/12-coming-from-other-builders.md) diff --git a/.docs/wiki/Home.md b/.docs/wiki/Home.md index 7291d3b5..9fa38d76 100644 --- a/.docs/wiki/Home.md +++ b/.docs/wiki/Home.md @@ -2,7 +2,7 @@ FormWeb is the form family's visual website authoring application. A Rust engine owns editable sites and exports browser-native HTML, CSS and JavaScript. A Python/FastAPI service supplies projects, local publications, forms and MCP. A vanilla TypeScript/Vite window displays and changes the same engine state. -Release version: 0.34.0. Author: nodemode-ai. The repository README and changelog record this release. +Release version: 0.36.0. Author: nodemode-ai. The repository README and changelog record this release. | Surface | Current boundary | | --- | --- | diff --git a/.docs/wiki/Library.md b/.docs/wiki/Library.md index 400a1b62..468d19f6 100644 --- a/.docs/wiki/Library.md +++ b/.docs/wiki/Library.md @@ -30,11 +30,15 @@ Placeholders in a template are `$parent`, `@@key@@` for a node id and `{{field}} ## Import site from zip -`backend/app/site_import.py` reads a static site zip in memory with `zipfile` under hard caps (64 MiB; 40,000 entries and a 2 MiB file list checked from the end record before parsing; then 1,000 entries and 12 levels counted only outside the ignored `__MACOSX`, `node_modules` and dot folders; 128 MiB unpacked, an expansion limit, per-type file caps) and refuses traversal, absolute and drive-letter names, links and passwords outright. A project's source (a `package.json` at the top or one folder down, plus one of: no HTML page; `.ts`, `.tsx`, `.jsx`, `.vue` or `.svelte` files under that project's `src` folder; a page loading such a script, holding `%PUBLIC_URL%`, or loading a module script that imports a package by name while no page has an import map) is refused with a sentence that says to build it and import the output folder (`_project`; `_peek` reads names from the file list of an archive refused before it is opened, only to choose that sentence). Both routes also take loose pages as JSON, `{"files": [{"name", "html"}]}`, which `read_files` turns into the same structure as a zip holding them at its top level. The review route plans without changing anything; the import route re-reads the same bytes, refuses a changed revision, stores assets through `ingest` and sends one batch of `page.add`, `page.update`, `node.add` and `code.section.set` (and `node.remove` in replace mode, offered only when no extension entry or component source points into the page). Each page is one code section built with Import HTML's `kit_script`, so the script policy is the same; both paths use `site_import.script_type` to leave out script elements that are not JavaScript (JSON-LD among them) with the same warning. The editor view is `features/library/site-import.ts` (File > Import site from zip..., `file.import-site`, and the review of File > Import HTML files..., `file.import-html`); both commands share its one hidden `multiple` file input, whose `accept` `choose(kind)` sets just before `click()`, after `reset()` has cleared any earlier import, so the picker opens inside the person's click over a clean view. The view has one Bring ... in as choice for pages and a section, its result note at the end of the scroller and work in progress on the import button. Agents use `library_import_site`. +`backend/app/site_import.py` reads a static site zip in memory with `zipfile` under hard caps (64 MiB; 40,000 entries and a 2 MiB file list checked from the end record before parsing; then 1,000 entries and 12 levels counted only outside the ignored `__MACOSX`, `node_modules` and dot folders; 128 MiB unpacked, an expansion limit, per-type file caps) and refuses traversal, absolute and drive-letter names, links and passwords outright. A project's source (a `package.json` at the top or one folder down, plus one of: no HTML page; `.ts`, `.tsx`, `.jsx`, `.vue` or `.svelte` files under that project's `src` folder; a page loading such a script, holding `%PUBLIC_URL%`, or loading a module script that imports a package by name while no page has an import map) is refused with a sentence that says to build it and import the output folder (`_project`; `_peek` reads names from the file list of an archive refused before it is opened, only to choose that sentence). Both routes also take loose pages as JSON, `{"files": [{"name", "html"}]}`, which `read_files` turns into the same structure as a zip holding them at its top level. The review route plans without changing anything; the import route re-reads the same bytes, refuses a changed revision, stores assets through `ingest` and sends one batch of `page.add`, `page.update`, `node.add` and `code.section.set` (and `node.remove` in replace mode, offered only when no extension entry or component source points into the page). Each page is one code section built with Import HTML's `kit_script`, so the script policy is the same; both paths use `site_import.script_type` to leave out script elements that are not JavaScript (JSON-LD among them) with the same warning. The editor view is `features/library/site-import.ts` (File > Import site from zip..., `file.import-site`, and the review of File > Import HTML files..., `file.import-html`); both commands share its one hidden `multiple` file input, whose `accept` `choose(kind)` sets just before `click()`, after `reset()` has cleared any earlier import, so the picker opens inside the person's click over a clean view. The view has one Bring ... in as choice for pages and a section, its result note at the end of the scroller and work in progress on the import button. Since 0.35.0 the review gives each page `outside` and `outsideMore`: the stylesheets and scripts it loads from other hosts as `{kind, host, url}`, read by `outside_file` the way a browser reads a link (no regular expression, bounded), in document order, at most 20; nothing is fetched. `outsideWarnings` holds the indexes of the older outside-script and head-stylesheet warnings that `outside` names in full (every counted reference parsed and `outsideMore` 0), and the view leaves those warnings out of the row. The view names those hosts per page in plain text and starts the Bring choice on Code sections, with the reason, when any page has them (set once when the review arrives). Agents use `library_import_site`. ## Convert to editable elements -`frontend/src/features/convert/` turns a code section into ordinary elements: `rules.ts` (pure: tag and attribute mapping, style reduction against a bare twin, text runs, selector scoping, the result sentence), `measure.ts` (two hidden `sandbox="allow-same-origin"` frames with a `default-src 'none'` policy, one with the section's sanitized HTML and CSS at 1440 px, one with the export's base styles and a bare twin per new element) and `index.ts` (the `library.convert-section` command, its dialog, the canvas and layer menu entry, and one `/api/batch` of `node.add` with chosen ids, retried without any value the engine refuses). Import HTML and Import site from zip offer Editable elements or Code sections (`features/library/bring.ts`); with elements they call the converter through the library hook `convert` after the import. The MCP import tools reach it through the window command bridge with `bring_in: "elements"`. An own-asset background picture sized cover or contain becomes an `img` behind the content (`rules.ts` `backdropLayers`). Limits, losses and the security of the measuring frame: `docs/LIBRARY.md`, Convert to editable elements. +`frontend/src/features/convert/` turns a code section into ordinary elements: `rules.ts` (pure: tag and attribute mapping, style reduction against a bare twin, text runs, selector scoping, the result sentence), `measure.ts` (two hidden `sandbox="allow-same-origin"` frames with a `default-src 'none'` policy, one with the section's sanitized HTML and CSS at 1440 px, one with the export's base styles and a bare twin per new element) and `index.ts` (the `library.convert-section` command, its dialog, the canvas and layer menu entry, and one `/api/batch` of `node.add` with chosen ids, retried without any value the engine refuses). Import HTML and Import site from zip offer Editable elements or Code sections (`features/library/bring.ts`); with elements they call the converter through the library hook `convert` after the import. The MCP import tools reach it through the window command bridge with `bring_in: "elements"`. An own-asset background picture sized cover or contain becomes an `img` behind the content (`rules.ts` `backdropLayers`). Since 0.35.0, with the script kept, `measure.ts` `keepRules` stores the rules no converted element uses (and the class rules the script names) in the script's code section CSS, scoped to the converted root and guarded with `:where(:not([data-fw-node]))`, at most 3,000 rules and 192 KiB, with a 2 s matching bound; `fillWindow` writes heights that followed the window in vh, so a page that filled the window fills the canvas and Preview. Since 0.36.0 `convertSections(ids, keepScript, part, run)` with `run` true first runs the section's script in `sealed.ts` (a hidden `sandbox="allow-scripts"` srcdoc frame with a no-network policy, FormWeb's measuring script first, one checked plain-data message back) and measures the section's own markup with the classes and attributes it had afterwards and its CSS followed by the rules the script produced; everything after that is the 0.35.0 path, and `run` false is unchanged. The site review passes `run` for pages listed in the import's `outside.pages`. Limits, losses and the security of the measuring frames: `docs/LIBRARY.md`, Convert to editable elements. + +## Files from the web (0.36.0) + +`backend/app/outside_fetch.py` downloads one ticked file at a time for the review, through one network seam `connect(host, port, pick, seconds)`: the caller's `pick` holds the every-address-public check and a connection on which `pick` was never called is refused, so a stand-in seam cannot skip it. Guards, limits and the token store (in memory, 30 files and 8 MiB per token, 20 tokens, 20 minutes idle) are listed in `docs/LIBRARY.md`, Import site from zip. Routes `POST /api/library/outside/fetch` and `/outside/drop` in `library_routes.py`; `import-site?...&outside=TOKEN` merges, in `site_import.py`, only kept files the page names. The review (`features/library/site-import.ts`) keeps one map of outside files by URL across pages, sends fetches and drops on one promise chain, and drops the whole token on a new pick, Back, reset or after the import; MCP tools never fetch. ## Page components diff --git a/.docs/wiki/Publishing.md b/.docs/wiki/Publishing.md index 4a7fb303..09e28328 100644 --- a/.docs/wiki/Publishing.md +++ b/.docs/wiki/Publishing.md @@ -28,7 +28,7 @@ FormWeb exports portable HTML/CSS/JavaScript, serves immutable local versions an The Rust exporter creates responsive page output, queried/templated CMS records, locale routes/alternates, metadata and runtime behavior. The Python service validates output paths, bundles stored raster assets, archives exports and hosts publications. Preview uses this compiled output in persistent opaque iframe slots; the old design/runtime remains visible until its replacement loads. Check warnings and desktop/mobile behavior before sharing output. -In the editor, File > Export static site (`file.export`, the toolbar's Export button) and File > Download .fweb project (`file.download`) go through `deliver()` in `frontend/src/ui/downloads.ts`. While the ZIP is fetched the Export button is `disabled` with `aria-busy="true"` (same size, progress pointer, pulsing icon, still with reduced motion) and `file.export` reports itself disabled, so no second export starts. `download()` in `frontend/src/api.ts` attaches its hidden link to the document before the click, keeps the blob URL for 60 seconds, and throws the service's `detail` when the reply is not OK. The result is shown in `ui/notice.ts`, one notice in the overlay root (role `status`, 12 seconds, 30 for an error, paused while hovered or focused): "Downloaded coldmere-site.zip" in a browser; in the desktop shell "Exported coldmere-site.zip to your Downloads folder", then, when the shell's `formweb-download` window event names the path it really wrote, the folder and a Show in folder action (the `reveal_download` command). When it cannot show the file, `reveal_download` answers a code with the file, its folder and the system's reason (`download.none`, `download.moved`, `download.reveal-failed`), never an English sentence, and `shellSentence()` in `ui/downloads.ts` turns it into a translated one. The engine start failures the shell shows in a native dialog before the editor exists stay English, since no editor is there to translate them. A failed export shows its message in the notice and the status line. `GET /api/export` itself is unchanged: same route, `site-export.zip` name and headers, which FormPublisher reads. +In the editor, File > Export static site (`file.export`, the toolbar's Export button) and File > Download .fweb project (`file.download`) go through `deliver()` in `frontend/src/ui/downloads.ts`. While the ZIP is fetched the Export button carries `aria-disabled="true"` and `aria-busy="true"` (same size, progress pointer, pulsing icon, still with reduced motion; not `disabled`, which would drop the focus to the page body) and `file.export` reports itself disabled, so no second export starts. Since 0.35.0 every download of the editor goes through `deliver()` or `deliverFile()` (QR codes, the Website studio, the vector exports with `saveBlob()`), so in the desktop app all of them follow Preferences > General > Where exports are saved (`features/export-folder.ts`, handed to the shell's `set_export_place`); in ask mode the shell's save dialog (`ask_export_place`) opens before the fetch, ask-mode deliveries run one at a time, and a cancel returns null and says "Nothing was saved.". The `formweb-download` event now also carries `unusable` (the chosen folder that could not be used, and the file went to Downloads) and, for a download refused in ask mode, `reason: "not-asked"`. `download()` in `frontend/src/api.ts` attaches its hidden link to the document before the click, keeps the blob URL for 60 seconds, and throws the service's `detail` when the reply is not OK. The result is shown in `ui/notice.ts`, one notice in the overlay root (role `status`, 12 seconds, 30 for an error, paused while hovered or focused): "Downloaded coldmere-site.zip" in a browser; in the desktop shell "Exported coldmere-site.zip to your Downloads folder", then, when the shell's `formweb-download` window event names the path it really wrote, the folder and a Show in folder action (the `reveal_download` command). When it cannot show the file, `reveal_download` answers a code with the file, its folder and the system's reason (`download.none`, `download.moved`, `download.reveal-failed`), never an English sentence, and `shellSentence()` in `ui/downloads.ts` turns it into a translated one. The engine start failures the shell shows in a native dialog before the editor exists stay English, since no editor is there to translate them. A failed export shows its message in the notice and the status line. `GET /api/export` itself is unchanged: same route, `site-export.zip` name and headers, which FormPublisher reads. Local immutable /published/ URLs remain available while the service runs. Promotion changes only the active /sites/ route; rollback selects an earlier version. The seo.redirects map produces a portable manifest and the active local route consumes it. Splat rules are allowed: a path `/x/*` (one star, last segment only, non-empty base) may redirect to a target that uses `/:splat` once. `:splat` needs a splat path. A splat into its own prefix (`/docs/*` to `/docs/:splat`), `/*`, `/a/*/b`, `/a*` and splat cycles are refused. Exact paths win over splats, then the longest splat prefix. `redirects.json` keeps its shape (a map of path to target or {to, status}). Published releases follow splats and never let a splat become a redirect off the site. A page routed at `/404` is also exported as a root `404.html` (its URLs start at the base URL's path, such as `/assets/...` or `/repo/assets/...`, so it works at any missing address; not in the sitemap or routes.json), so static hosts that look for `404.html` find it; sites without a 404 page export as before. A published release answers a missing path with that page and status 404, after the same visitor and password gates as the page itself, and an unpublished preview answers a missing path with it too when the export has one. The served copy sends fragment-only links (the skip link, in-content anchors) to the request's own path so they scroll on the same document. With a base URL unset or example.com, a site with a 404 page gets an export warning and the audit issue seo.base-url-404; the Base URL field's help says that leaving it empty keeps the https://example.com placeholder. Protected member routes require backend authorization, and public static export of gated content is rejected. Page passwords live in the service database (`passwords.py`), so `Studio.publish` passes their routes to the exporter as `passwordRoutes`: the pages at or under those routes stay out of `search-index.json`, and so do the pages under a member gate, which `search::index` reads from the site itself; the index in the publication's folder therefore holds no gated text, whoever later copies that folder to another host. The exporter no longer drops `site.formweb.json` for them: `Studio.publish` is the one place that leaves it out of a local publication, for every site, and `serve_release` refuses it (`PRIVATE_FILES`) for releases written before that. `serve_release` also filters `search-index.json` at request time (`public_search_index`), which covers releases made before a password was set. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 840e4283..4de3b37d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -84,9 +84,9 @@ jobs: working-directory: backend run: python -m pytest tests -q -p no:cacheprovider - window: + window-build: runs-on: ubuntu-latest - timeout-minutes: 45 + timeout-minutes: 7 steps: - name: Apt mirror fallback if: runner.os == 'Linux' @@ -119,9 +119,39 @@ jobs: run: | npm ci npm run build + - name: Pack the engine binary and the window + run: tar -cf window-build.tar native/target/release/formweb-core frontend/dist + - uses: actions/upload-artifact@v4 + with: + name: window-build + path: window-build.tar + retention-days: 1 + + window: + needs: window-build + runs-on: ubuntu-latest + timeout-minutes: 7 + strategy: + fail-fast: false + matrix: + part: [1, 2, 3, 4, 5, 6, 7, 8] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + cache: pip + cache-dependency-path: backend/requirements.txt + - uses: actions/download-artifact@v4 + with: + name: window-build + - name: Unpack the engine binary and the window + run: tar -xf window-build.tar - name: Engine, pytest and Playwright run: | pip install -r backend/requirements.txt pytest==9.1.1 playwright==1.63.0 python -m playwright install --with-deps chromium - - name: Window smoke (F7) - run: python -m pytest frontend/tests/window -q -p no:cacheprovider + - name: Window smoke (F7), part ${{ matrix.part }} of 8 + run: | + files=$(grep -c "def test_" frontend/tests/window/test_*.py | sort -t: -k2,2nr -k1,1 | awk -F: -v k=${{ matrix.part }} 'NR % 8 == k % 8 {print $1}') + python -m pytest $files -q -p no:cacheprovider diff --git a/CHANGELOG.md b/CHANGELOG.md index bd7c7805..27b5f150 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,48 @@ # Changelog +## 0.36.0 · 2026-11-27 + +- The fifth of five releases that answer the follow-up on issue #36: imports that keep their look. +- The import review (Import site from zip and Import HTML files) lists, under each page that loads files from other websites, one row per file with a tick: what it is (Stylesheet, Script or Font file) and its host as plain text. Every tick is off at first, and a sentence above the rows says what a tick does: FormWeb on this computer downloads that file from its host now, and the file becomes part of the site. Nothing is downloaded without a tick. Unticking forgets the file again. +- While a ticked file downloads, its row says "Downloading" in place; once it has arrived, the row shows its size. Nothing else in the review moves. When the download is refused (too large, the wrong kind of file, a host that cannot be reached), the tick goes off and the row says why. Two pages that name the same file share one download and tick together. +- A ticked stylesheet that names font files lists them under it, indented, each with a tick of its own. Unticking the stylesheet removes its font rows. +- At Import, the ticked files become part of the site: a stylesheet's rules join the page's styles where its link stood, with its leading comment (its licence notice) and a line naming where it was downloaded from; a script joins the page's script, before the page's own; a WOFF2 font becomes a site asset that the stylesheet points to. Preview and the export then ask no outside host for them. The Import button waits for downloads still on their way and says so. The result says how many files from the web came along and, with fonts, that the fonts are now the site's. Pick another file, Back, Cancel or a finished import, and the downloads are forgotten. +- The download has fixed limits that nothing can switch off: https addresses only, on their usual port; only hosts whose every address is public; at most 256 KiB per stylesheet, 512 KiB per script and 2 MiB per font, and 10 seconds per file; at most 30 files and 8 MiB in one review. A stylesheet must arrive as a stylesheet, a script as a script, and a font must be WOFF2. A downloaded file is never run by FormWeb and never sent back to the editor. +- "Bring pages in as" still starts on Code sections when a page loads files from the web. The reason beside it now follows the ticks: with every file ticked and downloaded it says the pages keep their look either way, and otherwise it names the hosts whose files will be missing. Your choice is never changed for you. +- A page brought in as editable elements with ticked files has its script run first, in a sealed frame with no network, and is measured as it looks after the script ran: the classes the script gave its elements and the style rules it made are kept, so the converted elements look as they do in the browser. What only the script builds stays the script's. A script that does not finish within about 5 seconds is left out of the measuring and the result says so. +- For such pages the class and id of the page's body are kept on a wrapper around its content, so a look that hangs on the body (a background, a font) arrives too. +- Agents: `library_import_site` still never downloads anything; only a person's tick in the editor's review does. +- A downloaded stylesheet that names other addresses in a form that cannot be checked (escaped letters, `image-set`, an `@import` that survives) is left out whole, with a sentence, so the published page cannot be made to ask an outside host. A page script that tries to send the sealed frame to another address is stopped, and that page is then measured without running its script. +- Fixed: pressing Import in the site review no longer drops the focus to the page. +- Automated tests at four layers: 182 engine tests, 747 service tests, 746 editor function tests and 561 tests that drive the real editor window. Of these, 30 service tests, 9 editor function tests and 9 window tests are new and cover this release; the two new window files take under 20 seconds together. They were written after the features had been run and seen to work, by an agent that did not build them, and each was seen to fail once, against 0.35.0 where that release could run it and otherwise with a wrong expected value. No test reaches a real host: the service tests replace only the one place where a connection is made, so the checks above it still run. +- Known gaps: a page script that never stops freezes the editor window during the conversion in Chromium, because the sealed frame shares the window's process; reloading the window brings the site back with the page as code. Import HTML as a section has no ticks yet: its files from the web are still not brought along. Only WOFF2 fonts are taken, and an `@font-face` that also names another format is left out unless every file it names was downloaded. Addresses that start with `//` are listed but cannot be ticked into a download. The service's refusal sentences in the rows are English in every language. The real download path (name lookup, connection, certificate check) could not be run in the build workspace, which has no network; it was run against stand-in hosts only. Closing the Library does not forget the downloads at once; they are forgotten after 20 minutes. Nothing of this release was run in the desktop app, on Windows or macOS, in Firefox or Safari, on touch or with a screen reader. Where exports are saved (0.35.0) has still not been run in a launched desktop app; the owner's check is step 7 of docs/DESKTOP_TESTING.md, and the desktop shell's part of it has no automated tests. When the desktop app refuses a save it did not ask about, the notice says nothing was saved but the status line still says the site was exported. A marker does not follow its element while a motion preset plays. The audit's messages are in English in every language, and a result sentence joined from several parts does not follow a language switch until the next audit. Where a kept script builds content, the canvas stays blank there; Preview and the export show it. A picture of that content for the canvas is built and was seen working, but it is switched off: the export would copy the picture's file into its assets folder, and the moment it appears on the canvas was not checked for a shift. A button built by a kept script takes the page's font where the original page used the browser's own. With no trial on, a menu command chosen with the mouse leaves the focus on the page, so Delete and Backspace remove the selected element; a Layers row does the same. Moving the focus into Search properties ends a trial. While search results show, pressing Tab twice from the search box can leave the focus on the page. A kept line height in pixels that equals the one its section inherits is turned into a ratio on text a script builds. The translations are machine made and unread by native speakers. + +## 0.35.0 · 2026-11-27 + +- The fourth of five releases that answer the follow-up on issue #36: find it, check it, save it where you want. +- Audit markers: the Audit dialog (Page > Run SEO and accessibility audit, or the Audit button) has a switch, "Show audit markers on the page", off at first, with a sentence that says what it does and that the markers show once the dialog is closed; View > Show audit markers turns it on or off from the menu, with a check mark and a sentence in the status line. With it on, each element of the open page that has an issue gets one small marker centred on its top right corner on the canvas, showing how many issues it has; half of the marker lies outside the element, so it does not hide the element's text. A warning is a yellow diamond and a note a blue circle. Issues about the whole page or site have no marker; the dialog says how many there are. At most 200 markers are drawn on a page, and the dialog says so when there are more elements with issues. +- A click on a marker, or Enter or Space on it, selects its element and shows the issue in the status line and the notice, the way Select in the Audit dialog does; with several issues a small list under the marker shows each sentence. Pointing at a marker shows the sentences in its tooltip and changes nothing else. +- Markers follow your changes without pressing Audit again: once a change is saved, the audit is asked again (at most once every 0.6 s), so an issue you fix loses its marker within a moment and a new one gets a marker. They follow the canvas when it scrolls, zooms or changes size, breakpoint or page; a marker whose corner is out of view is hidden, not pinned to the edge, and markers keep up with the window while it is resized. Markers are hidden in Live preview and Preview as published, while you drag on the canvas, try a choice or edit text, and while a dialog is open, and come back afterwards. If the audit cannot be run, they hide and the status line says so once. The choice is kept in this browser only, never in the site or the export; Reset All Preferences turns it off. With markers off, nothing is asked beyond what the editor asked before. +- Where exports are saved (desktop app): Edit > Settings... (Preferences), General, has "Where exports are saved" with three choices: The Downloads folder (chosen at first), A folder you choose (with Choose folder... and the chosen path shown), and Ask each time. Export static site, Download .fweb project, QR codes and picture exports all follow it. In a browser the row says that the browser decides where downloads go, and downloads work as before. +- After every save the notice names the real folder, for example "Exported harbour-ferries-site.zip to" the folder, with Show in folder. A file whose name is taken there gets " (1)", " (2)" and so on. A name the page suggests can never place a file outside the folder. +- If the chosen folder is missing or cannot be written when a file is saved, the file goes to your Downloads folder and a red notice says "The chosen folder ... is missing or cannot be written, so ... was saved to ...". With Ask each time the system's save dialog opens before anything is downloaded; Cancel saves nothing and the status line says "Nothing was saved.". The chosen folder is kept by the app itself, survives a restart, and Reset All Preferences puts the choice back to Downloads. +- The import review names the files a page loads from other websites: for each such page, for example, "This page loads files from the web: 2 stylesheets from styles.example.com and 1 script from scripts.example.org. These files are not brought along." Host names are plain text, never links. When at least one page loads such files, Bring pages in as starts on Code sections, with the reason under it ("Kept as code, because 1 of 2 pages loads files from the web. ..."); picking Editable elements says what will be missing, and the result after the import names those hosts. An import with no such files starts on Editable elements, as before. Nothing is downloaded from those websites during the review or the import. +- Agents: the review of `library_import_site` and of the site import route gives each page `outside`, a list of `{kind, host, url}` (kind `stylesheet` or `script`) in the order the page loads them, each address once, at most 20, with `outsideMore` counting the rest; `/api/library/import-html` adds the same two fields to its answer. Each page of the review also has `outsideWarnings`, the positions in `warnings` of the older outside-file warnings that `outside` already names in full; the review row in the window shows such a warning once, as the plain sentence. Every earlier field is unchanged. +- A page whose script builds part of its content, converted to editable elements with its script kept, now keeps the style rules that none of the converted elements use (and the rules for classes the script names) with the script, so what the script builds is styled in Preview and in the export. The converted elements keep their measured look. The result says so, for example "Kept 6 style rules for the content the page's script builds.". With the script not kept nothing changes. A line height the page sets as a ratio of the text size is kept as that ratio, so smaller or larger text the script builds gets a line height that follows its own size. +- A converted page that filled the window (a page with `height: 100%` or `min-height: 100vh`) now fills the canvas and Preview at least to their height, instead of shrinking to its content. +- Search properties lists what matches with the tab and section where it is, as in "Opacity · Design > Appearance", and now finds choices, list items and motion presets too, as in "800 · Design > Typography > Weight" and "Fade up · Motion > Presets". It no longer goes to a result: a click, Enter and the arrow keys do nothing, and a sentence above the list says "Each result shows where to find it. Open that tab and section to use it." The results are no longer grouped under headings. Escape clears the search; Escape in an empty search field moves to the tab buttons. +- Opening a menu in the menu bar while you try a choice no longer ends the trial. Copy, Save, Search commands, Try choices before keeping them, Show audit markers and Show hover outlines keep it, and the focus goes back to the choice you were trying; Edit > Undo puts the page back and undoes nothing else; any other command puts the page back first. The same holds while a list field's list is open. +- Fixed: after a command chosen from a menu opens a dialog, closing the dialog no longer leaves Delete and Backspace able to remove the selected element. +- Fixed: Edit > Undo from the menu while trying an item of an open list no longer undoes an earlier saved change. +- Fixed: a click on an audit marker whose element was just removed elsewhere drops the marker and says nothing. +- Fixed: after a click on a toolbar button, such as Audit, Export or a breakpoint button, Delete and Backspace no longer remove the selected element. +- Fixed: the Convert to editable elements window keeps the focus while it works. Before, a Backspace pressed during a conversion could remove the selected section, and the conversion then selected its result over an element you had picked meanwhile. +- Fixed: an import no longer stalls on a stylesheet with an `@import` that has no closing semicolon. +- Fixed: a conversion no longer fails when the page's code would be too large; the style rules kept for the script are left out and the result says so. +- Fixed: the Export button no longer drops the focus while it is busy. +- Automated tests at four layers: 182 engine tests, 717 service tests, 737 editor function tests and 552 tests that drive the real editor window. Of these, 105 service tests, 37 editor function tests and 90 window tests are new and cover this release. Each was written after its feature had been run and seen to work, by an agent that did not build it, and each was seen to fail against 0.34.0 and once with a wrong expected value before it was accepted. The list that Search properties shows has one new and one rewritten window test and one rewritten editor function test, written by the lead, which did not build it. In CI the window tests now run as eight parts side by side, each with a limit of 7 minutes. +- Known gaps: where exports are saved was compiled for Windows and macOS and its page side was run in a browser with a stand-in for the app, but it was not run in a launched desktop app on any system; the owner's check is step 7 of docs/DESKTOP_TESTING.md. The desktop shell's part of it has no automated tests. When the desktop app refuses a save it did not ask about, the notice says nothing was saved but the status line still says the site was exported. A marker does not follow its element while a motion preset plays. The audit's messages are in English in every language, and a result sentence joined from several parts does not follow a language switch until the next audit. Where a kept script builds content, the canvas stays blank there; Preview and the export show it. A button built by a kept script takes the page's font where the original page used the browser's own. With no trial on, a menu command chosen with the mouse leaves the focus on the page, so Delete and Backspace remove the selected element, as before this release; a Layers row does the same. Moving the focus into Search properties ends a trial. While search results show, pressing Tab twice from the search box can leave the focus on the page, where Backspace removes the selected element. A kept line height in pixels that equals the one its section inherits is turned into a ratio on text a script builds. The search was run in Chromium only, with a mouse and a keyboard, and not with a screen reader. The eight-part CI job was not run before this release. The translations are machine made and unread by native speakers. + ## 0.34.0 · 2026-11-27 - The third of five releases that answer the follow-up on issue #36: try a choice before keeping it. diff --git a/README.md b/README.md index abf09541..8a704ae5 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@

- version 0.34.0 + version 0.36.0 TypeScript 7 Rust engine macOS, Linux, Windows diff --git a/VERSION b/VERSION index 85e60ed1..93d4c1ef 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.34.0 +0.36.0 diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 911cea5e..e5151871 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -1,5 +1,35 @@ # Backend context +## Files a person ticks in the import review are downloaded under guards and merged at import · v0.36.0 (2026-11-27) + +The last of five releases (0.32.0 to 0.36.0) that answer the follow-up on issue #36; `frontend/HASHOUT_LOG.md`, same version, has the review's ticks, the sealed frame and the body wrapper's editor side. New: `app/outside_fetch.py`; routes `POST /api/library/outside/fetch` and `/outside/drop` in `app/library_routes.py`; an optional `outside` query parameter on `import-site`. No engine change. With no token every answer is exactly the 0.35.0 one (no `outside` key, the same warnings). + +One network seam. Every byte goes through the module-level `outside_fetch.connect(host, port, pick, seconds)`: it resolves the name once, hands every address to the caller's `pick`, opens TCP to the address `pick` returned and verifies TLS for the host name. `pick` holds the every-address-public check (loopback, private, link-local, CGNAT, multicast, reserved, unspecified, IPv4-mapped, 6to4, Teredo and NAT64 forms; at most 64 addresses), and the caller refuses any connection on which `pick` was never called. That is why a replacement seam (a test, `/home/claude/wave5/standin_app.py`) cannot skip the address rule: the guards sit above the seam, and the seam only proves it asked. There is no setting, header or environment variable that turns a guard off. The connection goes to the checked address, so there is no second lookup to race. + +Time and size. The 10 second deadline holds for trickled headers and bodies because `http.client` reads through a RawIOBase wrapper that sets the socket timeout to the time left before each `recv`; the DNS lookup runs in a daemon thread joined with the time left. Caps are counted while reading (256 KiB stylesheet, 512 KiB script, 2 MiB font) and never taken from `Content-Length`; a body shorter than its `Content-Length` is refused as broken off (that case was accepted before the last fix of the wave). `Accept-Encoding: identity`, and any `Content-Encoding` is refused, so there is no decompression to bound. Content checks: `text/css`, JavaScript types, `wOF2` by the first four bytes, strict UTF-8. + +The token store. Downloaded files live only in memory, under a random token the first fetch creates: at most 30 files and 8 MiB per token, 20 tokens (the oldest is dropped), each forgotten 20 minutes after its last use, one download at a time per token through a lock with a 30 second wait. A font is accepted only when a stylesheet fetched under the same token names that exact URL; the stylesheet's `@font-face` rules are scanned with `find`, not a regular expression, at most 5,000 rules, 20 fonts listed plus `fontsMore`. No route returns a body and nothing downloaded is executed by the service: a file is data. + +What the security pass found in the merge. The two regular expressions that rewrite `url()` and `@import` match the plain forms only, and CSS lets a letter be written as an escape (`u\72l(`), an address hold an escaped bracket, or `image-set("...")` name an address with no `url()` at all. Rather than parse CSS, `outside_css` now looks at its own result: it resolves the escapes in a copy, and if that copy still holds a `url(` that is not `data:` or `/api/assets/`, an `@import` or an `image-set(`, the whole stylesheet is left out with a sentence (`notes['odd']`). The escapes icon fonts and utility class names use pass, since resolving them makes no such word. `store_fonts` catches the store's refusal per font, because only the first four bytes are checked at download and a refused font used to fail the import after the archive's assets were already stored. Known and left: fetches share the service's small thread pool, so many slow ones at once make the service slow for the window that asked for them; both routes need the window key. + +Merge (`site_import.py`, `_page` and `commands`, taking an optional `fetched`). Only files kept under the token AND named by the page being imported are used. `Site.outside_css` keeps the stylesheet's leading comment (its licence) and adds a `Downloaded from` line, leaves its `@import` out, points `url()` of a fetched font at `/api/assets/.woff2` (the name is the sha256 of the body exactly as the asset store names it, so `store_fonts` then ingests and owns the asset the CSS already points at), turns every other outside `url()` into `none` and leaves out each `@font-face` whose non-data `url()`s were not all fetched, counting them in a sentence. The `Downloaded from` comment keeps the source address in the CSS on purpose; a check for "no outside host" must look at `url()`, `src` and `href`, not at the text. Fetched classic scripts join before the page's own script in document order; a module and a classic script are not joined, and a fetched script past 512 KiB is left out, each with a sentence that names it. Over 256 KiB of CSS the page is built again without the fetched stylesheets. `Site.fetched`, `brought`, `fonts_used` and `notes` carry this per import; the old "not brought along" sentences are not given for files that came along. + +Body wrapper. `_page` takes only the text between `` and ``, so a body's class was lost at import and a look that hangs on it (a gradient, a font) never arrived. For a page that brought at least one fetched file (`site.brought`), the `id` and `class` of its `` tag (read from at most 4,096 characters, each value at most 2,048, escaped) are kept on a wrapper `

` around the page's markup. Only for such pages, so every other import is unchanged. Handlers and other attributes are not carried. + +Not run in this workspace: the real `connect` (name lookup, TCP, certificate check), since it has no network; the per-token and token-count limits, the 20 minute expiry and two concurrent fetches on one token; a fetched module script, the script and CSS caps, an outside `@import` inside a local stylesheet, two pages naming the same file, and replace mode with a token. `//host/x` addresses are listed by the review and never fetched (https only). The MCP tool `library_import_site` has no token parameter and never fetches; its description says only a person's tick in the editor's review downloads a file. + +## The import review names the files a page loads from other hosts · v0.35.0 (2026-11-27) + +The fourth of five releases (0.32.0 to 0.36.0) that answer the follow-up on issue #36; `frontend/HASHOUT_LOG.md`, same version, has the editor side and the desktop shell's export folder. The routes, `mode`, `revision`, the commands, undo and every earlier field and warning sentence are unchanged; the three new fields are additive. Nothing is fetched: no code added here resolves a name or opens a connection (`urlsplit` is not used for the host, and the `idna` codec is a string operation), and a run under `strace` saw no outside connection from the service during reviews and imports. + +`outside_file(kind, reference)` (`app/site_import.py`) reads one reference the way a browser reads an http or https link, without a regular expression and bounded before any parsing: leading and trailing C0 controls and spaces are trimmed and tabs and line breaks removed; the reference must be printable and at most 2,048 characters (`URL_MAX`); the scheme is read by hand and only `http`, `https` or none (protocol-relative) is taken; after it there must be two slashes, `/` or `\` in any mix, and every further slash is skipped; the authority ends at the first `/`, `\`, `?` or `#`, the last `@` ends the credentials (dropped), and the port follows the first `:`, digits only, at most 65535. Cases, each checked against the test browser's own URL parser (`new URL(x, base)`, 66 cases, 0 different): `https://tracker.evil\@cdn.example.net/x.js` is host `tracker.evil` (the browser reads the backslash as a slash, so the path is `/@cdn...`; the first version used `urlsplit` and named the trusted host, which a downloaded page could use to make the review and the agents reading it name the wrong host); `https:\\evil.com\x.css`, `\\evil.com/x.js`, `/\evil.com/x.js` and `https:///evil.com/x` are listed with their host; `https:evil.com/x` and `https:/evil.com/x` are not listed, because their host depends on the page's own scheme; a protocol-relative URL with port 80 or 443 is not listed for the same reason, while `//host:8080/` is; uppercase schemes and hosts are lower-cased; a default port is dropped and another kept in `host`; IPv6 (`[`), a host with `%`, `\`, `@` or white space, a host over 253 characters (`HOST_MAX`), labels outside 1 to 63 characters of `a-z`, `0-9` and `-` with no hyphen at either end (so `under_score` is refused), and a trailing dot are refused; a non-ASCII host goes through the `idna` codec unless it holds a UTS46 deviation character (`ß`, `ẞ`, `ς`, ZWJ, ZWNJ) or a code point unassigned in Unicode 3.2, and an `xn--` label must decode; a host whose last label is a number (decimal or `0x`) is read by the WHATWG IPv4 rules (hex, octal, fewer than four parts, `_ipv4`, `_number`) and listed dotted (`0x7f.1` is `127.0.0.1`) or refused (`1.2.3.4.5`, `256.1.1.1`); `data:`, `blob:`, `javascript:` and `ftp:` are not listed. The answer is `{kind, host, url}`, `url` with the scheme lower-cased, no credentials, the ASCII host, no default port and backslashes in the path turned to `/` (a protocol-relative URL stays `//host/...`). A reference it refuses stays only in the existing warning sentences, which agents still read. + +`Site.listing` collects `(kind, reference)` while one page is read (`_page`): every `') + assert listed[-1:] and listed[-1]["host"] == "control.example.net", f"the control script was not listed, so the page was not read: {listed}" + return listed[:-1] + + +def url_host(url): + assert url.startswith(("https://", "http://", "//")), f"the listed address is not absolute or protocol-relative: {url!r}" + authority = url.split("//", 1)[1] + for end in "/?#": + authority = authority.split(end, 1)[0] + assert "\\" not in authority and "@" not in authority, f"a browser would read another host out of the listed address {url!r}" + return authority + + +@pytest.mark.parametrize("reference, host", LISTED) +@pytest.mark.parametrize("kind", ["script", "stylesheet"]) +def test_an_outside_file_is_named_with_the_host_a_browser_loads_it_from(client, blank, reference, host, kind): + tag = f'' if kind == "script" else f'' + listed = one_with_control(client, tag) + assert [(item["kind"], item["host"]) for item in listed] == [(kind, host)], f"{reference!r} loads from {host}, the review named {listed}" + assert url_host(listed[0]["url"]) == host, f"the listed address {listed[0]['url']!r} does not lead to {host}" + + +@pytest.mark.parametrize("reference, host", LISTED_OR_LEFT_OUT) +def test_an_outside_file_is_named_with_the_host_a_browser_loads_it_from_or_not_at_all(client, blank, reference, host): + listed = one_with_control(client, f'') + assert listed == [] or [item["host"] for item in listed] == [host], f"{reference!r} loads from {host}, the review named {listed}" + assert all(url_host(item["url"]) == host for item in listed), listed + + +@pytest.mark.parametrize("case", list(LEFT_OUT)) +def test_an_address_that_does_not_name_one_outside_host_is_not_listed(client, blank, case): + reference = LEFT_OUT[case] + listed = one_with_control(client, f'') + assert listed == [], f"{case} was listed: {listed}" + + +def test_the_spoofed_host_is_named_as_the_real_one_inside_a_zip_too(client, blank): + sample = page("Spoof", "

x

", '') + r = client.post(REVIEW, content=zip_of({"index.html": sample})) + assert r.status_code == 200, r.text[:400] + listed = r.json()["pages"][0]["outside"] + assert [(item["kind"], item["host"]) for item in listed] == [("script", "tracker.example"), ("stylesheet", "evil.example")] + assert [url_host(item["url"]) for item in listed] == ["tracker.example", "evil.example"], listed + + +@pytest.mark.parametrize("reference", [ + "https://user:secret@cred.example.net/a.js", + "https://user@cred.example.net/a.js", + "//user:secret@cred.example.net/a.js", + "https://user:secret@cred.example.net:8443/a.js", + "https:\\\\user:secret@cred.example.net\\a.js", +]) +def test_credentials_in_an_address_never_appear_in_the_listed_host_or_address(client, blank, reference): + listed = one_with_control(client, f'') + assert [item["host"].split(":")[0] for item in listed] == ["cred.example.net"], listed + for item in listed: + assert "user" not in item["host"] + item["url"] and "secret" not in item["host"] + item["url"], item + assert "@" not in item["url"].split("/")[2], item + + +def test_an_international_host_is_listed_in_its_ascii_form_and_the_list_is_plain_json(client, blank): + listed = one_with_control(client, '') + assert [item["host"] for item in listed] == ["xn--bcher-kva.example", "cdn.example.net"] + assert all(item["host"].isascii() for item in listed) + assert json.loads(json.dumps(listed, ensure_ascii=True)) == listed + assert all(set(item) == {"kind", "host", "url"} and all(isinstance(v, str) for v in item.values()) for item in listed) + + +def test_a_stylesheet_with_an_unterminated_import_of_96_kib_is_reviewed_within_the_bound(client, blank): + stalling = "h1{color:#123456}\n@import " + "a" * (96 * 1024) + data = zip_of({"index.html": page("Stall", "

x

", ''), "css/site.css": stalling}) + r = answered_within(BOUND, lambda: client.post(REVIEW, content=data)) + assert r.status_code == 200, r.text[:400] + found = r.json()["pages"][0] + assert [item["host"] for item in found["outside"]] == ["cdn.example.net"] + assert client.get("/api/health").status_code == 200 diff --git a/backend/tests/outside_fetch/test_outside_fetch_guards.py b/backend/tests/outside_fetch/test_outside_fetch_guards.py new file mode 100644 index 00000000..720dd4f6 --- /dev/null +++ b/backend/tests/outside_fetch/test_outside_fetch_guards.py @@ -0,0 +1,200 @@ +"""The service's download of one ticked outside file (plan B1 to B9). Only the network seam `outside_fetch.connect` is +replaced, so the address check, redirects, time limit, caps and content checks above it still run.""" +import pytest + +from app import outside_fetch + +FETCH = "/api/library/outside/fetch" +DROP = "/api/library/outside/drop" +PUBLIC = "93.184.216.34" +WOFF2 = b"wOF2" + b"\x00" * 60 + + +class Stream: + def __init__(self, data, clock=None, step=0.0): + self.data, self.clock, self.step, self.sent = data, clock, step, b"" + + def sendall(self, data): + self.sent += data + + def settimeout(self, seconds): + pass + + def close(self): + pass + + def recv_into(self, buffer): + if self.clock is not None: + self.clock.now += self.step + n = min(len(buffer), len(self.data), 64) + buffer[:n] = self.data[:n] + self.data = self.data[n:] + return n + + +def answer(body, ctype="text/css", status="200 OK", headers=""): + data = body.encode() if isinstance(body, str) else body + return f"HTTP/1.1 {status}\r\nContent-Type: {ctype}\r\nContent-Length: {len(data)}\r\n{headers}\r\n".encode() + data + + +class Web: + """Stands in for the network below the seam: each host answers with fixed addresses and fixed bytes.""" + + def __init__(self, files, addresses=None): + self.files, self.addresses, self.calls = files, addresses or {}, [] + + def connect(self, host, port, pick, seconds): + chosen = pick(self.addresses.get(host, [PUBLIC])) + self.calls.append((host, port, chosen)) + return Stream(self.files[host]) if isinstance(self.files[host], bytes) else self.files[host]() + + +@pytest.fixture() +def web(monkeypatch): + def install(files, addresses=None): + fake = Web(files, addresses) + monkeypatch.setattr(outside_fetch, "connect", fake.connect) + return fake + return install + + +def refused(client, url, kind="stylesheet", token=None, words=""): + r = client.post(FETCH, json={"url": url, "kind": kind, "token": token}) + assert r.status_code >= 400, f"{url} as a {kind} was downloaded: {r.text[:300]}" + detail = str(r.json().get("detail", r.json())) + assert words.lower() in detail.lower(), f"the refusal of {url} says {detail!r}, expected it to mention {words!r}" + return detail + + +@pytest.mark.parametrize("url, words", [ + ("http://cdn.example.net/look.css", "https"), + ("https://cdn.example.net:8443/look.css", "port"), + ("https://user:secret@cdn.example.net/look.css", "password"), + ("https://cdn.example.net/" + "a" * 2050 + ".css", "2,048"), +], ids=["http", "another-port", "credentials", "over-2048"]) +def test_only_https_on_the_default_port_without_credentials_and_short_enough_is_fetched(client, web, url, words): + fake = web({"cdn.example.net": answer(".a{}")}) + refused(client, url, words=words) + assert fake.calls == [], f"the refused address still reached the network: {fake.calls}" + + +@pytest.mark.parametrize("addresses", [ + ["127.0.0.1"], ["10.1.2.3"], ["169.254.169.254"], ["100.64.0.9"], ["::ffff:127.0.0.1"], [PUBLIC, "192.168.1.4"], +], ids=["loopback", "private", "link-local", "shared-100.64", "ipv4-mapped-loopback", "public-plus-private"]) +def test_a_host_that_resolves_to_a_non_public_address_is_refused(client, web, addresses): + web({"cdn.example.net": answer(".a{}")}, {"cdn.example.net": addresses}) + refused(client, "https://cdn.example.net/look.css", words="private network") + + +def test_a_seam_that_never_asks_for_the_address_check_is_refused(client, monkeypatch): + monkeypatch.setattr(outside_fetch, "connect", lambda host, port, pick, seconds: Stream(answer(".a{}"))) + refused(client, "https://cdn.example.net/look.css", words="without its address being checked") + + +def test_the_connection_is_opened_to_exactly_the_address_the_check_returned(monkeypatch): + opened = [] + + class Sock: + def __init__(self, *args): + pass + + def settimeout(self, seconds): + pass + + def connect(self, where): + opened.append(where) + raise OSError("stop here") + + def close(self): + pass + + monkeypatch.setattr(outside_fetch, "_resolve", lambda host, port, seconds: ["8.8.8.8", "1.1.1.1"]) + monkeypatch.setattr(outside_fetch.socket, "socket", Sock) + with pytest.raises(outside_fetch.EngineError): + outside_fetch.connect("cdn.example.net", 443, lambda found: found[1], 5.0) + assert opened == [("1.1.1.1", 443)], f"the seam connected to {opened}, the check chose 1.1.1.1" + + +def redirect(to): + return answer("", status="302 Found", headers=f"Location: {to}\r\n") + + +def test_a_redirect_to_http_is_refused(client, web): + web({"cdn.example.net": redirect("http://cdn.example.net/look.css")}) + refused(client, "https://cdn.example.net/look.css", words="not https") + + +def test_a_redirect_to_a_host_on_a_private_address_is_refused(client, web): + fake = web({"cdn.example.net": redirect("https://inside.example.net/look.css"), "inside.example.net": answer(".a{}")}, {"inside.example.net": ["10.0.0.7"]}) + refused(client, "https://cdn.example.net/look.css", words="private network") + assert [call[0] for call in fake.calls] == ["cdn.example.net"], fake.calls + + +def test_a_fourth_redirect_is_refused_while_three_are_followed(client, web): + chain = {f"h{n}.example.net": redirect(f"https://h{n + 1}.example.net/x.css") for n in range(4)} + web({**chain, "h3.example.net": answer(".ok{}")}) + r = client.post(FETCH, json={"url": "https://h0.example.net/x.css", "kind": "stylesheet"}) + assert r.status_code == 200 and r.json()["bytes"] == len(".ok{}"), r.text[:300] + web({**chain, "h4.example.net": answer(".ok{}")}) + refused(client, "https://h0.example.net/x.css", words="redirects more than 3") + + +def test_a_body_over_the_cap_is_refused_while_it_is_read_when_no_length_is_given(client, web): + body = b".a{}" * (256 * 1024 // 4 + 100) + web({"cdn.example.net": b"HTTP/1.1 200 OK\r\nContent-Type: text/css\r\nConnection: close\r\n\r\n" + body}) + refused(client, "https://cdn.example.net/look.css", words="256 KiB") + + +def test_a_body_that_takes_longer_than_the_time_limit_is_refused(client, monkeypatch): + class Clock: + now = 1000.0 + + def monotonic(self): + return self.now + + clock = Clock() + monkeypatch.setattr(outside_fetch, "time", clock) + data = answer(".a{}" * 200) + monkeypatch.setattr(outside_fetch, "connect", lambda host, port, pick, seconds: (pick([PUBLIC]), Stream(data, clock, 1.0))[1]) + refused(client, "https://cdn.example.net/look.css", words="longer than 10 seconds") + + +@pytest.mark.parametrize("kind, ctype, body, words", [ + ("stylesheet", "text/plain", ".a{}", "not text/css"), + ("script", "text/plain", "1;", "not JavaScript"), + ("stylesheet", "text/css", b"\xff\xfe.a{}", "not UTF-8"), +], ids=["stylesheet-as-text", "script-as-text", "not-utf8"]) +def test_a_file_served_with_the_wrong_type_or_not_as_utf8_is_refused(client, web, kind, ctype, body, words): + web({"cdn.example.net": answer(body, ctype)}) + refused(client, "https://cdn.example.net/file", kind=kind, words=words) + + +def stylesheet_naming_font(client, web, font_body): + css = '@font-face{font-family:F;src:url("https://fonts.example.com/f.woff2") format("woff2")}' + web({"cdn.example.net": answer(css), "fonts.example.com": answer(font_body, "font/woff2")}) + r = client.post(FETCH, json={"url": "https://cdn.example.net/look.css", "kind": "stylesheet"}) + assert r.status_code == 200, r.text[:300] + assert [f["url"] for f in r.json()["fonts"]] == ["https://fonts.example.com/f.woff2"], r.json() + return r.json()["token"] + + +def test_a_font_that_is_not_woff2_is_refused(client, web): + token = stylesheet_naming_font(client, web, b"OTTO" + b"\x00" * 60) + refused(client, "https://fonts.example.com/f.woff2", kind="font", token=token, words="not WOFF2") + + +def test_a_font_is_fetched_only_when_a_stylesheet_fetched_under_the_token_names_it(client, web): + token = stylesheet_naming_font(client, web, WOFF2) + ok = client.post(FETCH, json={"url": "https://fonts.example.com/f.woff2", "kind": "font", "token": token}) + assert ok.status_code == 200 and ok.json()["bytes"] == len(WOFF2), ok.text[:300] + refused(client, "https://fonts.example.com/other.woff2", kind="font", token=token, words="names it") + + +def test_no_route_hands_back_the_body_of_a_fetched_file(client, web): + secret = ".marker-7f3a{color:red}" + web({"cdn.example.net": answer(secret)}) + r = client.post(FETCH, json={"url": "https://cdn.example.net/look.css", "kind": "stylesheet"}) + assert r.status_code == 200 and r.json()["bytes"] == len(secret), r.text[:300] + assert "marker-7f3a" not in r.text, f"the fetch answer carries the file's body: {r.text[:300]}" + d = client.post(DROP, json={"token": r.json()["token"], "url": "https://cdn.example.net/nothing.css"}) + assert d.status_code == 200 and "marker-7f3a" not in d.text, d.text[:300] diff --git a/backend/tests/site_import/test_outside_files.py b/backend/tests/site_import/test_outside_files.py new file mode 100644 index 00000000..f2c8222c --- /dev/null +++ b/backend/tests/site_import/test_outside_files.py @@ -0,0 +1,235 @@ +import pytest + +from site_zips import page, zip_of + +REVIEW = "/api/library/import-site/review" +PASTE = "/api/library/import-html" +EARLIER_PAGE_FIELDS = {"file", "name", "title", "description", "route", "newRoute", "replaces", "bytes", "warnings"} +EARLIER_REVIEW_FIELDS = {"pages", "assets", "supportFiles", "skipped", "ignored", "canReplace", "replaceNote", "notes", "revision"} +EARLIER_PASTE_FIELDS = {"canRedo", "canUndo", "revision", "site", "root", "warnings"} + + +@pytest.fixture() +def blank(client): + r = client.post("/api/new", json={"name": "Blank", "blank": True}) + assert r.status_code == 200, r.text + return r.json() + + +def zipped(client, files): + r = client.post(REVIEW, content=zip_of(files)) + assert r.status_code == 200, r.text[:400] + return r.json() + + +def loose(client, files): + r = client.post(REVIEW, json={"files": [{"name": name, "html": html} for name, html in files.items()]}) + assert r.status_code == 200, r.text[:400] + return r.json() + + +def page_of(review, file): + return next(p for p in review["pages"] if p["file"] == file) + + +def outside(review, file="index.html"): + found = page_of(review, file) + assert "outside" in found, f"the review of {file} has no outside list: {sorted(found)}" + return found["outside"] + + +def entries(listed): + return [(item["kind"], item["host"], item["url"]) for item in listed] + + +def link(href, rel="stylesheet"): + return f'' + + +def script(src): + return f'' + + +MIXED = page( + "Stopwatch", + "

Lap times

" + script("https://code.example.org/late.js") + link("https://cdn.example.net/print.css"), + link("https://cdn.example.net/look.css") + script("https://code.example.org/tick.js") + link("https://fonts.example.com/face.css"), +) +MIXED_LIST = [ + ("stylesheet", "cdn.example.net", "https://cdn.example.net/look.css"), + ("script", "code.example.org", "https://code.example.org/tick.js"), + ("stylesheet", "fonts.example.com", "https://fonts.example.com/face.css"), + ("script", "code.example.org", "https://code.example.org/late.js"), + ("stylesheet", "cdn.example.net", "https://cdn.example.net/print.css"), +] + + +def test_a_page_names_each_outside_stylesheet_and_script_with_its_kind_host_and_address_in_document_order(client, blank): + assert entries(outside(zipped(client, {"index.html": MIXED}))) == MIXED_LIST + + +def test_the_same_page_picked_as_a_loose_file_names_the_same_outside_files_as_inside_a_zip(client, blank): + as_zip = outside(zipped(client, {"index.html": MIXED})) + as_file = outside(loose(client, {"index.html": MIXED})) + assert as_file == as_zip + assert entries(as_file) == MIXED_LIST + + +def test_an_outside_file_the_page_names_twice_is_listed_once(client, blank): + twice = page("Twice", script("https://code.example.org/a.js"), link("https://cdn.example.net/a.css") + script("https://code.example.org/a.js") + link("https://cdn.example.net/a.css")) + assert entries(outside(loose(client, {"index.html": twice}))) == [ + ("stylesheet", "cdn.example.net", "https://cdn.example.net/a.css"), + ("script", "code.example.org", "https://code.example.org/a.js"), + ] + + +@pytest.mark.parametrize("count, kind, tag", [(21, "script", script), (25, "script", script), (300, "stylesheet", link)]) +def test_a_page_with_more_than_twenty_outside_files_lists_the_first_twenty_and_counts_the_rest(client, blank, count, kind, tag): + many = page("Many", "

many

", "".join(tag(f"https://cdn.example.net/f{i}.{'js' if kind == 'script' else 'css'}") for i in range(count))) + for review in (loose(client, {"index.html": many}), zipped(client, {"index.html": many})): + found = page_of(review, "index.html") + assert [item["url"] for item in outside(review)] == [f"https://cdn.example.net/f{i}.{'js' if kind == 'script' else 'css'}" for i in range(20)] + assert {item["kind"] for item in found["outside"]} == {kind} + assert found["outsideMore"] == count - 20 + + +def test_a_page_with_twenty_outside_files_lists_all_of_them_and_counts_none_more(client, blank): + twenty = page("Twenty", "

twenty

", "".join(script(f"https://code.example.org/f{i}.js") for i in range(20))) + found = page_of(loose(client, {"index.html": twenty}), "index.html") + assert len(found["outside"]) == 20 + assert found["outsideMore"] == 0 + + +def test_a_page_with_no_outside_files_gets_an_empty_list_and_every_earlier_field_as_written(client, blank): + plain = page("Opening hours", '

Open daily

', link("css/site.css"), "When we are open") + review = zipped(client, {"hours.html": plain, "css/site.css": "h1{color:#123456}", "js/app.js": "document.title = 'x';"}) + assert set(review) == EARLIER_REVIEW_FIELDS + found = page_of(review, "hours.html") + assert set(found) == EARLIER_PAGE_FIELDS | {"outside", "outsideMore", "outsideWarnings"} + assert (found["outside"], found["outsideMore"], found["outsideWarnings"]) == ([], 0, []) + assert (found["name"], found["title"], found["description"], found["newRoute"], found["warnings"]) == ("Opening hours", "Opening hours", "When we are open", "/hours", []) + assert found["bytes"] == len(plain.encode("utf-8")) + + +def test_naming_outside_files_changes_none_of_the_pages_other_fields_but_its_size_and_warnings(client, blank): + body = "

Lap times

" + without = page("Stopwatch", body, "", "Time your laps") + with_outside = page("Stopwatch", body, link("https://cdn.example.net/look.css") + script("https://code.example.org/tick.js"), "Time your laps") + plain = page_of(zipped(client, {"index.html": without}), "index.html") + loading = page_of(zipped(client, {"index.html": with_outside}), "index.html") + assert plain["outside"] == [] and len(loading["outside"]) == 2 + kept = EARLIER_PAGE_FIELDS - {"bytes", "warnings"} + assert {k: loading[k] for k in kept} == {k: plain[k] for k in kept} + assert plain["warnings"] == [] + assert any("https://code.example.org/tick.js" in w for w in loading["warnings"]), loading["warnings"] + assert any("https://cdn.example.net/look.css" in w for w in loading["warnings"]), loading["warnings"] + + +@pytest.mark.parametrize("reference", ["data:text/javascript,document.title='x'", "blob:https://cdn.example.net/1f2e3d", "DATA:text/css,body{}"]) +def test_data_and_blob_addresses_are_not_outside_files(client, blank, reference): + sample = page("Inline", "

x

", script(reference) + link(reference) + script("https://control.example.net/c.js")) + assert entries(outside(loose(client, {"index.html": sample}))) == [("script", "control.example.net", "https://control.example.net/c.js")] + + +@pytest.mark.parametrize("rel", ["preconnect", "icon", "dns-prefetch", "shortcut icon"]) +def test_a_link_that_is_not_a_stylesheet_is_not_an_outside_stylesheet(client, blank, rel): + sample = page("Links", "

x

", link("https://hints.example.net/x", rel) + link("https://cdn.example.net/look.css")) + assert entries(outside(loose(client, {"index.html": sample}))) == [("stylesheet", "cdn.example.net", "https://cdn.example.net/look.css")] + + +def test_a_script_and_a_stylesheet_inside_the_archive_are_local_and_not_listed(client, blank): + sample = page("Local", script("js/app.js") + script("/js/more.js"), link("css/site.css") + link("./css/print.css") + script("https://code.example.org/tick.js")) + review = zipped(client, {"index.html": sample, "css/site.css": "h1{color:red}", "css/print.css": "h1{color:blue}", "js/app.js": "1;", "js/more.js": "2;"}) + assert entries(outside(review)) == [("script", "code.example.org", "https://code.example.org/tick.js")] + + +def test_a_protocol_relative_address_is_an_outside_file_of_its_host(client, blank): + sample = page("Relative", script("//code.example.org/tick.js"), link("//cdn.example.net/look.css")) + listed = outside(loose(client, {"index.html": sample})) + assert [(item["kind"], item["host"]) for item in listed] == [("stylesheet", "cdn.example.net"), ("script", "code.example.org")] + assert [item["url"].split("/")[2] for item in listed] == ["cdn.example.net", "code.example.org"] + + +def test_an_upper_case_scheme_and_host_are_listed_in_lower_case(client, blank): + sample = page("Upper", "

x

", link("HTTPS://CDN.EXAMPLE.NET/Look.css") + script("Http://Code.Example.ORG/Tick.js")) + listed = outside(loose(client, {"index.html": sample})) + assert [item["host"] for item in listed] == ["cdn.example.net", "code.example.org"] + assert [item["url"].split("/")[2] for item in listed] == ["cdn.example.net", "code.example.org"] + assert [item["url"].split(":")[0] for item in listed] == ["https", "http"] + + +def test_an_import_of_an_outside_stylesheet_counts_as_a_stylesheet_from_that_host_from_a_local_stylesheet_and_from_a_style_block(client, blank): + sample = page("Imports", "

x

", link("css/site.css") + '') + review = zipped(client, { + "index.html": sample, + "css/site.css": '@import url(https://fonts.example.com/face.css);\n@import "base.css";\nh1{color:red}', + "css/base.css": "@import 'https://deep.example.net/deep.css';\nh2{color:blue}", + }) + assert entries(outside(review)) == [ + ("stylesheet", "fonts.example.com", "https://fonts.example.com/face.css"), + ("stylesheet", "deep.example.net", "https://deep.example.net/deep.css"), + ("stylesheet", "style.example.org", "https://style.example.org/block.css"), + ] + + +def test_five_files_from_one_host_are_five_entries_of_that_host_and_a_repeated_file_is_not_a_sixth(client, blank): + five = page("Five", "

x

", "".join(script(f"https://five.example.net/s{i}.js") for i in range(5)) + script("https://five.example.net/s2.js")) + listed = outside(loose(client, {"index.html": five})) + assert [item["host"] for item in listed] == ["five.example.net"] * 5 + assert [item["url"] for item in listed] == [f"https://five.example.net/s{i}.js" for i in range(5)] + + +def test_in_a_zip_of_three_pages_only_the_page_that_loads_outside_files_names_them(client, blank): + review = zipped(client, { + "index.html": page("Home", "

Home

", link("css/site.css")), + "about.html": page("About", "

About

", link("https://cdn.example.net/look.css") + script("https://code.example.org/tick.js")), + "contact.html": page("Contact", "

Contact

"), + "css/site.css": "h1{color:red}", + }) + named = {p["file"]: [item["host"] for item in p["outside"]] for p in review["pages"]} + assert named == {"index.html": [], "about.html": ["cdn.example.net", "code.example.org"], "contact.html": []} + + +def test_the_paste_route_answers_with_the_pages_outside_files_beside_its_earlier_fields(client, blank): + pasted = page("Stopwatch", "

Lap times

", link("https://cdn.example.net/look.css") + script("//code.example.org/tick.js")) + r = client.post(PASTE, json={"html": pasted}) + assert r.status_code == 200, r.text[:400] + answer = r.json() + assert set(answer) == EARLIER_PASTE_FIELDS | {"outside", "outsideMore"} + assert [(item["kind"], item["host"]) for item in answer["outside"]] == [("stylesheet", "cdn.example.net"), ("script", "code.example.org")] + assert answer["outsideMore"] == 0 + section = answer["site"]["extensions"]["code"]["sections"][answer["root"]] + assert section["html"] == "

Lap times

" + assert answer["revision"] == client.get("/api/state").json()["revision"] + + +def covered_warnings(found): + assert "outsideWarnings" in found, f"the review has no outsideWarnings: {sorted(found)}" + assert all(isinstance(i, int) and 0 <= i < len(found["warnings"]) for i in found["outsideWarnings"]), found + return [found["warnings"][i] for i in found["outsideWarnings"]] + + +def test_the_warnings_that_the_outside_list_names_in_full_are_pointed_at_and_the_warnings_stay_as_they_were(client, blank): + head = link("https://cdn.example.net/look.css") + script("https://code.example.org/tick.js") + '' + found = page_of(loose(client, {"index.html": page("Stopwatch", "

x

", head)}), "index.html") + covered = covered_warnings(found) + assert len(covered) == 2, found + script_line = next(w for w in covered if "script" in w) + sheet_line = next(w for w in covered if "stylesheet" in w) + assert "https://code.example.org/tick.js" in script_line and "cdn.example.net" not in script_line + assert "https://cdn.example.net/look.css" in sheet_line and "code.example.org" not in sheet_line + left = [w for i, w in enumerate(found["warnings"]) if i not in found["outsideWarnings"]] + assert len(left) == 1 and "https://style.example.org/block.css" in left[0], "the @import warning says more than the list and must not be pointed at" + + +@pytest.mark.parametrize("case, head", [ + ("a data script beside an outside one", script("data:text/javascript,1") + script("https://code.example.org/tick.js")), + ("a refused host beside a good one", script("https://under_score.example.net/x.js") + script("https://code.example.org/tick.js")), + ("twenty-one outside scripts", "".join(script(f"https://code.example.org/f{i}.js") for i in range(21))), +]) +def test_a_script_warning_that_counts_a_file_the_list_does_not_name_is_not_pointed_at(client, blank, case, head): + found = page_of(loose(client, {"index.html": page("Partly named", "

x

", head)}), "index.html") + assert found["outside"], f"{case}: nothing was listed, so the page was not read" + script_lines = [i for i, w in enumerate(found["warnings"]) if "external script" in w] + assert len(script_lines) == 1, found["warnings"] + assert script_lines[0] not in covered_warnings(found) and script_lines[0] not in found["outsideWarnings"], f"{case}: {found}" diff --git a/backend/tests/site_import/test_outside_merge.py b/backend/tests/site_import/test_outside_merge.py new file mode 100644 index 00000000..9f8ad694 --- /dev/null +++ b/backend/tests/site_import/test_outside_merge.py @@ -0,0 +1,165 @@ +"""What a site import does with the outside files a person ticked (plan B8, C1 to C6). Only the network seam +`outside_fetch.connect` is replaced; the downloads go through the real routes.""" +import re + +import pytest + +from app import outside_fetch +from site_zips import page, zip_of + +FETCH = "/api/library/outside/fetch" +REVIEW = "/api/library/import-site/review" +IMPORT = "/api/library/import-site" +WOFF2 = b"wOF2" + b"\x01" * 80 +LOOK = """/*! Look kit v1 | MIT licence */ +@import url("https://cdn.example.net/extra.css"); +@font-face { font-family: Face; src: url("face.woff2") format("woff2"); } +.card { font-family: Face; background: url("https://cdn.example.net/paper.png"); color: rgb(1, 2, 3); }""" +TICK = "window.fromTheWeb = 'tick';" +HEAD = '' +BODY = '
Lap
' +PAGE = page("Lap", BODY, HEAD).replace("", '') + + +def answer(body, ctype): + data = body.encode() if isinstance(body, str) else body + return f"HTTP/1.1 200 OK\r\nContent-Type: {ctype}\r\nContent-Length: {len(data)}\r\n\r\n".encode() + data + + +class Stream: + def __init__(self, data): + self.data = data + + def sendall(self, data): + pass + + def settimeout(self, seconds): + pass + + def close(self): + pass + + def recv_into(self, buffer): + n = min(len(buffer), len(self.data)) + buffer[:n] = self.data[:n] + self.data = self.data[n:] + return n + + +FILES = { + "/look.css": answer(LOOK, "text/css"), "/face.woff2": answer(WOFF2, "font/woff2"), "/tick.js": answer(TICK, "text/javascript"), + "/unused.css": answer(".unused-rule{color:red}", "text/css"), +} + + +@pytest.fixture() +def web(monkeypatch): + def connect(host, port, pick, seconds): + pick(["93.184.216.34"]) + holder = {} + + class Asked(Stream): + def sendall(self, data): + path = data.split(b" ", 2)[1].decode() + self.data = FILES[path] + return Asked(b"") + monkeypatch.setattr(outside_fetch, "connect", connect) + + +@pytest.fixture() +def blank(client): + r = client.post("/api/new", json={"name": "Blank", "blank": True}) + assert r.status_code == 200, r.text + return r.json() + + +def fetched(client, *items, token=None): + for url, kind in items: + r = client.post(FETCH, json={"url": url, "kind": kind, "token": token}) + assert r.status_code == 200, r.text[:300] + token = r.json()["token"] + return token + + +def imported(client, html, token=None): + query = f"?outside={token}" if token else "" + r = client.post(IMPORT + query, content=zip_of({"index.html": html})) + assert r.status_code == 200, r.text[:400] + return r.json() + + +def section(client): + sections = (client.get("/api/state").json()["site"].get("extensions", {}).get("code") or {}).get("sections") or {} + assert len(sections) == 1, sections + return next(iter(sections.values())) + + +ALL = [("https://cdn.example.net/look.css", "stylesheet"), ("https://cdn.example.net/face.woff2", "font"), ("https://code.example.org/tick.js", "script")] + + +def test_with_its_three_files_fetched_the_page_holds_the_font_as_a_stored_asset_the_script_first_and_no_outside_host(client, blank, web): + token = fetched(client, *ALL) + result = imported(client, PAGE, token) + code = section(client) + face = re.search(r"@font-face\s*\{[^}]*\}", code["css"]) + assert face, f"no @font-face in the imported styles: {code['css'][:400]}" + assert "example." not in face.group(0) and "url(" in face.group(0), face.group(0) + assert result["outside"]["fonts"] == 1, result["outside"] + assert 0 <= code["js"].find("fromTheWeb") < code["js"].find("ownScript"), code["js"] + every = code["html"] + code["css"] + code["js"] + named = re.findall(r"""(?:url\(\s*["']?|src=["']|href=["'])(https?://[^"')\s]+)""", every) + assert named == [], f"the imported page still loads from outside: {named}" + + +def test_an_import_inside_a_fetched_stylesheet_is_left_out_with_a_sentence(client, blank, web): + token = fetched(client, ALL[0]) + result = imported(client, PAGE, token) + assert "@import" not in section(client)["css"] + assert any("@import" in w and "left out" in w for w in result["warnings"]), result["warnings"] + + +def test_a_fetched_file_the_page_does_not_name_is_not_used_and_is_said(client, blank, web): + token = fetched(client, ("https://cdn.example.net/unused.css", "stylesheet")) + result = imported(client, PAGE, token) + assert "unused-rule" not in section(client)["css"] + assert any("not used by any imported page" in w for w in result["warnings"]), result["warnings"] + + +def test_the_stylesheets_licence_comment_stays_above_its_rules_with_a_line_naming_its_source(client, blank, web): + token = fetched(client, ALL[0]) + imported(client, PAGE, token) + css = section(client)["css"] + licence, source, rule = css.find("MIT licence"), css.find("https://cdn.example.net/look.css"), css.find(".card") + assert 0 <= licence < rule and 0 <= source < rule, css[:400] + + +def test_the_bodys_class_is_carried_on_a_wrapper_only_when_files_were_brought(client, blank, web): + imported(client, PAGE) + assert 'class="night"' not in section(client)["html"] + client.post("/api/new", json={"name": "Again", "blank": True}) + token = fetched(client, ALL[0]) + imported(client, PAGE, token) + assert re.match(r'\s*
', section(client)["html"]), section(client)["html"][:200] + + +def test_an_unknown_token_at_import_brings_nothing_from_the_web_and_says_so(client, blank, web): + result = imported(client, PAGE, "no-such-token") + assert result["outside"]["files"] == [], result["outside"] + assert "Downloaded from" not in section(client)["css"] + assert any("nothing from the web came along" in w for w in result["warnings"]), result["warnings"] + + +def test_without_a_token_the_review_and_the_import_equal_those_of_the_route_called_the_old_way(client, blank, web): + fetched(client, *ALL) + data = zip_of({"index.html": PAGE}) + first = client.post(REVIEW, content=data).json() + second = client.post(REVIEW + "?outside=", content=data).json() + assert first == second + a = client.post(IMPORT, content=data).json() + code_a = section(client) + client.post("/api/new", json={"name": "Again", "blank": True}) + b = client.post(IMPORT + "?outside=", content=data).json() + code_b = section(client) + strip = lambda r: {k: v for k, v in r.items() if k not in ("site", "revision", "canUndo", "canRedo")} + assert "outside" not in a and strip(a) == strip(b), (a.keys(), b.keys()) + assert code_a == code_b and "Downloaded from" not in code_a["css"] and "fromTheWeb" not in code_a["js"], code_a diff --git a/docs/ADVANCED_SCHEMA.md b/docs/ADVANCED_SCHEMA.md index bdeb6f9c..72dbe52c 100644 --- a/docs/ADVANCED_SCHEMA.md +++ b/docs/ADVANCED_SCHEMA.md @@ -209,7 +209,7 @@ interface ComponentContext { Export writes each enabled page component used on any page to `assets/components/.js` with its compiled JavaScript unchanged. The host renders as the node's own element with `data-fw-component=""` and, with a poster, a first child ``; route CSS keeps the host `position:relative` and the poster `display:block;width:100%;height:100%;object-fit:cover`. The page config holds `components.page = {host: {component, props}}` with asset props rewritten to exported URLs, and page instances render no iframe. `components.js` imports a module once when its host comes within one viewport, calls `mount`, and on `ready()` sets the poster to `visibility:hidden` so its box stays. An error keeps the poster, sets `data-fw-component-error` on the host (`data-fw-error` belongs to form fields) and logs one console error with the component id, the host node and the error. Page instances are drawn on the canvas as the poster (or a dashed "Component" placeholder) and never run there. When the site has themes and the component has both `poster` and `posterLight` (0.19.4), the host gets two images: the dark one with `data-fw-theme-only="dark"` and the light one with `data-fw-theme-only="light"`. The theme-only rule is emitted for them even when no node carries the attribute, and one sibling rule hides the second poster once the runtime hides the first on `ready()`, so `components.js` is unchanged. Without `posterLight`, or without themes, the output is the same as before. On the canvas the light poster is drawn while the Design system dialog previews the light theme. -Code sections need `code.allowSections: true`. A section is `code.sections. = {enabled,html?,css?,js?,module?,poster?}` with `html` up to 512 KiB, `css` 256 KiB, `js` 512 KiB, `module` boolean and `poster` an owned image path. The host node must have no children. Export renders the host's open tag, `html` raw and the close tag; appends `css` to that route's page stylesheet; and, when `js` exists, writes `assets/sections/.js` and loads it with `