Skip to content

fix(core): pathological markup can no longer stall the server - #678

Merged
allisonmahmood merged 3 commits into
mainfrom
fix/html-check-bounds
Oct 14, 2026
Merged

allisonmahmood merged 3 commits into
mainfrom
fix/html-check-bounds

Conversation

@allisonmahmood

@allisonmahmood allisonmahmood commented Oct 14, 2026 •

Copy link
Copy Markdown
Owner

One upload could freeze the server for everyone. Some static pages under the 512 KiB limit made the HTML checker work for tens of seconds, and the server answered nothing else in the meantime. The worst, 100k nested <div>s, took 42 seconds and then crashed the checker with a stack overflow. A tier 1 or 2 bundle's title read and a company look's logo check parse uploaded markup the same way.

Parts of the HTML parsing algorithm get slower the deeper markup nests, the more attributes an element carries, and the more nodes error recovery moves or clones. PatchPage hit this in the same checker (allisonmahmood/PatchPage#210), and this ports its fix. All three parses now run under one set of bounds:

  • Depth: at most 512 open elements. Chromium's parser stops nesting at the same depth.
  • Attributes: at most 256 on an element, including attributes merged from repeated <html>/<body> tags.
  • Repair: error recovery's sibling scans search from the end and draw from a fixed budget.
  • Creation (new here): budgets for the elements, attributes and attribute characters the parser creates. Without them, a short page that leaves formatting tags like <b> open across thousands of paragraphs makes the parser clone them, attributes and all, into every paragraph, and the other bounds never see it.

A static page or logo past a bound is refused with a plain error naming the limit. A bundle's title read gives up and the patch keeps its name. A page over the size limit is now rejected before it is parsed. The logo check also parses each CSS text once, so cloned styles cost nothing extra, and it reports a repeated external reference once. The skill and CLI README describe the bounds.

It works

Measured on Patchy's checker, before and after:

Input (all within their size limit) Before After
100k nested <div>s (tier 0) 42 s, then stack overflow 5 ms, refused
~50k attributes on one tag 4.6 s 2 ms, refused
60k distinct <body a…> tags 59 s 5 ms, refused
text inside <table> outside cells 8.2 s 87 ms, accepted
</b> crossing a block of ~130k children 1.0 s 70 ms, refused
250 open <b>s cloned into 5,000 paragraphs (315 KB) 13.2 s 75 ms, refused
one 256 KiB attribute cloned into 65k paragraphs 15 s 6 ms, refused
tier 1/2 title read, clone attack in 64 KiB 2.6–6.5 s, ~800 MiB 18–25 ms, no title
logo: 60k attributes / 5,000 nested <g> 9.7 s / stack overflow 17 ms / 4 ms, refused
logo: a style cloned into 100k paragraphs 3.3 s 154 ms, accepted
sloppy export: a 2,000-character link left open across 1,100 paragraphs 16 ms 6 ms, accepted
~512 KB table, article, SVG 27–67 ms 28–93 ms, accepted
  • New tests pin each bound at its threshold: 510 deep is accepted and 511 refused, along with attributes, repair, cloned elements, cloned attribute length, the title fallback and the logo. Disabling either creation budget fails its tests.
  • The seed:dev accept fixtures and the existing reject fixtures still pass unchanged.
  • pnpm test passed in full (1747/1747) on the final commit. Earlier full pnpm verify runs passed format, lint, typecheck, synth, postgres-concurrency, cli-smoke, tier2-smoke and browser. Their offline stage lost a few timing tests to machine load, and each of those passed when rerun alone.
  • GPT 6.1 Sol reviewed at xhigh over four rounds.
    • Round one confirmed the port matches parse5 8.0.1's internals, with identical trees across 3,000 malformed-markup cases. It found the cloning bypass and the unbounded title and logo parses.
    • Round two found cloned attributes needed counting by length. Round three found cloned logo styles re-parsed per clone, and an over-tight character budget.
    • All of those are fixed. Round four found nothing significant left.
    • It also asked for these cases as fixtures. I didn't add them: the fixture corpus is Prettier-formatted, so a 600-deep generated page would balloon into hundreds of KB of indentation, and the thresholds are pinned inline instead.

Not in this PR:

  • patchy publish from a repo still parses a tier 0 bundle with plain parse5 before validating it. That runs only on the publisher's machine, never on the server.
  • css-tree's own error recovery is slow on some malformed CSS in a look. That's a separate, pre-existing CSS-parser issue for its own change.

Made by Claude Opus 5.5 via Claude Code in T3 Code

Some tier 0 pages under the 512 KiB limit took the HTML checker tens of
seconds, and the server answered nothing else meanwhile. Steps of the
HTML parsing algorithm cost time in proportion to how deep markup
nests, how many attributes an element carries, and how many nodes
error recovery moves or clones. A page of 100k nested divs held the
checker for 42 seconds and then overflowed the stack in its walk. A
scripted bundle's title read and a company look's logo check parse
uploaded markup the same way.

All three now parse under one set of bounds: at most 512 open
elements, at most 256 attributes on an element, a fixed budget for
error recovery's sibling scans, which now search from the end, and a
budget for the elements and attributes the parser creates, which
catches formatting tags cloned into every block they were left open
across. A static page or logo past a bound is refused with a plain
error; a bundle's title falls back to the patch's name. A page over
the size limit is rejected before it is parsed. Ported from
PatchPage's fix for the same checker, plus the creation budget.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli area area:core Touches the core area area:docs Touches the docs area size:m 100-500 changed lines labels Oct 14, 2026
allisonmahmood and others added 2 commits October 15, 2026 00:36
Error recovery clones a formatting element with its attributes, so one
long attribute on a <b> left open across many blocks was checked once
per clone: a 256 KiB attribute across 65k blocks held the checker for
15 seconds, and long CSS in a logo's <desc> was parsed once per clone.
The parser now also budgets the characters of the attributes it
creates, and the skill's example of heavy repair names many tags left
open, which is what the budgets catch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ccepted

A logo's <desc> holds HTML, so one styled formatting element left open
across many blocks was cloned into each, and the logo check parsed its
CSS once per clone: 100k clones took 3 seconds. Each CSS text now parses
once, and a reference repeated across the logo is reported once.

Reading a cloned attribute costs about a nanosecond a character, so the
attribute-character budget rises to 2^24. That still stops a long
attribute cloned up to the size limit in a few milliseconds, and stops
refusing a sloppy export with a long link left open across a thousand
paragraphs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@allisonmahmood
allisonmahmood merged commit b58b899 into main Oct 14, 2026
13 checks passed
@allisonmahmood
allisonmahmood deleted the fix/html-check-bounds branch October 14, 2026 23:09
allisonmahmood added a commit that referenced this pull request Oct 14, 2026
… Patchy is smoother (#679)

Release 12's What's new entry, written from `b58b899`, ahead of
deploying it. `patchy` and `CURRENT_RELEASE` move to `0.12.0`, so CLIs
and patch repos installed before this deploy are told to upgrade.

| Change | PRs |
| --- | --- |
| Fixed: Links within a page jump to their section | #677 |
| Improved: Set up Patchy however you ask | #672, #674 |
| Improved: Claude Code can know Patchy is your company's own | #676 |
| Fixed: Your agent remembers Patchy after a Node.js update | #673 |
| Fixed: Sign-in codes say how many minutes they have left | #675 |
| Behind the scenes: uploaded pages and logos are checked within strict
limits | #678 |

Made by Claude Opus 5.5 via Claude Code in T3 Code

Co-authored-by: Claude Opus 5.5 <[email protected]>
allisonmahmood added a commit that referenced this pull request Oct 15, 2026
`validateHtml` parsed pages in parse5's default scripting-enabled mode,
where `<noscript>` holds raw text, so a `<form>`, `<iframe>` or
`javascript:` link inside it passed the static-page policy. Tier 0
frames run with scripts off, so the browser reads that text as real
elements.

`validateHtml` now parses with `scriptingEnabled: false`, as the repo
bundle check already does for tier 0. A new reject fixture,
`noscript-blocked-tag.html`, puts a `<form>` inside `<noscript>`. Every
caller of `validateHtml` checks tier 0 pages, so this matches how they
are served; a page that hid blocked tags in `<noscript>` is refused on
its next publish.

## Tried by hand

In a `pnpm dev up team` environment built from this branch before it was
rebased onto #678, using the environment's CLI on a page whose only
`<form>` sits inside `<noscript>`:

- `patchy validate` → `HTML failed Patchy Cloud validation:` / `-
Blocked <form> tag found.`, exit 1. With `--json`:
`{"ok":false,"error":"HTML failed Patchy Cloud validation:\n- Blocked
<form> tag found.","kind":"local"}`.
- `patchy publish --json` → the same refusal, exit 1.
- The same page posted straight to `POST /api/publish`, bypassing the
CLI → `422 {"ok":false,"error":"Blocked <form> tag found."}`.
- `pnpm seed:dev` still publishes all four accept fixtures.

The rebase onto #678 only moved `scriptingEnabled: false` onto its
bounded parser; the policy test and the fail-without-it check were rerun
after it.

## Surfaces

- Fixtures: the new reject fixture is read by the policy test;
`seed:dev` reads only accept fixtures.
- CLI `validate`, file-mode `publish` and the server publish route share
`validateHtml`. No message, flag or exit code changed, so the README,
ADR-0004, `docs/API.md` and the skill stay as they are.
- Not applicable: wire contract, dev loop, vocabulary, migrations,
company resources, served pages, reverse states, repo layout.

Closes #622

Made by Claude Opus 5.5 in Claude Code, running in T3 Code.
allisonmahmood added a commit that referenced this pull request Oct 15, 2026
…the source (#685)

Stacked on #682

A static page whose `@font-face` loads from `https://…`, or whose CSS
uses `@import`, published with `warnings: []`. Tier 0's content policy
blocks both (`font-src data:`, `style-src 'unsafe-inline'`), so the page
quietly fell back to another font and the agent never heard why.

`validateHtml` now reads each `<style>` with css-tree, which core
already uses for looks, and adds one warning per blocked source, naming
it:

- `@font-face source "<source>" won't load: static pages load fonts only
from data: URLs. Embed the font as a data: URL or use a system font
stack.`
- `@import "<source>" won't load: static pages can't load other
stylesheets. Inline its CSS, with any fonts embedded as data: URLs.`

The page still validates. `data:` and in-page `#fragment` sources,
`local()` and `format()` strings, `url()` outside a font `src` (an https
`background-image` is allowed) and `<template>` content stay quiet.
Escaped names such as `\73rc` count as the browser reads them. css-tree
recurses, so CSS nested too deeply to parse is skipped rather than
failing the page.

The new accept fixture `remote-font.html` joins the corpus, and the
policy test now asserts exact warnings for every accept fixture; the
others expect `[]`. The global `patchy` skill's HTML safety rules now
say fonts load only from `data:` URLs and `@import` never loads, and its
hash in `skills-lock.json` is refreshed.

## Tried by hand

In a `pnpm dev up team` environment built from this branch before it was
rebased onto #678, using the environment's CLI on a page with `@import
url("https://example.test/theme.css")`, `@font-face { src:
local("Brand"), url("https://example.test/brand.woff2") format("woff2")
}` and an https `background-image`:

- `patchy validate` → `HTML passed Patchy Cloud validation.` and exactly
two `Warning:` lines, the import and the font URL, exit 0. With
`--json`: `{"ok":true,"warnings":[…the same two…]}`.
- `patchy publish`, text and `--json` → published, with the same two
warnings.
- The same page posted straight to `POST /api/publish` → `201` with the
same two warnings.
- `pnpm dev shot ada /acme/remote-font` → the page renders in serif. The
browser reports `Loading the font 'https://example.test/brand.woff2'
violates … "font-src data:"` and `Loading the stylesheet
'https://example.test/theme.css' violates … "style-src
'unsafe-inline'"`, the two sources the warnings name. The background
image passes the policy; only its made-up host fails to resolve.
- `pnpm seed:dev` publishes all five accept fixtures, `remote-font.html`
included.

The rebase onto #678 changed no behaviour here; the policy tests and
each fail-without-fix check were rerun after it.

## Surfaces

- Fixtures: the new accept fixture is read by the policy test and `pnpm
seed:dev`.
- CLI `validate`, file-mode `publish` and the server publish route
already surface `warnings`. No flag, exit code or API description
changed, so the README, ADR-0004 and `docs/API.md` stay as they are.
- Global skill: HTML safety rules updated, hash refreshed.
- Not applicable: wire contract, dev loop, vocabulary, migrations,
company resources, served pages, reverse states, repo layout.

Closes #586

Made by Claude Opus 5.5 in Claude Code, running in T3 Code.
allisonmahmood added a commit that referenced this pull request Oct 15, 2026
The look checks read logo.svg with parse5's forgiving HTML parser, but every
consumer shows the logo as an image, which browsers parse as strict,
namespace-aware XML. An inline <svg> copied from a page passed the checks and
then showed as a broken image in the specimen and in every patch.

checkLogo now parses logo.svg with saxes (xmlns on) and walks that parse. A
logo that isn't well-formed or namespace-valid is refused with its position,
saxes' problem and the general fix, including XMLSerializer for an inline
<svg>. A DOCTYPE, an XML 1.1 declaration and a namespace with spaces around it
(saxes trims it, browsers don't) are refused, and the root must be svg in the
SVG namespace. Every existing logo check keeps its message; attribute names
still match case-insensitively, xlink:href counts as a reference, namespace
declarations don't, and <style> CDATA goes to the CSS reference check.

The XML parse replaces the bounded HTML parse from #678 for the logo. saxes
has no repair or recursion, but resolves each element's namespace by
searching the open elements, pairs each namespace with every prefixed
attribute's name, and builds an Error per problem. So a logo nests at most 64
elements deep, a namespace is at most 256 characters, problems are recorded
without Errors, and a logo past the look's size limit is refused for its size
without being parsed.

Closes #597

Co-Authored-By: Claude Opus 5.5 <[email protected]>
allisonmahmood added a commit that referenced this pull request Oct 15, 2026
`look publish` read `logo.svg` with parse5's HTML parser, which recovers
from mistakes. Every place a logo appears loads it as an image, and
browsers parse images as strict, namespace-aware XML. So an inline
`<svg>` copied from a company's site during onboarding (no `xmlns`,
`&nbsp;`, an undeclared `xlink:` prefix) passed every check, then showed
as a broken image in the specimen and in every patch.

## Fix

`checkLogo` in `@patchy/core/look` now parses the logo with
[`saxes`](https://github.com/lddubeau/saxes), with namespaces on, and
walks that parse. saxes is about 8 KB, ISC and pure JS, so the module
stays browser-safe. parse5 stays in core for the HTML policy.

- A logo that isn't well-formed or namespace-valid is refused with one
line: the position, saxes' problem, and the general fix. The general fix
is always included because saxes sometimes names the wrong thing (a bare
`&` in `<title>` reports `unclosed tag: title`). It also tells the agent
to run an inline `<svg>` through `new
XMLSerializer().serializeToString(svg)`:
`logo.svg:1:56 is not well-formed XML (undefined entity); a logo is XML,
not HTML, so quote every attribute, close every tag, declare prefixes
such as xmlns:xlink, and write & as &amp; and &nbsp; as &#160;. For an
inline <svg> copied from a page, serialize it with new
XMLSerializer().serializeToString(svg) in a browser.`
- A `<!DOCTYPE>` is refused. The root must be `svg` in the
`http://www.w3.org/2000/svg` namespace, as resolved from the
declarations. That covers a missing or wrong `xmlns`, and only
`xmlns:svg` on an unprefixed root.
- A namespace declaration with spaces around its value is refused. saxes
trims declarations, but browsers compare them exactly: a padded root
`xmlns`, or a padded reserved `xmlns:xml`, is a broken image in Chromium
and Firefox.
- An XML declaration other than `version="1.0"` is refused: Firefox
shows any XML 1.1 logo as a broken image.
- Every existing logo check keeps its message. Attribute names still
match case-insensitively, as parse5's did. `xlink:href` counts as a
reference, `xmlns:*` declarations don't, and `<style>` text, including
CDATA, goes to the CSS reference check.

### With #678's bounds

#678 bounded the logo's parse5 parse (512 deep, 256 attributes, a repair
budget) so that no upload could stall the server. The XML parse replaces
that for the logo. saxes has no error repair and no recursion, but it
has three costs of its own that I measured:

- It finds each element's namespace by searching every open element,
which is quadratic in depth. A 20,000-deep logo took 2.4 s, and 220,000
deep took over 300 s.
- It pairs each namespace with every prefixed attribute's name: a 16 KB
namespace across 20k attributes took 0.9 s.
- It builds an `Error` with a stack trace for every problem: about 0.5 s
for 175k undefined entities in 512 KiB.

So a logo nests at most **64** elements deep, and a namespace is at most
**256** characters. Real logos nest a few elements deep, Chromium and
Firefox render well past 5,000, and real namespaces are short URIs, so
both are purely cost bounds. Problems are recorded without building an
`Error`, and a logo past the look's 512 KiB limit is refused for its
size without being parsed. Measured warm against `main`'s bounded parse5
on the same inputs:

| Input | This branch | `main` |
| --- | --- | --- |
| 500 KiB of `<rect/>` siblings | 28 ms | 24 ms |
| 500 KiB of `<g/>` siblings at depth 63 (the worst case left) | 99 ms |
30 ms |
| 500 KiB nested or left unclosed | 1 ms, refused | 1 ms, refused |
| 500 KiB of undefined entities | 14 ms | 30 ms |
| 500 KiB of prefixed attributes under a 250-character namespace | 57 ms
| not measured |
| any shape at 1.5 MiB (the request cap) | 1–2 ms, refused for size |
64–93 ms |

#678's logo-bounds test is replaced by the 64/65 depth threshold. All of
its inputs are malformed XML now.

## Surfaces

- **Wire contract:** the publish endpoint's description lists the logo
rule, including both bounds, and `docs/API.md` is re-rendered. No
request or response shape changed.
- **CLI:** the `patchy` README's look section describes the rule. There
is no new command, flag or exit code, so ADR-0004 is unchanged. The
global skill gains one sentence in `look-capture.md`'s `logo.svg`
section. `SKILL.md` is unchanged, so `skills-lock.json` is untouched.
- Not applicable: dev loop, vocabulary and product shape, migrations,
company resources, served pages (the HTML policy is untouched), reverse
states and repo layout.

## Tried by hand

In Chromium (Playwright), I took two inline logos as a browser reads
them back through the DOM: GitHub's header mark from github.com, and the
brief's typical site logo after parsing it as HTML. Each went into a
look folder next to a fixture `look.css` and `LOOK.md`. Both read-backs
render as broken images, and `main`'s checks accept both.

Against this branch's dev environment (`pnpm dev up`, team scenario),
using the environment's packed CLI as Ada:

- `patchy look preview` on GitHub's mark printed `look publish would
refuse this look: - logo.svg's <svg> is not in the SVG namespace; set
xmlns="http://www.w3.org/2000/svg" on it.` `--json` carried the same
line in `failures`, where it used to report none.
- `patchy look publish` refused both read-backs with exit 1 and
`invalid_look`. The brief's logo gave the `logo.svg:1:56 … undefined
entity …` line above.
- I also POSTed both read-backs straight to `/api/look/publish` with
curl, skipping the CLI's own check. The instance answered `422
invalid_look` with the same lines.
- I ran `new XMLSerializer().serializeToString(svg)` on both logos in
Chromium. Preview then reported no failures, and publish stored them as
revisions 1 and 2.
- Opened in Chromium, the specimen for the read-back showed a
broken-image icon followed by the alt text `Linear's look`, which reads
like a wordmark (`naturalWidth` 0). The specimen for the serialized logo
rendered it (`naturalWidth` 300).

That run was on the commit before the rebase onto #678. On the rebased
commit, `pnpm patchy look preview` from source gives the same four
results.

I checked every refusal or acceptance added after review as an image in
both Chromium and Firefox: padded `xmlns` and `xmlns:xml`, XML 1.1,
namespace declarations, uppercase attributes, depth, and the brief's
must-pass logos, including Patchy's own. WebKit couldn't launch on this
machine.

## Review

GPT 6.1 Sol reviewed at xhigh over three rounds.

- **Round 1** found six issues and I fixed five: a padded `xmlns`, XML
1.1 (widened after Firefox showed any 1.1 logo broken), namespace
declarations read as `href`/`on*`, attribute-name case, and README
wording. The sixth is dismissed in a comment below.
- **Round 2**, after the rebase onto #678, found a padded reserved
`xmlns:xml` and the long-namespace cost. Both are fixed.
- **Round 3** found nothing.

## Left out

- Per the brief: the `forceStates` gaps and logo `<style>` cascade rules
stay accepted. Stored revisions aren't re-checked, and publish never
repairs a logo.
- css-tree throws on a non-CSS attribute value containing `url(`, e.g.
`data-x="fill:url(#g)"`, which makes `checkLook` throw instead of
refusing. This predates this PR on `main` and needs its own fix.

Closes #597

Made by Claude Opus 5.5 in Claude Code, running in T3 Code.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli area area:core Touches the core area area:docs Touches the docs area size:m 100-500 changed lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant