Skip to content

feat(content): import a brand page by its URL into a draft - #1288

Merged
gkhngyk merged 58 commits into
ansvisor:mainfrom
cihan-gyk:feature/content-url-import
Oct 21, 2026
Merged

gkhngyk merged 58 commits into
ansvisor:mainfrom
cihan-gyk:feature/content-url-import

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

Content Editor, PR 6c of the plan: bring a page in by its URL (CE-003; spec §9 "Optimize content (URL, paste, file)"), and let Start's "Optimize this page instead" (#1287) open the editor with the page's live text.

Stacked on #1287 → #1286 → #1262 → #1261 → #1260 → #1259 → #1258 → #1256. Please merge them in order. This PR's own change is 4e1f3bf.

Deploy the server before the web. The web calls the new POST /api/content-pages/import. Without it, the import says it couldn't read the page, and Start falls back to the page's title.

What it does

  • New content › Optimize content › Page URL, now the first of Page URL · Paste text · Upload file, as in the v1 mockup.
  • Start's "Optimize /… instead": Open editor reads the page's live text first. If it can't, the draft starts with the page's title and a warning says so.
  • Reasons a page couldn't be read are named:
    • not on the brand's site;
    • not a web page;
    • "The page answered 404";
    • too large;
    • too slow;
    • unreachable;
    • too many redirects.

Server: a guarded fetch (server/src/lib/safe-fetch.js). The address is a person's, so:

  • Address rules: only http(s), only on the web ports, and no credentials in the address.
  • Public addresses only:
    • Every address the host resolves to must be public: private, loopback, link-local (cloud metadata), shared, documentation, multicast, reserved, and their IPv6 forms are refused (net.BlockList).
    • The check runs in the connection's own lookup, so the address checked is the address connected to. That closes DNS rebinding.
    • An address written as an IP is checked in checkPageUrl too, because net.connect skips lookup for a literal. The URL parser has already turned 2130706433 or 0x7f.1 into 127.0.0.1.
    • The tests caught this: before the fix, http://127.0.0.1/ reached a local server.
  • Limits: redirects are followed by hand, at most 5, each checked like the first; 10 s for the whole fetch; 3 MB of body; HTML only. gzip, deflate and br are decoded.
  • No new dependencies: node:http(s), dns, net, zlib, util.

Server: the page's own content (server/src/lib/page-content.js, cheerio)

  • Where: main, article, [role=main], #content or #main, else the body.
  • Removed: nav, header, footer, aside, forms, scripts and the like.
  • Links and images: made absolute against the page's address.
  • H1: a page H1 outside the content (a hero) heads it.
  • JSON-LD: up to 5 blocks are kept after the content, with < escaped inside the script.

Server: the route (server/src/routes/content-pages.js, mounted at /api/content-pages)

  • Who: a member of the brand's organization (assertBrandAccess).
  • Which pages: only the brand's own domains or their subdomains (onBrandDomain), checked before the fetch and again after redirects. The editor optimizes the brand's content, not anyone else's, and the fetch stays on sites the brand named.
  • Validation: brandId is validated with z.guid(), as the other routes do. Zod 4's uuid() refuses seeded ids such as the demo brand's.
  • Errors: they come back as { code } with a 4xx/5xx. The web's importContentPage returns the code instead of throwing, since production hides a server action's errors.

Related issue

Content Editor CE-003 (Optimize content by URL), CE-015 (Optimize instead). Stacked on #1287 → … → #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

Run the server from this branch. The brand needs a reachable site among its domains.

  1. Content › Library › New content › Optimize content › Page URL. Enter a page of the brand's site (a bare host works) and click Import.
    • The summary shows its title, path and headings.
    • Continue: "Optimize: {title}", with the type read from the page.
    • Open editor: the page's text, links, images and schema are in the draft. The tag reads "{type} · /path". Menus and footers are left out.
  2. Try:
    • another site's page: "Use a page on your brand's site…";
    • a missing page on the brand's site: "The page answered 404.";
    • http://localhost/… or http://169.254.169.254/: refused.
  3. Create from scratch with prompts one of the brand's pages answers, then Optimize /… instead and Open editor: the editor opens with that page's live text.

Checked on a real site, temporarily added to the demo brand:

  • ansvisor.com/blog → www.ansvisor.com/blog, a redirect on the brand's site;
  • Wikipedia, refused as off-site;
  • a missing page: 404;
  • Start's Optimize-instead with the live page.

Checked in light and dark, and at 1024 px.

Tests:

  • safe-fetch.test.js (16):
    • public and private v4 and v6 addresses, mapped forms included;
    • URL rules;
    • blocked hosts: localhost, IP literals, decimal and hex IPs, cloud metadata, [::ffff:127.0.0.1];
    • against a local site: charset, redirects (to an end, to ftp, to a private name, to an IP, in a loop), gzip, not HTML, 404, size, timeout.
  • page-content.test.js (5): frame removed, absolute links and images, JSON-LD kept and escaped, article and body fallback, H1 outside the content.
  • content-pages.test.js (5):
    • a brand page read, with a bare host as https;
    • off-site pages never fetched;
    • a redirect off the site;
    • error codes and statuses;
    • another organization's brand, and a bad id.
  • content-drafts-start.test.ts: importContentPage sends the session and body, maps error codes (unknown → failed, network → failed), and sends nothing for bad input.
  • new-content-dialog.test.tsx:
    • Page URL import, cleaned, with the type from the address and source_url;
    • error messages;
    • Optimize-instead brings the live text;
    • the fallback with a warning;
    • paste and file under their tabs.

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

Web: yarn test (2,082 tests) and yarn build pass. Server: npm run format, npm run lint and npm test (1,945 tests) pass.

🤖 Generated with Claude Code

cihan-gyk and others added 22 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]>
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
On the user's request, as Webflow's custom code in rich text: as many
HTML blocks as a page needs, each carrying code as written (an embed, a
widget, a form), and one-click Copy HTML for a block or the whole page.

- An HTML block is added from the toolbar where the cursor is, and edited
  or removed from its own Edit. The editor shows its code as text; it
  never runs in Ansvisor. A draft stores it as UTF-8 base64 in an empty
  element, so no markup in it can act, and the server checks each one
  decodes and fits 50,000 characters.
- Copy HTML (header) puts the page on the clipboard as HTML to publish:
  each block as its own code, schema JSON-LD as its script. A block's
  own Copy HTML copies just its code. A refused Clipboard API falls back
  to the browser's copy command.
- The HTML view shows each block between <!-- html-block --> markers,
  kept as written; code typed between new markers becomes a block. A
  paste from elsewhere can't bring blocks in.
- The link, image and block dialogs focus their field when they open.

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

# Conflicts:
#	web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsx
#	web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx
Inserting an HTML block scrolls the cursor into view, and ProseMirror
measures a Range to do it. jsdom's ranges have no getClientRects, so on
CI's Node 20 the measuring threw on a timer after the test and failed the
run as an unhandled error. The editor test gives ranges an empty
measurement, as jsdom has no layout anyway.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…es to a draft

A paperclip tool and drag-and-drop on the editor (CE-006). Excel and CSV
open a preview (sheet picker, first 10 rows, header row) and insert as a
table, asking first above 200 rows. Word (.docx, via mammoth), Markdown,
HTML and plain text import as content through the same cleaning as a
paste. Images, old .xls/.doc and files over 10 MB get a clear message.
Imports land under a table when the cursor is inside one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Page types follow the kind of site (CE-023). Brand settings get a Site
type (B2B SaaS, E-commerce, B2C; guessed from Shopping mode and the
industry until picked), stored in brands.site_type (migration 00205). A
draft's page type is detected from its URL, JSON-LD schema and title,
and kept in step as the page changes, until the person picks one from
the editor header's page type menu (content_drafts.page_type_source).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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]>
New content (CE-003) starts a page from an open Content Opportunity, a
tracked prompt or a topic, or brings content to optimize by pasting
(cleaned like the editor's paste) or uploading a Word, Markdown, HTML or
text file. Start (CE-015) offers the site type's page types, the one the
title or content shows picked first, and opens the editor.

The draft keeps the opportunity it came from and the prompts it should
answer (migration 00206: opportunity_id, prompt_ids, and a trigger that
refuses another brand's opportunity or prompts). A new page starts with
its title as the H1; content to optimize is checked against the draft
allow-list. The editor's file readers move to lib/content/import-document
so both use them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Start (CE-015) now shows which of the brand's own pages AI already cites
for the prompts a new page would answer: prompts in common, citations in
the last 30 days and the Google position from Search Console, through a
new security-definer RPC, content_page_overlap (migration 00207). It
recommends one option: optimize a page that already answers half the
prompts or more, otherwise create the page and link the others to it,
or say it is safe to create.

Picking an existing page makes the draft that page's: optimize, its
title as H1, the page type read from its address, and its URL kept in
content_drafts.source_url, which the editor shows beside the page type.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Optimize content gets a Page URL option (CE-003), and Start's "Optimize
this page instead" now brings the page's live text. The API reads the
page through a new guarded fetch (server lib/safe-fetch.js):
- http(s) on the web ports, no credentials in the address;
- every address the host resolves to must be public, checked in the
  connection's own lookup, and an address written as an IP checked
  before it, since a literal skips the lookup;
- redirects followed by hand and checked the same way; 10 s, 3 MB,
  HTML only.
POST /api/content-pages/import reads only the brand's own domains,
before and after redirects, and returns the page's main content, title
and JSON-LD (lib/page-content.js). The web cleans it like a paste and
reads the page type from the address and the content.

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

Copy link
Copy Markdown
Collaborator Author

@gkhngyk Content Editor PR 6c (CE-003 Optimize by URL): a new server route POST /api/content-pages/import reads a page of the brand's own domains through a guarded fetch (server/src/lib/safe-fetch.js: public addresses only, checked in the connection's lookup and for IP literals; redirects checked by hand; 10 s / 3 MB / HTML only) and returns its main content. Since it fetches user-given URLs, could you review the SSRF checks closely? Deploy the server before the web. Stacked on #1287 → … → #1256.

gkhngyk
gkhngyk previously approved these changes 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.

Looks good. The guarded fetch is solid:

  • the lookup checks every address it connects to, so DNS rebinding can't get through;
  • IP literals are checked before connecting;
  • each redirect is checked again;
  • the size limit counts the decompressed body.

The imported HTML goes through cleanHtml on the client and sanitizeDraftHtml on the server before it's stored.

A few small hardening points, none blocking:

  1. Redirect hops between the first and last address aren't held to the brand's domains (server/src/routes/content-pages.js:57-65). Only the first and the final URL go through onBrandDomain. An open redirect on a brand's site therefore makes the server request any public URL before the route refuses the result. Brand domains are member-editable, so the public-address check is the real boundary, but closing this is cheap: pass an allowUrl predicate into fetchPage and check it in the redirect loop (server/src/lib/safe-fetch.js:253) before the next request.

  2. The charset only comes from the Content-Type header (server/src/lib/safe-fetch.js:141-152). A page that declares windows-1254 or iso-8859-9 only in <meta charset> comes in as UTF-8 mojibake. Sniff the first ~1 KB for <meta charset=…> / http-equiv when the header has no charset.

  3. Two things in the body stream (server/src/lib/safe-fetch.js:189-209):

    • On too_large, only req is destroyed. The zlib stream keeps inflating whatever it has already buffered.
    • res.pipe(zlib…) doesn't forward an error from res, so a connection reset in the middle of the body waits out the full 10 s and then reports timeout.

    Using stream.pipeline(res, decoder, …) and destroying the pipeline on overflow fixes both.

  4. readPage has no catch (web/src/components/content/new-content-dialog.tsx:250). If the server action itself throws (a deploy skew or a network drop), the result is an unhandled rejection, and the person sees no error message. Catch the error and set urlError to failed.

Approving this PR's own change. It merges once the PRs below it in the stack are ready; see the overview on #1256.

…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]>
cihan-gyk and others added 17 commits October 21, 2026 15:50
…re Start's guess as detected

- check_content_draft_links checks only the prompt ids a write adds, and a
  statement-level trigger on prompts removes deleted ids from every draft
  (prompt_ids has no foreign key), so the Brief tab's append no longer
  fails with 23514 once a tracked prompt is gone (00206).
- Start sends whether the person picked the type: a pick is stored as
  'user', Start's guess (or the Blog post fallback) as 'detected', so it
  follows the page. A save that finds no type keeps the one the draft had.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	supabase/schema.sql
#	web/src/components/content/new-content-dialog.tsx
#	web/src/lib/actions/content-drafts.ts
…and leave ChatGPT Shopping out

content_page_overlap took 8.9 s cold on the brand with the most citations,
mostly reading prompt_results' wide rows one citation at a time for
prompt_id. The window's answers to the prompts now come from
idx_prompt_results_brand_created_cover alone (brand_id, created_at, with
id and prompt_id included), materialized and hash-joined to the brand's
citations and its own pages. ChatGPT Shopping answers are left out, as
Impact does, so Start and Impact count the same citations. The function is
planned for each call's values (plan_cache_mode = force_custom_plan).

Checked against the old version on a fixture: same pages and prompts in
common; the only difference is the Shopping citations.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	web/src/components/content/new-content-dialog.tsx
…İ before them keeps them

`toLowerCase()` turns 'İ' into two UTF-16 units, so every İ before a JSON-LD
script shifted the positions taken from the lower-cased copy: the schema was
dropped on save, with as many characters of the text after it. Only ASCII
letters are lower-cased now, which keeps the length and stays linear.

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

# Conflicts:
#	web/src/lib/content/sanitize-draft-html.test.ts
The test merged up from ansvisor#1259 used extractJsonLd, which this branch
replaces with extractKeptBlocks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
gkhngyk
gkhngyk previously approved these changes 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.

Fixes check out. The only changes since the last review are the merges of the earlier PRs' fixes (the dialog now passes typePicked), and this PR's incremental diff is otherwise unchanged. The low items are in the follow-up PR.

The PRs below this one are squash-merged on main; this keeps only this branch's own change on top.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

@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 ba10b86 into ansvisor:main Oct 21, 2026
4 checks passed
@github-actions github-actions Bot removed the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants