Skip to content

feat(content): clean pasted content and edit a draft as HTML - #1259

Merged
gkhngyk merged 17 commits into
ansvisor:mainfrom
cihan-gyk:feature/content-paste-html
Oct 21, 2026
Merged

gkhngyk merged 17 commits into
ansvisor:mainfrom
cihan-gyk:feature/content-paste-html

Conversation

@cihan-gyk

@cihan-gyk cihan-gyk commented Oct 20, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Content Editor (spec v2), PR 3 of the approved plan: CE-005 (paste cleaning) and CE-020 (HTML view).

Stacked on #1258 (editor core), which is stacked on #1256 (Library). Please merge them in order. This PR's own change is d69347f.

One allow-list, used twice (lib/content/html-allowlist.ts).

  • Kept: h1–h3 (h4–h6 become h3), p, br, strong/b, em/i, a[href], ul/ol/li, blockquote, tables (colspan/rowspan), img[src, alt, title], and schema JSON-LD.
  • Everything else goes: fonts, colors, classes, inline styles, ids, on*, scripts, iframes, objects, forms.
  • Links go through safeLinkHref (feat(content): write and save drafts in the content editor #1258), and utm_*, gclid and fbclid are dropped.

Paste (CE-005, spec §9) via TipTap's transformPastedHTML, with lib/content/clean-html.ts (DOMPurify, its own instance so the hooks stay local).

  • Google Docs:
    • Its non-bold <b id="docs-internal-guid-…"> wrapper is unwrapped.
    • Bold and italic set as styles (font-weight:700, font-style:italic) become <strong> and <em> before styles go. Without this, bold and italic would be lost.
  • Word: classes, mso- styles and <o:p> go; empty paragraphs are dropped.
  • Pasted images are left out until attachments (CE-006). Docs' image addresses expire and Word's are embedded data. The toast says so.
  • A copy from the editor itself keeps its images and its data-pm-slice, so pasting part of a list still works.
  • Toasts as in the v1 mockup: "Pasted · formatting cleaned (headings, lists, links and tables kept)". Cmd/Ctrl + Shift + V pastes plain text (ProseMirror's own): "Pasted as plain text".

HTML view (CE-020, spec §12).

  • </> HTML in the toolbar shows the page's HTML as a draft stores it, one block per line. The editor's own table widths and link targets are left out.
  • The other tools are off while it's open. Leaving with edited HTML asks first.
  • Back to visual cleans the HTML with the same allow-list and says how many unsafe tags it removed: "HTML applied · 1 unsafe tag removed". Going back without edits changes nothing and saves nothing.
  • Not done: the block "while agent suggestions are open" comes with CE-018, since there are no suggestions yet.

Schema JSON-LD is kept, as the spec asks.

  • Valid blocks are taken out before cleaning and put back as <script type="application/ld+json"> with the JSON parsed and written again, <, > and & escaped. Nothing but JSON can sit in the element.
  • In the editor it's a labelled, non-text block, "Schema · Product (JSON-LD)" (json-ld-node.ts), so it doesn't count toward the length.

Server re-check. saveContentDraft runs sanitizeDraftHtml (sanitize-html, lib/content/sanitize-draft-html.ts) on every save. A request made without the editor can't store a script, a handler or a javascript: link. It's tested with break-out attempts: a </script> inside JSON-LD, //host, data: images.

New dependencies (approved in the plan), pinned exact, each at least two weeks old:

  • dompurify 3.4.16 (MPL-2.0 or Apache-2.0)
  • sanitize-html 2.17.0 (MIT). Not 2.18.0, which needs Node 22.12 or later, while CI and the web Docker image run Node 20.
  • @types/sanitize-html 2.16.0 (dev), matching 2.17.0; both use htmlparser2 8.

sanitize-html lives in web/ because the save is a Next.js server action. yarn.lock only gains entries; nanoid's entry merges a key at the same version.

Next. On the user's request, HTML blocks come next in their own PR: as many custom-code blocks as needed per draft, kept verbatim and never run in Ansvisor, with one-click Copy HTML per block and for the whole page.

Related issue

Content Editor spec v2 (CE-005, CE-020). Stacked on #1258 → #1256.

Type of change

  • feat — New feature
  • fix — Bug fix
  • chore — Maintenance / dependencies
  • docs — Documentation only
  • refactor — Code change that neither fixes a bug nor adds a feature
  • test — Adding or updating tests

How to test

  1. Open a draft (Content › Library › New content).
  2. Copy a section from Google Docs (a heading, bold and italic words, a link with ?utm_source=x, a bulleted list, a table, an image) and paste it on an empty line.
    • The structure, bold and italic stay.
    • The link loses utm_source.
    • The image is left out, with a toast.
  3. Paste the same with Cmd/Ctrl + Shift + V: plain text.
  4. Click </> HTML: clean source, one block per line.
    • Add <h4>Care</h4><p style="color:red">x <script>alert(1)</script></p><iframe src="https://example.com"></iframe> and click Back to visual.
    • The toast says 2 unsafe tags removed, the H4 is an H3, and the color is gone.
  5. Add <script type="application/ld+json">{"@type":"Product","name":"X"}</script> in the HTML view: it shows as "Schema · Product (JSON-LD)".
  6. Reload. The draft as saved has no styles, scripts or tracking parameters, and keeps the JSON-LD.

Tests:

  • html-allowlist.test.ts: links, JSON-LD.
  • clean-html.test.ts: a Google Docs paste, a Word paste, unsafe tags, JSON-LD, images, data-pm-slice, source formatting.
  • sanitize-draft-html.test.ts: the server check, including break-outs.
  • content-drafts.test.ts: save sanitizes.
  • page.test.tsx: HTML view apply, unedited return, JSON-LD block.

Checklist

  • Branch follows the naming convention (feature/, fix/, chore/, docs/) — see CONTRIBUTING.md
  • Commits follow Conventional Commits
  • yarn lint passes (run from web/) (0 errors; the 6 warnings are in untouched files, as on main)
  • yarn typecheck passes (run from web/)
  • yarn format:check passes (run from web/)
  • Changes are focused — one concern per PR

yarn test (1,960 tests) and yarn build pass.

🤖 Generated with Claude Code

cihan-gyk and others added 3 commits October 20, 2026 17:09
Content Editor CE-001 and CE-002. Content becomes a group in the sidebar,
like Prompts: Opportunities keeps /dashboard/content, and the new Library
(/dashboard/content/library) lists every page a person or the Content Agent
writes or changes in Ansvisor, by status (Drafts, In review, Ready,
Published), with its page type, method, author and AEO score.

- Migration 00203: content_drafts with member RLS (select, insert, update;
  no delete yet). A guard trigger keeps author, created_by, brand and the
  scores server-side, so a member can't pass a draft off as the agent's.
- Sidebar: each submenu remembers its own open state (Prompts keeps its
  key), and only the longest matching entry is current, so Opportunities
  isn't marked on the Library.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Content Editor CE-004, stacked on the Library (ansvisor#1256). A draft opens at
/dashboard/content/editor/{id}: a header with its title, page type,
method and status, whether it's saved, and Mark ready; the toolbar (H1 H2
H3, bold, italic, link, lists, quote, table with add row / add column /
delete, image by address) with the length counter against the page
type's target; and the page as rich text (TipTap 3.31.4, pinned).

- Autosave after a pause in typing; saves never overlap, a failed one
  keeps the text and offers Retry, and leaving with unsaved text asks.
  The draft's title is its first H1.
- saveContentDraft validates the body (500k chars) and title and says
  when RLS matched no row; markContentDraftReady moves draft or in review
  to ready only.
- Links: http(s), mailto or a path on the brand's site; javascript:,
  //host and /\host are refused, in the dialog and when content loads.
- The Library gets New content (a blank draft, until the Start screen),
  and its entry stays current while a draft is open in the editor.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Content Editor CE-005 and CE-020, stacked on the editor core (ansvisor#1258).

- Paste: from Word, Google Docs, Notion or a web page, headings (H4-H6
  as H3), paragraphs, bold, italic, lists, links, tables and quotes stay;
  fonts, colors, classes, inline styles, scripts, iframes and utm_*,
  gclid, fbclid on links go. Google Docs' styled bold and italic become
  strong and em first. Pasted images wait for attachments. Cmd/Ctrl +
  Shift + V pastes plain text.
- </> HTML shows the page's HTML as a draft stores it, one block per
  line; Back to visual cleans it with the same allow-list and says how
  many unsafe tags it removed. Schema JSON-LD is kept: a block in the
  editor, written again from its JSON so it can't carry markup.
- The server checks every save against the allow-list again
  (sanitize-html), so a request made without the editor can't store a
  script, a handler or a javascript: link.
- dompurify 3.4.16 and sanitize-html 2.18.0, pinned.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk third Content Editor PR: paste cleaning (CE-005) and the HTML view (CE-020). It's stacked on #1258 → #1256, so please merge those first. One allow-list serves the browser (DOMPurify) and the server's check on every save (sanitize-html, in web/ since the save is a server action). Schema JSON-LD is kept, its JSON parsed and written again so it can't carry markup; the break-out attempts are in the tests. Both packages are pinned to versions at least two weeks old. Could you take a look?

@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 20, 2026
cihan-gyk and others added 3 commits October 20, 2026 18:41
sanitize-html 2.18.0 needs Node 22.12 or later, and CI and the web
Docker image run Node 20, so yarn install refused it. 2.17.0 has no
engine limit and the same API; @types/sanitize-html 2.16.0 matches it
(both on htmlparser2 8).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Links in a draft looked like the text around them (dark, barely
underlined), so a link just added seemed not to be there. They're blue
and underlined now. With the cursor in a link, the toolbar shows its
address, which opens it in a new tab; Cmd/Ctrl + click on it in the page
does too. A click alone still puts the cursor in it to edit. A path on
the brand's own site is shown, not opened: it has no address here.

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

# Conflicts:
#	web/messages/en.json
#	web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx
#	web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsx
#	web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk CI fix (ab0bda2): sanitize-html 2.18.0 needs Node ≥ 22.12, and CI and the web Docker image run Node 20, so yarn install refused it. It's now 2.17.0 (no engine limit, same API) with @types/sanitize-html 2.16.0; both use htmlparser2 8. The PR body says so. #1258's link fix is merged in (94f1565).

cihan-gyk and others added 4 commits October 20, 2026 20:49
ansvisor#1257 took 00203 (citation gap rollups) on main, so the content drafts
table moves to the next free number. The file is otherwise unchanged;
schema.sql is rebuilt.

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

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few fixes before merge:

  1. The JSON-LD regex backtracks catastrophically, and the server runs it on raw input (web/src/lib/content/html-allowlist.ts:114-128, called from sanitize-draft-html.ts:20, i.e. on every saveContentDraft at content-drafts.ts:135). <script\b[^>]*\btype…["']?[^>]*> has two [^>]* runs around \btype. On input with many <script type=application/ld+json and no >, the cost grows cubically. Measured in Node: about 2 s at 16.5k characters and about 16 s at 33k. The Zod cap is 500k characters, so one save request from any member can keep a server action busy until the function timeout, and they can repeat it. (Pasting the same text freezes the browser tab too, through cleanHtml.) Replace the regex with a linear scan: indexOf('<script'), then indexOf('>') for the end of the tag, test only that tag's slice for type=application/ld+json, then indexOf('</script'). Or let htmlparser2, already installed with sanitize-html, find the elements. Add a test that runs a pathological 500k input under a time budget. #1262's detectPageType reuses JSON_LD_SCRIPT, so the fix covers it too.

  2. The server re-check is advisory, since body_html can be written without the action (supabase/migrations/00204_content_drafts.sql:120-138). The member update policy lets any member PATCH content_drafts.body_html directly through PostgREST with their own session, so "a request made without the editor can't store a script" doesn't hold. Nothing renders the stored HTML raw today (every reader parses it through TipTap's schema), so this is fine for now. Either move draft writes behind the server (revoke insert/update (body_html) from authenticated and write with the admin client after the membership check), or say in sanitize-draft-html.ts that stored HTML is untrusted. That way later readers (Copy HTML, the API/MCP exports later in the stack) won't assume it's clean.

cihan-gyk and others added 5 commits October 21, 2026 15:01
…unsaved text ready

- saveContentDraft takes the version the editor last saw (updated_at and
  a SHA-256 of the page) and writes with .eq('updated_at', base). When
  another write came first, the page tells which kind: the same page means
  only other columns changed (Mark ready, the type), and the save goes over
  them; another page comes back `conflict` and nothing is overwritten. The
  header then says "Changed elsewhere · Reload" and autosave stops.
- Results are typed ({ ok: false, reason }) since Next.js hides server
  action messages in production: a page over 500,000 characters says "Too
  long to save" (and isn't sent at all), not "Couldn't save · Retry".
- Mark ready settles first: it waits for a save under way and isn't run
  when the page can't be saved.
- Nit: the title limit comes from 00204.

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

# Conflicts:
#	web/src/lib/actions/content-drafts.test.ts
#	web/src/lib/actions/content-drafts.ts
…king regex

The JSON-LD pattern had two [^>]* runs around \btype, so input with many
unclosed `<script type=application/ld+json ` tags took cubic time (about
16 s at 33k characters), and the server runs it on every save. It is now
a scan (indexOf for the tag, its end and </script>, the type tested on the
tag alone), linear in the length; a 500,000-character page built to
backtrack takes milliseconds. The paste cleaner uses the same scan.

sanitize-draft-html.ts now says stored HTML is untrusted: a member can
write body_html through PostgREST past this check, so readers parse or
clean it again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk Review fixes for #1259 are in c997d1b (merged up the stack):

  1. The JSON-LD regex is now a linear scan (jsonLdScripts in html-allowlist.ts).
    • It uses indexOf('<script'), then the tag's >, then </script, and tests type=application/ld+json on that tag's slice alone.
    • Each step moves past what it read, and a script's text is skipped as text (as HTML does).
    • The paste cleaner, the server check and, from feat(content): detect a draft's page type and set the brand's site type #1262 on, detectPageType all use it.
    • New tests run 500k-character inputs built to backtrack (unclosed tags, scripts with no end tag) under a time budget, through extractJsonLd and sanitizeDraftHtml. They take milliseconds.
  2. Stored HTML: I took the documentation route. sanitize-draft-html.ts now says body_html can be written through PostgREST past this check, so stored HTML is untrusted: readers parse it through the editor's schema or clean it again. Moving draft writes behind the server is a bigger change across the stack (the API, suggestions, history all write drafts). Happy to do it as a follow-up if you'd rather close that path.

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The scan is linear now, but it introduces one fix before merge:

  • I timed jsonLdScripts / extractKeptBlocks in Node on 500,000-character adversarial inputs: unclosed tags, scripts without an end tag, <script with no >, one huge tag full of type, whitespace runs and type= runs, </script without >, <scripts. Each finished in 0.2 to 22 ms. Four times the input took 3.5 to 6 times as long. The old regex took 16 s at 33k characters. The "stored HTML is untrusted" note is fine as the resolution of the second item.
  1. toLowerCase() changes the string's length, so the offsets taken from lower don't line up with html (web/src/lib/content/html-allowlist.ts:125, used at :144 and by extractKeptBlocks). 'İ'.toLowerCase() is two UTF-16 units (i + U+0307). Every İ before a JSON-LD script shifts start, end and text by one. The JSON then fails to parse and the block is dropped, the tail of the tag is kept, and that many characters after the script are cut.
    • Run through the save path with sanitize-html, a page with three İ in its headings and text before a JSON-LD block is stored without the schema and without the paragraph after it.
    • This happens on every save, in Copy HTML (#1260), in paste and the HTML view, and in #1262's schema detection, for any page with a Turkish capital İ before its schema.
    • Fix: lowercase only ASCII, which keeps the length and stays linear: const lower = html.replace(/[A-Z]+/g, (s) => s.toLowerCase()); (I checked it on the sample above and on the 500k inputs: 0.4 ms). Add a test with İ before a JSON-LD block.

@github-actions github-actions Bot removed the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 21, 2026

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fixes check out. Merging with the stack.

@gkhngyk
gkhngyk merged commit f110f92 into ansvisor:main Oct 21, 2026
4 checks passed
gkhngyk added a commit that referenced this pull request Oct 21, 2026