//! Building a new document from an import. //! //! The server's only way to write content. Everything else in this crate //! reads; an import is the one place the server, rather than an editor, //! decides what a document holds, and it decides from a file somebody //! uploaded. So the input is not ProseMirror JSON and not anything yrs //! would accept: it is a closed instruction list naming paragraphs, //! headings with a level, and text runs whose marks are rows of //! `fragment.rs`'s MARKS table. Only the text is free, and text only ever //! lands in a text run. Nothing from a file can reach an attribute, a tag //! name, or a mark this build cannot render. //! //! What comes out is what y-prosemirror itself writes for the same //! ProseMirror document: one `XmlElement` per block named after its node //! type, a heading's level as a number (not the string yrs' XML calls //! would write), one `XmlText` per block carrying //! its runs as a delta, each mark an attribute whose value is the mark's //! (empty) attrs, and no child at all for an empty block. yrs encodes it; //! nothing here writes Yjs bytes by hand. //! //! The whole list is decoded and checked before the document is touched, //! and then written in one transaction, so a refusal leaves the document //! exactly as it was: empty. //! //! # The instruction list, version 1 //! //! Little-endian throughout. //! //! ```text //! u8 version (1) //! u32 block count //! per block: //! u8 kind: 1 paragraph, 2 heading //! u8 level, heading only: 1..=6 //! u32 run count //! per run: //! u8 mark count, then per mark: u8 length, that many bytes of name //! u32 text length in bytes, then that many bytes of UTF-8 //! ``` //! //! A run's text is never empty and holds no control character; a run //! carries at most one font mark and at most one size mark, and never //! the same mark twice. Adjacent runs with the same marks are allowed and //! are merged, as y-prosemirror merges them. Nothing may follow the last //! block. use crate::fragment::MARKS; use std::collections::BTreeSet; use yrs::branch::{Branch, BranchPtr}; use yrs::types::xml::{XmlDeltaPrelim, XmlIn}; use yrs::types::{Attrs, Delta}; use yrs::{Any, Doc, In, Map, MapRef, Transact, XmlElementPrelim, XmlFragment, XmlOut}; /// The instruction-list version this build reads. pub const VERSION: u8 = 1; /// The largest instruction list accepted, in bytes. pub const MAX_INPUT: usize = 8 << 20; /// The most blocks one import may write. pub const MAX_BLOCKS: u32 = 50_000; /// The most runs one import may write, across every block. pub const MAX_RUNS: u32 = 500_000; /// Why an instruction list was refused. None of them carries anything /// from the input: a refusal is a code, never a quotation. #[derive(Debug, PartialEq, Eq)] pub enum BuildError { /// The bytes do not follow the format above: a wrong version, an /// unknown block kind or mark, a level out of range, a short read, /// trailing bytes, empty or non-UTF-8 text, a control character, /// or two marks of one kind on a run. Malformed, /// The list is well formed but larger than MAX_INPUT, MAX_BLOCKS or /// MAX_RUNS allow. Limit, /// The document already has content. An import writes only into a /// fresh document. NotEmpty, /// The document's client id is past `MAX_SAFE_CLIENT_ID`, so the /// update would carry an id no browser can decode. UnsafeClientId, } /// The largest client id an import may write under: JavaScript's /// Number.MAX_SAFE_INTEGER. lib0's decoder refuses a larger varuint, so an /// update written under one is unreadable by every editor, while the /// server, reading through yrs, would accept it without complaint. pub const MAX_SAFE_CLIENT_ID: u64 = (1 << 53) - 1; /// The marks an import may write: every MARKS row except the retired /// four-step sizes (`size_sm`, `size_lg`, `size_xl`, which the control no /// longer offers) and `code`, which an import never produces. fn allowed(name: &str) -> bool { MARKS.iter().any(|(m, _, _)| *m == name) && !matches!(name, "size_sm" | "size_lg" | "size_xl" | "code") } struct Reader<'a> { bytes: &'a [u8], at: usize, } impl<'a> Reader<'a> { fn take(&mut self, n: usize) -> Result<&'a [u8], BuildError> { let end = self.at.checked_add(n).ok_or(BuildError::Malformed)?; let out = self.bytes.get(self.at..end).ok_or(BuildError::Malformed)?; self.at = end; Ok(out) } fn u8(&mut self) -> Result { Ok(self.take(1)?[0]) } fn u32(&mut self) -> Result { let b = self.take(4)?; Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]])) } } struct Run { marks: BTreeSet<&'static str>, text: String, } fn marks(r: &mut Reader) -> Result, BuildError> { let count = r.u8()?; let mut out = BTreeSet::new(); let (mut font, mut size) = (false, false); for _ in 0..count { let len = r.u8()? as usize; let name = std::str::from_utf8(r.take(len)?).map_err(|_| BuildError::Malformed)?; if !allowed(name) { return Err(BuildError::Malformed); } // The table's own &'static str, so nothing borrowed from the // input survives the decode. let name = MARKS .iter() .find(|(m, _, _)| *m == name) .map(|(m, _, _)| *m) .ok_or(BuildError::Malformed)?; let is_font = name.starts_with("font_"); let is_size = name.starts_with("size_"); if (is_font && font) || (is_size && size) || !out.insert(name) { return Err(BuildError::Malformed); } font |= is_font; size |= is_size; } Ok(out) } fn text(r: &mut Reader) -> Result { let len = r.u32()? as usize; let s = std::str::from_utf8(r.take(len)?).map_err(|_| BuildError::Malformed)?; if s.is_empty() || s.chars().any(char::is_control) { return Err(BuildError::Malformed); } Ok(s.to_string()) } /// One decoded block: its prelim, and the heading level to set on it /// once it is in the document. struct Block { prelim: XmlIn, level: Option, } fn block(r: &mut Reader, runs_left: &mut u32) -> Result { let (mut element, level) = match r.u8()? { 1 => (XmlElementPrelim::empty("paragraph"), None), 2 => { let level = r.u8()?; if !(1..=6).contains(&level) { return Err(BuildError::Malformed); } (XmlElementPrelim::empty("heading"), Some(level)) } _ => return Err(BuildError::Malformed), }; let count = r.u32()?; if count > *runs_left { return Err(BuildError::Limit); } *runs_left -= count; let mut runs: Vec = Vec::new(); for _ in 0..count { let run = Run { marks: marks(r)?, text: text(r)?, }; match runs.last_mut() { Some(last) if last.marks == run.marks => last.text.push_str(&run.text), _ => runs.push(run), } } if !runs.is_empty() { let delta = runs .into_iter() .map(|run| { let attrs = if run.marks.is_empty() { None } else { let attrs: Attrs = run .marks .iter() .map(|m| ((*m).into(), Any::Map(Default::default()))) .collect(); Some(Box::new(attrs)) }; Delta::Inserted(In::Any(Any::from(run.text)), attrs) }) .collect(); element.children.push(XmlIn::Text(XmlDeltaPrelim { attributes: Default::default(), delta, })); } Ok(Block { prelim: XmlIn::Element(element), level, }) } /// Decodes and checks a whole instruction list, writing nothing. fn decode(ops: &[u8]) -> Result, BuildError> { if ops.len() > MAX_INPUT { return Err(BuildError::Limit); } let mut r = Reader { bytes: ops, at: 0 }; if r.u8()? != VERSION { return Err(BuildError::Malformed); } let count = r.u32()?; if count > MAX_BLOCKS { return Err(BuildError::Limit); } let mut runs_left = MAX_RUNS; let mut blocks = Vec::with_capacity(count as usize); for _ in 0..count { blocks.push(block(&mut r, &mut runs_left)?); } if r.at != ops.len() { return Err(BuildError::Malformed); } Ok(blocks) } /// Writes the document an instruction list describes into `doc`, which /// must be empty. On any error `doc` is left untouched. pub fn build(doc: &Doc, ops: &[u8]) -> Result<(), BuildError> { if doc.client_id() > MAX_SAFE_CLIENT_ID { return Err(BuildError::UnsafeClientId); } let blocks = decode(ops)?; let root = doc.get_or_insert_xml_fragment(crate::FRAGMENT_ROOT); let mut txn = doc.transact_mut(); if root.len(&txn) != 0 { return Err(BuildError::NotEmpty); } // Last block first, each at the front. yrs finds an index by walking // the list from its start, so appending block by block is quadratic // in the number of blocks (ten thousand took 1.6 s, past the host's // one-second call limit); inserting at index 0 finds its place at // once. The document is the same either way. for b in blocks.into_iter().rev() { let inserted = root.insert(&mut txn, 0, b.prelim); if let (Some(level), XmlOut::Element(e)) = (b.level, inserted) { // A heading's level is a number, as y-prosemirror writes it // and as the editor's schema (`validate: "number"`) expects. // yrs' XML attribute calls take only strings, but an // element's attributes are its map, which is what Yjs' // setAttribute writes too; so the number goes in through // the map. MapRef::from(BranchPtr::from(AsRef::::as_ref(&e))).insert( &mut txn, "level", Any::Number(level as f64), ); } } Ok(()) }