oficina / docs Public

feat/google-import

Squashed from feat/google-import into main.
Paul Campbell pushed by codex agent, operated by paul@keymail.dev 02ac4cf1f10fcf3b29233c3e17044e86348917e0 parent 3f5b4b6
37 files changed, +4,356 −175
  • cmd/docs/main.go +13 −4
  • core/src/abi.rs +43 −0
  • core/src/build.rs +282 −0
  • core/src/fragment.rs +1 −1
  • core/src/lib.rs +3 −1
  • core/tests/build.rs +280 −0
  • fixtures/engines/google-import.mjs +83 −0
  • fixtures/import-interop.mjs +59 −0
  • go.mod +1 −1
  • go.sum +2 −2
  • internal/core/build_test.go +147 −0
  • internal/core/core.go +123 −1
  • internal/core/testdata/docs_core.wasm binary
  • internal/docs/app.go +17 −1
  • internal/docs/content_cipher.go +5 −0
  • internal/docs/content_migration.go +20 −10
  • internal/docs/content_rows.go +25 −0
  • internal/docs/content_runtime.go +18 −1
  • internal/docs/google_import_browser_test.go +131 −0
  • internal/docs/handlers.go +31 −0
  • internal/docs/import.go +643 −0
  • internal/docs/import_interop_test.go +123 −0
  • internal/docs/import_team_test.go +51 −0
  • internal/docs/import_test.go +470 −0
  • internal/docs/migrations/0009_import_reports.sql +17 −0
  • internal/docs/models.go +16 −0
  • internal/docs/render.go +55 −0
  • internal/docs/suite_import_test.go +59 −0
  • internal/docs/views/import.html +49 −0
  • internal/docs/views/import_report.html +14 −0
  • internal/docs/views/list.html +2 −1
  • internal/docs/views/partials/import_report.html +12 −0
  • internal/docs/views/show.html +24 −0
  • internal/docx/docx.go +6 −140
  • internal/docx/docx_test.go +24 −12
  • internal/docx/read.go +1,027 −0
  • internal/docx/read_test.go +480 −0

CI failed — run details

landed from feat/google-import

diff --git a/cmd/docs/main.go b/cmd/docs/main.go
index e5ae0ad..3d2805b 100644
--- a/cmd/docs/main.go
+++ b/cmd/docs/main.go
@@ -10,6 +10,7 @@ import (
"strings"
"syscall"
+ "amadan.net/oficina/estilo.git/googleimport"
"amadan.net/oficina/home/teammode"
"amadan.net/oficina/suite/server"
"amadan.net/rastrillo/rastrillo"
@@ -274,10 +275,18 @@ func main() {
// — otherwise Serve would open a second connection to the file New
// already owns.
cfg := docs.Config{
- AgentIssuer: os.Getenv("DOCS_AGENT_ISSUER"),
- AgentTeam: os.Getenv("DOCS_AGENT_TEAM"),
- DBPath: opts.DBPath,
- ContentKey: os.Getenv("DOCS_CONTENT_KEY"),
+ AgentIssuer: os.Getenv("DOCS_AGENT_ISSUER"),
+ AgentTeam: os.Getenv("DOCS_AGENT_TEAM"),
+ DBPath: opts.DBPath,
+ ContentKey: os.Getenv("DOCS_CONTENT_KEY"),
+ // The Google Drive chooser on the import page: all three public
+ // values or none (docs.Config.GoogleImport; estilo's googleimport
+ // README has the Google Cloud setup).
+ GoogleImport: googleimport.Config{
+ ClientID: os.Getenv("DOCS_GOOGLE_CLIENT_ID"),
+ APIKey: os.Getenv("DOCS_GOOGLE_API_KEY"),
+ AppID: os.Getenv("DOCS_GOOGLE_APP_ID"),
+ },
Env: env,
Origin: origin,
InstanceKey: instanceKey,
diff --git a/core/src/abi.rs b/core/src/abi.rs
index 48d5f62..364539b 100644
--- a/core/src/abi.rs
+++ b/core/src/abi.rs
@@ -550,3 +550,46 @@ pub unsafe extern "C" fn docs_core_edit(
Err(crate::edit::EditError::Pending) => -9,
}
}
+
+/// The instruction list was refused by `build`: see `BuildError::Malformed`.
+pub const ERR_BUILD_MALFORMED: i32 = -6;
+/// The instruction list exceeds one of `build`'s limits.
+pub const ERR_BUILD_LIMIT: i32 = -7;
+/// The handle's document is not empty; an import writes only into a
+/// fresh one.
+pub const ERR_BUILD_NOT_EMPTY: i32 = -8;
+/// The handle's client id is past `build::MAX_SAFE_CLIENT_ID`.
+pub const ERR_BUILD_UNSAFE_CLIENT_ID: i32 = -9;
+
+pub fn build_slice(handle: u32, ops: &[u8]) -> i32 {
+ match get_doc(handle) {
+ None => ERR_NO_DOC,
+ Some(doc) => match crate::build::build(&doc, ops) {
+ Ok(()) => 0,
+ Err(crate::build::BuildError::Malformed) => ERR_BUILD_MALFORMED,
+ Err(crate::build::BuildError::Limit) => ERR_BUILD_LIMIT,
+ Err(crate::build::BuildError::NotEmpty) => ERR_BUILD_NOT_EMPTY,
+ Err(crate::build::BuildError::UnsafeClientId) => ERR_BUILD_UNSAFE_CLIENT_ID,
+ },
+ }
+}
+
+/// Writes the document `build`'s instruction list describes into
+/// `handle`, which must be empty. 0 on success; on any error the
+/// document is unchanged.
+///
+/// # Safety
+///
+/// `ptr` and `len` must describe a byte range that lies entirely within
+/// this module's linear memory and is not mutated for the duration of
+/// this call. (Checked by `in_bounds` before any slice is constructed —
+/// this safety requirement covers what that check cannot see, such as
+/// concurrent mutation.)
+#[no_mangle]
+pub unsafe extern "C" fn docs_core_build(handle: u32, ptr: u32, len: u32) -> i32 {
+ if !in_bounds(ptr, len) {
+ return ERR_INVALID_LENGTH;
+ }
+ let bytes = std::slice::from_raw_parts(ptr as *const u8, len as usize);
+ build_slice(handle, bytes)
+}
diff --git a/core/src/build.rs b/core/src/build.rs
new file mode 100644
index 0000000..ddb7cdb
--- /dev/null
+++ b/core/src/build.rs
@@ -0,0 +1,282 @@
+//! 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<u8, BuildError> {
+ Ok(self.take(1)?[0])
+ }
+ fn u32(&mut self) -> Result<u32, BuildError> {
+ 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<BTreeSet<&'static str>, 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<String, BuildError> {
+ 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<u8>,
+}
+
+fn block(r: &mut Reader, runs_left: &mut u32) -> Result<Block, BuildError> {
+ 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<Run> = 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<Vec<Block>, 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::<Branch>::as_ref(&e))).insert(
+ &mut txn,
+ "level",
+ Any::Number(level as f64),
+ );
+ }
+ }
+ Ok(())
+}
diff --git a/core/src/fragment.rs b/core/src/fragment.rs
index 9cb4e68..2d365c1 100644
--- a/core/src/fragment.rs
+++ b/core/src/fragment.rs
@@ -72,7 +72,7 @@ fn escape(s: &str, out: &mut String) {
/// that moving it is a change to the manifest and not to this table.
/// `font_serif` and `font_sans` are why: each was once the absence of a
/// mark, and became unsayable the moment it stopped being the default.
-const MARKS: &[(&str, &str, &str)] = &[
+pub(crate) const MARKS: &[(&str, &str, &str)] = &[
// One row per family in internal/fonts/fonts.json, in its order, so
// the last font mark on a run is the innermost span and the one the
// cascade draws; internal/fonts' ForMarks and fixtures/fonts.mjs
diff --git a/core/src/lib.rs b/core/src/lib.rs
index 8efefd3..218b821 100644
--- a/core/src/lib.rs
+++ b/core/src/lib.rs
@@ -54,6 +54,7 @@
//! above) rather than relying on `fastrand` to fail loudly when it can't —
//! it won't.
pub mod abi;
+pub mod build;
pub mod edit;
mod fragment;
pub mod initial;
@@ -90,6 +91,7 @@ extern "Rust" fn __getrandom_v03_custom(
///
/// Version 5 adds bounded initial paragraph/heading construction.
/// Version 6 adds bounded semantic splices on a disposable replay handle.
+/// Version 7 adds rich document imports through `docs_core_build`.
///
/// Adding an export is, strictly, backwards compatible — a host that
/// never calls the new function cannot tell 3 from 2 — so the bump is
@@ -103,7 +105,7 @@ extern "Rust" fn __getrandom_v03_custom(
/// here.
#[no_mangle]
pub extern "C" fn docs_core_abi_version() -> u32 {
- 6
+ 7
}
use yrs::updates::decoder::Decode;
diff --git a/core/tests/build.rs b/core/tests/build.rs
new file mode 100644
index 0000000..47ca13b
--- /dev/null
+++ b/core/tests/build.rs
@@ -0,0 +1,280 @@
+use docs_core::abi::{
+ build_slice, doc_free, doc_new, json_string, ERR_BUILD_LIMIT, ERR_BUILD_MALFORMED,
+ ERR_BUILD_NOT_EMPTY, ERR_NO_DOC,
+};
+use docs_core::build::{build, BuildError, MAX_BLOCKS, VERSION};
+use docs_core::{apply_update, fragment_html, fragment_json, snapshot_bytes, FRAGMENT_ROOT};
+use yrs::branch::{Branch, BranchPtr};
+use yrs::{Any, Doc, Map, MapRef, Options, Out, Text, Transact, XmlFragment, XmlOut};
+
+fn fresh() -> Doc {
+ Doc::with_options(Options::with_guid_and_client_id("build-test".into(), 9))
+}
+
+/// A run: its marks and its text.
+type Run<'a> = (&'a [&'a str], &'a str);
+/// A block: its kind, its level (headings only) and its runs.
+type Block<'a> = (u8, u8, &'a [Run<'a>]);
+
+/// The instruction list for `blocks`.
+fn ops(blocks: &[Block]) -> Vec<u8> {
+ let mut out = vec![VERSION];
+ out.extend((blocks.len() as u32).to_le_bytes());
+ for (kind, level, runs) in blocks {
+ out.push(*kind);
+ if *kind == 2 {
+ out.push(*level);
+ }
+ out.extend((runs.len() as u32).to_le_bytes());
+ for (marks, text) in runs.iter() {
+ out.push(marks.len() as u8);
+ for m in marks.iter() {
+ out.push(m.len() as u8);
+ out.extend(m.as_bytes());
+ }
+ out.extend((text.len() as u32).to_le_bytes());
+ out.extend(text.as_bytes());
+ }
+ }
+ out
+}
+
+#[test]
+fn builds_paragraphs_headings_and_marks() {
+ let doc = fresh();
+ build(
+ &doc,
+ &ops(&[
+ (2, 2, &[(&[], "Title")]),
+ (
+ 1,
+ 0,
+ &[
+ (&[], "Plain "),
+ (&["strong"], "bold"),
+ (&[], " then "),
+ (&["em", "font_sans", "size_14"], "styled"),
+ ],
+ ),
+ (1, 0, &[]),
+ ]),
+ )
+ .unwrap();
+ assert_eq!(
+ fragment_json(&doc),
+ r#"{"type":"doc","content":[{"type":"heading","attrs":{"level":2},"content":[{"type":"text","text":"Title"}]},{"type":"paragraph","content":[{"type":"text","text":"Plain "},{"type":"text","text":"bold","marks":[{"type":"strong"}]},{"type":"text","text":" then "},{"type":"text","text":"styled","marks":[{"type":"font_sans"},{"type":"size_14"},{"type":"em"}]}]},{"type":"paragraph","content":[]}]}"#
+ );
+ assert_eq!(
+ fragment_html(&doc),
+ "<h2>Title</h2><p>Plain <strong>bold</strong> then <span class=\"docs-font-sans\"><span class=\"docs-size-14\"><em>styled</em></span></span></p><p></p>"
+ );
+}
+
+/// y-prosemirror writes a heading's level as a number and the editor's
+/// schema validates it as one; a string level is what yrs' own XML
+/// attribute calls would have written.
+#[test]
+fn a_heading_level_is_a_number() {
+ let doc = fresh();
+ build(&doc, &ops(&[(2, 3, &[(&[], "H")])])).unwrap();
+ let root = doc.get_or_insert_xml_fragment(FRAGMENT_ROOT);
+ let txn = doc.transact();
+ let Some(XmlOut::Element(h)) = root.get(&txn, 0) else {
+ panic!("no heading")
+ };
+ let level = MapRef::from(BranchPtr::from(AsRef::<Branch>::as_ref(&h))).get(&txn, "level");
+ assert!(
+ matches!(level, Some(Out::Any(Any::Number(n))) if n == 3.0),
+ "level {level:?}"
+ );
+}
+
+/// An empty block has no child at all, as y-prosemirror writes one; and
+/// a block's runs share one XmlText.
+#[test]
+fn one_text_per_block_and_none_when_empty() {
+ let doc = fresh();
+ build(
+ &doc,
+ &ops(&[(1, 0, &[(&[], "a"), (&["strong"], "b")]), (1, 0, &[])]),
+ )
+ .unwrap();
+ let root = doc.get_or_insert_xml_fragment(FRAGMENT_ROOT);
+ let txn = doc.transact();
+ let lens: Vec<u32> = root
+ .children(&txn)
+ .map(|c| match c {
+ XmlOut::Element(e) => e.len(&txn),
+ _ => panic!("not an element"),
+ })
+ .collect();
+ assert_eq!(lens, vec![1, 0]);
+}
+
+#[test]
+fn an_unmarked_run_after_a_marked_one_inherits_nothing() {
+ let doc = fresh();
+ build(
+ &doc,
+ &ops(&[(1, 0, &[(&["strong"], "a"), (&[], "b"), (&["em"], "c")])]),
+ )
+ .unwrap();
+ assert_eq!(fragment_html(&doc), "<p><strong>a</strong>b<em>c</em></p>");
+}
+
+#[test]
+fn adjacent_runs_with_the_same_marks_merge() {
+ let doc = fresh();
+ build(
+ &doc,
+ &ops(&[(1, 0, &[(&["strong", "em"], "a"), (&["em", "strong"], "b")])]),
+ )
+ .unwrap();
+ let root = doc.get_or_insert_xml_fragment(FRAGMENT_ROOT);
+ let txn = doc.transact();
+ let Some(XmlOut::Element(p)) = root.get(&txn, 0) else {
+ panic!()
+ };
+ let Some(XmlOut::Text(t)) = p.get(&txn, 0) else {
+ panic!()
+ };
+ assert_eq!(t.diff(&txn, yrs::types::text::YChange::identity).len(), 1);
+}
+
+/// Every refusal leaves the document exactly as it was.
+#[test]
+fn refuses_malformed_lists_and_writes_nothing() {
+ let good = ops(&[(1, 0, &[(&[], "x")])]);
+ let mut wrong_version = good.clone();
+ wrong_version[0] = 2;
+ let mut trailing = good.clone();
+ trailing.push(0);
+ let truncated = good[..good.len() - 1].to_vec();
+ let mut bad_utf8 = good.clone();
+ *bad_utf8.last_mut().unwrap() = 0xff;
+ let cases: Vec<(&str, Vec<u8>)> = vec![
+ ("empty input", vec![]),
+ ("wrong version", wrong_version),
+ ("trailing bytes", trailing),
+ ("truncated", truncated),
+ ("invalid utf-8", bad_utf8),
+ ("unknown kind", {
+ let mut v = good.clone();
+ v[5] = 3;
+ v
+ }),
+ ("level 0", ops(&[(2, 0, &[(&[], "x")])])),
+ ("level 7", ops(&[(2, 7, &[(&[], "x")])])),
+ ("unknown mark", ops(&[(1, 0, &[(&["link"], "x")])])),
+ ("retired size", ops(&[(1, 0, &[(&["size_lg"], "x")])])),
+ ("code", ops(&[(1, 0, &[(&["code"], "x")])])),
+ (
+ "two fonts",
+ ops(&[(1, 0, &[(&["font_sans", "font_serif"], "x")])]),
+ ),
+ ("two sizes", ops(&[(1, 0, &[(&["size_8", "size_9"], "x")])])),
+ ("same mark twice", ops(&[(1, 0, &[(&["em", "em"], "x")])])),
+ ("empty text", ops(&[(1, 0, &[(&[], "")])])),
+ ("tab", ops(&[(1, 0, &[(&[], "a\tb")])])),
+ ("newline", ops(&[(1, 0, &[(&[], "a\nb")])])),
+ ("nul", ops(&[(1, 0, &[(&[], "a\0b")])])),
+ (
+ "a good block, then a bad one",
+ ops(&[(1, 0, &[(&[], "fine")]), (1, 0, &[(&[], "")])]),
+ ),
+ ];
+ for (name, bytes) in cases {
+ let doc = fresh();
+ let before = snapshot_bytes(&doc);
+ assert_eq!(build(&doc, &bytes), Err(BuildError::Malformed), "{name}");
+ assert_eq!(snapshot_bytes(&doc), before, "{name} wrote something");
+ assert_eq!(
+ fragment_json(&doc),
+ r#"{"type":"doc","content":[]}"#,
+ "{name}"
+ );
+ }
+}
+
+#[test]
+fn refuses_past_its_limits() {
+ let mut v = vec![VERSION];
+ v.extend((MAX_BLOCKS + 1).to_le_bytes());
+ assert_eq!(build(&fresh(), &v), Err(BuildError::Limit));
+
+ let mut v = vec![VERSION];
+ v.extend(1u32.to_le_bytes());
+ v.push(1);
+ v.extend(u32::MAX.to_le_bytes());
+ assert_eq!(build(&fresh(), &v), Err(BuildError::Limit));
+
+ let big = vec![0u8; docs_core::build::MAX_INPUT + 1];
+ assert_eq!(build(&fresh(), &big), Err(BuildError::Limit));
+}
+
+/// An update written under a client id past 2^53 - 1 decodes in yrs and
+/// in no browser (lib0 refuses the varuint), so the builder refuses to
+/// write under one at all.
+#[test]
+fn refuses_a_client_id_a_browser_cannot_read() {
+ let list = ops(&[(1, 0, &[(&[], "x")])]);
+ for id in [docs_core::build::MAX_SAFE_CLIENT_ID + 1, u64::MAX >> 1] {
+ let doc = Doc::with_options(Options::with_guid_and_client_id("build-test".into(), id));
+ let before = snapshot_bytes(&doc);
+ assert_eq!(build(&doc, &list), Err(BuildError::UnsafeClientId));
+ assert_eq!(snapshot_bytes(&doc), before);
+ }
+ let doc = Doc::with_options(Options::with_guid_and_client_id(
+ "build-test".into(),
+ docs_core::build::MAX_SAFE_CLIENT_ID,
+ ));
+ build(&doc, &list).unwrap();
+}
+
+#[test]
+fn writes_only_into_an_empty_document() {
+ let doc = fresh();
+ let list = ops(&[(1, 0, &[(&[], "x")])]);
+ build(&doc, &list).unwrap();
+ let before = snapshot_bytes(&doc);
+ assert_eq!(build(&doc, &list), Err(BuildError::NotEmpty));
+ assert_eq!(snapshot_bytes(&doc), before);
+}
+
+/// What is built replays, from its snapshot, into a second document as
+/// the same structure: the check the host makes before saving.
+#[test]
+fn the_snapshot_replays_to_the_same_structure() {
+ let doc = fresh();
+ build(
+ &doc,
+ &ops(&[
+ (2, 1, &[(&["font_caladea"], "Über 🦀")]),
+ (1, 0, &[(&["size_11"], "x")]),
+ ]),
+ )
+ .unwrap();
+ let replay = Doc::with_options(Options::with_guid_and_client_id("build-test".into(), 10));
+ apply_update(&replay, &snapshot_bytes(&doc)).unwrap();
+ assert_eq!(fragment_json(&replay), fragment_json(&doc));
+}
+
+#[test]
+fn the_abi_reports_each_refusal_as_its_own_code() {
+ let h = doc_new("abi-build", 3);
+ assert_eq!(build_slice(h, &[]), ERR_BUILD_MALFORMED);
+ let mut v = vec![VERSION];
+ v.extend((MAX_BLOCKS + 1).to_le_bytes());
+ assert_eq!(build_slice(h, &v), ERR_BUILD_LIMIT);
+ assert_eq!(build_slice(h, &ops(&[(1, 0, &[(&[], "x")])])), 0);
+ assert_eq!(
+ build_slice(h, &ops(&[(1, 0, &[(&[], "x")])])),
+ ERR_BUILD_NOT_EMPTY
+ );
+ assert_eq!(
+ json_string(h).unwrap(),
+ r#"{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"x"}]}]}"#
+ );
+ doc_free(h);
+ assert_eq!(build_slice(h, &ops(&[])), ERR_NO_DOC);
+}
diff --git a/fixtures/engines/google-import.mjs b/fixtures/engines/google-import.mjs
new file mode 100644
index 0000000..9e21ea5
--- /dev/null
+++ b/fixtures/engines/google-import.mjs
@@ -0,0 +1,83 @@
+// Real Docs app, controlled Google responses. This is not a live Google test.
+import assert from 'node:assert/strict'
+import { pathToFileURL } from 'node:url'
+const playwright = process.env.DOCS_IMPORT_PLAYWRIGHT
+ ? await import(pathToFileURL(process.env.DOCS_IMPORT_PLAYWRIGHT + '/index.mjs'))
+ : await import('playwright')
+const config = JSON.parse(process.env.DOCS_GOOGLE_IMPORT_TEST)
+const fixture = Buffer.from(config.fixture, 'base64')
+const gis = `window.google={accounts:{oauth2:{initTokenClient(c){return{requestAccessToken(){c.callback({access_token:'controlled-google-bearer',scope:'https://www.googleapis.com/auth/drive.file'})}}},hasGrantedAllScopes(r,s){return r.scope===s}}}};`
+const gapi = `window.gapi={load(name,c){google.picker={Action:{PICKED:'picked',CANCEL:'cancel'},DocsView:class{setMimeTypes(){return this}},PickerBuilder:class{setDeveloperKey(){return this}setAppId(){return this}setOAuthToken(){return this}setOrigin(){return this}addView(){return this}setCallback(fn){this.cb=fn;return this}build(){const cb=this.cb;let el;return{setVisible(){el=document.createElement('button');el.textContent='Select import fixture';el.onclick=()=>cb({action:'picked',docs:[{id:'controlled_file',name:'Import fixture',mimeType:'application/vnd.google-apps.document'}]});document.body.append(el)},dispose(){el?.remove()}}}}};c.callback()}};`
+const expected = ['Import fixture', 'linked words', 'bold text', 'plain text', 'Table cell']
+for (const engine of ['chromium', 'webkit']) {
+ const browser = await playwright[engine].launch()
+ try {
+ const context = await browser.newContext({ viewport: { width: 900, height: 850 } })
+ const cookies = config.cookies.map(c => ({ name: c.Name, value: c.Value, url: config.origin, httpOnly: c.HttpOnly, sameSite: 'Lax' }))
+ await context.addCookies(cookies)
+ const page = await context.newPage()
+ const violations = [], failures = []
+ let exports = 0, leaked = false, externalRelationship = false
+ page.on('pageerror', e => failures.push(e.message))
+ await page.addInitScript(() => document.addEventListener('securitypolicyviolation', e => console.log('IMPORT-CSP:' + e.violatedDirective)))
+ page.on('console', message => { if (message.text().startsWith('IMPORT-CSP:')) violations.push(message.text()) })
+ page.on('request', request => {
+ if (request.url().startsWith(config.origin) && ((request.postData() || '').includes('controlled-google-bearer') || JSON.stringify(request.headers()).includes('controlled-google-bearer'))) leaked = true
+ if (request.url().startsWith('https://fixture.invalid/')) externalRelationship = true
+ })
+ await context.route('https://accounts.google.com/gsi/client', r => r.fulfill({ contentType: 'text/javascript', body: gis }))
+ await context.route('https://apis.google.com/js/api.js', r => r.fulfill({ contentType: 'text/javascript', body: gapi }))
+ await context.route('https://www.googleapis.com/drive/v3/files/**', async r => {
+ exports++
+ assert.equal(r.request().headers().authorization, 'Bearer controlled-google-bearer')
+ await r.fulfill({ headers: { 'Access-Control-Allow-Origin': '*' }, contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', body: fixture })
+ })
+ await page.goto(config.origin + '/import')
+ await page.waitForFunction(() => !document.querySelector('[data-google-choose]')?.disabled)
+ await page.locator('[data-google-choose]').click()
+ await page.getByRole('button', { name: 'Select import fixture', exact: true }).click()
+ await page.waitForURL(url => url.pathname !== '/import')
+ const editorPath = new URL(page.url()).pathname
+ assert.match(editorPath, /^\/d\/[^/]+$/)
+ const reportURL = config.origin + editorPath + '/import-report'
+ assert.match(await page.locator('body').innerText(), /import/i)
+ assert.match(await page.locator('body').innerText(), /table/i)
+ assert.match(await page.locator('body').innerText(), /link/i)
+ assert.equal(await page.locator('[docs-import-report]').count(), 1)
+ await page.goto(config.origin + editorPath)
+ const editor = page.locator('[docs-text][contenteditable="true"]')
+ try { await editor.waitFor({ state: 'visible', timeout: 30000 }) }
+ catch (cause) { throw new Error(engine + ': editor unavailable; errors=' + JSON.stringify(failures) + '; page=' + (await page.locator('body').innerText()).slice(0, 1500), { cause }) }
+ for (const text of expected) assert((await editor.innerText()).includes(text), 'missing ' + text)
+ assert.match(await editor.locator('strong').innerText(), /bold text/)
+ assert(!(await editor.locator('strong').innerText()).includes('plain text'))
+ assert.equal(await editor.locator('a').count(), 0)
+ const saved = page.waitForResponse(r => r.request().method() === 'POST' && r.url().endsWith('/updates') && r.ok())
+ await editor.click()
+ await page.keyboard.press('End')
+ await page.keyboard.insertText(' Edited after import.')
+ await saved
+ await page.reload()
+ await page.waitForFunction(() => document.querySelector('[docs-text]')?.textContent.includes('Edited after import.'))
+ await page.goto(reportURL)
+ assert.match(await page.locator('body').innerText(), /table/i)
+ assert.equal(exports, 1)
+ assert.equal(leaked, false)
+ assert.equal(externalRelationship, false)
+ assert.deepEqual(violations, [])
+ assert.deepEqual(failures, [])
+
+ const plainContext = await browser.newContext({ javaScriptEnabled: false })
+ await plainContext.addCookies(cookies)
+ const plain = await plainContext.newPage()
+ await plain.goto(config.origin + '/import')
+ assert.equal(await plain.locator('[data-google-choose]').isVisible(), false)
+ await plain.locator('input[type="file"]').setInputFiles({ name: 'scriptless.docx', mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', buffer: fixture })
+ await plain.locator('form:has(input[type="file"]) button[type="submit"]').click()
+ await plain.waitForURL(url => url.pathname !== '/import')
+ assert.match(await plain.locator('body').innerText(), /table/i)
+ await plainContext.close()
+ await context.close()
+ console.log(engine + ': actual import route, nested text, marks, editable persistence, report reopening and scriptless upload passed')
+ } finally { await browser.close() }
+}
diff --git a/fixtures/import-interop.mjs b/fixtures/import-interop.mjs
new file mode 100644
index 0000000..932cc90
--- /dev/null
+++ b/fixtures/import-interop.mjs
@@ -0,0 +1,59 @@
+// fixtures/import-interop.mjs — reads an imported document's update, as
+// the server's import path (internal/docs/import.go) wrote it, on stdin,
+// and checks the editor can take it as it is:
+//
+// - Yjs decodes it at all. lib0 refuses a client id past
+// Number.MAX_SAFE_INTEGER, which yrs writes without complaint; an
+// import written under one applied on the server and in no browser.
+// - y-prosemirror builds the editor's own schema's document from it
+// without changing the Yjs document. y-prosemirror deletes, and then
+// saves the deletion of, any node the schema refuses; an import it
+// had to clean up would lose text the first time it was opened.
+// - That document passes the schema's full check, attribute validators
+// included (a heading level must be a number).
+//
+// Prints {"clients": [...], "doc": <ProseMirror JSON>} for the Go side
+// (internal/docs/import_interop_test.go) to compare with what the
+// reader meant. Exits non-zero, saying why, on any failure.
+import * as Y from 'yjs'
+import { yXmlFragmentToProseMirrorRootNode } from 'y-prosemirror'
+import { schema } from './schema.mjs'
+
+const chunks = []
+for await (const chunk of process.stdin) chunks.push(chunk)
+const update = new Uint8Array(Buffer.concat(chunks))
+
+function fail (why) {
+ console.error('import-interop: ' + why)
+ process.exit(1)
+}
+
+if (update.length === 0) fail('empty update on stdin')
+
+const doc = new Y.Doc()
+try {
+ Y.applyUpdate(doc, update)
+} catch (err) {
+ fail('Yjs cannot decode the update: ' + err.message)
+}
+const clients = [...Y.decodeStateVector(Y.encodeStateVector(doc)).keys()]
+for (const c of clients) {
+ if (!Number.isSafeInteger(c)) fail('a client id is not a safe integer')
+}
+
+let changed = false
+doc.on('update', () => { changed = true })
+let root
+try {
+ root = yXmlFragmentToProseMirrorRootNode(doc.getXmlFragment('prosemirror'), schema)
+} catch (err) {
+ fail('y-prosemirror cannot build the document: ' + err.message)
+}
+if (changed) fail('y-prosemirror changed the document while reading it (schema clean-up)')
+try {
+ root.check()
+} catch (err) {
+ fail('the editor schema refuses the document: ' + err.message)
+}
+
+process.stdout.write(JSON.stringify({ clients, doc: root.toJSON() }))
diff --git a/go.mod b/go.mod
index cfd48d5..92aaa9f 100644
--- a/go.mod
+++ b/go.mod
@@ -4,7 +4,7 @@ go 1.26.5
require (
amadan.net/oficina/agent-access.git v0.0.0-20261024232549-8ed8ba826000
- amadan.net/oficina/estilo.git v0.0.0-20261030224852-1348c4b3b407
+ amadan.net/oficina/estilo.git v0.0.0-20261110225909-62be5bcc8ad7
amadan.net/oficina/home/connect v0.0.0-20261030223040-6d99b0ccc542
amadan.net/oficina/home/dashboard v0.0.0-20261024235511-baa2503c7064
amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489
diff --git a/go.sum b/go.sum
index 66b5e02..688073f 100644
--- a/go.sum
+++ b/go.sum
@@ -1,7 +1,7 @@
amadan.net/oficina/agent-access.git v0.0.0-20261024232549-8ed8ba826000 h1:L07nc+dmLI7c1PBkSkbnrjOK5f8p6OBbA/yTxznxCAw=
amadan.net/oficina/agent-access.git v0.0.0-20261024232549-8ed8ba826000/go.mod h1:Ph9PIa3VE1IEaUzZiQH6D+IQ6HThWWGfVr0ecMMgrFA=
-amadan.net/oficina/estilo.git v0.0.0-20261030224852-1348c4b3b407 h1:lpD4zWYtPc77ZNpYXk54+AqQ66i5kLIP2XGa40r1Nmw=
-amadan.net/oficina/estilo.git v0.0.0-20261030224852-1348c4b3b407/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw=
+amadan.net/oficina/estilo.git v0.0.0-20261110225909-62be5bcc8ad7 h1:BxvPwmUzKfreL7+ufLoVtpBM6MMnga2bMH6w3ZcmXG4=
+amadan.net/oficina/estilo.git v0.0.0-20261110225909-62be5bcc8ad7/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw=
amadan.net/oficina/home/connect v0.0.0-20261030223040-6d99b0ccc542 h1:b2JT0B0Y+5sTsCmVhX6cywCRdGd9s3lRP8wpqOytlbM=
amadan.net/oficina/home/connect v0.0.0-20261030223040-6d99b0ccc542/go.mod h1:ix81eFV87yE9f2SXiRuxYCVM4lAgTRC5YoQMiH3+TDk=
amadan.net/oficina/home/dashboard v0.0.0-20261024235511-baa2503c7064 h1:2YbDksZDxpY9khlhXmTeiM89yze7w2XfYSumtrzH4tc=
diff --git a/internal/core/build_test.go b/internal/core/build_test.go
new file mode 100644
index 0000000..bf5eb91
--- /dev/null
+++ b/internal/core/build_test.go
@@ -0,0 +1,147 @@
+package core_test
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ "github.com/carlosframework/docs/internal/core"
+)
+
+func TestBuildWritesTheDocumentItDescribes(t *testing.T) {
+ ctx := context.Background()
+ rt, err := core.New(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rt.Close(ctx)
+
+ ops, err := core.EncodeBuild([]core.BuildBlock{
+ {Heading: 1, Runs: []core.BuildRun{{Text: "Title"}}},
+ {Runs: []core.BuildRun{{Text: "plain "}, {Marks: []string{"strong"}, Text: "bold"}}},
+ {},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ update, err := rt.Build(ctx, "6f1a1d1e-0000-4000-8000-000000000001", 41, ops)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // Replayed into a second document, it is the same structure.
+ h, err := rt.NewDoc(ctx, "6f1a1d1e-0000-4000-8000-000000000001", 42)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer h.Close(ctx)
+ if err := h.Apply(ctx, update); err != nil {
+ t.Fatal(err)
+ }
+ got, err := h.JSON(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := `{"type":"doc","content":[{"type":"heading","attrs":{"level":1},"content":[{"type":"text","text":"Title"}]},{"type":"paragraph","content":[{"type":"text","text":"plain "},{"type":"text","text":"bold","marks":[{"type":"strong"}]}]},{"type":"paragraph","content":[]}]}`
+ if got != want {
+ t.Fatalf("replayed structure\n got %s\nwant %s", got, want)
+ }
+}
+
+func TestBuildRefusesAClientIDABrowserCannotRead(t *testing.T) {
+ ctx := context.Background()
+ rt, err := core.New(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rt.Close(ctx)
+ ops, err := core.EncodeBuild([]core.BuildBlock{{Runs: []core.BuildRun{{Text: "x"}}}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := rt.Build(ctx, "6f1a1d1e-0000-4000-8000-000000000005", core.MaxBuildClientID+1, ops); !errors.Is(err, core.ErrBuildClientID) {
+ t.Errorf("got %v, want ErrBuildClientID", err)
+ }
+ if _, err := rt.Build(ctx, "6f1a1d1e-0000-4000-8000-000000000005", core.MaxBuildClientID, ops); err != nil {
+ t.Errorf("the largest safe id: %v", err)
+ }
+}
+
+func TestBuildRefusesWhatTheBuilderRefuses(t *testing.T) {
+ ctx := context.Background()
+ rt, err := core.New(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rt.Close(ctx)
+
+ for name, blocks := range map[string][]core.BuildBlock{
+ "unknown mark": {{Runs: []core.BuildRun{{Marks: []string{"link"}, Text: "x"}}}},
+ "level 7": {{Heading: 7, Runs: []core.BuildRun{{Text: "x"}}}},
+ "empty run": {{Runs: []core.BuildRun{{Text: ""}}}},
+ "control": {{Runs: []core.BuildRun{{Text: "a\tb"}}}},
+ } {
+ ops, err := core.EncodeBuild(blocks)
+ if err != nil {
+ t.Fatal(name, err)
+ }
+ if _, err := rt.Build(ctx, "6f1a1d1e-0000-4000-8000-000000000002", 1, ops); !errors.Is(err, core.ErrBuildMalformed) {
+ t.Errorf("%s: got %v, want ErrBuildMalformed", name, err)
+ }
+ }
+
+ many := make([]core.BuildBlock, 50_001)
+ ops, err := core.EncodeBuild(many)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := rt.Build(ctx, "6f1a1d1e-0000-4000-8000-000000000003", 1, ops); !errors.Is(err, core.ErrBuildLimit) {
+ t.Errorf("too many blocks: got %v, want ErrBuildLimit", err)
+ }
+}
+
+// The largest import the reader lets through (internal/docx's
+// maxBlocks, maxRuns and maxText) must build inside Build's allowance and
+// then replay inside the ordinary call limit, which is what every later
+// opening of the document needs.
+func TestBuildAtTheReadersLimitFitsTheCallTimeout(t *testing.T) {
+ ctx := context.Background()
+ rt, err := core.New(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rt.Close(ctx)
+
+ // 5,000 blocks of two runs, 52 bytes each: about 508 KiB of text in
+ // 10,000 runs.
+ text := make([]byte, 52)
+ for i := range text {
+ text[i] = 'a' + byte(i%26)
+ }
+ blocks := make([]core.BuildBlock, 5_000)
+ for i := range blocks {
+ blocks[i].Runs = []core.BuildRun{
+ {Text: string(text)},
+ {Marks: []string{"strong", "font_sans", "size_14"}, Text: string(text)},
+ }
+ }
+ ops, err := core.EncodeBuild(blocks)
+ if err != nil {
+ t.Fatal(err)
+ }
+ update, err := rt.Build(ctx, "6f1a1d1e-0000-4000-8000-000000000004", 1, ops)
+ if err != nil {
+ t.Fatal(err)
+ }
+ h, err := rt.NewDoc(ctx, "6f1a1d1e-0000-4000-8000-000000000004", 2)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer h.Close(ctx)
+ if err := h.Apply(ctx, update); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := h.HTML(ctx); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/internal/core/core.go b/internal/core/core.go
index d8cb334..43d1bc8 100644
--- a/internal/core/core.go
+++ b/internal/core/core.go
@@ -52,8 +52,10 @@ package core
import (
"context"
_ "embed"
+ "encoding/binary"
"errors"
"fmt"
+ "math"
"time"
"github.com/tetratelabs/wazero"
@@ -76,7 +78,8 @@ var moduleWASM []byte
// side: the module and this binary ship embedded together with no
// version skew to tolerate, so the bump exists to catch a stale .wasm
// at load time instead of "unknown export" deep inside a request.
-const abiVersion = 6
+// Version 7 adds rich imports alongside initialization and semantic editing.
+const abiVersion = 7
// ABIVersion is abiVersion, exported for callers outside this package
// (snapshot storage and its tests) that need to know which ABI contract
@@ -779,3 +782,122 @@ func readOn(ctx context.Context, timeout time.Duration, mod api.Module, docHandl
}
return string(buf), nil
}
+
+// ErrBuildMalformed and ErrBuildLimit are Build's refusals of an
+// instruction list: one that does not follow core/src/build.rs's format,
+// and one past its limits. Neither carries anything from the list.
+// buildTimeoutFactor is how many ordinary call limits Build's one call
+// into the builder may take. See Build.
+const buildTimeoutFactor = 5
+
+var (
+ ErrBuildMalformed = errors.New("core: import instructions are malformed")
+ ErrBuildLimit = errors.New("core: import instructions exceed the builder's limits")
+ // ErrBuildClientID: Build was asked to write under a client id past
+ // MaxBuildClientID, which no browser could decode.
+ ErrBuildClientID = errors.New("core: import client id is not safe for JavaScript")
+)
+
+// MaxBuildClientID is the largest client id Build writes under:
+// JavaScript's Number.MAX_SAFE_INTEGER. lib0 refuses a larger varuint,
+// so an update written under one would apply here (yrs reads it) and in
+// no editor. The builder refuses it too (core/src/build.rs); this check
+// fails before the call. Ids the server only reads with are not bound.
+const MaxBuildClientID = 1<<53 - 1
+
+// Build writes the document an import instruction list describes
+// (core/src/build.rs) into a fresh document with this guid and client id,
+// and returns that document's whole state as one update. The list is
+// checked in full before anything is written, and the instance is
+// discarded either way, so a refusal or a trap leaves nothing behind.
+//
+// The build call alone may run for buildTimeoutFactor times the usual
+// limit. Writing a document costs about three times what applying the
+// result costs, and the result must still apply within the ordinary
+// limit every time the document is opened; the instance a slow build
+// runs in is thrown away regardless, so the longer allowance risks
+// nothing that the ordinary one protects.
+func (r *Runtime) Build(ctx context.Context, guid string, clientID uint64, ops []byte) ([]byte, error) {
+ if clientID > MaxBuildClientID {
+ return nil, ErrBuildClientID
+ }
+ h, err := r.NewDoc(ctx, guid, clientID)
+ if err != nil {
+ return nil, err
+ }
+ defer h.Close(ctx)
+
+ ptr, err := allocIn(ctx, r.callTimeout, h.mod, uint64(len(ops)))
+ if err != nil {
+ return nil, fmt.Errorf("core: build: alloc: %w", err)
+ }
+ defer freeIn(ctx, r.callTimeout, h.mod, ptr, uint64(len(ops)))
+ if !h.mod.Memory().Write(uint32(ptr), ops) {
+ return nil, fmt.Errorf("core: build: writing %d bytes at %d: out of range", len(ops), ptr)
+ }
+ rc, err := callGuest(ctx, buildTimeoutFactor*r.callTimeout, h.mod.ExportedFunction("docs_core_build"), h.handle, ptr, uint64(len(ops)))
+ if err != nil {
+ return nil, fmt.Errorf("core: build trapped or timed out: %w", err)
+ }
+ switch code := int32(rc[0]); code {
+ case 0:
+ case -6:
+ return nil, ErrBuildMalformed
+ case -7:
+ return nil, ErrBuildLimit
+ case -9:
+ return nil, ErrBuildClientID
+ default:
+ return nil, fmt.Errorf("core: build refused: code %d", code)
+ }
+ return h.Snapshot(ctx)
+}
+
+// BuildBlock is one block of an import: a paragraph when Heading is 0,
+// otherwise a heading of that level (1 to 6).
+type BuildBlock struct {
+ Heading int
+ Runs []BuildRun
+}
+
+// BuildRun is one run of text and the names of its marks.
+type BuildRun struct {
+ Marks []string
+ Text string
+}
+
+// EncodeBuild writes blocks as core/src/build.rs's instruction list,
+// version 1. It checks only what the encoding itself needs (lengths that
+// fit their fields); everything else, the vocabulary included, is the
+// builder's to refuse.
+func EncodeBuild(blocks []BuildBlock) ([]byte, error) {
+ out := []byte{1}
+ out = binary.LittleEndian.AppendUint32(out, uint32(len(blocks)))
+ for _, b := range blocks {
+ if b.Heading == 0 {
+ out = append(out, 1)
+ } else {
+ if b.Heading < 0 || b.Heading > 255 {
+ return nil, ErrBuildMalformed
+ }
+ out = append(out, 2, byte(b.Heading))
+ }
+ out = binary.LittleEndian.AppendUint32(out, uint32(len(b.Runs)))
+ for _, r := range b.Runs {
+ if len(r.Marks) > 255 || uint64(len(r.Text)) > math.MaxUint32 {
+ return nil, ErrBuildLimit
+ }
+ out = append(out, byte(len(r.Marks)))
+ for _, m := range r.Marks {
+ if len(m) > 255 {
+ return nil, ErrBuildMalformed
+ }
+ out = append(out, byte(len(m)))
+ out = append(out, m...)
+ }
+ out = binary.LittleEndian.AppendUint32(out, uint32(len(r.Text)))
+ out = append(out, r.Text...)
+ }
+ }
+ return out, nil
+}
diff --git a/internal/core/testdata/docs_core.wasm b/internal/core/testdata/docs_core.wasm
index bc3d747..b1deebb 100755
Binary files a/internal/core/testdata/docs_core.wasm and b/internal/core/testdata/docs_core.wasm differ
diff --git a/internal/docs/app.go b/internal/docs/app.go
index bbef648..be7e596 100644
--- a/internal/docs/app.go
+++ b/internal/docs/app.go
@@ -40,6 +40,8 @@ import (
"github.com/go-chi/chi/v5"
"github.com/carlosframework/docs/internal/core"
+
+ "amadan.net/oficina/estilo.git/googleimport"
)
// Config configures New.
@@ -52,6 +54,14 @@ type Config struct {
Directory string
Team *TeamConfig
+ // GoogleImport is the optional Google Drive chooser on the import
+ // page (estilo's googleimport): a public OAuth client ID, a public
+ // Picker API key and the Cloud project number, all three or none.
+ // None leaves the ordinary file import as it is; a partial or
+ // malformed setting refuses to start. cmd/docs reads
+ // $DOCS_GOOGLE_CLIENT_ID, $DOCS_GOOGLE_API_KEY and $DOCS_GOOGLE_APP_ID.
+ GoogleImport googleimport.Config
+
// DBPath is the SQLite file New opens via rastrillo's db package.
DBPath string
ContentKey string
@@ -419,6 +429,9 @@ func New(cfg Config) (*App, error) {
if err != nil {
return nil, err
}
+ if err := cfg.GoogleImport.Validate(); err != nil {
+ return nil, err
+ }
d, err := db.Open(cfg.DBPath, logger)
if err != nil {
@@ -551,7 +564,7 @@ func New(cfg Config) (*App, error) {
d.Close()
return nil, err
}
- h = &handlers{render: render, logger: logger, store: store, hub: newHub(), previews: newPreviews(), origin: cfg.Origin, isMember: list.configured, oneShots: newOneShots(), directory: directory}
+ h = &handlers{render: render, logger: logger, store: store, hub: newHub(), previews: newPreviews(), origin: cfg.Origin, isMember: list.configured, oneShots: newOneShots(), directory: directory, google: cfg.GoogleImport, imports: make(chan struct{}, maxImportsAtOnce)}
render.frame = h.frame
// peek: the viewer on routes no session guards (chrome.go). Standalone
// reads rastrillo/auth's own cookie; with Home, the Home bridge's.
@@ -760,6 +773,9 @@ func New(cfg Config) (*App, error) {
}
r.Get("/", h.list)
r.Post("/documents", h.create)
+ r.Get("/import", h.importGet)
+ r.Post("/import", h.importPost)
+ r.Get("/d/{sqid}/import-report", h.importReport)
// Title search for the jump-to palette (search.go). Inside
// this group like every other document route, and reader-scoped
// through Store.Search → Store.List rather than through a
diff --git a/internal/docs/content_cipher.go b/internal/docs/content_cipher.go
index fc837cc..8d2abf5 100644
--- a/internal/docs/content_cipher.go
+++ b/internal/docs/content_cipher.go
@@ -19,6 +19,11 @@ const contentUpdateKind byte = 1
const contentSnapshotKind byte = 2
const contentKeyCheckKind byte = 3
+// contentReportKind seals an import report (doc_import_reports). Its own
+// kind byte, so a report's ciphertext can never open as an update or a
+// snapshot of the same document, nor one of those as a report.
+const contentReportKind byte = 4
+
var developmentContentKey = sha256.Sum256([]byte("docs-development-content-key-not-a-secret"))
var errContentKey = errors.New("docs: invalid content key")
var errContentAuthentication = errors.New("docs: content authentication failed")
diff --git a/internal/docs/content_migration.go b/internal/docs/content_migration.go
index 7b82759..438e607 100644
--- a/internal/docs/content_migration.go
+++ b/internal/docs/content_migration.go
@@ -28,7 +28,7 @@ func readContentSealing(ctx context.Context, g *gorm.DB, c *contentCipher) (*con
err := g.WithContext(ctx).First(&state, 1).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
var count int64
- if err := g.WithContext(ctx).Raw("SELECT (SELECT COUNT(*) FROM doc_updates WHERE content_encoding != 0) + (SELECT COUNT(*) FROM doc_snapshots WHERE content_encoding != 0)").Scan(&count).Error; err != nil {
+ if err := g.WithContext(ctx).Raw("SELECT (SELECT COUNT(*) FROM doc_updates WHERE content_encoding != 0) + (SELECT COUNT(*) FROM doc_snapshots WHERE content_encoding != 0) + (SELECT COUNT(*) FROM doc_import_reports WHERE content_encoding != 0)").Scan(&count).Error; err != nil {
return nil, err
}
if count != 0 {
@@ -66,12 +66,12 @@ func convertContent(ctx context.Context, g *gorm.DB, c *contentCipher) error {
}
var hadLegacy bool
if state != nil {
- if err := tx.Raw("SELECT EXISTS(SELECT 1 FROM doc_updates WHERE content_encoding = 0 LIMIT 1) OR EXISTS(SELECT 1 FROM doc_snapshots WHERE content_encoding = 0 LIMIT 1)").Scan(&hadLegacy).Error; err != nil {
+ if err := tx.Raw("SELECT EXISTS(SELECT 1 FROM doc_updates WHERE content_encoding = 0 LIMIT 1) OR EXISTS(SELECT 1 FROM doc_snapshots WHERE content_encoding = 0 LIMIT 1) OR EXISTS(SELECT 1 FROM doc_import_reports WHERE content_encoding = 0 LIMIT 1)").Scan(&hadLegacy).Error; err != nil {
return err
}
}
- for _, snapshot := range []bool{false, true} {
- if err := convertContentRows(ctx, tx, c, snapshot, state != nil); err != nil {
+ for _, table := range contentTables {
+ if err := convertContentRows(ctx, tx, c, table, state != nil); err != nil {
return err
}
}
@@ -99,16 +99,26 @@ type contentMigrationRow struct {
GUID string
}
-func convertContentRows(ctx context.Context, tx *gorm.DB, c *contentCipher, snapshot, active bool) error {
- table, column, abi, kind := "doc_updates", "update_bin", "0", contentUpdateKind
- if snapshot {
- table, column, abi, kind = "doc_snapshots", "state", "r.abi_version", contentSnapshotKind
- }
+// contentTable is one table of sealed content: its body column, the SQL
+// for the seq and ABI version in its associated data, and its kind byte.
+type contentTable struct {
+ table, column, seq, abi string
+ kind byte
+}
+
+var contentTables = []contentTable{
+ {"doc_updates", "update_bin", "r.seq", "0", contentUpdateKind},
+ {"doc_snapshots", "state", "r.seq", "r.abi_version", contentSnapshotKind},
+ {"doc_import_reports", "report_bin", "0", "0", contentReportKind},
+}
+
+func convertContentRows(ctx context.Context, tx *gorm.DB, c *contentCipher, t contentTable, active bool) error {
+ table, column, seq, abi, kind := t.table, t.column, t.seq, t.abi, t.kind
last := int64(0)
first := true
for {
var rows []contentMigrationRow
- query := "SELECT r.id, r.doc_id, r.seq, " + abi + " AS abi_version, r.content_encoding, r." + column + " AS body, d.guid FROM " + table + " r LEFT JOIN documents d ON d.id=r.doc_id WHERE (? OR r.id > ?) ORDER BY r.id LIMIT 100"
+ query := "SELECT r.id, r.doc_id, " + seq + " AS seq, " + abi + " AS abi_version, r.content_encoding, r." + column + " AS body, d.guid FROM " + table + " r LEFT JOIN documents d ON d.id=r.doc_id WHERE (? OR r.id > ?) ORDER BY r.id LIMIT 100"
if err := tx.WithContext(ctx).Raw(query, first, last).Scan(&rows).Error; err != nil {
return err
}
diff --git a/internal/docs/content_rows.go b/internal/docs/content_rows.go
index 9076e32..231453e 100644
--- a/internal/docs/content_rows.go
+++ b/internal/docs/content_rows.go
@@ -45,3 +45,28 @@ func (c *contentCipher) openSnapshot(guid string, row *DocSnapshot) error {
row.State = plain
return nil
}
+
+// A report has no seq or ABI of its own; it is the document's one
+// report, so both are 0 in its associated data and the kind byte keeps it
+// apart.
+func (c *contentCipher) sealReport(guid string, row *DocImportReport) error {
+ sealed, err := c.seal(contentReportKind, guid, 0, 0, row.ReportBin)
+ if err != nil {
+ return fmt.Errorf("docs: seal import report: %w", err)
+ }
+ row.ReportBin = sealed
+ row.ContentEncoding = contentEncoding
+ return nil
+}
+
+func (c *contentCipher) openReport(guid string, row *DocImportReport) error {
+ if row.ContentEncoding != contentEncoding {
+ return errContentEncoding
+ }
+ plain, err := c.open(contentReportKind, guid, 0, 0, row.ReportBin)
+ if err != nil {
+ return fmt.Errorf("docs: open import report %d: %w", row.ID, err)
+ }
+ row.ReportBin = plain
+ return nil
+}
diff --git a/internal/docs/content_runtime.go b/internal/docs/content_runtime.go
index ce5d239..a1693b5 100644
--- a/internal/docs/content_runtime.go
+++ b/internal/docs/content_runtime.go
@@ -12,7 +12,7 @@ var errContentMixed = errors.New("docs: mixed content encodings; run docs-seal o
func requireSealedContent(ctx context.Context, g *gorm.DB) error {
var mixed bool
- if err := g.WithContext(ctx).Raw(`SELECT EXISTS(SELECT 1 FROM doc_updates WHERE content_encoding != 1 LIMIT 1) OR EXISTS(SELECT 1 FROM doc_snapshots WHERE content_encoding != 1 LIMIT 1)`).Scan(&mixed).Error; err != nil {
+ if err := g.WithContext(ctx).Raw(`SELECT EXISTS(SELECT 1 FROM doc_updates WHERE content_encoding != 1 LIMIT 1) OR EXISTS(SELECT 1 FROM doc_snapshots WHERE content_encoding != 1 LIMIT 1) OR EXISTS(SELECT 1 FROM doc_import_reports WHERE content_encoding != 1 LIMIT 1)`).Scan(&mixed).Error; err != nil {
return err
}
if mixed {
@@ -65,3 +65,20 @@ func (s *Store) openContentSnapshot(guid string, row *DocSnapshot) error {
}
return s.content.openSnapshot(guid, row)
}
+
+func (s *Store) prepareContentReport(tx *gorm.DB, guid string, row *DocImportReport) error {
+ if s.content == nil {
+ return refuseActivatedLegacyWrite(tx)
+ }
+ return s.content.sealReport(guid, row)
+}
+
+func (s *Store) openContentReport(guid string, row *DocImportReport) error {
+ if s.content == nil {
+ if row.ContentEncoding != 0 {
+ return errContentEncoding
+ }
+ return nil
+ }
+ return s.content.openReport(guid, row)
+}
diff --git a/internal/docs/google_import_browser_test.go b/internal/docs/google_import_browser_test.go
new file mode 100644
index 0000000..1eb8e84
--- /dev/null
+++ b/internal/docs/google_import_browser_test.go
@@ -0,0 +1,131 @@
+//go:build browser
+
+package docs_test
+
+import (
+ "archive/zip"
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/estilo.git/googleimport"
+ "amadan.net/rastrillo/rastrillo"
+
+ "github.com/carlosframework/docs/internal/docs"
+)
+
+// Controlled Google responses exercise the actual app routes, middleware,
+// converter, report and editor. The OOXML below is synthesized, not a real
+// Google export; this does not certify real account consent or export.
+func TestGoogleImportBrowserCreatesAnEditableDocument(t *testing.T) {
+ server := httptest.NewUnstartedServer(nil)
+ origin := "http://" + server.Listener.Addr().String()
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ key := bytes.Repeat([]byte{113}, 32) // synthetic fixture key, never deployment configuration
+ encoded := base64.StdEncoding.EncodeToString(key)
+ dbPath := filepath.Join(t.TempDir(), "docs.db")
+ if err := os.WriteFile(dbPath, nil, 0600); err != nil {
+ t.Fatal(err)
+ }
+ if err := docs.MaintainContent(context.Background(), docs.ContentMaintenanceConfig{
+ DBPath: dbPath, ContentKey: encoded, ExpectedFingerprint: fmt.Sprintf("%x", sha256.Sum256(key)), Logger: logger,
+ }); err != nil {
+ t.Fatal(err)
+ }
+ app, err := docs.NewForTestWith(t, docs.Config{DBPath: dbPath, ContentKey: encoded, Origin: origin, Logger: logger, GoogleImport: googleimport.Config{
+ ClientID: "123456789-client.apps.googleusercontent.com", APIKey: "AIzaPublicBrowserKey123456789", AppID: "123456789",
+ }})
+ if err != nil {
+ t.Fatal(err)
+ }
+ served, done, err := rastrillo.Handler(docs.ServeOptions(rastrillo.Options{}, app))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if done != nil {
+ t.Cleanup(func() { _ = done() })
+ }
+ server.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == http.MethodPost && r.URL.Path == "/import" {
+ body, err := io.ReadAll(io.LimitReader(r.Body, 11<<20))
+ if err != nil {
+ t.Error(err)
+ }
+ _ = r.Body.Close()
+ r.Body = io.NopCloser(bytes.NewReader(body))
+ if bytes.Contains(body, []byte("controlled-google-bearer")) || strings.Contains(r.Header.Get("Authorization"), "controlled-google-bearer") || strings.Contains(r.URL.String(), "controlled-google-bearer") {
+ t.Error("Google token reached Docs")
+ }
+ }
+ served.ServeHTTP(w, r)
+ })
+ server.Start()
+ t.Cleanup(server.Close)
+ config, err := json.Marshal(map[string]any{
+ "origin": origin, "cookies": signInCookies(t, app, "import-browser@example.com"),
+ "fixture": googleBrowserDOCX(t),
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, "node", "google-import.mjs")
+ cmd.Dir = "../../fixtures/engines"
+ cmd.Env = append(os.Environ(), "DOCS_GOOGLE_IMPORT_TEST="+string(config))
+ if out, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("Google import browser flow: %v\n%s", err, out)
+ }
+ for _, suffix := range []string{"", "-wal"} {
+ data, err := os.ReadFile(dbPath + suffix)
+ if suffix == "-wal" && os.IsNotExist(err) {
+ continue
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, content := range []string{"linked words", "Table cell", "Edited after import.", "table_flattened"} {
+ if bytes.Contains(data, []byte(content)) {
+ t.Errorf("imported content or report persisted unsealed in database%s", suffix)
+ }
+ }
+ }
+}
+
+func googleBrowserDOCX(t *testing.T) []byte {
+ t.Helper()
+ var buf bytes.Buffer
+ z := zip.NewWriter(&buf)
+ parts := map[string]string{
+ "[Content_Types].xml": `<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>`,
+ "_rels/.rels": `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>`,
+ "word/document.xml": `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><w:body><w:p><w:r><w:t>Import fixture</w:t></w:r></w:p><w:p><w:hyperlink r:id="rId9"><w:r><w:t>linked words</w:t></w:r></w:hyperlink></w:p><w:p><w:r><w:rPr><w:b/></w:rPr><w:t>bold text</w:t></w:r><w:r><w:rPr><w:b w:val="0"/></w:rPr><w:t xml:space="preserve"> plain text</w:t></w:r></w:p><w:tbl><w:tr><w:tc><w:p><w:r><w:t>Table cell</w:t></w:r></w:p></w:tc></w:tr></w:tbl></w:body></w:document>`,
+ "word/_rels/document.xml.rels": `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId9" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://fixture.invalid/never-fetch" TargetMode="External"/></Relationships>`,
+ }
+ for name, body := range parts {
+ w, err := z.Create(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := io.WriteString(w, body); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := z.Close(); err != nil {
+ t.Fatal(err)
+ }
+ return buf.Bytes()
+}
diff --git a/internal/docs/handlers.go b/internal/docs/handlers.go
index dae406a..7fbba28 100644
--- a/internal/docs/handlers.go
+++ b/internal/docs/handlers.go
@@ -18,6 +18,7 @@ import (
"gorm.io/gorm"
"amadan.net/oficina/estilo.git/chrome"
+ "amadan.net/oficina/estilo.git/googleimport"
estilomenu "amadan.net/oficina/estilo.git/menu"
"amadan.net/oficina/estilo.git/savestatus"
"amadan.net/rastrillo/rastrillo"
@@ -41,6 +42,12 @@ const maxUpdateBytes = 1 << 20
// instead: this app reads and writes documents through Store, never
// through a *gorm.DB of its own.
type handlers struct {
+ // google is the Google Drive chooser's public configuration; its
+ // zero value is off (import.go).
+ google googleimport.Config
+ // imports holds a slot per import converting now (maxImportsAtOnce).
+ imports chan struct{}
+
requireCurrent func(http.Handler) http.Handler
homeEnabled bool
// homeLinked reports a local person's stored Home link (linkstore.Linked).
@@ -141,6 +148,9 @@ type listPage struct {
// bare error page is a control that exists to fail — the same defect
// as the editor a reader could type into. (Re-review, finding 3.)
CanCreate bool
+ // ImportLabel is the list's link to the import page (import.go),
+ // shown with the create form, to members only.
+ ImportLabel string
Title string
Groups []docGroup
@@ -294,6 +304,7 @@ func (h *handlers) list(w http.ResponseWriter, r *http.Request) {
EmptyTitle: rastrillo.T(r, "docs.list.empty.title"),
EmptyBody: rastrillo.T(r, "docs.list.empty.body"),
CreateLabel: rastrillo.T(r, "docs.list.create.label"),
+ ImportLabel: rastrillo.T(r, "docs.list.import"),
CreatePlaceholder: rastrillo.T(r, "docs.list.create.placeholder"),
SignOutLabel: rastrillo.T(r, "docs.signout.label"),
Query: query,
@@ -427,6 +438,12 @@ type showPage struct {
Frame Frame
HomeLinkLabel string
+ // ImportReport is the import's report, shown once on arrival from
+ // POST /import (?imported=1); nil otherwise. CloseReport labels its
+ // close button.
+ ImportReport *reportView
+ CloseReport string
+
Title string
HTML template.HTML
SignOutLabel string // see listPage.SignOutLabel's own doc comment
@@ -678,6 +695,20 @@ func (h *handlers) show(w http.ResponseWriter, r *http.Request) {
if data.CanShare {
chromeFor.actions = []chrome.Action{{Item: estilomenu.Item{Href: "/d/" + doc.Sqid + "/share", Label: rastrillo.T(r, "docs.share.action")}}}
}
+ // An imported document keeps its report one click away, for anybody
+ // who can read the document; it shows itself once on arrival.
+ if h.store.hasImportReport(r.Context(), doc.ID) {
+ chromeFor.actions = append(chromeFor.actions, chrome.Action{Item: estilomenu.Item{Href: "/d/" + doc.Sqid + "/import-report", Label: rastrillo.T(r, "docs.import.report.open")}})
+ if r.URL.Query().Get("imported") == "1" {
+ rep, err := h.store.ImportReport(r.Context(), doc)
+ if err != nil {
+ h.logger.Error("docs: open import report", "doc_id", doc.ID, "err", err)
+ } else if rep != nil {
+ data.ImportReport = newReportView(r, doc.Sqid, rep)
+ data.CloseReport = rastrillo.T(r, "docs.import.report.close")
+ }
+ }
+ }
data.Frame = h.frame(r, chromeFor)
if err := h.render.page(w, r, "show", data); err != nil {
h.logger.Error("docs: render show", "err", err)
diff --git a/internal/docs/import.go b/internal/docs/import.go
new file mode 100644
index 0000000..6a45c3f
--- /dev/null
+++ b/internal/docs/import.go
@@ -0,0 +1,643 @@
+package docs
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ mrand "math/rand/v2"
+ "net/http"
+ "path"
+ "slices"
+ "strings"
+ "time"
+
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+
+ "amadan.net/oficina/estilo.git/googleimport"
+ "amadan.net/rastrillo/rastrillo"
+
+ "github.com/carlosframework/docs/internal/core"
+ "github.com/carlosframework/docs/internal/docx"
+ "github.com/carlosframework/docs/internal/export"
+)
+
+// Importing a .docx (spec §11.2; implementation/google-drive-import.md
+// in estilo). One route serves both ways in: the ordinary file form, and
+// the Google Drive chooser, which exports the chosen file in the browser
+// and puts it in that same form's file input. The server never talks to
+// Google and never sees a Google token.
+//
+// The path is read (docx.Import) -> instructions (core.EncodeBuild) ->
+// a genuine Yjs update written by the core's yrs builder -> that update
+// replayed into a second document and its structure compared with what
+// the reader meant -> one transaction writing the document row, its
+// first update and its report (Store.CreateImported). A failure at any
+// step creates nothing.
+
+// maxImportFile is the largest file accepted: the shared chooser's
+// export bound, which is also Google's own export limit.
+const maxImportFile = googleimport.MaxExportBytes
+
+// maxImportBody is maxImportFile plus room for the multipart framing,
+// the creation token and the filename.
+const maxImportBody = maxImportFile + 64<<10
+
+// maxImportsAtOnce bounds the imports converting at one time. Each holds
+// its file and up to 64 MiB of decompressed parts; beyond this a request
+// is told to try again rather than queued.
+const maxImportsAtOnce = 2
+
+// errImportUnsealed: this instance's content sealing is not activated.
+// New content here is sealed or it is not written; an import is new
+// content, so until an operator runs `docs docs-seal` an import is
+// refused rather than stored in the clear. (The update log keeps its
+// legacy behaviour for existing documents; that is a different promise.)
+var errImportUnsealed = errors.New("docs: content sealing is not activated; run docs docs-seal before importing")
+
+// errImportMismatch: the built document did not replay to the structure
+// the reader produced. Never expected; refused rather than saved,
+// because a report is only true of the document it was made for.
+var errImportMismatch = errors.New("docs: imported document does not match what was read")
+
+// imported is a converted file, ready to store.
+type imported struct {
+ guid string
+ clientID uint64 // the row's, for the server's read handles
+ builder uint64 // the one the update is written under
+ update []byte
+ report []byte
+ blocks int
+}
+
+// convertImport turns a .docx into an update and a report, and proves the
+// update is the document the report describes.
+func convertImport(ctx context.Context, rt *core.Runtime, data []byte) (*imported, error) {
+ res, err := docx.Import(data)
+ if err != nil {
+ return nil, err
+ }
+ blocks := buildBlocks(res.Document)
+ ops, err := core.EncodeBuild(blocks)
+ if err != nil {
+ return nil, err
+ }
+ guid := uuid.NewString()
+ // The client id the import writes under. A uint32, as Yjs draws its
+ // own: unlike the row's client id, which the server only ever reads
+ // with, this one is in the update every browser decodes, and lib0
+ // refuses a client id past Number.MAX_SAFE_INTEGER. Drawn here, never
+ // by yrs (core/src/lib.rs), and never equal to the row's.
+ builder := uint64(mrand.Uint32())
+ stored := uint64(mrand.Int64())
+ for stored == builder || stored == builder+1 {
+ stored = uint64(mrand.Int64())
+ }
+ update, err := rt.Build(ctx, guid, builder, ops)
+ if err != nil {
+ return nil, err
+ }
+
+ h, err := rt.NewDoc(ctx, guid, builder+1)
+ if err != nil {
+ return nil, err
+ }
+ defer h.Close(ctx)
+ if err := h.Apply(ctx, update); err != nil {
+ return nil, err
+ }
+ structure, err := h.JSON(ctx)
+ if err != nil {
+ return nil, err
+ }
+ replayed, err := export.Parse("", structure)
+ if err != nil {
+ return nil, err
+ }
+ if !slices.Equal(canonicalBlocks(buildBlocks(replayed)), canonicalBlocks(blocks)) {
+ return nil, errImportMismatch
+ }
+
+ report, err := json.Marshal(res.Report)
+ if err != nil {
+ return nil, err
+ }
+ return &imported{guid: guid, clientID: stored, builder: builder, update: update, report: report, blocks: len(blocks)}, nil
+}
+
+// buildBlocks is a document's top-level paragraphs and headings as the
+// builder's blocks. The reader writes nothing else, and the replayed
+// document can hold nothing else, so anything else is left out here and
+// shows up as a mismatch.
+func buildBlocks(d export.Document) []core.BuildBlock {
+ var out []core.BuildBlock
+ for _, n := range d.Root.Content {
+ b := core.BuildBlock{}
+ switch n.Type {
+ case "paragraph":
+ case "heading":
+ b.Heading = n.Attrs.Level
+ default:
+ b.Heading = -1
+ }
+ for _, r := range n.Content {
+ run := core.BuildRun{Text: r.Text}
+ if !r.IsText() {
+ run.Text = "\x00" + r.Type
+ }
+ for _, m := range r.Marks {
+ run.Marks = append(run.Marks, m.Type)
+ }
+ b.Runs = append(b.Runs, run)
+ }
+ out = append(out, b)
+ }
+ return out
+}
+
+// canonicalBlocks renders blocks one string per block, with runs of the
+// same marks merged and each run's marks sorted, so two spellings of
+// one document compare equal: the builder merges adjacent runs, and the
+// core lists a run's marks in its own table's order.
+func canonicalBlocks(blocks []core.BuildBlock) []string {
+ out := make([]string, len(blocks))
+ for i, b := range blocks {
+ var s strings.Builder
+ fmt.Fprintf(&s, "%d", b.Heading)
+ last := "\x01"
+ for _, r := range b.Runs {
+ marks := slices.Clone(r.Marks)
+ slices.Sort(marks)
+ key := strings.Join(marks, ",")
+ if key != last {
+ fmt.Fprintf(&s, "\x02%s\x03", key)
+ last = key
+ }
+ s.WriteString(r.Text)
+ }
+ out[i] = s.String()
+ }
+ return out
+}
+
+// CreateImported makes an imported document: the row, its first update
+// and its report, in one transaction, with membership checked inside it
+// as CreateDraft does. A creation token already used by this owner
+// returns that document and writes nothing, so a retried submission
+// after a lost answer cannot import twice.
+func (s *Store) CreateImported(ctx context.Context, owner int64, title, token string, imp *imported) (*Document, error) {
+ if s.content == nil {
+ return nil, errImportUnsealed
+ }
+ actor := s.ownerActor(ctx, owner)
+ if err := s.requireMember(ctx, actor); err != nil {
+ return nil, err
+ }
+ now := time.Now().UTC()
+ revision, err := newRevision(noRevisionTaken)
+ if err != nil {
+ return nil, err
+ }
+ var lastErr error
+ for attempt := 0; attempt < maxSqidAttempts; attempt++ {
+ sqid, err := newSqid()
+ if err != nil {
+ return nil, err
+ }
+ doc := &Document{Sqid: sqid, Title: title, OwnerID: owner, GUID: imp.guid, ClientID: imp.clientID,
+ Visibility: VisibilityTeam, Revision: revision, CreatedAt: now, UpdatedAt: now}
+ err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if err := s.requireMember(ctx, actor); err != nil {
+ return err
+ }
+ if token != "" {
+ var existing Document
+ err := tx.Where("owner_id = ? AND creation_token = ?", owner, token).First(&existing).Error
+ if err == nil {
+ if existing.DeletedAt != nil {
+ return gorm.ErrRecordNotFound
+ }
+ *doc = existing
+ return s.requireMember(ctx, actor)
+ }
+ if !errors.Is(err, gorm.ErrRecordNotFound) {
+ return err
+ }
+ doc.CreationToken = &token
+ }
+ if err := tx.Create(doc).Error; err != nil {
+ return err
+ }
+ row := &DocUpdate{DocID: doc.ID, Seq: 1, UpdateBin: imp.update, CreatedAt: now}
+ if err := s.prepareContentUpdate(tx, doc.GUID, row); err != nil {
+ return err
+ }
+ if err := tx.Create(row).Error; err != nil {
+ return err
+ }
+ report := &DocImportReport{DocID: doc.ID, ReportBin: imp.report, CreatedAt: now}
+ if err := s.prepareContentReport(tx, doc.GUID, report); err != nil {
+ return err
+ }
+ if err := tx.Create(report).Error; err != nil {
+ return err
+ }
+ if err := announce(tx, doc.ID, doc.Revision, false); err != nil {
+ return err
+ }
+ return s.requireMember(ctx, actor)
+ })
+ if err == nil {
+ return doc, nil
+ }
+ lastErr = err
+ if !errors.Is(err, gorm.ErrDuplicatedKey) {
+ break
+ }
+ }
+ return nil, fmt.Errorf("docs: create imported document: %w", lastErr)
+}
+
+// ImportReport is doc's import report, or nil for a document that was
+// not imported. The caller has already established the reader may see
+// doc; the report says nothing the document does not.
+func (s *Store) ImportReport(ctx context.Context, doc *Document) (*docx.Report, error) {
+ var row DocImportReport
+ err := s.db.WithContext(ctx).Where("doc_id = ?", doc.ID).First(&row).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ if err := s.openContentReport(doc.GUID, &row); err != nil {
+ return nil, err
+ }
+ var rep docx.Report
+ if err := json.Unmarshal(row.ReportBin, &rep); err != nil {
+ return nil, err
+ }
+ return &rep, nil
+}
+
+// hasImportReport is whether doc has a report, without opening it.
+func (s *Store) hasImportReport(ctx context.Context, docID int64) bool {
+ var n int64
+ return s.db.WithContext(ctx).Model(&DocImportReport{}).Where("doc_id = ?", docID).Count(&n).Error == nil && n > 0
+}
+
+// ---- pages
+
+type importPage struct {
+ Frame Frame
+ Title, Intro, Fidelity, FileLabel, Submit, Error string
+ Token string
+ Google googleimport.View
+ GoogleScript string
+}
+
+// importErrorKey is the catalog key for a refusal. Every one is a whole
+// answer that quotes nothing from the file.
+func importErrorKey(err error) string {
+ switch {
+ case errors.Is(err, docx.ErrNotWord):
+ return "docs.import.error.notword"
+ case errors.Is(err, docx.ErrMalformed):
+ return "docs.import.error.damaged"
+ case errors.Is(err, docx.ErrTooLarge), errors.Is(err, core.ErrBuildLimit):
+ return "docs.import.error.toolarge"
+ case errors.Is(err, docx.ErrEmpty):
+ return "docs.import.error.empty"
+ }
+ return "docs.import.error.failed"
+}
+
+func (h *handlers) importView(r *http.Request, token, errKey string) importPage {
+ title := rastrillo.T(r, "docs.import.title")
+ p := importPage{
+ Frame: h.frame(r, frameOptions{titleParts: []string{title}}),
+ Title: title,
+ Intro: rastrillo.T(r, "docs.import.intro"),
+ Fidelity: rastrillo.T(r, "docs.import.fidelity"),
+ FileLabel: rastrillo.T(r, "docs.import.file"),
+ Submit: rastrillo.T(r, "docs.import.submit"),
+ Token: token,
+ }
+ if errKey != "" {
+ p.Error = rastrillo.T(r, errKey)
+ }
+ if h.google.Enabled() {
+ p.Google = googleimport.View{Config: h.google, Kind: googleimport.Docs, FormID: "docs-import-form", InputID: "docs-import-file", Labels: googleimport.Text(rastrillo.LocaleFrom(r))}
+ p.GoogleScript = h.render.assets.Path("static/estilo/" + googleimport.JSName())
+ }
+ return p
+}
+
+// renderImport draws the import page, with the Google policy when the
+// chooser is on, at status (0 for 200).
+func (h *handlers) renderImport(w http.ResponseWriter, r *http.Request, p importPage, status int) {
+ // This page has no document to establish its emission guard. Keep
+ // membership live through rendering and each response chunk instead.
+ h.store.rememberResponse(r.Context(), permissionRead)
+ if access, ok := r.Context().Value(accessContextKey{}).(*requestAccess); ok && access != nil && h.store.team != nil && access.runtime == h.store.team {
+ prior := access.extraCheck
+ access.extraCheck = func(ctx context.Context) error {
+ if prior != nil {
+ if err := prior(ctx); err != nil {
+ return err
+ }
+ }
+ return h.store.requireMember(ctx, access.actor)
+ }
+ }
+ if h.google.Enabled() {
+ if err := googleimport.Headers(w, ContentSecurityPolicy); err != nil {
+ h.logger.Error("docs: import page policy", "err", err)
+ h.fail(w, r, http.StatusInternalServerError, failStatus)
+ return
+ }
+ } else {
+ w.Header().Set("Cache-Control", "no-store")
+ }
+ if err := h.render.pageStatus(w, r, "import", p, status); err != nil {
+ h.logger.Error("docs: render import page", "err", err)
+ h.fail(w, r, http.StatusInternalServerError, failStatus)
+ }
+}
+
+func (h *handlers) importGet(w http.ResponseWriter, r *http.Request) {
+ if !h.requireMemberRequest(w, r, false) {
+ return
+ }
+ if h.store.content == nil {
+ h.logger.Error("docs: import unavailable", "err", errImportUnsealed)
+ h.renderImport(w, r, h.importView(r, "", "docs.import.error.unsealed"), http.StatusServiceUnavailable)
+ return
+ }
+ h.renderImport(w, r, h.importView(r, uuid.NewString(), ""), 0)
+}
+
+// importPost reads the form without spilling to disk: MultipartReader,
+// one part at a time, the file read into memory up to maxImportFile.
+func (h *handlers) importPost(w http.ResponseWriter, r *http.Request) {
+ if !h.requireMemberRequest(w, r, false) {
+ return
+ }
+ owner, err := h.owner(r)
+ if err != nil {
+ h.logger.Error("docs: resolve signed-in person", "err", err)
+ h.fail(w, r, h.internalFailureStatus(), failStatus)
+ return
+ }
+ if h.store.content == nil {
+ h.logger.Error("docs: import unavailable", "err", errImportUnsealed)
+ h.renderImport(w, r, h.importView(r, "", "docs.import.error.unsealed"), http.StatusServiceUnavailable)
+ return
+ }
+ r.Body = http.MaxBytesReader(w, r.Body, maxImportBody)
+ token, name, data, status, errKey := readImportForm(r)
+ if token == "" {
+ token = uuid.NewString()
+ }
+ refuse := func(status int, key string) {
+ h.renderImport(w, r, h.importView(r, token, key), status)
+ }
+ if errKey != "" {
+ h.logger.Warn("docs: import refused", "reason", errKey)
+ refuse(status, errKey)
+ return
+ }
+
+ select {
+ case h.imports <- struct{}{}:
+ defer func() { <-h.imports }()
+ default:
+ refuse(http.StatusServiceUnavailable, "docs.import.error.busy")
+ return
+ }
+ started := time.Now()
+ imp, err := convertImport(r.Context(), h.store.core, data)
+ if err != nil {
+ key := importErrorKey(err)
+ // The reason only: never the file's name, title or content.
+ h.logger.Warn("docs: import refused", "reason", key, "bytes", len(data))
+ if key == "docs.import.error.failed" {
+ h.logger.Error("docs: import conversion failed", "err", err)
+ }
+ status := http.StatusUnprocessableEntity
+ if key == "docs.import.error.toolarge" {
+ status = http.StatusRequestEntityTooLarge
+ }
+ refuse(status, key)
+ return
+ }
+ title := importTitle(name)
+ if title == "" {
+ title = rastrillo.T(r, "docs.document.untitled")
+ }
+ doc, err := h.store.CreateImported(r.Context(), owner, title, token, imp)
+ if err != nil {
+ switch {
+ case errors.Is(err, errTeamNotMember):
+ h.fail(w, r, http.StatusForbidden, failStatus)
+ return
+ case errors.Is(err, errTeamUnavailable):
+ h.fail(w, r, http.StatusServiceUnavailable, failStatus)
+ return
+ }
+ h.logger.Error("docs: store imported document", "err", err)
+ refuse(h.internalFailureStatus(), "docs.import.error.failed")
+ return
+ }
+ h.logger.Info("docs: imported document", "doc_id", doc.ID, "bytes", len(data), "blocks", imp.blocks, "ms", time.Since(started).Milliseconds())
+ http.Redirect(w, r, "/d/"+doc.Sqid+"?imported=1", http.StatusSeeOther)
+}
+
+// readImportForm reads the creation token and the file. A refusal is a
+// status and a catalog key.
+func readImportForm(r *http.Request) (token, name string, data []byte, status int, errKey string) {
+ mr, err := r.MultipartReader()
+ if err != nil {
+ return "", "", nil, http.StatusBadRequest, "docs.import.error.nofile"
+ }
+ for parts := 0; ; parts++ {
+ if parts > 8 {
+ return token, "", nil, http.StatusBadRequest, "docs.import.error.nofile"
+ }
+ part, err := mr.NextPart()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ var tooLarge *http.MaxBytesError
+ if errors.As(err, &tooLarge) {
+ return token, "", nil, http.StatusRequestEntityTooLarge, "docs.import.error.toolarge"
+ }
+ return token, "", nil, http.StatusBadRequest, "docs.import.error.nofile"
+ }
+ switch part.FormName() {
+ case "creation_token":
+ b, err := io.ReadAll(io.LimitReader(part, 128))
+ if err == nil {
+ if id, err := uuid.Parse(strings.TrimSpace(string(b))); err == nil {
+ token = id.String()
+ }
+ }
+ case "file":
+ if data != nil {
+ return token, "", nil, http.StatusBadRequest, "docs.import.error.nofile"
+ }
+ name = part.FileName()
+ var buf bytes.Buffer
+ n, err := io.Copy(&buf, io.LimitReader(part, maxImportFile+1))
+ if err != nil {
+ var tooLarge *http.MaxBytesError
+ if errors.As(err, &tooLarge) {
+ return token, "", nil, http.StatusRequestEntityTooLarge, "docs.import.error.toolarge"
+ }
+ return token, "", nil, http.StatusBadRequest, "docs.import.error.nofile"
+ }
+ if n > maxImportFile {
+ return token, "", nil, http.StatusRequestEntityTooLarge, "docs.import.error.toolarge"
+ }
+ data = buf.Bytes()
+ }
+ part.Close()
+ }
+ if len(data) == 0 {
+ return token, "", nil, http.StatusBadRequest, "docs.import.error.nofile"
+ }
+ if !strings.EqualFold(path.Ext(importBase(name)), ".docx") {
+ return token, "", nil, http.StatusUnsupportedMediaType, "docs.import.error.notword"
+ }
+ // The ZIP signature, before anything opens the archive.
+ if !bytes.HasPrefix(data, []byte("PK\x03\x04")) {
+ return token, "", nil, http.StatusUnsupportedMediaType, "docs.import.error.notword"
+ }
+ return token, name, data, 0, ""
+}
+
+// importBase is a filename with any directories taken off, whichever
+// separator a browser or the chooser used.
+func importBase(name string) string {
+ if i := strings.LastIndexAny(name, `/\`); i >= 0 {
+ name = name[i+1:]
+ }
+ return name
+}
+
+// importTitle is the document title a filename gives: its base, without
+// .docx, trimmed and bounded like a typed title.
+func importTitle(name string) string {
+ base := importBase(name)
+ base = base[:len(base)-len(path.Ext(base))]
+ base = strings.Map(func(c rune) rune {
+ if c < 0x20 || c == 0x7f {
+ return -1
+ }
+ return c
+ }, base)
+ base = strings.TrimSpace(base)
+ if len(base) > 1024 {
+ base = strings.ToValidUTF8(base[:1024], "")
+ }
+ return base
+}
+
+// reportView is a report as the page shows it: the statement of what an
+// import brings, always first, and one line per kind of loss.
+type reportView struct {
+ Heading, Statement, Incomplete, Empty string
+ Lines []reportLine
+ Href, OpenLabel string
+}
+
+type reportLine struct {
+ Text, Where string
+}
+
+func newReportView(r *http.Request, sqid string, rep *docx.Report) *reportView {
+ v := &reportView{
+ Heading: rastrillo.T(r, "docs.import.report.heading"),
+ Statement: rastrillo.T(r, "docs.import.fidelity"),
+ Incomplete: rastrillo.T(r, "docs.import.report.incomplete"),
+ Href: "/d/" + sqid + "/import-report",
+ OpenLabel: rastrillo.T(r, "docs.import.report.open"),
+ }
+ for _, it := range rep.Items {
+ key := "docs.import.report." + string(it.Code)
+ if !slices.Contains(docx.Codes, it.Code) {
+ continue
+ }
+ line := reportLine{Text: rastrillo.Tf(r, key, "count", it.Count)}
+ if len(it.Paragraphs) > 0 {
+ nums := make([]string, len(it.Paragraphs))
+ for i, p := range it.Paragraphs {
+ nums[i] = fmt.Sprint(p)
+ }
+ line.Where = rastrillo.Tf(r, "docs.import.report.where", "paragraphs", strings.Join(nums, ", "))
+ if it.Count > len(it.Paragraphs) {
+ line.Where = rastrillo.Tf(r, "docs.import.report.where.more", "paragraphs", strings.Join(nums, ", "))
+ }
+ }
+ v.Lines = append(v.Lines, line)
+ }
+ if len(v.Lines) == 0 {
+ v.Empty = rastrillo.T(r, "docs.import.report.none")
+ }
+ return v
+}
+
+type importReportPage struct {
+ Frame Frame
+ Report *reportView
+ Back string
+ BackHref string
+}
+
+// importReport is GET /d/{sqid}/import-report: the report, reopened.
+// Readable by anybody who can read the document; a document that was
+// not imported, or that the reader cannot see, is 404 alike.
+func (h *handlers) importReport(w http.ResponseWriter, r *http.Request) {
+ actor, err := h.actor(r)
+ if err != nil {
+ h.logger.Error("docs: resolve signed-in person", "err", err)
+ h.fail(w, r, h.internalFailureStatus(), failStatus)
+ return
+ }
+ doc, err := h.store.GetFor(r.Context(), actor, r.PathValue("sqid"))
+ if err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ h.fail(w, r, http.StatusNotFound, failDocument)
+ return
+ }
+ h.logger.Error("docs: get document", "err", err)
+ h.fail(w, r, h.internalFailureStatus(), failStatus)
+ return
+ }
+ rep, err := h.store.ImportReport(r.Context(), doc)
+ if err != nil {
+ h.logger.Error("docs: open import report", "doc_id", doc.ID, "err", err)
+ h.fail(w, r, h.internalFailureStatus(), failStatus)
+ return
+ }
+ if rep == nil {
+ h.fail(w, r, http.StatusNotFound, failDocument)
+ return
+ }
+ heading := rastrillo.T(r, "docs.import.report.heading")
+ data := importReportPage{
+ Frame: h.frame(r, frameOptions{titleParts: []string{heading, doc.Title}, context: doc.Title}),
+ Report: newReportView(r, doc.Sqid, rep),
+ Back: rastrillo.T(r, "docs.import.report.back"),
+ BackHref: "/d/" + doc.Sqid,
+ }
+ w.Header().Set("Cache-Control", "no-store")
+ if err := h.render.page(w, r, "import-report", data); err != nil {
+ h.logger.Error("docs: render import report", "err", err)
+ h.fail(w, r, http.StatusInternalServerError, failStatus)
+ }
+}
diff --git a/internal/docs/import_interop_test.go b/internal/docs/import_interop_test.go
new file mode 100644
index 0000000..3012f88
--- /dev/null
+++ b/internal/docs/import_interop_test.go
@@ -0,0 +1,123 @@
+package docs
+
+import (
+ "archive/zip"
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/docs/internal/core"
+ "github.com/carlosframework/docs/internal/docx"
+ "github.com/carlosframework/docs/internal/export"
+)
+
+// interopDocx is a SYNTHESIZED .docx (not a real Google export) with
+// every block and mark an import can write: six heading levels, empty
+// paragraphs, faces, ladder sizes, bold, italic, text from a link, a
+// table cell and a suggestion, and characters past the BMP.
+func interopDocx(t *testing.T) []byte {
+ t.Helper()
+ const ns = `xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"`
+ var body strings.Builder
+ for level := 1; level <= 6; level++ {
+ body.WriteString(`<w:p><w:pPr><w:pStyle w:val="Heading` + string(rune('0'+level)) + `"/></w:pPr><w:r><w:t>Level</w:t></w:r></w:p>`)
+ }
+ body.WriteString(`<w:p/>`)
+ body.WriteString(`<w:p><w:r><w:t xml:space="preserve">plain </w:t></w:r>` +
+ `<w:r><w:rPr><w:rFonts w:ascii="Cambria"/><w:b/><w:sz w:val="28"/></w:rPr><w:t>Caladea 14 bold</w:t></w:r>` +
+ `<w:r><w:rPr><w:rFonts w:ascii="Courier New"/><w:i/><w:sz w:val="16"/></w:rPr><w:t xml:space="preserve"> mono 8 italic</w:t></w:r>` +
+ `<w:hyperlink r:id="rId1"><w:r><w:t xml:space="preserve"> linked 🦀 café</w:t></w:r></w:hyperlink></w:p>`)
+ body.WriteString(`<w:tbl><w:tr><w:tc><w:p><w:r><w:rPr><w:sz w:val="144"/></w:rPr><w:t>cell at 72</w:t></w:r></w:p></w:tc></w:tr></w:tbl>`)
+ body.WriteString(`<w:p><w:ins w:id="1" w:author="x"><w:r><w:t>suggested</w:t></w:r></w:ins></w:p>`)
+ var buf bytes.Buffer
+ z := zip.NewWriter(&buf)
+ for name, part := range map[string]string{
+ "word/styles.xml": `<w:styles ` + ns + `><w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/></w:style></w:styles>`,
+ "word/document.xml": `<w:document ` + ns + `><w:body>` + body.String() + `</w:body></w:document>`,
+ } {
+ w, err := z.Create(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ io.WriteString(w, part)
+ }
+ if err := z.Close(); err != nil {
+ t.Fatal(err)
+ }
+ return buf.Bytes()
+}
+
+// The editor must be able to open what an import writes, as it is, with
+// the client ids the converter actually draws: fixed small ids in a
+// fixture cannot show that an id past 2^53 is unreadable in a browser,
+// which is exactly how the first version of this path broke. So this
+// runs the real convertImport, many times, and hands each update to
+// Yjs and y-prosemirror under the editor's own schema
+// (fixtures/import-interop.mjs).
+func TestImportedUpdatesOpenInTheEditorUnchanged(t *testing.T) {
+ node, err := exec.LookPath("node")
+ modules := filepath.Join("..", "..", "fixtures", "node_modules", "y-prosemirror")
+ if _, statErr := os.Stat(modules); err != nil || statErr != nil {
+ if os.Getenv("DOCS_REQUIRE_WASM") == "1" {
+ t.Fatal("the gate needs node and fixtures/node_modules for this check")
+ }
+ t.Skip("needs node and `npm ci` in fixtures/")
+ }
+
+ ctx := context.Background()
+ rt, err := core.New(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rt.Close(ctx)
+
+ data := interopDocx(t)
+ read, err := docx.Import(data)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := canonicalBlocks(buildBlocks(read.Document))
+
+ for i := 0; i < 12; i++ {
+ imp, err := convertImport(ctx, rt, data)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if imp.builder > core.MaxBuildClientID || imp.builder == imp.clientID {
+ t.Fatalf("builder id %d (row id %d)", imp.builder, imp.clientID)
+ }
+ cmd := exec.Command(node, "import-interop.mjs")
+ cmd.Dir = filepath.Join("..", "..", "fixtures")
+ cmd.Stdin = bytes.NewReader(imp.update)
+ var stderr bytes.Buffer
+ cmd.Stderr = &stderr
+ out, err := cmd.Output()
+ if err != nil {
+ t.Fatalf("import %d: %v: %s", i, err, stderr.String())
+ }
+ var got struct {
+ Clients []float64 `json:"clients"`
+ Doc json.RawMessage `json:"doc"`
+ }
+ if err := json.Unmarshal(out, &got); err != nil {
+ t.Fatal(err)
+ }
+ if len(got.Clients) != 1 || uint64(got.Clients[0]) != imp.builder {
+ t.Fatalf("import %d: clients %v, want only the builder's %d", i, got.Clients, imp.builder)
+ }
+ pm, err := export.Parse("", string(got.Doc))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if g := canonicalBlocks(buildBlocks(pm)); !slices.Equal(g, want) {
+ t.Fatalf("import %d: the editor reads\n%q\nwant\n%q", i, g, want)
+ }
+ }
+}
diff --git a/internal/docs/import_team_test.go b/internal/docs/import_team_test.go
new file mode 100644
index 0000000..a8e990c
--- /dev/null
+++ b/internal/docs/import_team_test.go
@@ -0,0 +1,51 @@
+package docs
+
+import (
+ "bytes"
+ "context"
+ "encoding/base64"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestTeamImportFormAndRefusalRender(t *testing.T) {
+ f := newTeamRouterFixture(t)
+ b := f.browser()
+ b.localSignin(t, "alice@example.com")
+ b.linkProof(t, teamSubject('a'), "alice@example.com")
+ routerRedirect(t, b.do("POST", "/account/home/confirm", ""), connectedURL("/"))
+ // These requests only render a form; no content is written.
+ var err error
+ f.app.store.content, err = newContentCipher(base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{73}, 32)), "production")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, tc := range []struct {
+ method string
+ want int
+ }{{"GET", 200}, {"POST", 400}} {
+ r := b.do(tc.method, "/import", "")
+ if r.Code != tc.want || !strings.Contains(r.Body.String(), "docs-import-form") {
+ t.Errorf("%s import: status %d, want %d with import form", tc.method, r.Code, tc.want)
+ }
+ }
+}
+
+func TestTeamImportFormRefusesExpiredMembershipAtEmission(t *testing.T) {
+ app, _ := sealedApp(t, Config{})
+ owner := app.TestPerson(t, "owner@example.com")
+ rt, clock, subject := testTeamRoster(t, app.store, app)
+ ctx := t.Context()
+ access := rt.resolveAccess(ctx, requestIdentity{Actor: localActor(owner, "owner@example.com"), HomeSubject: subject})
+ ctx = context.WithValue(ctx, accessContextKey{}, access)
+ r := httptest.NewRequest("GET", "https://docs.example/import", nil).WithContext(ctx)
+ p := app.handlers.importView(r, "test-token", "")
+ clock.step(60 * time.Second)
+ w := &teamDeadlineRecorder{ResponseRecorder: httptest.NewRecorder()}
+ app.handlers.renderImport(w, r, p, 0)
+ if w.Code != 503 || strings.Contains(w.Body.String(), "docs-import-form") {
+ t.Fatalf("expired member received import form: status %d", w.Code)
+ }
+}
diff --git a/internal/docs/import_test.go b/internal/docs/import_test.go
new file mode 100644
index 0000000..7606254
--- /dev/null
+++ b/internal/docs/import_test.go
@@ -0,0 +1,470 @@
+package docs
+
+import (
+ "archive/zip"
+ "bytes"
+ "context"
+ "encoding/base64"
+ "errors"
+ "io"
+ "log/slog"
+ "mime/multipart"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/estilo.git/googleimport"
+ "amadan.net/rastrillo/rastrillo"
+)
+
+// The fixtures here are SYNTHESIZED .docx files, not real Google exports.
+
+// importMarker is text that must never appear at rest: in the database,
+// its WAL, or the log.
+const importMarker = "Zanzibar-quokka"
+
+// importName is a filename that must never reach the log.
+const importName = "Secret board minutes.docx"
+
+const wordNS = `xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"`
+
+func wordDoc(t *testing.T, body string) []byte {
+ t.Helper()
+ var buf bytes.Buffer
+ z := zip.NewWriter(&buf)
+ w, err := z.Create("word/document.xml")
+ if err != nil {
+ t.Fatal(err)
+ }
+ io.WriteString(w, `<w:document `+wordNS+`><w:body>`+body+`</w:body></w:document>`)
+ if err := z.Close(); err != nil {
+ t.Fatal(err)
+ }
+ return buf.Bytes()
+}
+
+// nestedDoc has text in a link and a table, a bold-off run, and a
+// suggestion, so a report has lines and the text has places to hide.
+func nestedDoc(t *testing.T) []byte {
+ return wordDoc(t, `<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>Minutes</w:t></w:r></w:p>`+
+ `<w:p><w:hyperlink r:id="rId1"><w:r><w:t>`+importMarker+` link</w:t></w:r></w:hyperlink></w:p>`+
+ `<w:tbl><w:tr><w:tc><w:p><w:r><w:t>cell text</w:t></w:r></w:p></w:tc></w:tr></w:tbl>`+
+ `<w:p><w:r><w:rPr><w:b w:val="0"/></w:rPr><w:t>not bold</w:t></w:r></w:p>`)
+}
+
+// sealedApp is an app on a database whose content sealing is activated,
+// as activatedContentApp makes one, with the caller's Config.
+func sealedApp(t *testing.T, cfg Config) (*App, string) {
+ t.Helper()
+ key := base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{73}, 32))
+ cfg.DBPath = filepath.Join(t.TempDir(), "docs.db")
+ cfg.Env = "development"
+ cfg.ContentKey = key
+ app, err := New(cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := app.Close(); err != nil {
+ t.Fatal(err)
+ }
+ cipher, err := newContentCipher(key, "production")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := MaintainContent(context.Background(), ContentMaintenanceConfig{DBPath: cfg.DBPath, ContentKey: key, ExpectedFingerprint: cipher.fingerprint}); err != nil {
+ t.Fatal(err)
+ }
+ app, err = New(cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { app.Close() })
+ return app, cfg.DBPath
+}
+
+// signedIn caches one session per app and address: signing in afresh
+// for every request runs into the sign-in rate limit.
+var signedIn = map[*App]map[string][]*http.Cookie{}
+
+// asSignedIn is app.TestRequest without a fresh sign-in each time.
+func asSignedIn(t *testing.T, app *App, who, method, path string, body io.Reader) *http.Request {
+ t.Helper()
+ if signedIn[app] == nil {
+ signedIn[app] = map[string][]*http.Cookie{}
+ t.Cleanup(func() { delete(signedIn, app) })
+ }
+ cookies, ok := signedIn[app][who]
+ if !ok {
+ cookies = app.TestRequest(t, who, method, path, nil).Cookies()
+ signedIn[app][who] = cookies
+ }
+ req := httptest.NewRequest(method, path, body)
+ for _, c := range cookies {
+ req.AddCookie(c)
+ }
+ if method != http.MethodGet {
+ req.Header.Set("Sec-Fetch-Site", "same-origin")
+ }
+ return req
+}
+
+func importRequest(t *testing.T, app *App, who, token, name string, file []byte) *http.Request {
+ t.Helper()
+ var body bytes.Buffer
+ mw := multipart.NewWriter(&body)
+ if token != "" {
+ mw.WriteField("creation_token", token)
+ }
+ if file != nil {
+ w, err := mw.CreateFormFile("file", name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ w.Write(file)
+ }
+ mw.Close()
+ req := asSignedIn(t, app, who, http.MethodPost, "/import", &body)
+ req.Header.Set("Content-Type", mw.FormDataContentType())
+ return req
+}
+
+func countRows(t *testing.T, app *App, table string) int64 {
+ t.Helper()
+ var n int64
+ if err := app.store.db.Table(table).Count(&n).Error; err != nil {
+ t.Fatal(err)
+ }
+ return n
+}
+
+func TestImportCreatesASealedEditableDocumentWithItsReport(t *testing.T) {
+ var logs bytes.Buffer
+ app, dbPath := sealedApp(t, Config{Logger: slog.New(slog.NewTextHandler(&logs, nil))})
+ const who = "owner@example.com"
+ const token = "1b0f8a52-6f0e-4a7e-9a0c-2f7f8d7f0a11"
+
+ rec := serve(app, importRequest(t, app, who, token, importName, nestedDoc(t)))
+ if rec.Code != http.StatusSeeOther {
+ t.Fatalf("POST /import: %d %s", rec.Code, rec.Body.String())
+ }
+ loc := rec.Header().Get("Location")
+ sqid, ok := strings.CutSuffix(strings.TrimPrefix(loc, "/d/"), "?imported=1")
+ if !ok || sqid == "" {
+ t.Fatalf("Location %q", loc)
+ }
+
+ // The same submission again, after a lost answer, is the same document.
+ again := serve(app, importRequest(t, app, who, token, importName, nestedDoc(t)))
+ if again.Code != http.StatusSeeOther || again.Header().Get("Location") != loc {
+ t.Fatalf("a retried import: %d %q, want the first document", again.Code, again.Header().Get("Location"))
+ }
+ if n := countRows(t, app, "documents"); n != 1 {
+ t.Fatalf("%d documents after a retried import, want 1", n)
+ }
+
+ ctx := context.Background()
+ owner := app.TestPerson(t, who)
+ doc, err := app.store.Get(ctx, owner, sqid)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if doc.Title != "Secret board minutes" {
+ t.Errorf("title %q", doc.Title)
+ }
+ text, err := app.store.Text(ctx, doc)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, want := range []string{"Minutes", importMarker + " link", "cell text", "not bold"} {
+ if !strings.Contains(text, want) {
+ t.Errorf("the document has no %q: %q", want, text)
+ }
+ }
+
+ // Sealed at rest: the update, the report, and neither in the clear
+ // in the database or its WAL.
+ var upd DocUpdate
+ if err := app.store.db.Where("doc_id = ?", doc.ID).First(&upd).Error; err != nil {
+ t.Fatal(err)
+ }
+ var rep DocImportReport
+ if err := app.store.db.Where("doc_id = ?", doc.ID).First(&rep).Error; err != nil {
+ t.Fatal(err)
+ }
+ if upd.Seq != 1 || upd.ContentEncoding != contentEncoding || rep.ContentEncoding != contentEncoding {
+ t.Fatalf("update seq %d encoding %d, report encoding %d", upd.Seq, upd.ContentEncoding, rep.ContentEncoding)
+ }
+ for _, f := range []string{dbPath, dbPath + "-wal"} {
+ b, err := os.ReadFile(f)
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ t.Fatal(err)
+ }
+ for _, s := range []string{importMarker, "table_flattened", "link_text_kept"} {
+ if bytes.Contains(b, []byte(s)) {
+ t.Errorf("%s holds %q in the clear", filepath.Base(f), s)
+ }
+ }
+ }
+ // A report's ciphertext does not open as an update of the same
+ // document: its own kind byte.
+ probe := DocUpdate{Seq: 0, UpdateBin: append([]byte(nil), rep.ReportBin...), ContentEncoding: contentEncoding}
+ if err := app.store.content.openUpdate(doc.GUID, &probe); err == nil {
+ t.Error("a sealed report opened as an update")
+ }
+
+ // Editable: an ordinary update applies on top.
+ if rec := serve(app, asSignedIn(t, app, who, http.MethodPost, "/d/"+sqid+"/updates", bytes.NewReader(validUpdate(t)))); rec.Code != http.StatusNoContent {
+ t.Fatalf("POST update to the import: %d", rec.Code)
+ }
+
+ // The report shows once on arrival, and reopens from the bar.
+ arrival := serve(app, asSignedIn(t, app, who, http.MethodGet, loc, nil)).Body.String()
+ for _, want := range []string{"<dialog docs-dialog docs-import-arrival open>", "<section docs-import-report", "docs.import.report.table_flattened", "/d/" + sqid + "/import-report"} {
+ if !strings.Contains(arrival, want) {
+ t.Errorf("the arrival page has no %q", want)
+ }
+ }
+ plain := serve(app, asSignedIn(t, app, who, http.MethodGet, "/d/"+sqid, nil)).Body.String()
+ if strings.Contains(plain, "<dialog docs-dialog docs-import-arrival") || !strings.Contains(plain, "/d/"+sqid+"/import-report") {
+ t.Error("the report should show only on arrival, and its link always")
+ }
+ page := serve(app, asSignedIn(t, app, who, http.MethodGet, "/d/"+sqid+"/import-report", nil))
+ if page.Code != http.StatusOK || !strings.Contains(page.Body.String(), "docs.import.report.link_text_kept") || !strings.Contains(page.Body.String(), "docs.import.report.incomplete") {
+ t.Fatalf("the report page: %d", page.Code)
+ }
+ if rec := serve(app, asSignedIn(t, app, "stranger@example.com", http.MethodGet, "/d/"+sqid+"/import-report", nil)); rec.Code != http.StatusOK {
+ t.Errorf("an admitted member reading a team import report: %d, want 200", rec.Code)
+ }
+ if err := app.store.SetVisibility(ctx, owner, sqid, VisibilityPrivate); err != nil {
+ t.Fatal(err)
+ }
+ if rec := serve(app, asSignedIn(t, app, "stranger@example.com", http.MethodGet, "/d/"+sqid+"/import-report", nil)); rec.Code != http.StatusNotFound {
+ t.Errorf("a stranger reading the report: %d, want 404", rec.Code)
+ }
+ created := createDocFor(t, app, who)
+ if rec := serve(app, asSignedIn(t, app, who, http.MethodGet, "/d/"+created+"/import-report", nil)); rec.Code != http.StatusNotFound {
+ t.Errorf("the report of a document never imported: %d, want 404", rec.Code)
+ }
+
+ if strings.Contains(logs.String(), importMarker) || strings.Contains(logs.String(), "Secret board") {
+ t.Error("the log carries the file's content or name")
+ }
+}
+
+func createDocFor(t *testing.T, app *App, who string) string {
+ t.Helper()
+ req := asSignedIn(t, app, who, http.MethodPost, "/documents", strings.NewReader("title=Typed"))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ rec := serve(app, req)
+ if rec.Code != http.StatusSeeOther {
+ t.Fatalf("POST /documents: %d", rec.Code)
+ }
+ return strings.TrimPrefix(rec.Header().Get("Location"), "/d/")
+}
+
+// Every refusal creates nothing, says why in words, and logs no name or
+// content.
+func TestImportRefusalsCreateNothing(t *testing.T) {
+ var logs bytes.Buffer
+ app, _ := sealedApp(t, Config{Logger: slog.New(slog.NewTextHandler(&logs, nil))})
+ const who = "owner@example.com"
+ damaged := nestedDoc(t)
+ damaged = append(damaged[:len(damaged)/2:len(damaged)/2], bytes.Repeat([]byte{0}, 64)...)
+ for _, c := range []struct {
+ name string
+ file []byte
+ fname string
+ status int
+ says string
+ }{
+ {"no file", nil, "", http.StatusBadRequest, "docs.import.error.nofile"},
+ {"a PDF", []byte("%PDF-1.7 " + importMarker), "minutes.pdf", http.StatusUnsupportedMediaType, "docs.import.error.notword"},
+ {"a PDF named .docx", []byte("%PDF-1.7 " + importMarker), importName, http.StatusUnsupportedMediaType, "docs.import.error.notword"},
+ {"a damaged archive", damaged, importName, http.StatusUnprocessableEntity, "docs.import.error.notword"},
+ {"broken XML", wordDoc(t, `<w:p><w:r><w:t>`+importMarker), importName, http.StatusUnprocessableEntity, "docs.import.error.damaged"},
+ {"no text", wordDoc(t, `<w:p/><w:p><w:r><w:drawing/></w:r></w:p>`), importName, http.StatusUnprocessableEntity, "docs.import.error.empty"},
+ {"too large", append([]byte("PK\x03\x04"), bytes.Repeat([]byte("x"), googleimport.MaxExportBytes)...), importName, http.StatusRequestEntityTooLarge, "docs.import.error.toolarge"},
+ } {
+ rec := serve(app, importRequest(t, app, who, "", c.fname, c.file))
+ body := rec.Body.String()
+ if rec.Code != c.status || !strings.Contains(body, "docs-import-error") || !strings.Contains(body, c.says) {
+ t.Errorf("%s: %d, want %d saying %q", c.name, rec.Code, c.status, c.says)
+ }
+ if strings.Contains(body, importMarker) {
+ t.Errorf("%s: the page quotes the file", c.name)
+ }
+ }
+ for _, table := range []string{"documents", "doc_updates", "doc_import_reports"} {
+ if n := countRows(t, app, table); n != 0 {
+ t.Errorf("%d rows in %s after refusals", n, table)
+ }
+ }
+ if strings.Contains(logs.String(), importMarker) || strings.Contains(logs.String(), "Secret board") {
+ t.Error("the log carries the file's content or name")
+ }
+}
+
+// New content on this instance is sealed or it is not written: until
+// sealing is activated, the page says so and an import is refused.
+// Existing legacy documents are untouched by this.
+func TestImportIsRefusedUntilContentSealingIsActivated(t *testing.T) {
+ app, err := NewForTest(t)
+ if err != nil {
+ t.Fatal(err)
+ }
+ const who = "owner@example.com"
+ get := serve(app, asSignedIn(t, app, who, http.MethodGet, "/import", nil))
+ if get.Code != http.StatusServiceUnavailable || !strings.Contains(get.Body.String(), "docs.import.error.unsealed") {
+ t.Errorf("GET /import unsealed: %d", get.Code)
+ }
+ post := serve(app, importRequest(t, app, who, "", importName, nestedDoc(t)))
+ if post.Code != http.StatusServiceUnavailable || !strings.Contains(post.Body.String(), "docs.import.error.unsealed") {
+ t.Errorf("POST /import unsealed: %d", post.Code)
+ }
+ if _, err := app.store.CreateImported(context.Background(), app.TestPerson(t, who), "x", "", &imported{}); !errors.Is(err, errImportUnsealed) {
+ t.Errorf("CreateImported unsealed: %v", err)
+ }
+ for _, table := range []string{"documents", "doc_updates", "doc_import_reports"} {
+ if n := countRows(t, app, table); n != 0 {
+ t.Errorf("%d rows in %s", n, table)
+ }
+ }
+ // The ordinary legacy path still writes.
+ createDocFor(t, app, who)
+}
+
+// A guest, admitted by a grant to one document, does not import any more
+// than they create.
+func TestAGuestCannotImport(t *testing.T) {
+ app, _ := sealedApp(t, Config{AllowedAddresses: "alice@example.com"})
+ sqid := createDocFor(t, app, "alice@example.com")
+ share := asSignedIn(t, app, "alice@example.com", http.MethodPost, "/d/"+sqid+"/share", strings.NewReader("address=bob@example.com&role=writer"))
+ share.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ if rec := serve(app, share); rec.Code != http.StatusSeeOther {
+ t.Fatalf("share: %d", rec.Code)
+ }
+ if rec := serve(app, asSignedIn(t, app, "bob@example.com", http.MethodGet, "/import", nil)); rec.Code != http.StatusForbidden {
+ t.Errorf("guest GET /import: %d, want 403", rec.Code)
+ }
+ if rec := serve(app, importRequest(t, app, "bob@example.com", "", importName, nestedDoc(t))); rec.Code != http.StatusForbidden {
+ t.Errorf("guest POST /import: %d, want 403", rec.Code)
+ }
+ if n := countRows(t, app, "documents"); n != 1 {
+ t.Errorf("%d documents, want alice's one", n)
+ }
+}
+
+// A cross-site POST is refused by the same origin check as every other
+// form, before anything is read.
+func TestImportRefusesACrossSitePost(t *testing.T) {
+ app, _ := sealedApp(t, Config{})
+ req := importRequest(t, app, "owner@example.com", "", importName, nestedDoc(t))
+ req.Header.Set("Sec-Fetch-Site", "cross-site")
+ if rec := serve(app, req); rec.Code != http.StatusForbidden {
+ t.Errorf("cross-site import: %d, want 403", rec.Code)
+ }
+ if n := countRows(t, app, "documents"); n != 0 {
+ t.Errorf("%d documents", n)
+ }
+}
+
+var testGoogle = googleimport.Config{
+ ClientID: "1234567890-abcdefghijklmnop.apps.googleusercontent.com",
+ APIKey: "AIzaSyTESTONLYabcdefghijklmnopqrstuvw",
+ AppID: "1234567890",
+}
+
+// Served through rastrillo's production middleware, as the binary serves
+// it: the import page alone gains Google's origins, keeps every
+// directive that matters, sets no COOP, and with Google off is the app's
+// own policy with no Google anywhere.
+func TestImportPagePolicy(t *testing.T) {
+ for _, on := range []bool{false, true} {
+ cfg := Config{}
+ if on {
+ cfg.GoogleImport = testGoogle
+ }
+ app, _ := sealedApp(t, cfg)
+ served, done, err := rastrillo.Handler(ServeOptions(rastrillo.Options{}, app))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if done != nil {
+ defer done()
+ }
+ page := func(req *http.Request) *httptest.ResponseRecorder {
+ req.Header.Set("Accept", "text/html")
+ rec := httptest.NewRecorder()
+ served.ServeHTTP(rec, req)
+ return rec
+ }
+ for _, req := range []*http.Request{
+ asSignedIn(t, app, "owner@example.com", http.MethodGet, "/import", nil),
+ importRequest(t, app, "owner@example.com", "", "notes.pdf", []byte("%PDF")),
+ } {
+ rec := page(req)
+ policies := rec.Header().Values("Content-Security-Policy")
+ body := rec.Body.String()
+ if len(policies) != 1 {
+ t.Fatalf("google %v %s: %d policies", on, req.Method, len(policies))
+ }
+ if rec.Header().Get("Cross-Origin-Opener-Policy") != "" {
+ t.Errorf("google %v %s: a COOP header", on, req.Method)
+ }
+ if rec.Header().Get("Cache-Control") != "no-store" {
+ t.Errorf("google %v %s: Cache-Control %q", on, req.Method, rec.Header().Get("Cache-Control"))
+ }
+ policy := policies[0]
+ for _, d := range []string{"form-action 'self'", "frame-ancestors 'none'", "base-uri 'self'"} {
+ if !strings.Contains(policy, d) {
+ t.Errorf("google %v %s: the policy lost %q", on, req.Method, d)
+ }
+ }
+ if on {
+ want, _ := googleimport.Policy(ContentSecurityPolicy)
+ if policy != want || !strings.Contains(body, "estilo-google-import") || !strings.Contains(body, "/static/estilo/google-import.") {
+ t.Errorf("google on %s: policy %q, chooser rendered %v", req.Method, policy, strings.Contains(body, "estilo-google-import"))
+ }
+ } else if policy != ContentSecurityPolicy || strings.Contains(body, "estilo-google-import") || strings.Contains(body, "google") {
+ t.Errorf("google off %s: policy %q, or Google on the page", req.Method, policy)
+ }
+ }
+ // Elsewhere the policy is the app's own either way.
+ list := page(asSignedIn(t, app, "owner@example.com", http.MethodGet, "/", nil))
+ if got := list.Header().Get("Content-Security-Policy"); got != ContentSecurityPolicy {
+ t.Errorf("google %v: the list's policy is %q", on, got)
+ }
+ }
+}
+
+func TestPartialGoogleConfigurationRefusesToStart(t *testing.T) {
+ for _, cfg := range []googleimport.Config{
+ {ClientID: testGoogle.ClientID},
+ {ClientID: testGoogle.ClientID, APIKey: testGoogle.APIKey},
+ {ClientID: "not a client id", APIKey: testGoogle.APIKey, AppID: testGoogle.AppID},
+ {ClientID: testGoogle.ClientID, APIKey: testGoogle.APIKey, AppID: "my-project"},
+ } {
+ if _, err := NewForTestWith(t, Config{GoogleImport: cfg}); err == nil {
+ t.Errorf("%+v: started", cfg)
+ }
+ }
+}
+
+func TestImportTitleFromAFilename(t *testing.T) {
+ for in, want := range map[string]string{
+ "Board minutes.docx": "Board minutes",
+ `C:\Users\x\Q3 plan.DOCX`: "Q3 plan",
+ "../../etc/passwd.docx": "passwd",
+ " spaced .docx": "spaced",
+ "tab\there.docx": "tabhere",
+ ".docx": "",
+ strings.Repeat("é", 600) + ".docx": strings.Repeat("é", 512),
+ } {
+ if got := importTitle(in); got != want {
+ t.Errorf("importTitle(%q) = %q, want %q", in, got, want)
+ }
+ }
+}
diff --git a/internal/docs/migrations/0009_import_reports.sql b/internal/docs/migrations/0009_import_reports.sql
new file mode 100644
index 0000000..6f123f1
--- /dev/null
+++ b/internal/docs/migrations/0009_import_reports.sql
@@ -0,0 +1,17 @@
+-- doc_import_reports holds the report an import made, one per imported
+-- document: codes, counts and paragraph numbers saying what the import
+-- could not bring in, never the document's text. It is written in the
+-- same transaction as the document row and its first update
+-- (Store.CreateImported), so a report never exists without its document
+-- or a document without its report, and it follows the content-sealing
+-- rules the update log does (content_encoding 1 is sealed under the
+-- content key with its own kind byte; 0 only before activation).
+--
+-- Additive: creates a table, touches no existing row.
+CREATE TABLE IF NOT EXISTS doc_import_reports (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ doc_id INTEGER NOT NULL UNIQUE REFERENCES documents(id) ON DELETE CASCADE,
+ report_bin BLOB NOT NULL,
+ content_encoding INTEGER NOT NULL DEFAULT 0,
+ created_at DATETIME NOT NULL
+);
diff --git a/internal/docs/models.go b/internal/docs/models.go
index 42e7e17..b1532af 100644
--- a/internal/docs/models.go
+++ b/internal/docs/models.go
@@ -145,6 +145,22 @@ type DocUpdate struct {
//
// ABIVersion records the core that produced State. Without it, "discard
// a snapshot from an older ABI" is unenforceable prose.
+// DocImportReport is the report an import made
+// (migrations/0009_import_reports.sql): docx.Report as JSON, sealed like
+// the update log. One per imported document; a document made any other
+// way has none.
+type DocImportReport struct {
+ ID int64 `gorm:"primaryKey"`
+ DocID int64 `gorm:"column:doc_id;not null;uniqueIndex"`
+
+ ReportBin []byte `gorm:"column:report_bin;not null"`
+ ContentEncoding int `gorm:"column:content_encoding;not null"`
+
+ CreatedAt time.Time `gorm:"column:created_at;not null"`
+}
+
+func (DocImportReport) TableName() string { return "doc_import_reports" }
+
type DocSnapshot struct {
ID int64 `gorm:"primaryKey"`
DocID int64 `gorm:"column:doc_id;not null;index"`
diff --git a/internal/docs/render.go b/internal/docs/render.go
index 6613a0d..07e15ab 100644
--- a/internal/docs/render.go
+++ b/internal/docs/render.go
@@ -1,6 +1,7 @@
package docs
import (
+ "amadan.net/oficina/estilo.git/googleimport"
"amadan.net/oficina/estilo.git/sky"
"bytes"
"embed"
@@ -327,6 +328,52 @@ var Catalog = rastrillo.Catalog{
// key rather than a hardcoded default.
"docs.document.untitled": "Untitled document",
+ // Import (import.go): the page, its refusals, and the report. English
+ // like the rest of Docs; the Google chooser's own strings are
+ // estilo's, in twelve locales.
+ "docs.list.import": "Import…",
+ "docs.import.title": "Import a Word document",
+ "docs.import.intro": "Choose a .docx file. Docs makes a new, editable copy; the file itself is not changed or kept.",
+ "docs.import.fidelity": "An import brings in paragraph text, headings, bold and italic, and the fonts and sizes Docs has. Headings take Docs' own heading look. Lists and tables become plain paragraphs, links keep their text, and spacing, indentation, colors, images, comments, footnotes, headers and footers are left out. Docs lists what it noticed afterwards.",
+ "docs.import.file": "Word document (.docx)",
+ "docs.import.submit": "Import",
+ "docs.import.error.nofile": "Choose a .docx file to import.",
+ "docs.import.error.notword": "That file is not a Word document Docs can read. Choose a .docx file, or download the document from Google Docs as Microsoft Word (.docx).",
+ "docs.import.error.damaged": "That Word document looks damaged, so nothing was imported. Try saving it again from the program that made it.",
+ "docs.import.error.toolarge": "That document is too large to import. The limit is a 10 MB file holding up to 5,000 paragraphs and about 500 KB of text.",
+ "docs.import.error.empty": "That document has no text Docs can import, so nothing was created.",
+ "docs.import.error.busy": "Docs is busy importing other documents. Try again in a moment.",
+ "docs.import.error.failed": "The import did not finish, and nothing was created. Try again.",
+ "docs.import.error.unsealed": "Importing is not available here yet: this instance has not turned on content sealing, and an import is only ever stored sealed. Ask whoever runs it to run docs docs-seal.",
+
+ "docs.import.report.heading": "Import report",
+ "docs.import.report.open": "Import report",
+ "docs.import.report.back": "Back to the document",
+ "docs.import.report.close": "Close",
+ "docs.import.report.incomplete": "This report lists what Docs noticed. It may not name everything the original had, so compare the two before relying on the copy.",
+ "docs.import.report.none": "Docs noticed nothing it could not bring in.",
+ "docs.import.report.where": "(paragraphs {paragraphs})",
+ "docs.import.report.where.more": "(paragraphs {paragraphs} and more)",
+
+ "docs.import.report.table_flattened": "Tables became plain paragraphs, cell by cell: {count}.",
+ "docs.import.report.list_flattened": "List items became plain paragraphs, without bullets or numbers: {count}.",
+ "docs.import.report.link_text_kept": "Links kept their text but are no longer links: {count}.",
+ "docs.import.report.insertion_kept": "Suggested insertions were kept as ordinary text: {count}.",
+ "docs.import.report.deletion_omitted": "Suggested deletions were left out: {count}.",
+ "docs.import.report.object_omitted": "Images, drawings, equations and other objects were left out: {count}.",
+ "docs.import.report.notes_omitted": "Footnotes and endnotes were left out: {count}.",
+ "docs.import.report.comments_omitted": "Comments were left out: {count}.",
+ "docs.import.report.headers_footers_omitted": "Headers and footers were left out.",
+ "docs.import.report.title_as_heading": "Titles became first-level headings: {count}.",
+ "docs.import.report.subtitle_as_paragraph": "Subtitles became ordinary paragraphs: {count}.",
+ "docs.import.report.font_substituted": "Text in fonts Docs does not have is in the default font instead: {count} runs.",
+ "docs.import.report.size_dropped": "Text in sizes Docs does not offer is at the default size instead: {count} runs.",
+ "docs.import.report.formatting_lost": "Underline, strikethrough, color, highlight, superscript, subscript and capitals were left out: {count} runs.",
+ "docs.import.report.alignment_lost": "Centered and right-aligned paragraphs are left-aligned: {count}.",
+ "docs.import.report.tab_as_space": "Tabs became spaces: {count}.",
+ "docs.import.report.line_break_split": "Line breaks became new paragraphs: {count}.",
+ "docs.import.report.page_break_split": "Page and column breaks became new paragraphs: {count}.",
+
// docs.signin.* — GET /signin (auth.go's signin handler): the
// form itself, and every outcome rastrillo/auth's own handlers
// redirect back here with (?sent=1,
@@ -576,6 +623,8 @@ var pageTemplates = map[string]string{
"colophon": "views/colophon.html",
"colophon-licence": "views/colophon_licence.html",
"help-fonts": "views/help_fonts.html",
+ "import": "views/import.html",
+ "import-report": "views/import_report.html",
"error": "views/error.html",
"home-link": "views/home_link.html",
"list": "views/list.html",
@@ -627,6 +676,9 @@ func newRenderer() (*renderer, error) {
if base, err = base.ParseFS(colophon.Templates(), "templates/*.html"); err != nil {
return nil, fmt.Errorf("docs: parse estilo colophon templates: %w", err)
}
+ if base, err = base.ParseFS(googleimport.Templates(), "templates/*.html"); err != nil {
+ return nil, fmt.Errorf("docs: parse estilo google import template: %w", err)
+ }
if base, err = base.ParseFS(viewsFS, layoutTemplate, headTemplate); err != nil {
return nil, fmt.Errorf("docs: parse layout: %w", err)
}
@@ -723,6 +775,9 @@ func vendoredStaticFS() (fs.FS, error) {
// The sky behind the sign-in door; images from sky.Handler.
"static/estilo/sky.css": {Data: sky.CSS()},
"static/estilo/chrome.js": {Data: chrome.JS()},
+ // The Google Drive chooser, linked only from a configured
+ // import page (import.go).
+ "static/estilo/" + googleimport.JSName(): {Data: googleimport.JS()},
}
for _, name := range []string{"icon-32.png", "apple-touch-icon.png", "brand.css", "LICENSE.lucide"} {
body, err := brandFS.ReadFile("brand/" + name)
diff --git a/internal/docs/suite_import_test.go b/internal/docs/suite_import_test.go
new file mode 100644
index 0000000..a290d94
--- /dev/null
+++ b/internal/docs/suite_import_test.go
@@ -0,0 +1,59 @@
+package docs
+
+import (
+ "context"
+ crand "crypto/rand"
+ "testing"
+)
+
+func TestSuiteImportIsTeamRandomAndAnnouncedOnce(t *testing.T) {
+ app, _ := sealedApp(t, Config{})
+ owner := app.TestPerson(t, "owner@example.com")
+ ctx := context.Background()
+ imp, err := convertImport(ctx, app.store.core, nestedDoc(t))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { randomSource = crand.Reader })
+ randomSource = draws(101, 102)
+ doc, err := app.store.CreateImported(ctx, owner, "Imported", "suite-import", imp)
+ randomSource = crand.Reader
+ if err != nil {
+ t.Fatal(err)
+ }
+ if doc.Visibility != VisibilityTeam || doc.Revision != 101 {
+ t.Errorf("import visibility/revision = %q/%d, want team/101", doc.Visibility, doc.Revision)
+ }
+ rows := feedRowsOf(t, app.store, doc.ID)
+ if len(rows) != 1 || rows[0].Revision != doc.Revision || rows[0].Stamp != 102 || rows[0].Gone {
+ t.Errorf("import feed = %+v, want one current revision with nonce 102", rows)
+ }
+ again, err := app.store.CreateImported(ctx, owner, "Retry", "suite-import", imp)
+ if err != nil || again.ID != doc.ID || again.Revision != doc.Revision {
+ t.Fatalf("retry changed document: %+v, %v", again, err)
+ }
+ if rows := feedRowsOf(t, app.store, doc.ID); len(rows) != 1 {
+ t.Errorf("retry announced %d rows, want 1", len(rows))
+ }
+}
+
+func TestSuiteImportRollsBackWithoutItsFeedRow(t *testing.T) {
+ app, _ := sealedApp(t, Config{})
+ owner := app.TestPerson(t, "owner@example.com")
+ ctx := context.Background()
+ imp, err := convertImport(ctx, app.store.core, nestedDoc(t))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := app.store.db.Exec(`CREATE TRIGGER suite_feed_refuses BEFORE INSERT ON suite_feed BEGIN SELECT RAISE(ABORT, 'refused'); END`).Error; err != nil {
+ t.Fatal(err)
+ }
+ if _, err := app.store.CreateImported(ctx, owner, "Imported", "suite-import", imp); err == nil {
+ t.Error("import committed without its feed row")
+ }
+ for _, table := range []string{"documents", "doc_updates", "doc_import_reports", "suite_feed"} {
+ if n := countRows(t, app, table); n != 0 {
+ t.Errorf("failed import left %d rows in %s", n, table)
+ }
+ }
+}
diff --git a/internal/docs/views/import.html b/internal/docs/views/import.html
new file mode 100644
index 0000000..cd1cbea
--- /dev/null
+++ b/internal/docs/views/import.html
@@ -0,0 +1,49 @@
+{{/* The import page (import.go). One ordinary multipart form, which works
+ with no script at all; the Google Drive chooser (estilo's
+ googleimport), when this instance configures it, exports the chosen
+ file in the browser and submits it through this same form's file
+ input, so both ways in reach one route, one origin check and one
+ server path. The chooser's script is linked only here and only then. */}}
+{{define "pagehead"}}{{if .GoogleScript}}<script type="module" src="{{.GoogleScript}}"></script>{{end}}{{end}}
+{{define "content"}}<style>
+ [docs-import] {
+ display: flex;
+ flex-direction: column;
+ gap: var(--rst-sp-5);
+ max-inline-size: 44rem;
+ }
+ [docs-import] > [rst-page-header] {
+ margin-block-end: 0;
+ }
+ [docs-import-field] {
+ display: flex;
+ flex-direction: column;
+ gap: var(--rst-sp-2);
+ }
+ [docs-import-field] input[type="file"] {
+ max-inline-size: 100%;
+ min-block-size: 24px;
+ font-size: max(1rem, 1em);
+ }
+</style>
+<article rst-stack docs-import>
+ <header rst-page-header>
+ <div rst-page-header-titles>
+ <h1>{{.Title}}</h1>
+ <p rst-muted>{{.Intro}}</p>
+ </div>
+ </header>
+ {{if .Error}}<div docs-import-error role="alert">{{template "callout" (dict "Body" .Error "Tone" "negative")}}</div>{{end}}
+ <p docs-import-fidelity>{{.Fidelity}}</p>
+ <form rst-form id="docs-import-form" method="post" action="/import" enctype="multipart/form-data">
+ <input type="hidden" name="creation_token" value="{{.Token}}">
+ <div docs-import-field>
+ <label for="docs-import-file">{{.FileLabel}}</label>
+ <input id="docs-import-file" type="file" name="file" required
+ accept=".docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document">
+ </div>
+ <div rst-form-foot><button rst-btn="primary" type="submit">{{.Submit}}</button></div>
+ </form>
+ {{template "estilo-google-import" .Google}}
+</article>
+{{end}}
diff --git a/internal/docs/views/import_report.html b/internal/docs/views/import_report.html
new file mode 100644
index 0000000..e0e27ab
--- /dev/null
+++ b/internal/docs/views/import_report.html
@@ -0,0 +1,14 @@
+{{/* GET /d/{sqid}/import-report: the report an import made, reopened. */}}
+{{define "content"}}<style>
+ [docs-import-report-page] {
+ display: flex;
+ flex-direction: column;
+ gap: var(--rst-sp-5);
+ max-inline-size: 44rem;
+ }
+</style>
+<article rst-stack docs-import-report-page>
+ {{template "docs-import-report" .Report}}
+ <p><a rst-btn="ghost" href="{{.BackHref}}">{{.Back}}</a></p>
+</article>
+{{end}}
diff --git a/internal/docs/views/list.html b/internal/docs/views/list.html
index 243478c..17fcb89 100644
--- a/internal/docs/views/list.html
+++ b/internal/docs/views/list.html
@@ -298,7 +298,8 @@
{{if .CanCreate}} <form docs-create-form method="post" action="/documents">
<input rst-input type="text" name="title" placeholder="{{.CreatePlaceholder}}" aria-label="{{.CreateLabel}}" autocomplete="off">
<button rst-btn="primary" type="submit">{{.CreateLabel}}</button>
- </form>{{end}}
+ </form>
+ <a rst-btn="ghost" href="/import" docs-import-link>{{.ImportLabel}}</a>{{end}}
</div>
</header>
{{if .PartialCatalog}}{{template "callout" (dict "Body" .PartialCatalog "Tone" "warning")}}{{end}}
diff --git a/internal/docs/views/partials/import_report.html b/internal/docs/views/partials/import_report.html
new file mode 100644
index 0000000..c705023
--- /dev/null
+++ b/internal/docs/views/partials/import_report.html
@@ -0,0 +1,12 @@
+{{/* An import report (import.go's reportView): the statement of what an
+ import brings first, always, so no report reads as full fidelity,
+ then one line per kind of loss with the paragraphs it happened at.
+ Shown on the document after an import, and on its own page. */}}
+{{define "docs-import-report"}}<section docs-import-report aria-labelledby="docs-import-report-heading">
+ <h2 id="docs-import-report-heading">{{.Heading}}</h2>
+ <p>{{.Statement}}</p>
+ {{if .Lines}}<ul docs-import-report-lines>
+ {{range .Lines}}<li>{{.Text}}{{with .Where}} <span rst-muted>{{.}}</span>{{end}}</li>
+ {{end}}</ul>{{else}}<p>{{.Empty}}</p>{{end}}
+ <p rst-muted>{{.Incomplete}}</p>
+</section>{{end}}
diff --git a/internal/docs/views/show.html b/internal/docs/views/show.html
index 8593ae3..1e8cb86 100644
--- a/internal/docs/views/show.html
+++ b/internal/docs/views/show.html
@@ -476,6 +476,23 @@
color: var(--rst-text);
box-shadow: var(--rst-shadow-pop);
}
+ /* Opened by the server, not showModal(), so it is not in the top
+ layer: it floats over the desk itself, under the bars. */
+ [docs-import-arrival][open] {
+ position: fixed;
+ inset-block-start: calc(var(--rst-sp-6) * 3);
+ inset-inline: 0;
+ margin-inline: auto;
+ max-block-size: calc(100vh - var(--rst-sp-6) * 4);
+ overflow: auto;
+ z-index: 30;
+ }
+ [docs-import-report] h2 {
+ margin-block: 0 var(--rst-sp-3);
+ }
+ [docs-import-report] ul {
+ padding-inline-start: var(--rst-sp-4);
+ }
[docs-dialog]::backdrop {
background: var(--rst-overlay);
}
@@ -1413,6 +1430,13 @@
Outside [docs-editor], like every other piece of chrome on this
screen: ProseMirror's {mount: el} takes over everything inside that
element. */}}
+{{/* The import report, once, on arrival from POST /import. Open from
+ the server and closed by a dialog form, so it needs no script; it
+ reopens from the bar's Import report link (/d/{sqid}/import-report). */}}
+{{with .ImportReport}}<dialog docs-dialog docs-import-arrival open>
+ {{template "docs-import-report" .}}
+ <form method="dialog"><button rst-btn="primary" type="submit" autofocus>{{$.CloseReport}}</button></form>
+</dialog>{{end}}
<dialog docs-dialog docs-wordcount>
<h2>{{.Dialogs.WordCountTitle}}</h2>
<dl docs-dialog-rows>
diff --git a/internal/docx/docx.go b/internal/docx/docx.go
index 680a24c..89a886e 100644
--- a/internal/docx/docx.go
+++ b/internal/docx/docx.go
@@ -8,13 +8,12 @@
// Carlito and Cambria Caladea. The names are internal/fonts' manifest
// (Docx.Name, and ByDocxName for the way back).
//
-// Docs has no DOCX import or export yet (spec §11.2/§11.3). This package
-// is deliberately only what the font rulings need, so that the feature
-// builds on it rather than re-deciding them: paragraphs and headings,
-// runs with their family, weight, slope and size, the document default
-// in w:docDefaults and every family named in fontTable.xml. Lists,
-// tables, images and links are not written yet, and Read reads only
-// paragraph text and run formatting. Nothing routes to it.
+// Write is deliberately only what the font rulings need: paragraphs and
+// headings, runs with their family, weight, slope and size, the document
+// default in w:docDefaults and every family named in fontTable.xml.
+// Lists, tables, images and links are not written yet, and nothing routes
+// to Write. Import (read.go) is the reading half, used by the import page
+// (spec §11.2 and implementation/google-drive-import.md).
package docx
import (
@@ -24,15 +23,12 @@ import (
"fmt"
"io"
"sort"
- "strconv"
"strings"
"github.com/carlosframework/docs/internal/export"
"github.com/carlosframework/docs/internal/fonts"
)
-const wNS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
-
// Write writes doc as a .docx.
func Write(doc export.Document) ([]byte, error) {
used := map[*fonts.Family]bool{fonts.Default: true}
@@ -195,133 +191,3 @@ const documentRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
`<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>` +
`<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable" Target="fontTable.xml"/>` +
`</Relationships>`
-
-// Read reads a .docx's paragraphs and their runs' formatting. Each run's
-// face comes from its own w:rFonts, else the document's w:docDefaults;
-// a Word face with a twin here becomes the twin (Calibri is Carlito,
-// Cambria is Caladea), and a run in Docs' own default carries no mark.
-// A face Docs does not have reads as the default and is reported in
-// unknown, for the import report spec §11.2 requires.
-func Read(data []byte) (doc export.Document, unknown []string, err error) {
- z, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
- if err != nil {
- return doc, nil, fmt.Errorf("docx: %w", err)
- }
- part := func(name string) ([]byte, error) {
- for _, f := range z.File {
- if f.Name == name {
- r, err := f.Open()
- if err != nil {
- return nil, err
- }
- defer r.Close()
- return io.ReadAll(io.LimitReader(r, 64<<20))
- }
- }
- return nil, nil
- }
- missing := map[string]bool{}
- resolve := func(name string) *fonts.Family {
- if name == "" {
- return nil
- }
- f, ok := fonts.ByDocxName(name)
- if !ok {
- missing[name] = true
- return nil
- }
- return f
- }
-
- base := fonts.Default
- if s, err := part("word/styles.xml"); err != nil {
- return doc, nil, err
- } else if s != nil {
- var st struct {
- Fonts struct {
- ASCII string `xml:"ascii,attr"`
- } `xml:"docDefaults>rPrDefault>rPr>rFonts"`
- }
- if err := xml.Unmarshal(s, &st); err != nil {
- return doc, nil, fmt.Errorf("docx: styles.xml: %w", err)
- }
- if f := resolve(st.Fonts.ASCII); f != nil {
- base = f
- }
- }
-
- d, err := part("word/document.xml")
- if err != nil {
- return doc, nil, err
- }
- if d == nil {
- return doc, nil, fmt.Errorf("docx: no word/document.xml")
- }
- type val struct {
- Val string `xml:"val,attr"`
- }
- var parsed struct {
- Body struct {
- Paragraphs []struct {
- Style val `xml:"pPr>pStyle"`
- Runs []struct {
- Fonts struct {
- ASCII string `xml:"ascii,attr"`
- } `xml:"rPr>rFonts"`
- Bold *struct{} `xml:"rPr>b"`
- Italic *struct{} `xml:"rPr>i"`
- Size val `xml:"rPr>sz"`
- Text []string `xml:"t"`
- } `xml:"r"`
- } `xml:"p"`
- } `xml:"body"`
- }
- if err := xml.Unmarshal(d, &parsed); err != nil {
- return doc, nil, fmt.Errorf("docx: document.xml: %w", err)
- }
-
- doc.Root = export.Node{Type: "doc"}
- for _, p := range parsed.Body.Paragraphs {
- block := export.Node{Type: "paragraph"}
- if lvl, ok := strings.CutPrefix(p.Style.Val, "Heading"); ok {
- if n, err := strconv.Atoi(lvl); err == nil && n >= 1 && n <= 6 {
- block = export.Node{Type: "heading", Attrs: export.Attrs{Level: n}}
- }
- }
- for _, r := range p.Runs {
- text := strings.Join(r.Text, "")
- if text == "" {
- continue
- }
- run := export.Node{Type: "text", Text: text}
- family := base
- if f := resolve(r.Fonts.ASCII); f != nil {
- family = f
- }
- if family != fonts.Default {
- run.Marks = append(run.Marks, export.Mark{Type: family.Mark()})
- }
- if half, err := strconv.Atoi(r.Size.Val); err == nil {
- for _, mark := range export.SizeMarks() {
- if pt, ok := export.SizePt(mark); ok && int(pt*2) == half {
- run.Marks = append(run.Marks, export.Mark{Type: mark})
- break
- }
- }
- }
- if r.Bold != nil {
- run.Marks = append(run.Marks, export.Mark{Type: "strong"})
- }
- if r.Italic != nil {
- run.Marks = append(run.Marks, export.Mark{Type: "em"})
- }
- block.Content = append(block.Content, run)
- }
- doc.Root.Content = append(doc.Root.Content, block)
- }
- for name := range missing {
- unknown = append(unknown, name)
- }
- sort.Strings(unknown)
- return doc, unknown, nil
-}
diff --git a/internal/docx/docx_test.go b/internal/docx/docx_test.go
index b551df6..0be5df1 100644
--- a/internal/docx/docx_test.go
+++ b/internal/docx/docx_test.go
@@ -75,12 +75,13 @@ func TestCarlitoAndCaladeaRoundTripAsCalibriAndCambria(t *testing.T) {
t.Error("Inter does not tell Word what to fall back to")
}
- back, unknown, err := docx.Read(data)
+ res, err := docx.Import(data)
if err != nil {
t.Fatal(err)
}
- if len(unknown) > 0 {
- t.Errorf("faces Docs ships came back unknown: %v", unknown)
+ back := res.Document
+ if len(res.Report.Items) > 0 {
+ t.Errorf("a document Docs wrote imports with losses: %+v", res.Report.Items)
}
runs := back.Root.Content[1].Content
want := []struct {
@@ -118,19 +119,20 @@ func TestImportingWordsDefaults(t *testing.T) {
for _, c := range []struct {
defaultFace, runFace string
marks string
- unknown string
+ unknown bool
}{
- {"Calibri", "", "", ""},
- {"Cambria", "", "font_caladea", ""},
- {"Calibri", "Cambria", "font_caladea", ""},
- {"Cambria", "Calibri", "", ""},
- {"Calibri", "Wingdings", "", "Wingdings"},
+ {"Calibri", "", "", false},
+ {"Cambria", "", "font_caladea", false},
+ {"Calibri", "Cambria", "font_caladea", false},
+ {"Cambria", "Calibri", "", false},
+ {"Calibri", "Wingdings", "", true},
} {
data := wordFile(t, c.defaultFace, c.runFace)
- doc, unknown, err := docx.Read(data)
+ res, err := docx.Import(data)
if err != nil {
t.Fatal(err)
}
+ doc, unknown := res.Document, substituted(res.Report)
var marks []string
for _, m := range doc.Root.Content[0].Content[0].Marks {
marks = append(marks, m.Type)
@@ -138,8 +140,8 @@ func TestImportingWordsDefaults(t *testing.T) {
if strings.Join(marks, " ") != c.marks {
t.Errorf("default %s, run %q: marks %v, want [%s]", c.defaultFace, c.runFace, marks, c.marks)
}
- if strings.Join(unknown, ",") != c.unknown {
- t.Errorf("default %s, run %q: unknown %v, want %q", c.defaultFace, c.runFace, unknown, c.unknown)
+ if unknown != c.unknown {
+ t.Errorf("default %s, run %q: substitution reported %v, want %v", c.defaultFace, c.runFace, unknown, c.unknown)
}
}
}
@@ -161,3 +163,13 @@ func wordFile(t *testing.T, defaultFace, runFace string) []byte {
z.Close()
return buf.Bytes()
}
+
+// substituted is whether the report says a face was substituted.
+func substituted(r docx.Report) bool {
+ for _, it := range r.Items {
+ if it.Code == docx.CodeFontSubstituted {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/docx/read.go b/internal/docx/read.go
new file mode 100644
index 0000000..012aa3c
--- /dev/null
+++ b/internal/docx/read.go
@@ -0,0 +1,1027 @@
+package docx
+
+import (
+ "archive/zip"
+ "bytes"
+ "encoding/xml"
+ "errors"
+ "io"
+ "slices"
+ "sort"
+ "strconv"
+ "strings"
+ "unicode"
+
+ "github.com/carlosframework/docs/internal/export"
+ "github.com/carlosframework/docs/internal/fonts"
+)
+
+// Import reads a .docx into the paragraphs, headings and text runs Docs
+// can hold, and reports everything it could not bring in and where.
+//
+// It is a bounded token walk rather than an unmarshal into structs,
+// because the text that matters is nested: Google Docs exports a link
+// as w:p>w:hyperlink>w:r, a table as w:tbl>w:tr>w:tc>w:p, a suggestion
+// as w:ins or w:del around runs, and some content under w:sdt or
+// w:smartTag. The reader this replaced bound w:body>w:p>w:r>w:t alone
+// and dropped all of that without a word, and read <w:b w:val="0"/> as
+// bold. Every container below is walked for its text; what Docs cannot
+// represent is flattened or omitted and reported.
+//
+// The bounds are this package's, not the XML decoder's: encoding/xml
+// does not limit depth, and a ZIP header's sizes are claims, so entry
+// count, the bytes actually decompressed, element depth and the output's
+// blocks, runs and text are all counted here. Nothing is written to
+// disk and no relationship is followed, so a link's target, an image's
+// source or an external template is never even read. Errors carry no
+// source content.
+func Import(data []byte) (*Result, error) {
+ z, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
+ if err != nil {
+ return nil, ErrNotWord
+ }
+ if len(z.File) > maxEntries {
+ return nil, ErrTooLarge
+ }
+ parts := map[string]*zip.File{}
+ for _, f := range z.File {
+ if _, dup := parts[f.Name]; dup {
+ return nil, ErrMalformed
+ }
+ parts[f.Name] = f
+ }
+ doc := parts["word/document.xml"]
+ if doc == nil {
+ return nil, ErrNotWord
+ }
+
+ budget := maxTotalBytes
+ r := &reader{rep: newReporter()}
+ if f := parts["word/styles.xml"]; f != nil {
+ b, err := readPart(f, &budget)
+ if err != nil {
+ return nil, err
+ }
+ if err := r.readStyles(b); err != nil {
+ return nil, err
+ }
+ }
+ b, err := readPart(doc, &budget)
+ if err != nil {
+ return nil, err
+ }
+ if err := r.readDocument(b); err != nil {
+ return nil, err
+ }
+ // Comments are counted by their references in the text; a comments
+ // part with none (every anchor deleted, say) is still reported.
+ if parts["word/comments.xml"] != nil && r.rep.items[CodeCommentsOmitted] == nil {
+ r.rep.add(CodeCommentsOmitted, 0)
+ }
+ if r.text == 0 {
+ return nil, ErrEmpty
+ }
+ return &Result{Document: r.document(), Report: r.rep.report()}, nil
+}
+
+// The limits. The output's are what internal/core's builder test holds
+// to its call budget (TestBuildAtTheReadersLimitFitsTheCallTimeout).
+const (
+ maxEntries = 1000
+ maxPartBytes = 32 << 20
+ maxTotalBytes = 64 << 20
+ maxDepth = 256
+ maxBlocks = 5_000
+ maxRuns = 10_000
+ maxText = 512 << 10
+
+ // maxLocations is how many paragraph numbers one report item keeps;
+ // its Count is still exact.
+ maxLocations = 20
+)
+
+// Import's refusals. Each is a whole answer: none of them says anything
+// about the file's content.
+var (
+ // ErrNotWord: not a ZIP, or a ZIP with no word/document.xml.
+ ErrNotWord = errors.New("docx: not a Word document")
+ // ErrMalformed: a part is not well-formed XML, nests past maxDepth,
+ // declares a DTD, or the archive names one entry twice.
+ ErrMalformed = errors.New("docx: the document is damaged")
+ // ErrTooLarge: past one of the limits above.
+ ErrTooLarge = errors.New("docx: the document is too large to import")
+ // ErrEmpty: nothing Docs can hold has any text.
+ ErrEmpty = errors.New("docx: the document has no text to import")
+)
+
+// Result is what Import read: the document and its report.
+type Result struct {
+ Document export.Document
+ Report Report
+}
+
+// Report is everything Import could not bring in as it was, in Codes
+// order. An empty report still never means full fidelity: it means
+// nothing this reader knows to look for was found.
+type Report struct {
+ Items []Item `json:"items"`
+}
+
+// Item is one kind of loss: how many times it happened and, where it
+// has one, the first maxLocations paragraphs (1-based, in the imported
+// document) it happened at. Closed metadata only: nothing from the file
+// is ever quoted, not even a face name, which is as arbitrary as text.
+type Item struct {
+ Code Code `json:"code"`
+ Count int `json:"count"`
+ Paragraphs []int `json:"paragraphs,omitempty"`
+}
+
+// Code names one kind of loss. The set is closed: Codes lists it.
+type Code string
+
+const (
+ CodeListFlattened Code = "list_flattened"
+ CodeTableFlattened Code = "table_flattened"
+ CodeLinkTextKept Code = "link_text_kept"
+ CodeInsertionKept Code = "insertion_kept"
+ CodeDeletionOmitted Code = "deletion_omitted"
+ CodeTabAsSpace Code = "tab_as_space"
+ CodeLineBreakSplit Code = "line_break_split"
+ CodePageBreakSplit Code = "page_break_split"
+ CodeTitleAsHeading Code = "title_as_heading"
+ CodeSubtitleAsParagraph Code = "subtitle_as_paragraph"
+ CodeSizeDropped Code = "size_dropped"
+ CodeFontSubstituted Code = "font_substituted"
+ CodeFormattingLost Code = "formatting_lost"
+ CodeAlignmentLost Code = "alignment_lost"
+ CodeObjectOmitted Code = "object_omitted"
+ CodeNotesOmitted Code = "notes_omitted"
+ CodeCommentsOmitted Code = "comments_omitted"
+ CodeHeadersOmitted Code = "headers_footers_omitted"
+)
+
+// Codes is every Code, in the order a report lists them.
+var Codes = []Code{
+ CodeTableFlattened, CodeListFlattened, CodeLinkTextKept,
+ CodeInsertionKept, CodeDeletionOmitted, CodeObjectOmitted,
+ CodeNotesOmitted, CodeCommentsOmitted, CodeHeadersOmitted,
+ CodeTitleAsHeading, CodeSubtitleAsParagraph, CodeFontSubstituted,
+ CodeSizeDropped, CodeFormattingLost, CodeAlignmentLost,
+ CodeTabAsSpace, CodeLineBreakSplit, CodePageBreakSplit,
+}
+
+func readPart(f *zip.File, budget *int) ([]byte, error) {
+ rc, err := f.Open()
+ if err != nil {
+ return nil, ErrMalformed
+ }
+ defer rc.Close()
+ limit := min(maxPartBytes, *budget)
+ b, err := io.ReadAll(io.LimitReader(rc, int64(limit)+1))
+ if err != nil {
+ return nil, ErrMalformed
+ }
+ if len(b) > limit {
+ return nil, ErrTooLarge
+ }
+ *budget -= len(b)
+ return b, nil
+}
+
+// ---- the report
+
+type reporter struct {
+ items map[Code]*Item
+}
+
+func newReporter() *reporter {
+ return &reporter{items: map[Code]*Item{}}
+}
+
+// add counts one occurrence of code at paragraph (1-based; 0 for none).
+func (r *reporter) add(code Code, paragraph int) {
+ it := r.items[code]
+ if it == nil {
+ it = &Item{Code: code}
+ r.items[code] = it
+ }
+ it.Count++
+ if paragraph > 0 && len(it.Paragraphs) < maxLocations && !slices.Contains(it.Paragraphs, paragraph) {
+ it.Paragraphs = append(it.Paragraphs, paragraph)
+ }
+}
+
+func (r *reporter) report() Report {
+ var out Report
+ for _, c := range Codes {
+ if it := r.items[c]; it != nil {
+ sort.Ints(it.Paragraphs)
+ out.Items = append(out.Items, *it)
+ }
+ }
+ return out
+}
+
+// ---- styles
+
+const (
+ wNS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
+ mcNS = "http://schemas.openxmlformats.org/markup-compatibility/2006"
+)
+
+type style struct {
+ name, basedOn string
+ rp props // the style's own run properties
+ numbered bool
+ aligned bool // centred or right-aligned
+}
+
+// styleKind is what a paragraph style makes of a block.
+type styleKind struct {
+ heading int
+ title bool
+ subtitle bool
+}
+
+// ---- the walk
+
+type block struct {
+ heading int
+ runs []export.Node
+}
+
+// tri is an OOXML toggle as stated somewhere in the cascade: unset,
+// on, or explicitly off. An explicit off stops inheritance.
+type tri int8
+
+const (
+ unset tri = iota
+ on
+ off
+)
+
+func triOf(b bool) tri {
+ if b {
+ return on
+ }
+ return off
+}
+
+// props are run properties at one level of the cascade: a run's own
+// w:rPr, a character style, a paragraph style, or the document default.
+type props struct {
+ bold, italic tri
+ font string // a Word face name, "" for unset
+ size int // half-points, 0 for unset
+ lost bool // underline, strike, colour, highlight, raised, caps
+ rstyle string // a run's character style
+}
+
+// over is p with every property p leaves unset taken from base. Lost
+// formatting accumulates: a style's colour is as lost as a run's.
+func (p props) over(base props) props {
+ if p.bold == unset {
+ p.bold = base.bold
+ }
+ if p.italic == unset {
+ p.italic = base.italic
+ }
+ if p.font == "" {
+ p.font = base.font
+ }
+ if p.size == 0 {
+ p.size = base.size
+ }
+ p.lost = p.lost || base.lost
+ return p
+}
+
+type reader struct {
+ dec *xml.Decoder
+ depth int
+
+ styles map[string]*style // paragraph styles
+ charStyles map[string]*style
+ defaultStyle string
+ base props // w:docDefaults' run properties
+ blocks []block
+ runs, text int
+ rep *reporter
+ tables int
+ headersCounted bool
+}
+
+// next is the one way the walk reads a token, so depth is counted for
+// every element, skipped ones included.
+func (r *reader) next() (xml.Token, error) {
+ t, err := r.dec.Token()
+ if err != nil {
+ if errors.Is(err, io.EOF) {
+ return nil, io.EOF
+ }
+ return nil, ErrMalformed
+ }
+ switch t.(type) {
+ case xml.StartElement:
+ r.depth++
+ if r.depth > maxDepth {
+ return nil, ErrMalformed
+ }
+ case xml.EndElement:
+ r.depth--
+ case xml.Directive:
+ // A DTD has no place in OOXML, and an entity declaration is the
+ // one way XML grows past the bytes it arrived as.
+ return nil, ErrMalformed
+ }
+ return t, nil
+}
+
+// children calls visit for each child element of the element just
+// opened and returns at its end. Character data between children is
+// passed to text, when it is not nil.
+func (r *reader) children(visit func(xml.StartElement) error, text func([]byte)) error {
+ for {
+ t, err := r.next()
+ if err != nil {
+ if err == io.EOF {
+ return ErrMalformed
+ }
+ return err
+ }
+ switch t := t.(type) {
+ case xml.StartElement:
+ if err := visit(t); err != nil {
+ return err
+ }
+ case xml.EndElement:
+ return nil
+ case xml.CharData:
+ if text != nil {
+ text(t)
+ }
+ }
+ }
+}
+
+// skip consumes the element just opened, counting depth as it goes.
+func (r *reader) skip() error {
+ return r.children(func(xml.StartElement) error { return r.skip() }, nil)
+}
+
+func isW(e xml.StartElement, local string) bool {
+ return e.Name.Space == wNS && e.Name.Local == local
+}
+
+func attr(e xml.StartElement, local string) (string, bool) {
+ for _, a := range e.Attr {
+ if a.Name.Space == wNS && a.Name.Local == local {
+ return a.Value, true
+ }
+ }
+ return "", false
+}
+
+// toggle reads an OOXML on/off property: present with no w:val, or with
+// one of the true spellings, is on; "0", "false" and "off" are off.
+func toggle(e xml.StartElement) bool {
+ v, ok := attr(e, "val")
+ if !ok {
+ return true
+ }
+ switch strings.ToLower(v) {
+ case "0", "false", "off", "none":
+ return false
+ }
+ return true
+}
+
+func newDecoder(b []byte) *xml.Decoder {
+ d := xml.NewDecoder(bytes.NewReader(b))
+ d.Strict = true
+ return d
+}
+
+// root opens the part's root element, refusing anything before it but
+// the XML declaration, whitespace and comments.
+func (r *reader) root(local string) error {
+ for {
+ t, err := r.next()
+ if err != nil {
+ return ErrMalformed
+ }
+ if e, ok := t.(xml.StartElement); ok {
+ if !isW(e, local) {
+ return ErrNotWord
+ }
+ return nil
+ }
+ }
+}
+
+func (r *reader) readStyles(b []byte) error {
+ r.dec = newDecoder(b)
+ r.depth = 0
+ r.styles = map[string]*style{}
+ r.charStyles = map[string]*style{}
+ if err := r.root("styles"); err != nil {
+ return err
+ }
+ return r.children(func(e xml.StartElement) error {
+ switch {
+ case isW(e, "docDefaults"):
+ return r.children(func(e xml.StartElement) error {
+ if !isW(e, "rPrDefault") {
+ return r.skip()
+ }
+ return r.children(func(e xml.StartElement) error {
+ if !isW(e, "rPr") {
+ return r.skip()
+ }
+ return r.runProps(&r.base)
+ }, nil)
+ }, nil)
+ case isW(e, "style"):
+ kind, _ := attr(e, "type")
+ id, _ := attr(e, "styleId")
+ def, _ := attr(e, "default")
+ s := &style{}
+ err := r.children(func(c xml.StartElement) error {
+ switch {
+ case isW(c, "name"):
+ s.name, _ = attr(c, "val")
+ case isW(c, "basedOn"):
+ s.basedOn, _ = attr(c, "val")
+ case isW(c, "rPr"):
+ return r.runProps(&s.rp)
+ case isW(c, "pPr"):
+ return r.children(func(p xml.StartElement) error {
+ switch {
+ case isW(p, "numPr"):
+ s.numbered = true
+ case isW(p, "jc"):
+ s.aligned = alignedValue(p)
+ }
+ return r.skip()
+ }, nil)
+ }
+ return r.skip()
+ }, nil)
+ if err != nil {
+ return err
+ }
+ switch {
+ case id == "":
+ case kind == "paragraph":
+ r.styles[id] = s
+ if toggle1(def) {
+ r.defaultStyle = id
+ }
+ case kind == "character":
+ r.charStyles[id] = s
+ }
+ return nil
+ }
+ return r.skip()
+ }, nil)
+}
+
+func toggle1(v string) bool {
+ return v == "1" || strings.EqualFold(v, "true") || strings.EqualFold(v, "on")
+}
+
+// chain is a style and its ancestors, nearest first, at most ten deep and
+// never revisiting one (a basedOn loop is a damaged file, read as far as
+// it makes sense).
+func (r *reader) chain(id string) []*style {
+ return chainIn(r.styles, id)
+}
+
+func chainIn(styles map[string]*style, id string) []*style {
+ var out []*style
+ seen := map[string]bool{}
+ for id != "" && !seen[id] && len(out) < 10 {
+ seen[id] = true
+ s := styles[id]
+ if s == nil {
+ break
+ }
+ out = append(out, s)
+ id = s.basedOn
+ }
+ return out
+}
+
+func (r *reader) kind(id string) styleKind {
+ names := []string{strings.ToLower(id)}
+ for _, s := range r.chain(id) {
+ names = append(names, strings.ToLower(strings.TrimSpace(s.name)))
+ }
+ for _, n := range names {
+ compact := strings.ReplaceAll(n, " ", "")
+ if lvl, ok := strings.CutPrefix(compact, "heading"); ok {
+ if n, err := strconv.Atoi(lvl); err == nil && n >= 1 && n <= 6 {
+ return styleKind{heading: n}
+ }
+ }
+ switch compact {
+ case "title":
+ return styleKind{heading: 1, title: true}
+ case "subtitle":
+ return styleKind{subtitle: true}
+ }
+ }
+ return styleKind{}
+}
+
+// inherited is what a run in a paragraph of this style inherits: the
+// style chain's run properties, nearest first, then the document
+// default's.
+func (r *reader) inherited(id string) props {
+ if id == "" {
+ id = r.defaultStyle
+ }
+ var p props
+ for _, s := range r.chain(id) {
+ p = p.over(s.rp)
+ }
+ return p.over(r.base)
+}
+
+// charInherited is a character style chain's run properties.
+func (r *reader) charInherited(id string) props {
+ var p props
+ for _, s := range chainIn(r.charStyles, id) {
+ p = p.over(s.rp)
+ }
+ return p
+}
+
+func (r *reader) alignedStyle(id string) bool {
+ if id == "" {
+ id = r.defaultStyle
+ }
+ for _, s := range r.chain(id) {
+ if s.aligned {
+ return true
+ }
+ }
+ return false
+}
+
+// alignedValue is whether a w:jc is an alignment Docs does not import:
+// centred, right, or anything else that is not the start edge or
+// justification.
+func alignedValue(e xml.StartElement) bool {
+ switch v, _ := attr(e, "val"); v {
+ case "", "left", "start", "both", "distribute":
+ return false
+ }
+ return true
+}
+
+func (r *reader) numberedStyle(id string) bool {
+ for _, s := range r.chain(id) {
+ if s.numbered {
+ return true
+ }
+ }
+ return false
+}
+
+// ---- document.xml
+
+func (r *reader) readDocument(b []byte) error {
+ r.dec = newDecoder(b)
+ r.depth = 0
+ if err := r.root("document"); err != nil {
+ return err
+ }
+ return r.children(func(e xml.StartElement) error {
+ if isW(e, "body") {
+ return r.blockContent()
+ }
+ return r.skip()
+ }, nil)
+}
+
+// blockContent walks the children of a body, a table cell, or a
+// block-level content control.
+func (r *reader) blockContent() error {
+ return r.children(func(e xml.StartElement) error {
+ switch {
+ case isW(e, "p"):
+ return r.paragraph()
+ case isW(e, "tbl"):
+ return r.table()
+ case isW(e, "sdt"):
+ return r.sdt(r.blockContent)
+ case isW(e, "customXml"), isW(e, "ins"), isW(e, "moveTo"):
+ return r.blockContent()
+ case isW(e, "del"), isW(e, "moveFrom"):
+ r.rep.add(CodeDeletionOmitted, len(r.blocks))
+ return r.skip()
+ case isW(e, "sectPr"):
+ return r.sectPr()
+ case isW(e, "altChunk"):
+ r.rep.add(CodeObjectOmitted, len(r.blocks))
+ return r.skip()
+ case e.Name.Space == mcNS && e.Name.Local == "AlternateContent":
+ r.rep.add(CodeObjectOmitted, len(r.blocks))
+ return r.skip()
+ }
+ return r.skip()
+ }, nil)
+}
+
+// sdt walks a content control's w:sdtContent with content, ignoring its
+// properties.
+func (r *reader) sdt(content func() error) error {
+ return r.children(func(e xml.StartElement) error {
+ if isW(e, "sdtContent") {
+ return content()
+ }
+ return r.skip()
+ }, nil)
+}
+
+func (r *reader) sectPr() error {
+ return r.children(func(e xml.StartElement) error {
+ if (isW(e, "headerReference") || isW(e, "footerReference")) && !r.headersCounted {
+ r.headersCounted = true
+ r.rep.add(CodeHeadersOmitted, 0)
+ }
+ return r.skip()
+ }, nil)
+}
+
+func (r *reader) table() error {
+ r.tables++
+ first := len(r.blocks) + 1
+ err := r.children(func(e xml.StartElement) error {
+ if !isW(e, "tr") {
+ return r.skip()
+ }
+ return r.children(func(e xml.StartElement) error {
+ switch {
+ case isW(e, "tc"):
+ return r.blockContent()
+ case isW(e, "sdt"):
+ return r.sdt(func() error {
+ return r.children(func(e xml.StartElement) error {
+ if isW(e, "tc") {
+ return r.blockContent()
+ }
+ return r.skip()
+ }, nil)
+ })
+ }
+ return r.skip()
+ }, nil)
+ }, nil)
+ if err != nil {
+ return err
+ }
+ if len(r.blocks) >= first {
+ r.rep.add(CodeTableFlattened, first)
+ } else {
+ r.rep.add(CodeTableFlattened, 0)
+ }
+ return nil
+}
+
+// para is the paragraph being read: its style, and the run properties
+// its runs inherit.
+type para struct {
+ style string
+ kind styleKind
+ inh props // what its runs inherit
+ listMarked bool
+ jcSet bool // the paragraph states its own alignment
+}
+
+func (r *reader) newBlock(p *para) error {
+ if len(r.blocks) >= maxBlocks {
+ return ErrTooLarge
+ }
+ r.blocks = append(r.blocks, block{heading: p.kind.heading})
+ return nil
+}
+
+func (r *reader) here() int { return len(r.blocks) }
+
+func (r *reader) paragraph() error {
+ p := &para{}
+ // The block exists from the paragraph's start, so a report line
+ // about anything inside it can name it; pPr, which always comes
+ // first, then settles what kind of block it is.
+ if err := r.newBlock(p); err != nil {
+ return err
+ }
+ first := true
+ err := r.children(func(e xml.StartElement) error {
+ if first {
+ first = false
+ if isW(e, "pPr") {
+ if err := r.paragraphProps(p); err != nil {
+ return err
+ }
+ r.settle(p)
+ return nil
+ }
+ r.settle(p)
+ }
+ return r.inline(p, e)
+ }, nil)
+ if err != nil {
+ return err
+ }
+ if first {
+ r.settle(p)
+ }
+ return nil
+}
+
+// settle applies the paragraph's style once pPr has been read.
+func (r *reader) settle(p *para) {
+ p.kind = r.kind(p.style)
+ p.inh = r.inherited(p.style)
+ if p.kind.heading > 0 {
+ // A heading looks like its level in Docs: the heading style's
+ // own size, weight, slope and colour are the level's here, and
+ // the import page says so. Only its face, and what its runs
+ // state themselves, are carried.
+ p.inh = props{font: p.inh.font}
+ } else if !p.jcSet && r.alignedStyle(p.style) {
+ r.rep.add(CodeAlignmentLost, r.here())
+ }
+ r.blocks[len(r.blocks)-1].heading = p.kind.heading
+ switch {
+ case p.kind.title:
+ r.rep.add(CodeTitleAsHeading, r.here())
+ case p.kind.subtitle:
+ r.rep.add(CodeSubtitleAsParagraph, r.here())
+ }
+ if !p.listMarked && r.numberedStyle(p.style) {
+ r.rep.add(CodeListFlattened, r.here())
+ }
+}
+
+func (r *reader) paragraphProps(p *para) error {
+ return r.children(func(e xml.StartElement) error {
+ switch {
+ case isW(e, "pStyle"):
+ p.style, _ = attr(e, "val")
+ case isW(e, "numPr"):
+ numbered := true
+ err := r.children(func(c xml.StartElement) error {
+ if isW(c, "numId") {
+ if v, _ := attr(c, "val"); v == "0" {
+ numbered = false
+ }
+ }
+ return r.skip()
+ }, nil)
+ if err != nil {
+ return err
+ }
+ if numbered {
+ p.listMarked = true
+ r.rep.add(CodeListFlattened, r.here())
+ }
+ return nil
+ case isW(e, "jc"):
+ p.jcSet = true
+ if alignedValue(e) {
+ r.rep.add(CodeAlignmentLost, r.here())
+ }
+ case isW(e, "sectPr"):
+ return r.sectPr()
+ }
+ return r.skip()
+ }, nil)
+}
+
+// inline walks one child of a paragraph or of anything inside one that
+// holds runs: links, suggestions, content controls, smart tags, fields.
+func (r *reader) inline(p *para, e xml.StartElement) error {
+ walk := func() error {
+ return r.children(func(c xml.StartElement) error { return r.inline(p, c) }, nil)
+ }
+ switch {
+ case isW(e, "r"):
+ return r.run(p)
+ case isW(e, "hyperlink"):
+ // Only the visible text: r:id and w:anchor are never read, so no
+ // target from the file reaches anything.
+ r.rep.add(CodeLinkTextKept, r.here())
+ return walk()
+ case isW(e, "ins"), isW(e, "moveTo"):
+ r.rep.add(CodeInsertionKept, r.here())
+ return walk()
+ case isW(e, "del"), isW(e, "moveFrom"):
+ r.rep.add(CodeDeletionOmitted, r.here())
+ return r.skip()
+ case isW(e, "smartTag"), isW(e, "customXml"), isW(e, "fldSimple"), isW(e, "dir"), isW(e, "bdo"):
+ return walk()
+ case isW(e, "sdt"):
+ return r.sdt(walk)
+ case e.Name.Space == mcNS && e.Name.Local == "AlternateContent",
+ e.Name.Local == "oMath" || e.Name.Local == "oMathPara":
+ r.rep.add(CodeObjectOmitted, r.here())
+ return r.skip()
+ }
+ return r.skip()
+}
+
+func (r *reader) run(p *para) error {
+ rp := props{}
+ return r.children(func(e xml.StartElement) error {
+ switch {
+ case isW(e, "rPr"):
+ return r.runProps(&rp)
+ case isW(e, "t"):
+ var b strings.Builder
+ err := r.children(func(xml.StartElement) error { return r.skip() }, func(c []byte) { b.Write(c) })
+ if err != nil {
+ return err
+ }
+ return r.emit(p, rp, b.String())
+ case isW(e, "tab"), isW(e, "ptab"):
+ r.rep.add(CodeTabAsSpace, r.here())
+ if err := r.emit(p, rp, " "); err != nil {
+ return err
+ }
+ case isW(e, "br"), isW(e, "cr"):
+ code := CodeLineBreakSplit
+ if v, _ := attr(e, "type"); v == "page" || v == "column" {
+ code = CodePageBreakSplit
+ }
+ if err := r.newBlock(p); err != nil {
+ return err
+ }
+ r.rep.add(code, r.here())
+ case isW(e, "noBreakHyphen"):
+ if err := r.emit(p, rp, "‑"); err != nil {
+ return err
+ }
+ case isW(e, "drawing"), isW(e, "pict"), isW(e, "object"), isW(e, "sym"), isW(e, "ruby"),
+ e.Name.Space == mcNS && e.Name.Local == "AlternateContent":
+ r.rep.add(CodeObjectOmitted, r.here())
+ case isW(e, "footnoteReference"), isW(e, "endnoteReference"):
+ r.rep.add(CodeNotesOmitted, r.here())
+ case isW(e, "commentReference"):
+ r.rep.add(CodeCommentsOmitted, r.here())
+ }
+ // delText, instrText, fldChar, softHyphen, lastRenderedPageBreak
+ // and anything unknown carry no visible text of their own.
+ return r.skip()
+ }, nil)
+}
+
+func (r *reader) runProps(p *props) error {
+ return r.children(func(e xml.StartElement) error {
+ switch {
+ case isW(e, "b"):
+ p.bold = triOf(toggle(e))
+ case isW(e, "i"):
+ p.italic = triOf(toggle(e))
+ case isW(e, "rStyle"):
+ p.rstyle, _ = attr(e, "val")
+ case isW(e, "rFonts"):
+ if v, ok := attr(e, "ascii"); ok && v != "" {
+ p.font = v
+ } else if v, ok := attr(e, "hAnsi"); ok && v != "" {
+ p.font = v
+ }
+ case isW(e, "sz"):
+ if v, ok := attr(e, "val"); ok {
+ if n, err := strconv.Atoi(v); err == nil && n > 0 {
+ p.size = n
+ }
+ }
+ case isW(e, "u"):
+ if v, _ := attr(e, "val"); v != "none" {
+ p.lost = true
+ }
+ case isW(e, "strike"), isW(e, "dstrike"), isW(e, "caps"), isW(e, "smallCaps"):
+ if toggle(e) {
+ p.lost = true
+ }
+ case isW(e, "color"):
+ if v, _ := attr(e, "val"); !strings.EqualFold(v, "auto") && v != "000000" && v != "" {
+ p.lost = true
+ }
+ case isW(e, "highlight"):
+ if v, _ := attr(e, "val"); v != "none" && v != "" {
+ p.lost = true
+ }
+ case isW(e, "vertAlign"):
+ if v, _ := attr(e, "val"); v == "superscript" || v == "subscript" {
+ p.lost = true
+ }
+ }
+ return r.skip()
+ }, nil)
+}
+
+// clean makes a run's text into what a run can hold: a tab or a line
+// ending inside w:t becomes a space, and any other control character
+// goes.
+func (r *reader) clean(s string) string {
+ if strings.IndexFunc(s, unicode.IsControl) < 0 {
+ return s
+ }
+ var b strings.Builder
+ for _, c := range s {
+ switch {
+ case c == '\t':
+ r.rep.add(CodeTabAsSpace, r.here())
+ b.WriteByte(' ')
+ case c == '\n' || c == '\r':
+ b.WriteByte(' ')
+ case unicode.IsControl(c):
+ default:
+ b.WriteRune(c)
+ }
+ }
+ return b.String()
+}
+
+func (r *reader) emit(p *para, rp props, s string) error {
+ s = r.clean(s)
+ if s == "" {
+ return nil
+ }
+ r.runs++
+ r.text += len(s)
+ if r.runs > maxRuns || r.text > maxText {
+ return ErrTooLarge
+ }
+ run := export.Node{Type: "text", Text: s}
+
+ // The cascade: the run's own properties, its character style, its
+ // paragraph's style, the document default.
+ rp = rp.over(r.charInherited(rp.rstyle)).over(p.inh)
+ face := rp.font
+ if face != "" {
+ if f, ok := fonts.ByDocxName(face); ok {
+ if f != fonts.Default {
+ run.Marks = append(run.Marks, export.Mark{Type: f.Mark()})
+ }
+ } else {
+ r.rep.add(CodeFontSubstituted, r.here())
+ }
+ }
+ size := rp.size
+ if size != 0 && size != export.BodySizePt*2 {
+ if mark, ok := sizeMark(size); ok {
+ run.Marks = append(run.Marks, export.Mark{Type: mark})
+ } else {
+ r.rep.add(CodeSizeDropped, r.here())
+ }
+ }
+ if rp.bold == on {
+ run.Marks = append(run.Marks, export.Mark{Type: "strong"})
+ }
+ if rp.italic == on {
+ run.Marks = append(run.Marks, export.Mark{Type: "em"})
+ }
+ if rp.lost {
+ r.rep.add(CodeFormattingLost, r.here())
+ }
+ b := &r.blocks[len(r.blocks)-1]
+ b.runs = append(b.runs, run)
+ return nil
+}
+
+// sizeMark is the point-ladder mark for a size in half-points. The ladder
+// alone: the retired four-step names are never written.
+func sizeMark(half int) (string, bool) {
+ for _, mark := range export.SizeMarks() {
+ if !strings.HasPrefix(mark, "size_") {
+ continue
+ }
+ if _, err := strconv.Atoi(strings.TrimPrefix(mark, "size_")); err != nil {
+ continue
+ }
+ if pt, ok := export.SizePt(mark); ok && float64(half) == pt*2 {
+ return mark, true
+ }
+ }
+ return "", false
+}
+
+func (r *reader) document() export.Document {
+ doc := export.Document{Root: export.Node{Type: "doc"}}
+ for _, b := range r.blocks {
+ n := export.Node{Type: "paragraph"}
+ if b.heading > 0 {
+ n = export.Node{Type: "heading", Attrs: export.Attrs{Level: b.heading}}
+ }
+ n.Content = b.runs
+ doc.Root.Content = append(doc.Root.Content, n)
+ }
+ return doc
+}
diff --git a/internal/docx/read_test.go b/internal/docx/read_test.go
new file mode 100644
index 0000000..93b6932
--- /dev/null
+++ b/internal/docx/read_test.go
@@ -0,0 +1,480 @@
+package docx_test
+
+import (
+ "archive/zip"
+ "bytes"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "strings"
+ "testing"
+ "unicode"
+
+ "github.com/carlosframework/docs/internal/docx"
+ "github.com/carlosframework/docs/internal/export"
+)
+
+// The fixtures in this file are SYNTHESIZED: OOXML written by hand in the
+// shapes Google Docs' DOCX export uses (its namespaces, its styles, a link
+// as w:hyperlink, a suggestion as w:ins/w:del, a table, a list paragraph).
+// None of them is a real Google export. A real export, with permission to
+// commit its contents, has not been supplied; until one is, this reader's
+// agreement with Google's actual output is unproven beyond these shapes,
+// and the gap is recorded in the branch discussion.
+
+const docNS = `xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ` +
+ `xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ` +
+ `xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" ` +
+ `xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" ` +
+ `xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" mc:Ignorable="w14"`
+
+// googleStyles is a styles part shaped like Google's: Arial 11pt as the
+// document default and on Normal, and the named heading, title and
+// subtitle styles.
+const googleStyles = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
+ `<w:styles ` + docNS + `>` +
+ `<w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="Arial" w:cs="Arial" w:eastAsia="Arial" w:hAnsi="Arial"/>` +
+ `<w:sz w:val="22"/><w:szCs w:val="22"/><w:lang w:val="en"/></w:rPr></w:rPrDefault>` +
+ `<w:pPrDefault><w:pPr><w:spacing w:line="276" w:lineRule="auto"/></w:pPr></w:pPrDefault></w:docDefaults>` +
+ `<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="normal"/></w:style>` +
+ `<w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:basedOn w:val="Normal"/>` +
+ `<w:pPr><w:keepNext w:val="1"/></w:pPr><w:rPr><w:sz w:val="40"/></w:rPr></w:style>` +
+ `<w:style w:type="paragraph" w:styleId="Heading2"><w:name w:val="heading 2"/><w:basedOn w:val="Normal"/>` +
+ `<w:rPr><w:sz w:val="32"/></w:rPr></w:style>` +
+ `<w:style w:type="paragraph" w:styleId="Title"><w:name w:val="Title"/><w:basedOn w:val="Normal"/>` +
+ `<w:rPr><w:sz w:val="52"/></w:rPr></w:style>` +
+ `<w:style w:type="paragraph" w:styleId="Subtitle"><w:name w:val="Subtitle"/><w:basedOn w:val="Normal"/>` +
+ `<w:rPr><w:color w:val="666666"/><w:sz w:val="30"/></w:rPr></w:style>` +
+ `</w:styles>`
+
+// The link targets are hostile on purpose. Import never reads the
+// relationships part, so none of them may appear anywhere in its output.
+const hostileRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
+ `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
+ `<Relationship Id="rId9" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="javascript:alert(document.cookie)" TargetMode="External"/>` +
+ `<Relationship Id="rId10" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="file:///etc/passwd" TargetMode="External"/>` +
+ `<Relationship Id="rId11" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="http://169.254.169.254/latest/meta-data/" TargetMode="External"/>` +
+ `</Relationships>`
+
+func run(props, text string) string {
+ if props != "" {
+ props = "<w:rPr>" + props + "</w:rPr>"
+ }
+ return `<w:r>` + props + `<w:t xml:space="preserve">` + text + `</w:t></w:r>`
+}
+
+func para(style, content string) string {
+ ppr := ""
+ if style != "" {
+ ppr = `<w:pPr><w:pStyle w:val="` + style + `"/></w:pPr>`
+ }
+ return `<w:p>` + ppr + content + `</w:p>`
+}
+
+// googleShaped is the synthesized fixture: every container whose text the
+// old reader lost, plus the omissions the report must name.
+func googleShaped(t *testing.T) []byte {
+ t.Helper()
+ body := para("Title", run("", "Quarterly plan")) +
+ para("Heading1", run("", "Summary")) +
+ // A link, inside a paragraph, with hostile targets in the rels.
+ para("", run("", "Visit ")+`<w:hyperlink r:id="rId9"><w:r><w:rPr><w:color w:val="1155CC"/><w:u w:val="single"/></w:rPr><w:t>our site</w:t></w:r></w:hyperlink>`+run("", ".")) +
+ // Explicit bold off, the true spellings of on, and italic.
+ para("", run(`<w:b w:val="0"/>`, "not bold, ")+run(`<w:b/>`, "bold, ")+run(`<w:b w:val="false"/>`, "off again, ")+run(`<w:b w:val="1"/><w:i w:val="true"/>`, "both")) +
+ // A list item.
+ `<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr>` + run("", "First item") + `</w:p>` +
+ // A table, with a nested table in one cell.
+ `<w:tbl><w:tblPr/><w:tr><w:tc><w:tcPr/>` + para("", run("", "A1")) + `</w:tc><w:tc>` + para("", run("", "B1")) + `</w:tc></w:tr>` +
+ `<w:tr><w:tc>` + para("", run("", "A2")) + `<w:tbl><w:tr><w:tc>` + para("", run("", "inner")) + `</w:tc></w:tr></w:tbl></w:tc><w:tc>` + para("", run("", "B2")) + `</w:tc></w:tr></w:tbl>` +
+ // A suggestion: an insertion is kept, a deletion is not.
+ para("", run("", "Kept ")+`<w:ins w:id="1" w:author="Someone" w:date="2026-10-01T00:00:00Z">`+run("", "added")+`</w:ins>`+
+ `<w:del w:id="2" w:author="Someone" w:date="2026-10-01T00:00:00Z"><w:r><w:delText>removed</w:delText></w:r></w:del>`+run("", " text")) +
+ // A block content control and a smart tag.
+ `<w:sdt><w:sdtPr><w:alias w:val="x"/></w:sdtPr><w:sdtContent>` + para("", run("", "in a control")) + `</w:sdtContent></w:sdt>` +
+ para("", `<w:smartTag w:uri="urn:x" w:element="place">`+run("", "Smart")+`</w:smartTag>`+` <w:sdt><w:sdtContent>`+run("", " inline")+`</w:sdtContent></w:sdt>`) +
+ // A tab, a line break and a page break.
+ para("", `<w:r><w:t>before</w:t><w:tab/><w:t>after</w:t><w:br/><w:t>next line</w:t><w:br w:type="page"/><w:t>next page</w:t></w:r>`) +
+ // An image, a footnote, a comment, a size off the ladder, an
+ // unknown face, a centred paragraph, a heading level.
+ para("", `<w:r><w:drawing><wp:inline/></w:drawing></w:r>`+run("", "Caption")+`<w:r><w:footnoteReference w:id="1"/></w:r>`+
+ `<w:commentRangeStart w:id="0"/>`+run(`<w:sz w:val="30"/>`, "fifteen")+`<w:commentRangeEnd w:id="0"/><w:r><w:commentReference w:id="0"/></w:r>`+
+ run(`<w:rFonts w:ascii="Comic Sans MS" w:hAnsi="Comic Sans MS"/>`, " comic")+run(`<w:sz w:val="28"/>`, " fourteen")) +
+ `<w:p><w:pPr><w:jc w:val="center"/></w:pPr>` + run("", "Centred") + `</w:p>` +
+ para("Subtitle", run("", "A subtitle")) +
+ para("Heading2", run(`<w:rFonts w:ascii="Times New Roman" w:hAnsi="Times New Roman"/>`, "Serif heading")) +
+ para("", "") +
+ `<w:sectPr><w:headerReference w:type="default" r:id="rId12"/><w:pgSz w:w="12240" w:h="15840"/></w:sectPr>`
+ return zipOf(t, map[string]string{
+ "[Content_Types].xml": `<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"/>`,
+ "word/document.xml": `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document ` + docNS + `><w:body>` + body + `</w:body></w:document>`,
+ "word/styles.xml": googleStyles,
+ "word/_rels/document.xml.rels": hostileRels,
+ "word/comments.xml": `<w:comments ` + docNS + `/>`,
+ })
+}
+
+func zipOf(t *testing.T, parts map[string]string) []byte {
+ t.Helper()
+ var buf bytes.Buffer
+ z := zip.NewWriter(&buf)
+ for name, body := range parts {
+ w, err := z.Create(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ io.WriteString(w, body)
+ }
+ if err := z.Close(); err != nil {
+ t.Fatal(err)
+ }
+ return buf.Bytes()
+}
+
+// shape renders a document as one line per block: its type, then each
+// run as text{marks}.
+func shape(d export.Document) []string {
+ var out []string
+ for _, b := range d.Root.Content {
+ line := b.Type
+ if b.Type == "heading" {
+ line += fmt.Sprint(b.Attrs.Level)
+ }
+ line += ":"
+ for _, r := range b.Content {
+ var marks []string
+ for _, m := range r.Marks {
+ marks = append(marks, m.Type)
+ }
+ line += r.Text
+ if len(marks) > 0 {
+ line += "{" + strings.Join(marks, ",") + "}"
+ }
+ line += "|"
+ }
+ out = append(out, line)
+ }
+ return out
+}
+
+func TestImportReadsEveryContainerGoogleExportsTextIn(t *testing.T) {
+ res, err := docx.Import(googleShaped(t))
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Arial is Liberation Sans (font_sans) and 11pt is size_11, Google's
+ // default, so ordinary runs carry both; headings carry no inherited
+ // size, because a heading's size is its level's here.
+ const body = "font_sans,size_11"
+ want := []string{
+ "heading1:Quarterly plan{font_sans}|",
+ "heading1:Summary{font_sans}|",
+ "paragraph:Visit {" + body + "}|our site{" + body + "}|.{" + body + "}|",
+ "paragraph:not bold, {" + body + "}|bold, {" + body + ",strong}|off again, {" + body + "}|both{" + body + ",strong,em}|",
+ "paragraph:First item{" + body + "}|",
+ "paragraph:A1{" + body + "}|",
+ "paragraph:B1{" + body + "}|",
+ "paragraph:A2{" + body + "}|",
+ "paragraph:inner{" + body + "}|",
+ "paragraph:B2{" + body + "}|",
+ "paragraph:Kept {" + body + "}|added{" + body + "}| text{" + body + "}|",
+ "paragraph:in a control{" + body + "}|",
+ "paragraph:Smart{" + body + "}| inline{" + body + "}|",
+ "paragraph:before{" + body + "}| {" + body + "}|after{" + body + "}|",
+ "paragraph:next line{" + body + "}|",
+ "paragraph:next page{" + body + "}|",
+ "paragraph:Caption{" + body + "}|fifteen{font_sans}| comic{size_11}| fourteen{font_sans,size_14}|",
+ "paragraph:Centred{" + body + "}|",
+ "paragraph:A subtitle{font_sans}|",
+ "heading2:Serif heading{font_serif}|",
+ "paragraph:",
+ }
+ got := shape(res.Document)
+ if strings.Join(got, "\n") != strings.Join(want, "\n") {
+ t.Errorf("document\n got:\n%s\nwant:\n%s", strings.Join(got, "\n"), strings.Join(want, "\n"))
+ }
+
+ type line struct {
+ count int
+ where string
+ names string
+ }
+ wantReport := map[docx.Code]line{
+ docx.CodeTableFlattened: {2, "6,9", ""},
+ docx.CodeListFlattened: {1, "5", ""},
+ docx.CodeLinkTextKept: {1, "3", ""},
+ docx.CodeInsertionKept: {1, "11", ""},
+ docx.CodeDeletionOmitted: {1, "11", ""},
+ docx.CodeObjectOmitted: {1, "17", ""},
+ docx.CodeNotesOmitted: {1, "17", ""},
+ docx.CodeCommentsOmitted: {1, "17", ""},
+ docx.CodeHeadersOmitted: {1, "", ""},
+ docx.CodeTitleAsHeading: {1, "1", ""},
+ docx.CodeSubtitleAsParagraph: {1, "19", ""},
+ docx.CodeFontSubstituted: {1, "17", ""},
+ docx.CodeSizeDropped: {2, "17,19", ""},
+ docx.CodeFormattingLost: {2, "3,19", ""},
+ docx.CodeAlignmentLost: {1, "18", ""},
+ docx.CodeTabAsSpace: {1, "14", ""},
+ docx.CodeLineBreakSplit: {1, "15", ""},
+ docx.CodePageBreakSplit: {1, "16", ""},
+ }
+ gotReport := map[docx.Code]line{}
+ for _, it := range res.Report.Items {
+ var where []string
+ for _, p := range it.Paragraphs {
+ where = append(where, fmt.Sprint(p))
+ }
+ gotReport[it.Code] = line{it.Count, strings.Join(where, ","), ""}
+ }
+ for code, w := range wantReport {
+ if g, ok := gotReport[code]; !ok {
+ t.Errorf("report has no %s", code)
+ } else if g != w {
+ t.Errorf("report %s: got %+v, want %+v", code, g, w)
+ }
+ }
+ for code := range gotReport {
+ if _, ok := wantReport[code]; !ok {
+ t.Errorf("report has an unexpected %s: %+v", code, gotReport[code])
+ }
+ }
+ // The report lists in Codes order.
+ at := map[docx.Code]int{}
+ for i, c := range docx.Codes {
+ at[c] = i
+ }
+ for i := 1; i < len(res.Report.Items); i++ {
+ if at[res.Report.Items[i-1].Code] > at[res.Report.Items[i].Code] {
+ t.Errorf("report out of order at %d", i)
+ }
+ }
+}
+
+// The reader this replaced bound w:body>w:p>w:r>w:t alone and read w:b
+// by presence, with no error and no report. Run against it (its Read at
+// 056b94d), the first eleven cases below failed: link, table, insertion,
+// both content controls, smart tag and field text came back missing,
+// bold-off and italic-off came back on, and a tab or break joined its
+// neighbours. The last two passed there too; they are here because a
+// walk that descends into everything could get them wrong where an
+// unmarshal into fixed paths could not.
+func TestImportKeepsWhatTheOldReaderLost(t *testing.T) {
+ for _, c := range []struct {
+ name, body, want string
+ }{
+ {"link", para("", `<w:hyperlink r:id="rId9">`+run("", "linked")+`</w:hyperlink>`), "paragraph:linked|"},
+ {"table", `<w:tbl><w:tr><w:tc>` + para("", run("", "cell")) + `</w:tc></w:tr></w:tbl>`, "paragraph:cell|"},
+ {"insertion", para("", `<w:ins w:id="1" w:author="a">`+run("", "inserted")+`</w:ins>`), "paragraph:inserted|"},
+ {"block content control", `<w:sdt><w:sdtContent>` + para("", run("", "controlled")) + `</w:sdtContent></w:sdt>`, "paragraph:controlled|"},
+ {"inline content control", para("", `<w:sdt><w:sdtContent>`+run("", "inline")+`</w:sdtContent></w:sdt>`), "paragraph:inline|"},
+ {"smart tag", para("", `<w:smartTag w:element="x">`+run("", "tagged")+`</w:smartTag>`), "paragraph:tagged|"},
+ {"simple field", para("", `<w:fldSimple w:instr="PAGE">`+run("", "7")+`</w:fldSimple>`), "paragraph:7|"},
+ {"bold off", para("", run(`<w:b w:val="0"/>`, "plain")), "paragraph:plain|"},
+ {"italic off", para("", run(`<w:i w:val="false"/>`, "plain")), "paragraph:plain|"},
+ {"tab", para("", `<w:r><w:t>a</w:t><w:tab/><w:t>b</w:t></w:r>`), "paragraph:a| |b|"},
+ {"break", para("", `<w:r><w:t>a</w:t><w:br/><w:t>b</w:t></w:r>`), "paragraph:a|\nparagraph:b|"},
+ {"deletion is not text", para("", run("", "kept")+`<w:del w:id="1" w:author="a"><w:r><w:delText>gone</w:delText></w:r></w:del>`), "paragraph:kept|"},
+ {"paragraph mark properties are not the run's", `<w:p><w:pPr><w:rPr><w:b/></w:rPr></w:pPr>` + run("", "plain") + `</w:p>`, "paragraph:plain|"},
+ } {
+ data := zipOf(t, map[string]string{
+ "word/document.xml": `<w:document ` + docNS + `><w:body>` + c.body + `</w:body></w:document>`,
+ })
+ res, err := docx.Import(data)
+ if err != nil {
+ t.Errorf("%s: %v", c.name, err)
+ continue
+ }
+ if got := strings.Join(shape(res.Document), "\n"); got != c.want {
+ t.Errorf("%s: got %q, want %q", c.name, got, c.want)
+ }
+ }
+}
+
+// Bold and italic come through the whole cascade: document default,
+// paragraph style chain, character style, run, with an explicit off at
+// any nearer level winning. What a style carries that Docs cannot hold is
+// reported for the paragraphs it reaches, not dropped in silence.
+func TestImportFollowsTheStyleCascade(t *testing.T) {
+ styles := `<w:styles ` + docNS + `>` +
+ `<w:docDefaults><w:rPrDefault><w:rPr><w:i/></w:rPr></w:rPrDefault></w:docDefaults>` +
+ `<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style>` +
+ `<w:style w:type="paragraph" w:styleId="Strong"><w:name w:val="Strong body"/><w:basedOn w:val="Normal"/><w:rPr><w:b/></w:rPr></w:style>` +
+ `<w:style w:type="paragraph" w:styleId="StrongChild"><w:name w:val="Strong child"/><w:basedOn w:val="Strong"/><w:rPr><w:i w:val="0"/></w:rPr></w:style>` +
+ `<w:style w:type="paragraph" w:styleId="Red"><w:name w:val="Red"/><w:rPr><w:color w:val="FF0000"/></w:rPr></w:style>` +
+ `<w:style w:type="paragraph" w:styleId="Centred"><w:name w:val="Centred"/><w:pPr><w:jc w:val="center"/></w:pPr></w:style>` +
+ `<w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:rPr><w:b/><w:color w:val="FF0000"/><w:sz w:val="40"/></w:rPr></w:style>` +
+ `<w:style w:type="character" w:styleId="Emph"><w:name w:val="Emph"/><w:rPr><w:i/><w:u w:val="single"/></w:rPr></w:style>` +
+ `</w:styles>`
+ body := para("", run("", "default italic")) +
+ para("Strong", run("", "style bold")+run(`<w:b w:val="0"/>`, "run says not bold")) +
+ para("StrongChild", run("", "inherited bold, italic off")) +
+ para("", run(`<w:rStyle w:val="Emph"/><w:i w:val="0"/>`, "character style, italic off")+run(`<w:rStyle w:val="Emph"/>`, "character style")) +
+ para("Red", run("", "red")) +
+ para("Centred", run("", "centred")) +
+ `<w:p><w:pPr><w:pStyle w:val="Centred"/><w:jc w:val="left"/></w:pPr>` + run("", "left after all") + `</w:p>` +
+ para("Heading1", run("", "heading"))
+ res, err := docx.Import(zipOf(t, map[string]string{
+ "word/styles.xml": styles,
+ "word/document.xml": `<w:document ` + docNS + `><w:body>` + body + `</w:body></w:document>`,
+ }))
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := []string{
+ "paragraph:default italic{em}|",
+ "paragraph:style bold{strong,em}|run says not bold{em}|",
+ "paragraph:inherited bold, italic off{strong}|",
+ "paragraph:character style, italic off|character style{em}|",
+ "paragraph:red{em}|",
+ "paragraph:centred{em}|",
+ "paragraph:left after all{em}|",
+ "heading1:heading|",
+ }
+ if got := strings.Join(shape(res.Document), "\n"); got != strings.Join(want, "\n") {
+ t.Errorf("document\n got:\n%s\nwant:\n%s", got, strings.Join(want, "\n"))
+ }
+ where := map[docx.Code]string{}
+ for _, it := range res.Report.Items {
+ var ps []string
+ for _, p := range it.Paragraphs {
+ ps = append(ps, fmt.Sprint(p))
+ }
+ where[it.Code] = strings.Join(ps, ",")
+ }
+ if where[docx.CodeFormattingLost] != "4,5" {
+ t.Errorf("formatting lost at %q, want the underlined character style (4) and the red paragraph style (5)", where[docx.CodeFormattingLost])
+ }
+ if where[docx.CodeAlignmentLost] != "6" {
+ t.Errorf("alignment lost at %q, want the centred style's paragraph only (6)", where[docx.CodeAlignmentLost])
+ }
+}
+
+func TestImportNeverReadsALinkTarget(t *testing.T) {
+ res, err := docx.Import(googleShaped(t))
+ if err != nil {
+ t.Fatal(err)
+ }
+ out, _ := json.Marshal(res)
+ for _, s := range []string{"javascript", "alert", "/etc/passwd", "169.254", "rId9", "Someone"} {
+ if strings.Contains(string(out), s) {
+ t.Errorf("the result carries %q from the file's metadata", s)
+ }
+ }
+ // The report is closed metadata: codes, counts and paragraph
+ // numbers. No text from the file, and no face name either.
+ rep, _ := json.Marshal(res.Report)
+ for _, s := range []string{"Comic", "Arial", "Quarterly", "Summary", "our site", "removed"} {
+ if strings.Contains(string(rep), s) {
+ t.Errorf("the report quotes %q from the file", s)
+ }
+ }
+}
+
+func TestImportDropsControlCharacters(t *testing.T) {
+ data := zipOf(t, map[string]string{
+ "word/document.xml": `<w:document ` + docNS + `><w:body>` + para("", run("", "a\u0085b&#x9;c\nd")) + `</w:body></w:document>`,
+ })
+ res, err := docx.Import(data)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := strings.Join(shape(res.Document), ""); got != "paragraph:ab c d|" {
+ t.Errorf("got %q", got)
+ }
+}
+
+func TestImportRefusals(t *testing.T) {
+ doc := func(body string) map[string]string {
+ return map[string]string{"word/document.xml": `<w:document ` + docNS + `><w:body>` + body + `</w:body></w:document>`}
+ }
+ deep := strings.Repeat(`<w:sdt><w:sdtContent>`, 300) + para("", run("", "x")) + strings.Repeat(`</w:sdtContent></w:sdt>`, 300)
+ many := map[string]string{"word/document.xml": doc(para("", run("", "x")))["word/document.xml"]}
+ for i := 0; i < 1001; i++ {
+ many[fmt.Sprintf("word/media/%d.bin", i)] = ""
+ }
+ cases := []struct {
+ name string
+ data []byte
+ want error
+ }{
+ {"not a zip", []byte("%PDF-1.7 not a word file"), docx.ErrNotWord},
+ {"no document part", zipOf(t, map[string]string{"word/styles.xml": googleStyles}), docx.ErrNotWord},
+ {"a spreadsheet", zipOf(t, map[string]string{"xl/workbook.xml": "<workbook/>"}), docx.ErrNotWord},
+ {"wrong root", zipOf(t, map[string]string{"word/document.xml": `<html/>`}), docx.ErrNotWord},
+ {"not well formed", zipOf(t, doc(`<w:p><w:r>`)), docx.ErrMalformed},
+ {"a DTD", zipOf(t, map[string]string{"word/document.xml": `<!DOCTYPE w:document [<!ENTITY a "aaaa">]><w:document ` + docNS + `/>`}), docx.ErrMalformed},
+ {"too deep", zipOf(t, doc(deep)), docx.ErrMalformed},
+ {"too many entries", zipOf(t, many), docx.ErrTooLarge},
+ {"nothing but empty paragraphs", zipOf(t, doc(para("", "")+para("", `<w:r><w:drawing/></w:r>`))), docx.ErrEmpty},
+ {"only deleted text", zipOf(t, doc(para("", `<w:del><w:r><w:delText>x</w:delText></w:r></w:del>`))), docx.ErrEmpty},
+ {"too many blocks", zipOf(t, doc(strings.Repeat(para("", run("", "x")), 5_001))), docx.ErrTooLarge},
+ {"too much text", zipOf(t, doc(para("", run("", strings.Repeat("x", 512<<10+1))))), docx.ErrTooLarge},
+ {"too many runs", zipOf(t, doc(para("", strings.Repeat(run("", "x"), 10_001)))), docx.ErrTooLarge},
+ }
+ for _, c := range cases {
+ if _, err := docx.Import(c.data); !errors.Is(err, c.want) {
+ t.Errorf("%s: got %v, want %v", c.name, err, c.want)
+ }
+ }
+}
+
+// A part whose decompressed size is far past its compressed one is
+// refused from the bytes actually read, not from the header's claim.
+func TestImportCountsDecompressedBytes(t *testing.T) {
+ var buf bytes.Buffer
+ z := zip.NewWriter(&buf)
+ w, _ := z.Create("word/document.xml")
+ io.WriteString(w, `<w:document `+docNS+`><w:body>`)
+ pad := bytes.Repeat([]byte(" "), 1<<20)
+ for i := 0; i < 33; i++ {
+ w.Write(pad)
+ }
+ io.WriteString(w, `</w:body></w:document>`)
+ z.Close()
+ if buf.Len() > 1<<20 {
+ t.Fatalf("the bomb is %d bytes compressed; the test means a small file", buf.Len())
+ }
+ if _, err := docx.Import(buf.Bytes()); !errors.Is(err, docx.ErrTooLarge) {
+ t.Errorf("got %v, want ErrTooLarge", err)
+ }
+}
+
+func TestImportRefusesADuplicatedPart(t *testing.T) {
+ var buf bytes.Buffer
+ z := zip.NewWriter(&buf)
+ for _, body := range []string{para("", run("", "one")), para("", run("", "two"))} {
+ w, _ := z.Create("word/document.xml")
+ io.WriteString(w, `<w:document `+docNS+`><w:body>`+body+`</w:body></w:document>`)
+ }
+ z.Close()
+ if _, err := docx.Import(buf.Bytes()); !errors.Is(err, docx.ErrMalformed) {
+ t.Errorf("got %v, want ErrMalformed", err)
+ }
+}
+
+// Whatever the bytes, Import either refuses with one of its own errors
+// or returns runs the builder accepts: non-empty, no control character.
+func FuzzImport(f *testing.F) {
+ var tb testing.T
+ f.Add(googleShaped(&tb))
+ f.Add([]byte("PK\x03\x04"))
+ f.Fuzz(func(t *testing.T, data []byte) {
+ res, err := docx.Import(data)
+ if err != nil {
+ for _, known := range []error{docx.ErrNotWord, docx.ErrMalformed, docx.ErrTooLarge, docx.ErrEmpty} {
+ if errors.Is(err, known) {
+ return
+ }
+ }
+ t.Fatalf("unexpected error %v", err)
+ }
+ for _, b := range res.Document.Root.Content {
+ for _, r := range b.Content {
+ if r.Text == "" || strings.IndexFunc(r.Text, unicode.IsControl) >= 0 {
+ t.Fatalf("a run the builder would refuse: %q", r.Text)
+ }
+ }
+ }
+ })
+}