Skip to content

fix(markdown): leave raw text alone, decode the front matter base, and cover graphic data - #123

Closed
tobocop2 wants to merge 3 commits into
fix/markdown-inline-image-datafrom
fix/markdown-raw-text-base-graphic
Closed

tobocop2 wants to merge 3 commits into
fix/markdown-inline-image-datafrom
fix/markdown-raw-text-base-graphic

Conversation

@tobocop2

@tobocop2 tobocop2 commented Sep 26, 2026 •

Copy link
Copy Markdown
Member

Stacked on #105. Merge that first, then retarget this to main.

Text inside raw text elements stays as written

The relative-link rewrite read <title>use <a href="x.html"> tags</title> as markup and put a full address into the front matter title. The rewrite now changes only the tags an HTML parser reads as tags, which html5ever's tokenizer and tree builder decide. So link-shaped text in title, textarea, script, style and the other raw text elements stays as written, while inline SVG and MathML, where those names are ordinary elements, no longer hide the rest of the page.

Base address in the front matter is decoded

<base href="https://example.com/it&#x27;s/"> gave base: https://example.com/it&#x27;s/, because the converter copies the value into the front matter without decoding it. The rewritten <base href> is now written unencoded between double quotes, with any ", < or > percent-encoded so the value cannot end the attribute or open markup.

<graphic> data addresses

The data: rule for images now covers the addresses of <graphic>. A data: address attribute is removed rather than emptied, so <graphic url="data:..." href="real.png"> falls through to the real address.

Closes #102
Closes #103
Closes #113

@tobocop2
tobocop2 force-pushed the fix/markdown-raw-text-base-graphic branch from 293204d to 250e0db Compare September 26, 2026 08:15
@tobocop2
tobocop2 marked this pull request as ready for review September 26, 2026 11:41
@tobocop2
tobocop2 requested a review from Goldziher as a code owner September 26, 2026 11:41
Goldziher added a commit that referenced this pull request Sep 26, 2026
html-to-markdown-rs 3.15 adds a `base_url` conversion option that
resolves relative href/src the same way `resolve_link_targets` does.
The requirement is a caret range, so 3.15 arrives on a routine
`cargo update` with the option left `None`: nothing fails to compile,
no output changes, and nothing says the crate now carries two
relative-link resolvers.

A canary test reads the serialised option set of a default
`ConversionOptions` and fails once `base_url` appears in it, with the
reconciliation in the failure message. `..Default::default()` stays, so
every other library default keeps flowing through; writing the fields
out exhaustively would have made this crate own ~30 defaults it has no
opinion on, and a later default change in the library would then stop
reaching it, replacing one silent divergence with another.

The option is deliberately not set. It would resolve the empty `src`
that marks a dropped inline-data payload to the page URL, and it would
rewrite the fragment-only hrefs this crate leaves as written, so it is
only safe after #123. Deleting the pre-pass in favour of it is tracked
in #190, which also closes out #104.

Also mirrors the #63 and #94 entries into the docs-site changelog,
which nothing syncs.
Goldziher added a commit that referenced this pull request Sep 26, 2026
* fix(markdown): resolve relative links against the page URL

The markdown kept each href and src as the HTML wrote it, so relative
links did not work outside the page and a <base href> had no effect.

html-to-markdown-rs has no base URL option. Before conversion, the
HTML's relative addresses are rewritten in place to absolute URLs: a
href, img src, the lazy-load image attributes, srcset candidates, media
sources and quotation citations. The base is the page's first
<base href>, resolved against the URL that served the page, the same
base the links list uses. Every <base href> is rewritten to that base,
so the front matter shows the address links resolve against.

Addresses are decoded before they are resolved and escaped when written
back. The decoding uses html5ever's tokenizer, which applies the WHATWG
rules a browser applies, including the Windows-1252 table for numeric
references 128-159. Values without an ampersand skip the tokenizer. Tag
names match in any case.

Absolute URLs of any scheme, fragment-only links and empty values stay
as written. The converter's escaping and output formats stay the same.

Closes #63
Closes #94

* test(markdown): fail if html-to-markdown-rs gains base_url

html-to-markdown-rs 3.15 adds a `base_url` conversion option that
resolves relative href/src the same way `resolve_link_targets` does.
The requirement is a caret range, so 3.15 arrives on a routine
`cargo update` with the option left `None`: nothing fails to compile,
no output changes, and nothing says the crate now carries two
relative-link resolvers.

A canary test reads the serialised option set of a default
`ConversionOptions` and fails once `base_url` appears in it, with the
reconciliation in the failure message. `..Default::default()` stays, so
every other library default keeps flowing through; writing the fields
out exhaustively would have made this crate own ~30 defaults it has no
opinion on, and a later default change in the library would then stop
reaching it, replacing one silent divergence with another.

The option is deliberately not set. It would resolve the empty `src`
that marks a dropped inline-data payload to the page URL, and it would
rewrite the fragment-only hrefs this crate leaves as written, so it is
only safe after #123. Deleting the pre-pass in favour of it is tracked
in #190, which also closes out #104.

Also mirrors the #63 and #94 entries into the docs-site changelog,
which nothing syncs.

* refactor(scrape): extract the x-robots-tag directive pair

scrape_from_crawl_response reached 81 lines against poly's 80-line limit
once this branch threaded the document URL through. The header value and
the directives derived from it are returned together because the raw value
is reported on ScrapeResult while the directives gate link following.

No behaviour change. Paid down here rather than added to the alef.toml
baseline, per the ground rule on #42.

---------

Co-authored-by: Na'aman Hirschfeld <nhirschfeld@gmail.com>
@tobocop2
tobocop2 marked this pull request as draft September 26, 2026 16:39
@Goldziher

Copy link
Copy Markdown
Member

Nothing has ever compiled this branch

5 checks, all red, one of them the PR base gets real CI guard that exists for exactly this: the base is fix/markdown-inline-image-data, which matches no workflow's pull_request: branches: [main] filter. Validate Rust, Rust (macos-latest), Rust (ubuntu-24.04-arm), Feature combinations, Changelog mirror and Validate / Validate (poly) never ran. #105, whose base is main, gets 24. Nothing has type-checked, clippy'd or tested this diff.

It is also CONFLICTING against its own base. git merge-tree origin/fix/markdown-raw-text-base-graphic origin/fix/markdown-inline-image-data:

CONFLICT (content): Merge conflict in CHANGELOG.md
CONFLICT (content): Merge conflict in crates/crawlberg/src/html/link_targets.rs
CONFLICT (content): Merge conflict in docs-site/src/content/docs/changelog.md

#105 gained f4a59a4be ("read link targets from the page with raw text masked") after this branch last merged it, and this diff reverts that commit's approach — hence the link_targets.rs conflict.

Most serious: this reintroduces the <base>-in-<title> hijack #105 fixed

resolve_link_targets goes back to tl::parse(html, ParserOptions::default()) and still calls effective_base_url(&dom, document_url). That helper is elements_named(dom, "base").find_map(...) over tl's tree of the unmasked source, and tl has no raw-text handling, so <title>x <base href="https://evil.example/"></title> is still a real <base> node and still decides where every link on the page resolves. real_start_tags only gates which tags get rewritten; it does nothing for the base lookup.

The test that covered it, a_base_written_inside_title_text_does_not_count, is deleted by this diff. Nothing replaces it: leaves_the_contents_of_raw_text_elements_as_written uses only <a href>, and a_tag_inside_another_tags_quoted_value_is_text asserts output == input over blobs whose every <a href> sits inside raw text, so it holds whichever base is chosen. Both pass with the hijack live.

Fix: resolve the base from a masked parse as #105 does, or take the first real <base href> out of real_start_tags, and restore the deleted test.

start_tags.rs is a second implementation of a rule that already has one, and they already disagree

64fb3853b landed mask_raw_text_markup (html/raw_text.rs, 435 lines), used by scrape.rs, map.rs, engine/redirect.rs, engine/crawl_state.rs and browser_detect.rs. This PR adds html/start_tags.rs (207 lines, html5ever tokenizer + tree builder) deciding the same question for one caller. This is not redundant with 64fb3853b — it covers more (xmp, iframe, noembed, noframes, plaintext, foreign-content nesting, a > inside a quoted value) — but it is a competing second implementation that must now be kept in step with the first.

They already diverge, silently. TreeBuilderOpts::default() sets scripting_enabled: true (html5ever 0.40.1, src/tree_builder/mod.rs:75), so real_start_tags reads <noscript> content as raw text. raw_text.rs's RAW_TEXT_ELEMENTS deliberately excludes it, with a ~keep saying why: "its content is raw text only when scripting is enabled, and a crawler's HTTP fetch has no scripting … it is also how <noscript><img src=…></noscript> tracking pixels stay discoverable". Net effect: <noscript><img src="lazy.jpg"> is discovered as an absolute asset by the crawler and rendered with a relative address in the markdown. The changelog entry for #102 lists <noscript> as a fix; it is a regression against the decision recorded in raw_text.rs.

Fix: pass TreeBuilderOpts { scripting_enabled: false, ..Default::default() } and drop <noscript> from the changelog list — or change raw_text.rs too and say why. The two must not disagree by accident. And if mask_raw_text_markup is genuinely not good enough for this path, that argument belongs in raw_text.rs.

Removal instead of emptying loses payload suppression on a duplicated attribute

<img src="data:…A" src="data:…B">: tl and html5ever both keep the first, attribute_removal deletes src="data:…A", and src="data:…B" becomes the only src. The converter reads the first src (resolve_effective_src, handlers/image.rs), so the payload reaches the markdown. #105's emptying prevented that, because src="" stayed first. a_repeated_attribute_is_rewritten_once already documents that only the first is touched.

Removal is only needed for <graphic>, and the ~keep says why. I checked it and it is accurate: handlers/graphic.rs does ["url","href","xlink:href","src"].into_iter().find_map(|name| decoded_attribute(tag, name)), and decoded_attribute is tag.attributes().get(name).flatten()?, which yields Some("") for a present-but-empty attribute — so an emptied url="" does shadow a real href. Suggest: keep emptying for <img>, remove only for <graphic>.

start_tag_end can disagree with html5ever and silently skip a tag

b'"' | b'\'' if after_equals => { /* skip to the matching quote */ }

after_equals stays set across the rest of an unquoted value, so <a href=a=b"c> sends this hunting for a closing quote past the real >, while html5ever ends the tag at > in the unquoted-value state. The computed end then matches no entry, find returns None, and the tag is left unrewritten with no diagnostic — a relative link silently ships relative. Reset after_equals on any non-whitespace byte that is not a quote immediately following the =, and add a tracing::debug! with the offset when find misses for a name that is in TARGETS, so the two scanners diverging is observable rather than silent.

Smaller

  • RealTags::find binary-searches tags by end. That is only sound because fed is monotonic and one start tag ends at one >; the invariant is not written down, and find would return the wrong tag if a later change pushed out of order. Worth a ~keep.
  • xlink:href on a <graphic> inside <svg>: html5ever's foreign-content attribute adjustment splits it into prefix xlink + local href, and parsed_value matches &*a.name.local == attr, so "xlink:href" never matches there and the attribute is skipped. an_inline_data_graphic_drops_the_payload only tests <graphic> at top level.
  • percent_encodes_quotes_and_angle_brackets_in_the_written_base has no case for a base whose serialized URL contains a literal &, which is the one character whose handling differs between <base href> and every other attribute. Add <base href="/a&amp;amp;b/"> to that table — the_front_matter_base_relies_on_the_converter_not_decoding_it covers the end-to-end path but not the unit.

Verified, for the record

The base-encoding design is correct against 3.14.3, not arbitrary: head_metadata.rs::extract_base and main_helpers.rs::collect_base_head_metadata both take tl's as_utf8_str() with no decoding, while handlers/link.rs:57 and utility/attributes.rs::decoded_attribute do decode. So writing the base unencoded and every other value encoded is right, and the_front_matter_base_relies_on_the_converter_not_decoding_it is a good tripwire for #509.

Changelog is under [Unreleased] → ### Fixed and the [Unreleased] block is byte-identical between the two files (extracted with the gate's own awk; both a631676f…). No public API change, so no binding regeneration. link_targets.rs 685 lines, start_tags.rs 207, collect_edits 56 — under poly's limits. No println!/eprintln!/dbg!.

Suggested process

Do not merge as-is. Settle the masking question first (restore the base fix; reconcile noscript), then retarget to main after #105 lands so real CI runs at least once. The <graphic> data: coverage and the base decode are small and independent of the raw-text rewrite — splitting them out would get two thirds of this landed behind real CI while the third is argued.

Not verified

No build, no cargo check, no cargo clippy, no tests, no poly lint, no poly fmt --check, no alef, no task. Everything above is from reading the diff, git merge-tree, gh pr checks, and the vendored html-to-markdown-rs 3.14.3 / html5ever 0.40.1 sources in the local cargo registry. In particular I have not confirmed that start_tags.rs compiles against html5ever 0.40.1's TokenSink/TreeSink signatures, and the <base>-in-<title> regression is read off the code path, not observed in a run.

tobocop2 added a commit that referenced this pull request Sep 26, 2026
…e too

The pre-pass emptied a data: address only on images, so a data: video, audio,
iframe or source address was written into the markdown in full. These elements
now get the same treatment, and a video or audio element falls back to a real
nested source.

The scrape test now asserts that fit_content keeps the image line, which the
PR claimed and no test checked, and the changelog entry for #97 no longer
describes the raw-text fix, which belongs to #123.
@tobocop2

Copy link
Copy Markdown
Member Author

Thanks for the review. Every point is answered below; the changes are in c195fa49c (the current #105 merged in) and c58c8bd05.

Nothing has ever compiled this branch

Agreed, and fixed. The branch now merges the current #105: the media list and the graphic share one data rule, every element on it has the attribute removed, and the two raw-text changelog sentences moved into the #102 entry. On a Linux box: cargo fmt --check rc=0, workspace clippy with -D warnings (without the php crate) rc=0, wasm32 check rc=0, and cargo test -p crawlberg --all-features gives 1184 passed, 0 failed over 60 binaries. The changelog mirror check passes. I will retarget to main once #105 lands, so real CI runs.

Most serious: this reintroduces the <base>-in-<title> hijack #105 fixed

This review read a head from before the branch took in the masked parse from #105. The current head parses the masked page and takes the base from that parse, and a_base_written_inside_title_text_does_not_count is back and passes. #232, stacked on this branch, then takes the base from the HTML parser itself.

start_tags.rs is a second implementation of a rule that already has one, and they already disagree

Agreed that two definitions must not drift apart. #232, stacked on this branch, deletes the hand-written masking scanner, so link extraction and the markdown share one parser-based definition of raw text. The <noscript> difference stays, on purpose and documented: link extraction reads it as markup, as a browser without scripting does; the markdown reads it as text, as the converter does.

Removal instead of emptying loses payload suppression on a duplicated attribute

The case is real, and it is fixed without going back to emptying (an empty src is the sentinel #190 says base_url would resolve to the page itself). Every later copy of a removed attribute goes too, because the converter reads the first copy and a leftover would take its place. The later copies are found in one pass over the rest of the tag: 32,000 copies in one tag take 11 ms in a release build. Tests removes_every_copy_of_a_removed_attribute and a_repeated_inline_data_address_drops_every_payload fail without the fix and pass with it.

start_tag_end can disagree with html5ever and silently skip a tag

Your exact input, <a href=a=b"c>, already ended at the right >. A sibling did not: <a href=x="y> gave the first link the second link's address. That case is fixed (test an_equals_sign_inside_an_unquoted_value_does_not_open_a_quote), but the underlying point stands: a hand-written tag-end scan still disagrees with html5ever on 5,800 of 283,305 start tags we measured, for example <a href=b ="x>. The fix that removes the disagreement rather than patching one more case is to take the tag end from html5ever itself, which #232 makes possible. That is #233, stacked on #232.

Smaller

  • The binary search invariant: there is now a ~keep on the lookup: tags are pushed as they are fed, so their ends only grow, and one > ends at most one start tag.
  • xlink:href inside <svg>: it already worked. The recorder reads the tokenizer's tokens, and the tree builder adjusts foreign attributes later, on its own copy. reads_the_xlink_href_of_a_graphic_inside_svg passes at the heads before this round too.
  • A base with a literal &: the row ("/a&amp;amp;b/", "https://example.com/a&amp;b/") is in the table and passes.

Suggested process

I would keep this as one PR. The masking question is settled in #232, on top of this branch, and splitting the graphic change from the base decode would leave an intermediate branch that nobody has gated, which this repository's own history argues against. I will retarget to main after #105 lands.

Not verified

Now verified on a Linux box: build, clippy, the wasm32 check, the full crawlberg test suite (1184 passed, 0 failed), fmt and the changelog mirror are green. The <base>-in-<title> case is a passing test. Not run here: the macOS leg, poly lint, and alef (no public API or generated file changed).

From your #105 review: srcset="" and the fallback to emptying

  • A candidate list whose every candidate is data: is now removed, not left as srcset="" (test removes_a_candidate_list_left_empty_by_inline_data).
  • The fallback to emptying is gone: the attribute name is looked up in the same bytes the tag parser read. The miss came from a masked < where the masking scan misread a quote (test removes_an_attribute_where_the_masking_scan_misreads_the_tag).
  • The refactor(markdown): delete the crawlberg-side link pre-pass once h2m base_url is adopted #190 note in markdown.rs now says a dropped address is removed, never emptied.

@Goldziher

Copy link
Copy Markdown
Member

Triage note: two of the three parts are upstream work in xberg-io/html-to-markdown.

The front-matter base re-encoding exists only because the converter does not decode <base href> (head_metadata.rs::extract_base takes as_utf8_str() undecoded), filed as xberg-io/html-to-markdown#509 — fixed there, this half becomes dead code plus a tripwire test. The <graphic> data: rule is the same converter gap as #97/#113: converter/handlers/graphic.rs:51 writes the destination verbatim and has no option not to, so the rule belongs on ConversionOptions rather than being maintained per element name in crates/crawlberg/src/html/link_targets.rs. The raw-text part is genuinely crawlberg's.

Goldziher pushed a commit that referenced this pull request Sep 27, 2026
…e too

The pre-pass emptied a data: address only on images, so a data: video, audio,
iframe or source address was written into the markdown in full. These elements
now get the same treatment, and a video or audio element falls back to a real
nested source.

The scrape test now asserts that fit_content keeps the image line, which the
PR claimed and no test checked, and the changelog entry for #97 no longer
describes the raw-text fix, which belongs to #123.
@Goldziher
Goldziher force-pushed the fix/markdown-raw-text-base-graphic branch from c821f58 to 500f5be Compare September 27, 2026 08:51
…d cover graphic data

tl has no raw-text handling, so the relative-link rewrite treated
<a href> inside <title> as markup and wrote a full address into the
front matter. The rewrite now walks tags in source order and skips any
tag that starts inside title, textarea, script, style, xmp, iframe,
noembed, noframes, noscript or plaintext, following the WHATWG
tokenizer: each ends only at its own end tag in any case, an end tag
inside a quoted attribute of the start tag does not end it, and an
unclosed one runs to the end of the page.

The front matter showed the base with character references encoded,
because html-to-markdown-rs copies <base href> without decoding it. The
rewritten <base href> is now always the resolved base written unencoded
between double quotes, which a serialized URL cannot break out of.

The data: rule for images now also empties <graphic> addresses.

The start tags a real parser reads come from html5ever's tokenizer and tree builder, which covers raw text, SVG and MathML. A tl tag is rewritten only when its end offset and name match one of them, and the rewrite uses html5ever's parsed value, so CR, CRLF and NUL are normalized as a browser reads them. The written base percent-encodes ", < and >. A data: address attribute on an image or graphic is removed rather than emptied, so the converter falls through to a real address. A test pins that the converter does not decode the base yet.
…tags as tl does

When the pre-pass drops an inline data address it now removes every later copy
of the same attribute on that tag, in one forward pass, so a duplicate never
takes the removed one's place. A srcset whose every candidate is inline data is
removed instead of left empty. The attribute lookup reads the same bytes tl
parsed, so a quote the masking scan misreads no longer makes the removal fall
back to emptying, and a tag such as <a href=x="y> no longer gives the next
link's address to the first.
Goldziher pushed a commit that referenced this pull request Sep 27, 2026
…e too

The pre-pass emptied a data: address only on images, so a data: video, audio,
iframe or source address was written into the markdown in full. These elements
now get the same treatment, and a video or audio element falls back to a real
nested source.

The scrape test now asserts that fit_content keeps the image line, which the
PR claimed and no test checked, and the changelog entry for #97 no longer
describes the raw-text fix, which belongs to #123.
…ext-base-graphic

# Conflicts:
#	CHANGELOG.md
#	docs-site/src/content/docs/changelog.md
@tobocop2

Copy link
Copy Markdown
Member Author

Agreed. The decoded base in the front matter is fixed in the converter by xberg-io/html-to-markdown#537, so this half is dropped once crawlberg adopts it. The graphic data rule goes into the converter option in xberg-io/html-to-markdown#528. The raw-text part stays here.

@tobocop2
tobocop2 removed this pull request from stack #305 September 27, 2026 22:07
@tobocop2
tobocop2 added this pull request to stack #455 September 27, 2026 22:07
@tobocop2

Copy link
Copy Markdown
Member Author

The three fixes here patch the link rewrite that #190 removes, and html-to-markdown now fixes the front-matter base (xberg-io/html-to-markdown#537) and inline data graphics (#566) itself. #102, #103 and #113 stay open until crawlberg takes the html-to-markdown release through #405 and #190.

@tobocop2 tobocop2 closed this Sep 29, 2026
@Goldziher
Goldziher deleted the fix/markdown-raw-text-base-graphic branch October 10, 2026 07:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants