diff --git a/crates/core/src/anatomy/mod.rs b/crates/core/src/anatomy/mod.rs new file mode 100644 index 00000000..8adc87ba --- /dev/null +++ b/crates/core/src/anatomy/mod.rs @@ -0,0 +1,4 @@ +//! The anatomy core (R3): SVG reading and sanitising, the annotation layer drawn from the +//! sheet document, and the composition of a view (canvas and highlight). + +pub mod svg; diff --git a/crates/core/src/anatomy/svg/mod.rs b/crates/core/src/anatomy/svg/mod.rs new file mode 100644 index 00000000..7123ced5 --- /dev/null +++ b/crates/core/src/anatomy/svg/mod.rs @@ -0,0 +1,3 @@ +//! SVG text → bounded, sanitised tree → text. + +pub mod prescan; diff --git a/crates/core/src/anatomy/svg/prescan.rs b/crates/core/src/anatomy/svg/prescan.rs new file mode 100644 index 00000000..02ea16f3 --- /dev/null +++ b/crates/core/src/anatomy/svg/prescan.rs @@ -0,0 +1,279 @@ +//! Bounds an SVG text before any XML parser sees it (plan R3 C2). roxmltree builds its tree +//! recursively enough to overflow the 1 MiB wasm stack between 1,000 and 3,000 nesting +//! levels (measured 2026-10-14), so the depth and the element count are taken here by a +//! markup scanner: comments, CDATA sections, processing instructions and quoted attribute +//! values are skipped as the XML grammar defines them, never by pattern matching. The scan +//! is an upper bound of what a parser would build; anything it cannot close is malformed. + +/// The resource limits of one SVG text. +#[derive(Debug, Clone, Copy)] +pub struct SvgCaps { + /// UTF-8 bytes of the whole text. + pub max_bytes: usize, + /// Elements, the root included. + pub max_elements: usize, + /// Nesting depth, the root at depth 1. + pub max_depth: usize, +} + +/// The engine's caps (`packages/pdf/src/svg/sanitize.ts` SANITIZER_CAPS) plus the byte cap +/// R3 adds before parsing. +pub const SVG_CAPS: SvgCaps = SvgCaps { + max_bytes: 2 * 1024 * 1024, + max_elements: 20_000, + max_depth: 64, +}; + +/// Why a text is refused before parsing. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PrescanError { + TooLarge, + /// A ` Result { + if text.len() > caps.max_bytes { + return Err(PrescanError::TooLarge); + } + if declares_doctype(text.as_bytes()) { + return Err(PrescanError::Doctype); + } + let mut scan = Scan { + bytes: text.as_bytes(), + at: 0, + depth: 0, + counted: Prescan { + elements: 0, + depth: 0, + }, + }; + while let Some(open) = find(scan.bytes, b"<", scan.at) { + scan.at = open; + scan.markup(caps)?; + } + if scan.depth != 0 { + return Err(PrescanError::Malformed); + } + Ok(scan.counted) +} + +struct Scan<'a> { + bytes: &'a [u8], + at: usize, + depth: usize, + counted: Prescan, +} + +impl Scan<'_> { + /// Consumes the markup starting at `self.at` (a `<`). + fn markup(&mut self, caps: &SvgCaps) -> Result<(), PrescanError> { + let rest = &self.bytes[self.at..]; + if rest.starts_with(b""); + } + if rest.starts_with(b""); + } + if rest.starts_with(b""); + } + if rest.starts_with(b"")?; + self.depth = self.depth.checked_sub(1).ok_or(PrescanError::Malformed)?; + return Ok(()); + } + let self_closing = self.skip_tag()?; + self.open_element(self_closing, caps) + } + + fn open_element(&mut self, self_closing: bool, caps: &SvgCaps) -> Result<(), PrescanError> { + self.counted.elements += 1; + if self.counted.elements > caps.max_elements { + return Err(PrescanError::TooManyElements); + } + let depth = self.depth + 1; + if depth > caps.max_depth { + return Err(PrescanError::TooDeep); + } + self.counted.depth = self.counted.depth.max(depth); + if !self_closing { + self.depth = depth; + } + Ok(()) + } + + fn skip_past(&mut self, end: &[u8]) -> Result<(), PrescanError> { + let found = find(self.bytes, end, self.at + 1).ok_or(PrescanError::Malformed)?; + self.at = found + end.len(); + Ok(()) + } + + /// Skips a start tag, quoted values included; answers whether it ends with `/>`. + fn skip_tag(&mut self) -> Result { + let mut quote: Option = None; + let mut i = self.at + 1; + while let Some(&b) = self.bytes.get(i) { + match (quote, b) { + (Some(q), _) if b == q => quote = None, + (Some(_), _) => {} + (None, b'"' | b'\'') => quote = Some(b), + (None, b'<') => return Err(PrescanError::Malformed), + (None, b'>') => { + self.at = i + 1; + return Ok(i > 0 && self.bytes[i - 1] == b'/'); + } + (None, _) => {} + } + i += 1; + } + Err(PrescanError::Malformed) + } +} + +fn find(haystack: &[u8], needle: &[u8], from: usize) -> Option { + haystack + .get(from..)? + .windows(needle.len()) + .position(|w| w == needle) + .map(|p| p + from) +} + +/// `/ bool { + let mut from = 0; + while let Some(at) = find(bytes, b"= w.len() && word[..w.len()].eq_ignore_ascii_case(w); + if starts(b"DOCTYPE") || starts(b"ENTITY") { + return true; + } + from = at + 2; + } + false +} + +#[cfg(test)] +mod tests { + use super::*; + + const SVG: &str = ""; + + fn nested(depth: usize) -> String { + format!( + "{SVG}{}{}", + "".repeat(depth - 1), + "".repeat(depth - 1) + ) + } + + #[test] + fn counts_depth_and_elements_with_the_root_at_depth_one() { + let text = format!("{SVG}"); + assert_eq!( + prescan(&text, &SVG_CAPS), + Ok(Prescan { + elements: 4, + depth: 3 + }) + ); + } + + #[test] + fn refuses_depth_and_element_counts_over_the_caps() { + assert!(prescan(&nested(64), &SVG_CAPS).is_ok()); + assert_eq!(prescan(&nested(65), &SVG_CAPS), Err(PrescanError::TooDeep)); + let many = |n: usize| format!("{SVG}{}", "".repeat(n - 1)); + assert!(prescan(&many(20_000), &SVG_CAPS).is_ok()); + assert_eq!( + prescan(&many(20_001), &SVG_CAPS), + Err(PrescanError::TooManyElements) + ); + } + + #[test] + fn stops_a_deep_text_at_the_cap_without_recursion() { + // 300,000 levels: the parser would overflow the wasm stack; the scan stops at 65. + let text = format!("{SVG}{}", "".repeat(300_000)); + assert_eq!(prescan(&text, &SVG_CAPS), Err(PrescanError::TooDeep)); + } + + #[test] + fn refuses_a_text_over_the_byte_cap_before_reading_it() { + let pad = "x".repeat(SVG_CAPS.max_bytes); + assert_eq!( + prescan(&pad, &SVG_CAPS), + Ok(Prescan { + elements: 0, + depth: 0 + }) + ); + let over = format!("{pad}x"); + assert_eq!(prescan(&over, &SVG_CAPS), Err(PrescanError::TooLarge)); + } + + #[test] + fn skips_markup_that_is_not_an_element() { + let text = format!( + "{SVG}]]>?>" + ); + // A quoted `<` is malformed XML: the scan skips it (still an upper bound), the parser refuses it. + assert_eq!( + prescan(&text, &SVG_CAPS), + Ok(Prescan { + elements: 2, + depth: 2 + }) + ); + let text = format!("{SVG}]]>?>"); + assert_eq!( + prescan(&text, &SVG_CAPS), + Ok(Prescan { + elements: 2, + depth: 2 + }) + ); + } + + #[test] + fn refuses_doctype_and_entity_anywhere_and_unclosed_markup() { + for text in [ + "", + "", + "", + ] { + assert_eq!( + prescan(text, &SVG_CAPS), + Err(PrescanError::Doctype), + "{text}" + ); + } + for text in [ + "