oficina / docs Public

Docs: import a .docx, with an optional Google Drive chooser.

GET/POST /import in the signed-in group, member-only like create: an
ordinary scriptless multipart form (#docs-import-form, #docs-import-file)
read through MultipartReader with no disk spill, 10 MiB plus framing,
.docx and ZIP signature checked, two conversions at a time. When
DOCS_GOOGLE_CLIENT_ID/API_KEY/APP_ID are all set (Config.GoogleImport,
validated at boot), estilo's googleimport chooser renders on that page
only, with its policy from googleimport.Headers over Docs' own constant;
it puts the exported file in the same input, so the server never sees a
Google token. Unset leaves no chooser and no Google origin anywhere.

The conversion: docx.Import -> core.EncodeBuild -> Runtime.Build under a
fresh uint32 client id (never the row's read-handle id; Runtime.Build
and the Rust builder both refuse ids past 2^53-1, which lib0 cannot
decode) -> the update replayed in a second handle and its structure
compared with what the reader meant -> Store.CreateImported, which
writes the row, sealed update 1 and the sealed report in one
transaction with membership checked inside it and creation-token
idempotence. Any failure creates nothing; refusals redraw the page with
a catalog message (4xx) and log a reason code only.

Reports live in doc_import_reports (migration 0009), sealed under the
content key with their own AAD kind byte (4), and follow the update
log's sealing rules, including the offline activation/migration and
the mixed-encoding census. The report shows once on arrival
(/d/{sqid}?imported=1, a server-opened dialog closed without script) and
reopens at /d/{sqid}/import-report from the bar. The list links Import.

TestImportedUpdatesOpenInTheEditorUnchanged runs the real converter's
updates (real client ids) through Yjs and y-prosemirror under the
editor schema (fixtures/import-interop.mjs): decodable, no schema
clean-up, check() passes. The browser flow test
(google_import_browser_test.go, fixtures/engines/google-import.mjs) is
the parent session's, validated by it in Chromium and WebKit with
controlled Google responses.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev be64677bea0f3cb3ed4fbe7ad1858fb24df742ad parent e877ead
26 files changed, +1,350 −15
  • cmd/docs/main.go +11 −2
  • core/src/abi.rs +3 −0
  • core/src/build.rs +12 −0
  • core/tests/build.rs +19 −0
  • fixtures/engines/google-import.mjs +83 −0
  • fixtures/import-interop.mjs +59 −0
  • internal/core/build_test.go +19 −0
  • internal/core/core.go +15 −0
  • 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 +101 −0
  • internal/docs/handlers.go +31 −0
  • internal/docs/import.go +601 −0
  • internal/docs/import_interop_test.go +123 −0
  • internal/docs/migrations/0009_import_reports.sql +17 −0
  • internal/docs/models.go +16 −0
  • internal/docs/render.go +54 −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

CI failed — run details

diff --git a/cmd/docs/main.go b/cmd/docs/main.go
index f984078..e306b70 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/rastrillo/rastrillo"
"amadan.net/rastrillo/rastrillo/mail"
@@ -273,8 +274,16 @@ func main() {
// — otherwise Serve would open a second connection to the file New
// already owns.
cfg := docs.Config{
- DBPath: opts.DBPath,
- ContentKey: os.Getenv("DOCS_CONTENT_KEY"),
+ 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 e392367..d0567c4 100644
--- a/core/src/abi.rs
+++ b/core/src/abi.rs
@@ -507,6 +507,8 @@ 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) {
@@ -516,6 +518,7 @@ pub fn build_slice(handle: u32, ops: &[u8]) -> i32 {
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,
},
}
}
diff --git a/core/src/build.rs b/core/src/build.rs
index e39509a..ddb7cdb 100644
--- a/core/src/build.rs
+++ b/core/src/build.rs
@@ -76,8 +76,17 @@ pub enum BuildError {
/// 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.
@@ -239,6 +248,9 @@ fn decode(ops: &[u8]) -> Result<Vec<Block>, BuildError> {
/// 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();
diff --git a/core/tests/build.rs b/core/tests/build.rs
index 7cbb28a..47ca13b 100644
--- a/core/tests/build.rs
+++ b/core/tests/build.rs
@@ -212,6 +212,25 @@ fn refuses_past_its_limits() {
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();
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/internal/core/build_test.go b/internal/core/build_test.go
index bb8fbcc..79e2572 100644
--- a/internal/core/build_test.go
+++ b/internal/core/build_test.go
@@ -48,6 +48,25 @@ func TestBuildWritesTheDocumentItDescribes(t *testing.T) {
}
}
+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)
diff --git a/internal/core/core.go b/internal/core/core.go
index 0510c87..262c9f5 100644
--- a/internal/core/core.go
+++ b/internal/core/core.go
@@ -795,8 +795,18 @@ 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
@@ -810,6 +820,9 @@ var (
// 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
@@ -834,6 +847,8 @@ func (r *Runtime) Build(ctx context.Context, guid string, clientID uint64, ops [
return nil, ErrBuildMalformed
case -7:
return nil, ErrBuildLimit
+ case -9:
+ return nil, ErrBuildClientID
default:
return nil, fmt.Errorf("core: build refused: code %d", code)
}
diff --git a/internal/core/testdata/docs_core.wasm b/internal/core/testdata/docs_core.wasm
index f8c3955..43be51a 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 9b65167..bf10275 100644
--- a/internal/docs/app.go
+++ b/internal/docs/app.go
@@ -39,6 +39,8 @@ import (
"github.com/go-chi/chi/v5"
"github.com/carlosframework/docs/internal/core"
+
+ "amadan.net/oficina/estilo.git/googleimport"
)
// Config configures New.
@@ -49,6 +51,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
@@ -394,6 +404,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 {
@@ -524,7 +537,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.
@@ -733,6 +746,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..bddf61b
--- /dev/null
+++ b/internal/docs/google_import_browser_test.go
@@ -0,0 +1,101 @@
+//go:build browser
+
+package docs_test
+
+import (
+ "archive/zip"
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "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()
+ app, err := docs.NewForTestWith(t, docs.Config{Origin: origin, Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), 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)
+ }
+}
+
+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 57c7b11..5298530 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..15cd244
--- /dev/null
+++ b/internal/docs/import.go
@@ -0,0 +1,601 @@
+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
+
+// 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) {
+ actor := s.ownerActor(ctx, owner)
+ if err := s.requireMember(ctx, actor); err != nil {
+ return nil, err
+ }
+ now := time.Now().UTC()
+ 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, 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
+ }
+ 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) {
+ 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
+ }
+ 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
+ }
+ 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/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 0522305..0c6f394 100644
--- a/internal/docs/models.go
+++ b/internal/docs/models.go
@@ -98,6 +98,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 bf04b19..574f764 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"
@@ -314,6 +315,51 @@ 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, colours, 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 10,000 paragraphs.",
+ "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.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, colour, highlight, superscript, subscript and capitals were left out: {count} runs.",
+ "docs.import.report.alignment_lost": "Centred 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,
@@ -560,6 +606,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",
@@ -611,6 +659,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)
}
@@ -707,6 +758,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/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>