oficina / estilo Public

Add optional Google Drive import chooser for Docs and Sheets. Reviewed by Claude Fable 5.1 in oficina/estilo discussion 31; CI and Chromium/WebKit checks pass. Co-Authored-By: Codex <noreply@openai.com>

Squashed from feat/google-import into main.
Codex pushed by codex agent, operated by paul@keymail.dev 7a19588e736f8489c68432f3c2195562a9de6a0a parent cca97df
11 files changed, +995 −0
  • googleimport/README.md +99 −0
  • googleimport/browser_test.go +80 −0
  • googleimport/google-import.browser.mjs +80 −0
  • googleimport/google-import.mjs +178 −0
  • googleimport/google-import.test.mjs +58 −0
  • googleimport/googleimport.go +71 −0
  • googleimport/googleimport_test.go +121 −0
  • googleimport/labels.go +49 −0
  • googleimport/policy.go +81 −0
  • googleimport/templates/google-import.html +9 −0
  • implementation/google-drive-import.md +169 −0

CI passed — run details

diff --git a/googleimport/README.md b/googleimport/README.md
new file mode 100644
index 0000000..2da6d78
--- /dev/null
+++ b/googleimport/README.md
@@ -0,0 +1,99 @@
+# Google Drive import
+
+This optional component connects to Google Identity Services, Google Picker
+and the Google Drive API on the import page. It exports one selected native
+Google document or spreadsheet into browser memory and submits it through the
+app's ordinary file upload form. The original Google file is unchanged.
+
+The Google access token is held only in page memory and sent only in the
+Authorization header to Google's fixed API origin. It is never uploaded to
+Oficina, persisted in browser storage, or written to a server database. No
+background synchronization or refresh token is involved. Google's authorization
+grant can outlive the page; people can remove it from their Google account's
+third-party connections. The requested `drive.file` scope grants per-file access
+and can authorize modifications, but this component only calls the export API.
+
+JavaScript is required for the chooser. With scripts disabled, a note explains
+how to download from Google and use the app's ordinary file form. Configuring
+none of the public Google fields hides the component entirely; partial or
+malformed configuration must refuse app startup through `Config.Validate`.
+
+## Google Cloud setup
+
+1. Create a Google Cloud project and enable **Google Drive API** and **Google
+ Picker API**.
+2. Configure the OAuth application's branding, audience and support information.
+ Request only `https://www.googleapis.com/auth/drive.file`. This scope is
+ non-sensitive. Follow the console's publishing requirements; while in
+ Testing, add the accounts that will exercise consent as test users.
+3. Create an OAuth **Web application** client. Add each app's exact HTTPS
+ origin to its authorized JavaScript origins, including the canary used for
+ verification. Local development can use its exact localhost origin and port.
+ Google does not accept a wildcard for arbitrary tenant subdomains; register
+ each deployed origin. This token flow does not use an OAuth redirect endpoint.
+4. Create a browser API key in the same project. Restrict it to Google Picker
+ API and Google Drive API. Its website restrictions must include the app's
+ origin (`https://example.test/*`) and `https://docs.google.com/*`, where
+ Picker's iframe runs. The key is public client configuration.
+5. Record the project's numeric **project number**, not its project name or ID.
+ It must be the OAuth client's project and is passed to Picker's `setAppId`;
+ mismatches can make valid selections fail to export.
+6. Set all three app settings together:
+
+ | Setting | Docs | Sheets |
+ | --- | --- | --- |
+ | OAuth client ID | `DOCS_GOOGLE_CLIENT_ID` | `SHEETS_GOOGLE_CLIENT_ID` |
+ | Public API key | `DOCS_GOOGLE_API_KEY` | `SHEETS_GOOGLE_API_KEY` |
+ | Project number | `DOCS_GOOGLE_APP_ID` | `SHEETS_GOOGLE_APP_ID` |
+
+There is no client secret setting. Leave production Google configuration unset
+until the real consent and import checks below have succeeded on an authorized
+canary origin.
+
+## App integration
+
+Pass `Config` through the app's config and validate at startup. Merge
+`Templates()` with the app templates (glob `templates/*.html`), then render
+`estilo-google-import` with `View{Config, Kind: Docs/Sheets, FormID, InputID,
+Labels: Text(locale)}`. The file input must belong to the named same-origin
+multipart POST form. Existing hidden fields, including creation tokens, remain
+intact. The app owns permissions, CSRF, upload limits, conversion and reports.
+
+Serve `JS()` as JavaScript at `JSName()` and load it with a module script only
+on configured import pages. The name contains the asset's hash and may be
+cached as immutable. Call `Headers(w, ContentSecurityPolicy)` before rendering
+the opted-in import page, including a refused POST's re-render. Handle errors
+before writing a response. This sets one expanded policy, preserves unrelated
+directives, and sets no-store. It adds no COOP header. Both current apps already
+allow inline styles; this component adds neither inline-script nor eval access.
+
+The scripts come directly from Google as Google requires; no CDN library is
+vendored or bundled. Loading waits until prerendered pages are activated.
+Picker is filtered by native MIME type, and returned shortcuts/other types
+are rejected again. Download uses a fixed URL built from a validated file ID,
+refuses redirects, and checks actual streamed bytes against `MaxExportBytes`
+(10 MiB). Google's export API also applies its own size limit. Files handed to
+the upload form use the chosen name with path separators removed and `.docx`
+or `.xlsx` appended. Never treat that name or MIME type as server validation.
+
+## Verification
+
+`go test ./googleimport` runs config/policy/template checks and the Node tests
+for fixed-origin export, bounded streaming, scope-independent response errors,
+and MIME/ID validation. `go test -tags browser ./googleimport` additionally
+exercises Chromium and WebKit through real headers, using controlled Google
+responses. Point `ESTILO_PLAYWRIGHT` at an installed Playwright package if it
+is not resolvable here. `ESTILO_BROWSERS` defaults to `chromium,webkit`.
+
+Mocked responses prove the integration's behavior, not real account consent.
+Before enabling a production origin, a person must connect a permitted Google
+account on the configured canary, select a real Google Doc and Sheet, verify
+their editable copies and omission reports, and retry after cancelling consent.
+Keep representative exports as regression fixtures only with permission to
+commit their contents. Real Google libraries were separately checked to load
+and create a Picker frame under the proposed CSP; that also is not proof of
+live consent or export with a real project.
+
+Google references: [token model](https://developers.google.com/identity/oauth2/web/guides/use-token-model),
+[Picker setup](https://developers.google.com/workspace/drive/picker/guides/web-picker),
+[exports](https://developers.google.com/workspace/drive/api/reference/rest/v3/files/export).
diff --git a/googleimport/browser_test.go b/googleimport/browser_test.go
new file mode 100644
index 0000000..f0c635e
--- /dev/null
+++ b/googleimport/browser_test.go
@@ -0,0 +1,80 @@
+//go:build browser
+
+package googleimport
+
+import (
+ "fmt"
+ "html/template"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/rastrillo/ui"
+)
+
+// TestChooserBrowser exercises the real module and multipart submission under
+// production-like headers. Google responses are controlled; this is not proof
+// of live Google consent, which needs the deployment's public configuration.
+func TestChooserBrowser(t *testing.T) {
+ tmpl := template.Must(template.New("root").Parse(Template()))
+ mux := http.NewServeMux()
+ mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Security-Policy", baseline)
+ if r.URL.Path != "/" {
+ http.NotFound(w, r)
+ return
+ }
+ if r.URL.Query().Get("disabled") != "1" {
+ if err := Headers(w, baseline); err != nil {
+ t.Error(err)
+ http.Error(w, "policy", 500)
+ return
+ }
+ }
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ fmt.Fprint(w, `<!doctype html><html><head><meta name="viewport" content="width=device-width"><link rel="stylesheet" href="/tokens.css"></head><body><form id="upload" method="post" action="/upload" enctype="multipart/form-data"><input name="creation_token" value="keep-this-token" type="hidden"><label for="file">File</label><input id="file" type="file" name="file" required><button type="submit">Import</button></form>`)
+ cfg := validConfig
+ if r.URL.Query().Get("disabled") == "1" {
+ cfg = Config{}
+ }
+ if err := tmpl.ExecuteTemplate(w, "estilo-google-import", View{Config: cfg, Kind: Docs, FormID: "upload", InputID: "file", Labels: Text("en")}); err != nil {
+ t.Error(err)
+ }
+ if cfg.Enabled() {
+ fmt.Fprintf(w, `<script type="module" src="/%s"></script>`, JSName())
+ }
+ fmt.Fprint(w, `</body></html>`)
+ })
+ mux.HandleFunc("/"+JSName(), func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/javascript")
+ w.Write(JS())
+ })
+ mux.HandleFunc("/tokens.css", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/css")
+ w.Write(ui.TokensCSS())
+ })
+ mux.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) {
+ b, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
+ if err != nil {
+ t.Error(err)
+ }
+ if strings.Contains(string(b), "test-google-bearer") || strings.Contains(r.URL.String(), "test-google-bearer") {
+ t.Error("Google token reached app")
+ }
+ if !strings.Contains(string(b), "keep-this-token") || !strings.Contains(string(b), `filename="Example.docx"`) || !strings.Contains(string(b), "fixture-export-bytes") {
+ t.Errorf("wrong multipart upload: %q", b)
+ }
+ fmt.Fprint(w, "Imported")
+ })
+ server := httptest.NewServer(mux)
+ defer server.Close()
+ cmd := exec.Command("node", "google-import.browser.mjs", server.URL)
+ cmd.Env = os.Environ()
+ if out, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("browser: %v\n%s", err, out)
+ }
+}
diff --git a/googleimport/google-import.browser.mjs b/googleimport/google-import.browser.mjs
new file mode 100644
index 0000000..85bd7a1
--- /dev/null
+++ b/googleimport/google-import.browser.mjs
@@ -0,0 +1,80 @@
+import { createRequire } from 'node:module'
+import assert from 'node:assert/strict'
+import { pathToFileURL } from 'node:url'
+const require = createRequire(import.meta.url)
+const playwright = process.env.ESTILO_PLAYWRIGHT
+ ? await import(pathToFileURL(process.env.ESTILO_PLAYWRIGHT + '/index.mjs'))
+ : require('playwright')
+const origin = process.argv[2]
+const gis = `window.google={accounts:{oauth2:{
+ initTokenClient(c){return {requestAccessToken(){window.requestCount=(window.requestCount||0)+1;
+ if(new URL(location).searchParams.has('popup')){c.error_callback({type:'popup_failed_to_open'});return}
+ if(new URL(location).searchParams.has('popup-closed')){c.error_callback({type:'popup_closed'});return}
+ setTimeout(()=>c.callback(new URL(location).searchParams.has('denied')?{error:'access_denied'}:{access_token:'test-google-bearer',scope:'https://www.googleapis.com/auth/drive.file'}),new URL(location).searchParams.has('slow-auth')?150:10)} }},
+ hasGrantedAllScopes(r,s){return r.scope===s}
+}}};`
+const gapi = `window.gapi={load(name,config){
+window.google.picker={Action:{CANCEL:'cancel',PICKED:'picked'},DocsView:class{setMimeTypes(s){return this}},
+PickerBuilder:class{setDeveloperKey(){return this}setAppId(){return this}setOAuthToken(){return this}setOrigin(){return this}addView(){return this}setCallback(fn){this.callback=fn;return this}
+build(){const cb=this.callback;let node;return{setVisible(){node=document.createElement('div');node.id='mock-picker';
+const pick=document.createElement('button');pick.textContent='Pick example';pick.onclick=()=>{const result={action:'picked',docs:[{id:'file_1',name:'Example',mimeType:new URL(location).searchParams.has('shortcut')?'application/vnd.google-apps.shortcut':'application/vnd.google-apps.document'}]};cb(result);if(new URL(location).searchParams.has('duplicate'))cb(result)};node.append(pick);
+const cancel=document.createElement('button');cancel.textContent='Cancel picker';cancel.onclick=()=>cb({action:'cancel'});node.append(cancel);document.body.append(node)},dispose(){node?.remove()}}}}}; config.callback()}};`
+
+for (const engine of (process.env.ESTILO_BROWSERS || 'chromium,webkit').split(',')) {
+ const browser = await playwright[engine].launch()
+ try {
+ const context = await browser.newContext({viewport:{width:320,height:700}})
+ const page = await context.newPage()
+ const violations = []
+ const errors = []
+ page.on('pageerror',e=>errors.push(e.message))
+ await page.addInitScript(()=>document.addEventListener('securitypolicyviolation',e=>console.log('CSP-VIOLATION:'+e.violatedDirective)))
+ page.on('console',m=>{if(m.text().startsWith('CSP-VIOLATION:'))violations.push(m.text())})
+ await context.route('https://accounts.google.com/gsi/client',route=>route.fulfill({contentType:'text/javascript',body:gis}))
+ await context.route('https://apis.google.com/js/api.js',route=>route.fulfill({contentType:'text/javascript',body:gapi}))
+ let exportMode = 'ok', calls=0
+ await context.route('https://www.googleapis.com/drive/v3/files/**',async route=>{
+ calls++
+ assert.equal(route.request().headers().authorization,'Bearer test-google-bearer')
+ assert(!route.request().url().includes('test-google-bearer'))
+ if(exportMode==='slow')await new Promise(r=>setTimeout(r,250))
+ await route.fulfill({status:exportMode==='error'?403:200,headers:{'Access-Control-Allow-Origin':'*'},
+ body:exportMode==='error'?'refused':'fixture-export-bytes'})
+ })
+ const choose=page.locator('[data-google-choose]'), status=page.locator('[data-google-status]')
+ const start=async query=>{const response=await page.goto(origin+query);assert(!response.headers()['cross-origin-opener-policy']);await choose.waitFor({state:'visible'});await page.waitForFunction(()=>!document.querySelector('[data-google-choose]').disabled)}
+ const select=async()=>{await choose.click();await page.getByText('Pick example',{exact:true}).click()}
+ await start('/'); await choose.focus(); await page.keyboard.press('Enter'); await page.getByText('Cancel picker',{exact:true}).click()
+ assert.match(await status.textContent(),/cancelled/)
+ assert.equal(await choose.isEnabled(),true)
+ assert.equal(calls,0)
+ await select(); await page.waitForURL(origin+'/upload'); assert.equal(await page.textContent('body'),'Imported')
+ assert.equal(calls,1)
+ await start('/?popup=1');await choose.click();assert.match(await status.textContent(),/popup/);assert(await choose.isEnabled())
+ await start('/?popup-closed=1');await choose.click();assert.match(await status.textContent(),/cancelled/);assert(await choose.isEnabled())
+ await page.locator('#file').setInputFiles({name:'previous.docx',mimeType:'application/octet-stream',buffer:Buffer.from('previous export')})
+ await page.evaluate(()=>dispatchEvent(new PageTransitionEvent('pageshow',{persisted:true})))
+ assert.equal(await page.locator('#file').evaluate(input=>input.files.length),0)
+ await start('/?denied=1');await choose.click();await page.waitForFunction(()=>document.querySelector('[data-google-status]').textContent.includes('did not allow'));assert(await choose.isEnabled())
+ await start('/?shortcut=1');await select();await page.waitForFunction(()=>document.querySelector('[data-google-status]').textContent.includes('could not be exported'));assert.equal(calls,1)
+ exportMode='error';await start('/');await select();await page.waitForFunction(()=>document.querySelector('[data-google-status]').textContent.includes('did not allow'));assert(await choose.isEnabled())
+ exportMode='ok';await select();await page.waitForURL(origin+'/upload');assert.equal(calls,3)
+ await start('/?slow-auth=1');await choose.click();await page.locator('[data-google-cancel]').click();await page.waitForTimeout(200)
+ assert.equal(await page.locator('#mock-picker').count(),0);assert.equal(calls,3);assert.match(await status.textContent(),/cancelled/)
+ await start('/?duplicate=1');await select();await page.waitForURL(origin+'/upload');assert.equal(calls,4)
+ exportMode='slow';await start('/');await select();await page.locator('[data-google-cancel]').click();await page.waitForTimeout(350)
+ assert.equal(page.url(),origin+'/');assert.match(await status.textContent(),/cancelled/);assert(await choose.isEnabled())
+ exportMode='ok'
+ await start('/');const box=await choose.boundingBox();assert(box.width>=24&&box.height>=24)
+ assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth))
+ assert.deepEqual(await page.evaluate(()=>({local:Object.keys(localStorage),session:Object.keys(sessionStorage)})),{local:[],session:[]})
+ await page.goto(origin+'/?disabled=1');assert.equal(await page.locator('[estilo-google-import]').count(),0)
+ assert.deepEqual(violations,[]);assert.deepEqual(errors,[])
+ const noJS=await browser.newContext({javaScriptEnabled:false});const plain=await noJS.newPage();await plain.goto(origin)
+ assert.equal(await plain.locator('[data-google-choose]').isVisible(),false)
+ assert.equal(await plain.locator('#file').isVisible(),true)
+ assert.match(await plain.locator('noscript').textContent(),/JavaScript/)
+ console.log(engine+': chooser, cancel, popup, denied scope, shortcut, export, retry, multipart, CSP, reflow and scriptless checks passed')
+ await noJS.close();await context.close()
+ } finally { await browser.close() }
+}
diff --git a/googleimport/google-import.mjs b/googleimport/google-import.mjs
new file mode 100644
index 0000000..e81d7ff
--- /dev/null
+++ b/googleimport/google-import.mjs
@@ -0,0 +1,178 @@
+// Google tokens exist only in this page's memory. The exported File is the only
+// thing passed to the app, through its ordinary multipart upload form.
+export const MAX_BYTES = 10 * 1024 * 1024
+const SCOPE = 'https://www.googleapis.com/auth/drive.file'
+const TYPES = {
+ docs: ['application/vnd.google-apps.document', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', '.docx'],
+ sheets: ['application/vnd.google-apps.spreadsheet', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', '.xlsx'],
+}
+let libraries
+
+function script(src) {
+ return new Promise((resolve, reject) => {
+ const tag = document.createElement('script')
+ const timer = setTimeout(() => { tag.remove(); reject(new Error('failed')) }, 15000)
+ tag.src = src
+ tag.onload = () => { clearTimeout(timer); resolve() }
+ tag.onerror = () => { clearTimeout(timer); tag.remove(); reject(new Error('failed')) }
+ document.head.append(tag)
+ })
+}
+
+function load() {
+ if (!libraries) libraries = Promise.all([
+ globalThis.google?.accounts?.oauth2 ? null : script('https://accounts.google.com/gsi/client'),
+ globalThis.gapi ? null : script('https://apis.google.com/js/api.js'),
+ ]).then(() => new Promise((resolve, reject) => {
+ gapi.load('picker', { callback: resolve, onerror: () => reject(new Error('failed')),
+ timeout: 15000, ontimeout: () => reject(new Error('failed')) })
+ })).catch(error => { libraries = null; throw error })
+ return libraries
+}
+
+export function selection(kind, item) {
+ const type = TYPES[kind]
+ if (!type || !item || item.mimeType !== type[0] || typeof item.id !== 'string' || !/^[a-zA-Z0-9_-]{1,256}$/.test(item.id)) throw new Error('unavailable')
+ const name = String(item.name || 'Import').replace(/[\\/\u0000-\u001f\u007f]/g, '_').slice(0, 200)
+ return { url: 'https://www.googleapis.com/drive/v3/files/' + item.id + '/export?mimeType=' + encodeURIComponent(type[1]),
+ name: name + type[2], mime: type[1] }
+}
+
+export async function download(kind, item, token, signal, fetcher = fetch) {
+ const selected = selection(kind, item)
+ const response = await fetcher(selected.url, { headers: { Authorization: 'Bearer ' + token },
+ credentials: 'omit', redirect: 'error', referrerPolicy: 'no-referrer', signal })
+ if (!response.ok) {
+ // Only inspect a bounded Google error code; never surface Google's raw text.
+ let reason = ''
+ if (response.body) {
+ const reader = response.body.getReader()
+ try {
+ let size = 0, body = '', decoder = new TextDecoder()
+ for (;;) {
+ const { done, value } = await reader.read()
+ if (done) break
+ size += value.byteLength
+ if (size > 16384) break
+ body += decoder.decode(value, { stream: true })
+ }
+ if (size <= 16384) {
+ try { reason = JSON.parse(body + decoder.decode()).error?.errors?.[0]?.reason || '' } catch {}
+ }
+ } finally { await reader.cancel() }
+ }
+ if (reason === 'exportSizeLimitExceeded' || response.status === 413) throw new Error('tooLarge')
+ throw new Error(response.status === 401 || response.status === 403 ? 'denied' : 'unavailable')
+ }
+ const declared = Number(response.headers.get('Content-Length'))
+ if (declared > MAX_BYTES) { await response.body?.cancel(); throw new Error('tooLarge') }
+ if (!response.body) throw new Error('failed')
+ const reader = response.body.getReader()
+ const chunks = []
+ let size = 0
+ try {
+ for (;;) {
+ const { done, value } = await reader.read()
+ if (done) break
+ size += value.byteLength
+ if (size > MAX_BYTES) throw new Error('tooLarge')
+ chunks.push(value)
+ }
+ } finally { await reader.cancel() }
+ if (!size) throw new Error('failed')
+ return new File(chunks, selected.name, { type: selected.mime })
+}
+
+export function mount(root) {
+ const data = root.dataset
+ const labels = JSON.parse(data.googleLabels)
+ const choose = root.querySelector('[data-google-choose]')
+ const cancel = root.querySelector('[data-google-cancel]')
+ const chooseWrap = root.querySelector('[data-google-choose-wrap]')
+ const cancelWrap = root.querySelector('[data-google-cancel-wrap]')
+ const status = root.querySelector('[data-google-status]')
+ const form = document.getElementById(data.googleForm)
+ const input = document.getElementById(data.googleInput)
+ if (!TYPES[data.googleKind] || !form || input?.form !== form || input.type !== 'file' ||
+ form.method.toLowerCase() !== 'post' || new URL(form.action).origin !== location.origin) return
+ let ready = false, active = false, generation = 0, picker = null, controller = null, timeout = null
+ const say = key => { status.textContent = labels[key] || labels.failed }
+ const reset = key => {
+ generation++
+ active = false
+ clearTimeout(timeout)
+ controller?.abort(); controller = null
+ picker?.dispose(); picker = null
+ choose.disabled = false
+ cancelWrap.hidden = true
+ root.removeAttribute('aria-busy')
+ if (key) say(key)
+ }
+ const initialize = async () => {
+ chooseWrap.hidden = false; choose.disabled = true; say('loading')
+ try { await load(); ready = true; say('ready') } catch { say('failed') }
+ choose.disabled = false
+ }
+ choose.addEventListener('click', () => {
+ if (active || document.prerendering) return
+ if (!ready) { initialize(); return } // Next click retains the popup's user gesture.
+ active = true
+ const attempt = ++generation
+ choose.disabled = true; cancelWrap.hidden = false; root.setAttribute('aria-busy', 'true'); say('connecting')
+ timeout = setTimeout(() => { if (attempt === generation) reset('failed') }, 120000)
+ try {
+ const client = google.accounts.oauth2.initTokenClient({ client_id: data.googleClient, scope: SCOPE,
+ include_granted_scopes: false,
+ error_callback: error => { if (attempt === generation) reset(error.type === 'popup_closed' ? 'cancelled' : 'failed') },
+ callback: response => {
+ if (attempt !== generation) return
+ if (response.error || !response.access_token || !google.accounts.oauth2.hasGrantedAllScopes(response, SCOPE)) { reset('denied'); return }
+ let token = response.access_token
+ let picked = false
+ clearTimeout(timeout)
+ try {
+ picker = new google.picker.PickerBuilder().setDeveloperKey(data.googleKey).setAppId(data.googleApp)
+ .setOAuthToken(token).setOrigin(location.origin)
+ .addView(new google.picker.DocsView().setMimeTypes(TYPES[data.googleKind][0]))
+ .setCallback(async result => {
+ if (attempt !== generation) { token = ''; return }
+ if (result.action === google.picker.Action.CANCEL && !picked) { token = ''; reset('cancelled'); choose.focus(); return }
+ if (result.action !== google.picker.Action.PICKED || picked) return
+ picked = true
+ picker?.dispose(); picker = null
+ controller = new AbortController()
+ const signal = controller.signal
+ timeout = setTimeout(() => controller?.abort(), 60000)
+ say('exporting')
+ try {
+ const file = await download(data.googleKind, result.docs?.[0], token, signal)
+ token = ''
+ if (attempt !== generation) return
+ clearTimeout(timeout)
+ const transfer = new DataTransfer()
+ transfer.items.add(file); input.files = transfer.files
+ if (!form.checkValidity()) { reset('ready'); form.reportValidity(); return }
+ form.requestSubmit()
+ } catch (error) {
+ token = ''
+ if (attempt === generation) reset(error.message in labels ? error.message : 'failed')
+ }
+ }).build()
+ picker.setVisible(true)
+ } catch { token = ''; reset('failed') }
+ },
+ })
+ client.requestAccessToken({ prompt: 'select_account' })
+ } catch { reset('failed') }
+ })
+ cancel.addEventListener('click', () => { reset('cancelled'); choose.focus() })
+ form.addEventListener('submit', () => { reset(); choose.disabled = true })
+ addEventListener('pagehide', () => reset())
+ addEventListener('pageshow', event => { if (event.persisted) { input.value = ''; reset('ready') } })
+ if (document.prerendering) document.addEventListener('prerenderingchange', initialize, { once: true })
+ else initialize()
+}
+
+if (typeof document !== 'undefined') {
+ for (const root of document.querySelectorAll('[estilo-google-import]')) mount(root)
+}
diff --git a/googleimport/google-import.test.mjs b/googleimport/google-import.test.mjs
new file mode 100644
index 0000000..6156673
--- /dev/null
+++ b/googleimport/google-import.test.mjs
@@ -0,0 +1,58 @@
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { selection, download, MAX_BYTES } from './google-import.mjs'
+
+const item = { id: 'chosen-file_123', name: '../A\\B', mimeType: 'application/vnd.google-apps.document' }
+test('selection only permits native file IDs on the fixed Google export origin', () => {
+ const chosen = selection('docs', item)
+ assert.equal(chosen.name, '.._A_B.docx')
+ assert.equal(new URL(chosen.url).origin, 'https://www.googleapis.com')
+ assert.equal(new URL(chosen.url).pathname, '/drive/v3/files/chosen-file_123/export')
+ for (const bad of [{...item,id:undefined},{...item,id:'../private'},{...item,id:'https://evil.test/x'},{...item,mimeType:'application/vnd.google-apps.shortcut'},null]) {
+ assert.throws(() => selection('docs',bad), /unavailable/)
+ }
+ assert.throws(() => selection('wrong',item))
+})
+
+test('export uses bearer header only, no credentials or redirects, and returns a File', async () => {
+ const signal = new AbortController().signal
+ let calls = 0
+ const file = await download('docs', item, 'private-token', signal, async (url, init) => {
+ calls++
+ assert(!url.includes('private-token'))
+ assert.equal(init.headers.Authorization, 'Bearer private-token')
+ assert.equal(init.credentials, 'omit')
+ assert.equal(init.redirect, 'error')
+ assert.equal(init.signal, signal)
+ return new Response(new Uint8Array([80,75,1,2]))
+ })
+ assert.equal(calls,1)
+ assert.equal(file.name,'.._A_B.docx')
+ assert.equal(file.size,4)
+ assert.equal(file.type,'application/vnd.openxmlformats-officedocument.wordprocessingml.document')
+})
+
+test('size limit is enforced on actual bytes even without or with a false Content-Length', async () => {
+ for (const headers of [{}, {'Content-Length':'1'}]) {
+ let cancelled = false
+ const stream = new ReadableStream({pull(c){c.enqueue(new Uint8Array(MAX_BYTES+1))},cancel(){cancelled=true}})
+ await assert.rejects(download('docs',item,'token',undefined,async()=>new Response(stream,{headers})), /tooLarge/)
+ assert(cancelled)
+ }
+ await assert.rejects(download('docs',item,'token',undefined,async()=>new Response('x',{headers:{'Content-Length':String(MAX_BYTES+1)}})),/tooLarge/)
+})
+
+test('Google error messages cannot leak through and split size refusals retain their meaning', async () => {
+ const body = JSON.stringify({error:{message:'secret document title',errors:[{reason:'exportSizeLimitExceeded'}]}})
+ const chunks = [body.slice(0,13),body.slice(13)]
+ const stream = new ReadableStream({start(c){ for(const s of chunks)c.enqueue(new TextEncoder().encode(s));c.close()}})
+ await assert.rejects(download('docs',item,'token',undefined,async()=>new Response(stream,{status:403})), /^Error: tooLarge$/)
+ for (const [status,code] of [[401,'denied'],[403,'denied'],[404,'unavailable'],[429,'unavailable'],[500,'unavailable']]) {
+ await assert.rejects(download('docs',item,'token',undefined,async()=>new Response('private data',{status})),new RegExp('^Error: '+code+'$'))
+ }
+ await assert.rejects(download('docs',item,'token',undefined,async()=>new Response('')),/^Error: failed$/)
+})
+
+test('an invalid selection is rejected before any network request', async () => {
+ await assert.rejects(download('docs',{...item,id:'foo/bar'},'token',undefined,()=>assert.fail('must not fetch')),/unavailable/)
+})
diff --git a/googleimport/googleimport.go b/googleimport/googleimport.go
new file mode 100644
index 0000000..f28f756
--- /dev/null
+++ b/googleimport/googleimport.go
@@ -0,0 +1,71 @@
+// Package googleimport supplies the optional Google Drive file chooser. Tokens
+// stay in the browser; selected exports use the caller's normal upload form.
+package googleimport
+
+import (
+ "crypto/sha256"
+ "embed"
+ "errors"
+ "fmt"
+ "io/fs"
+ "regexp"
+)
+
+const MaxExportBytes = 10 << 20
+
+type Kind string
+
+const (
+ Docs Kind = "docs"
+ Sheets Kind = "sheets"
+)
+
+// Config is public browser configuration, all from the same Google project.
+// No client secret or access/refresh token belongs here.
+type Config struct{ ClientID, APIKey, AppID string }
+
+func (c Config) Enabled() bool { return c.ClientID != "" && c.APIKey != "" && c.AppID != "" }
+
+var clientID = regexp.MustCompile(`^[0-9]+-[a-zA-Z0-9_-]+\.apps\.googleusercontent\.com$`)
+var apiKey = regexp.MustCompile(`^[a-zA-Z0-9_-]{20,100}$`)
+var appID = regexp.MustCompile(`^[0-9]{1,30}$`)
+
+func (c Config) Validate() error {
+ if c == (Config{}) {
+ return nil
+ }
+ if !c.Enabled() {
+ return errors.New("googleimport: client ID, API key and project number must be configured together")
+ }
+ if len(c.ClientID) > 256 || !clientID.MatchString(c.ClientID) || !apiKey.MatchString(c.APIKey) || !appID.MatchString(c.AppID) {
+ return errors.New("googleimport: invalid public Google configuration")
+ }
+ return nil
+}
+
+// View attaches to an existing same-origin multipart form and its file input.
+// The app owns the surrounding fidelity note, upload handler and import report.
+type View struct {
+ Config Config
+ Kind Kind
+ FormID, InputID string
+ Labels Labels
+}
+
+func (v View) Enabled() bool {
+ return v.Config.Enabled() && v.Config.Validate() == nil && (v.Kind == Docs || v.Kind == Sheets)
+}
+
+//go:embed templates/*.html
+var templates embed.FS
+
+//go:embed google-import.mjs
+var javascript []byte
+
+func Templates() fs.FS { return templates }
+func Template() string { b, _ := templates.ReadFile("templates/google-import.html"); return string(b) }
+func JS() []byte { return append([]byte(nil), javascript...) }
+func JSName() string {
+ h := sha256.Sum256(javascript)
+ return fmt.Sprintf("google-import.%x.mjs", h[:8])
+}
diff --git a/googleimport/googleimport_test.go b/googleimport/googleimport_test.go
new file mode 100644
index 0000000..a8f0794
--- /dev/null
+++ b/googleimport/googleimport_test.go
@@ -0,0 +1,121 @@
+package googleimport
+
+import (
+ "bytes"
+ "html/template"
+ "net/http/httptest"
+ "os/exec"
+ "reflect"
+ "strings"
+ "testing"
+)
+
+var validConfig = Config{"123456789-client.apps.googleusercontent.com", "AIzaPublicBrowserKey123456789", "123456789"}
+
+const baseline = "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'self'; form-action 'self'"
+
+func TestConfiguration(t *testing.T) {
+ if (Config{}).Validate() != nil || (Config{}).Enabled() {
+ t.Fatal("unset must be disabled")
+ }
+ if validConfig.Validate() != nil || !validConfig.Enabled() {
+ t.Fatal("valid public config")
+ }
+ for _, c := range []Config{{ClientID: validConfig.ClientID}, {ClientID: validConfig.ClientID, APIKey: validConfig.APIKey}, {"123.foo", validConfig.APIKey, "123"}, {validConfig.ClientID, "key\nheader", "123"}, {validConfig.ClientID, validConfig.APIKey, "project-name"}} {
+ if c.Validate() == nil {
+ t.Fatal("accepted malformed or partial config")
+ }
+ }
+}
+
+func TestPolicyOnlyExpandsGoogleSources(t *testing.T) {
+ policy, err := Policy(baseline)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.HasPrefix(policy, baseline+";") {
+ t.Fatalf("changed existing policy: %s", policy)
+ }
+ for _, want := range []string{"script-src 'self' https://accounts.google.com https://apis.google.com", "frame-src 'self' https://accounts.google.com https://docs.google.com", "connect-src 'self' https://accounts.google.com https://apis.google.com https://www.googleapis.com"} {
+ if !strings.Contains(policy, want) {
+ t.Fatal("missing", want)
+ }
+ }
+ if strings.Contains(policy, "unsafe-eval") || strings.Contains(policy, "*") {
+ t.Fatal("unbounded policy")
+ }
+ strict, err := Policy("default-src 'none'; script-src-elem 'none'")
+ if err != nil || !strings.Contains(strict, "script-src 'self' https://accounts.google.com") || !strings.Contains(strict, "script-src-elem 'self' https://accounts.google.com") {
+ t.Fatal("chooser's own module must be allowed", strict, err)
+ }
+ p, err := Policy(baseline + "; child-src 'none'; script-src-elem 'self'")
+ if err != nil || !strings.Contains(p, "frame-src https://accounts.google.com https://docs.google.com") || !strings.Contains(p, "script-src-elem 'self' https://accounts.google.com") {
+ t.Fatal(p, err)
+ }
+ for _, bad := range []string{"", "script-src 'self'", baseline + ", default-src *", baseline + "; DEFAULT-SRC *", baseline + "\r\n"} {
+ if _, err := Policy(bad); err == nil {
+ t.Fatal("accepted ambiguous policy")
+ }
+ }
+ w := httptest.NewRecorder()
+ w.Header().Set("Content-Security-Policy", baseline)
+ if err := Headers(w, baseline); err != nil {
+ t.Fatal(err)
+ }
+ if got := w.Header().Values("Content-Security-Policy"); len(got) != 1 || got[0] != policy {
+ t.Fatal(got)
+ }
+ if w.Header().Get("Cross-Origin-Opener-Policy") != "" || w.Header().Get("Cache-Control") != "no-store" {
+ t.Fatal(w.Header())
+ }
+ w.Header().Add("Content-Security-Policy", "default-src 'none'")
+ if Headers(w, baseline) == nil {
+ t.Fatal("multiple policies were replaced")
+ }
+}
+
+func TestTemplateAndTwelveLocales(t *testing.T) {
+ tmpl, err := template.New("root").ParseFS(Templates(), "templates/*.html")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(messages) != 12 {
+ t.Fatal("all twelve locales required")
+ }
+ for locale, labels := range messages {
+ for i := range reflect.ValueOf(labels).NumField() {
+ if reflect.ValueOf(labels).Field(i).String() == "" {
+ t.Fatal(locale, "missing label", i)
+ }
+ }
+ var buf bytes.Buffer
+ v := View{Config: validConfig, Kind: Docs, FormID: `bad" onclick="evil()`, InputID: "file", Labels: labels}
+ if err := tmpl.ExecuteTemplate(&buf, "estilo-google-import", v); err != nil {
+ t.Fatal(err)
+ }
+ html := buf.String()
+ if strings.Contains(html, ` onclick="evil()`) || strings.Contains(html, "<script") || !strings.Contains(html, "data-google-choose-wrap hidden") || !strings.Contains(html, "<noscript>") {
+ t.Fatal(locale, html)
+ }
+ v.Config = Config{}
+ buf.Reset()
+ if err := tmpl.ExecuteTemplate(&buf, "estilo-google-import", v); err != nil || strings.TrimSpace(buf.String()) != "" {
+ t.Fatal("disabled rendered", err)
+ }
+ }
+ if Text("zz") != Text("en") || Text("pt-BR") != Text("pt") {
+ t.Fatal("locale fallback")
+ }
+ a := JS()
+ a[0] = '!'
+ if bytes.Equal(a, JS()) || !strings.HasSuffix(JSName(), ".mjs") {
+ t.Fatal("asset mutability/name")
+ }
+}
+
+func TestBrowserModuleLogic(t *testing.T) {
+ out, err := exec.Command("node", "--test", "google-import.test.mjs").CombinedOutput()
+ if err != nil {
+ t.Fatalf("node: %v\n%s", err, out)
+ }
+}
diff --git a/googleimport/labels.go b/googleimport/labels.go
new file mode 100644
index 0000000..a6969d9
--- /dev/null
+++ b/googleimport/labels.go
@@ -0,0 +1,49 @@
+package googleimport
+
+import (
+ "encoding/json"
+ "strings"
+)
+
+// Labels are caller-overridable; Text supplies the suite's twelve base locales.
+type Labels struct {
+ Choose string `json:"choose"`
+ Cancel string `json:"cancel"`
+ Loading string `json:"loading"`
+ Ready string `json:"ready"`
+ Connecting string `json:"connecting"`
+ Exporting string `json:"exporting"`
+ Failed string `json:"failed"`
+ Cancelled string `json:"cancelled"`
+ Denied string `json:"denied"`
+ TooLarge string `json:"tooLarge"`
+ Unavailable string `json:"unavailable"`
+ NoScript string `json:"noScript"`
+ Disclosure string `json:"disclosure"`
+}
+
+func (l Labels) JSON() string { b, _ := json.Marshal(l); return string(b) }
+
+// Text falls back to English, including for apps without locale plumbing yet.
+func Text(locale string) Labels {
+ base := strings.ToLower(strings.Split(strings.ReplaceAll(locale, "_", "-"), "-")[0])
+ if l, ok := messages[base]; ok {
+ return l
+ }
+ return messages["en"]
+}
+
+var messages = map[string]Labels{
+ "en": {"Choose from Google Drive", "Cancel", "Loading Google Drive…", "Choose a file from Google Drive.", "Connecting to Google…", "Preparing your file…", "Google Drive could not connect. Try again, allowing the Google popup.", "Import cancelled. You can choose another file.", "Google did not allow this export. Choose again and grant access to the file.", "Google cannot export this file within the import size limit. Try a smaller file.", "This file could not be exported. Choose a Google document or spreadsheet you can download; if this persists, ask your administrator to check the Google setup.", "Google Drive needs JavaScript. You can download a file from Google and upload it using the form.", "Connect to Google to choose one file. Oficina imports a copy and leaves your Google original unchanged. This page contacts Google; it does not save your Google access token."},
+ "de": {"Aus Google Drive auswählen", "Abbrechen", "Google Drive wird geladen…", "Wählen Sie eine Datei aus Google Drive.", "Verbindung mit Google…", "Datei wird vorbereitet…", "Google Drive konnte keine Verbindung herstellen. Versuchen Sie es erneut und erlauben Sie das Google-Popup.", "Import abgebrochen. Sie können eine andere Datei auswählen.", "Google hat den Export nicht erlaubt. Wählen Sie erneut und erlauben Sie den Dateizugriff.", "Die Datei überschreitet das Importlimit von Google. Versuchen Sie eine kleinere Datei.", "Die Datei konnte nicht exportiert werden. Wählen Sie ein herunterladbares Google-Dokument oder eine Tabelle. Bleibt das Problem bestehen, lassen Sie die Google-Konfiguration prüfen.", "Google Drive benötigt JavaScript. Sie können eine Datei bei Google herunterladen und mit dem Formular hochladen.", "Verbinden Sie sich mit Google, um eine Datei auszuwählen. Oficina importiert eine Kopie; das Original bleibt unverändert. Diese Seite kontaktiert Google und speichert Ihr Google-Zugriffstoken nicht."},
+ "es": {"Elegir de Google Drive", "Cancelar", "Cargando Google Drive…", "Elige un archivo de Google Drive.", "Conectando con Google…", "Preparando el archivo…", "No se pudo conectar con Google Drive. Inténtalo de nuevo y permite la ventana emergente de Google.", "Importación cancelada. Puedes elegir otro archivo.", "Google no permitió exportar. Elige de nuevo y concede acceso al archivo.", "El archivo supera el límite de importación de Google. Prueba con uno más pequeño.", "No se pudo exportar. Elige un documento o una hoja de Google que puedas descargar. Si persiste, pide que revisen la configuración de Google.", "Google Drive necesita JavaScript. Puedes descargar un archivo de Google y subirlo con el formulario.", "Conecta con Google para elegir un archivo. Oficina importa una copia y deja el original sin cambios. Esta página contacta con Google; no guarda tu token de acceso."},
+ "fr": {"Choisir dans Google Drive", "Annuler", "Chargement de Google Drive…", "Choisissez un fichier dans Google Drive.", "Connexion à Google…", "Préparation du fichier…", "Connexion à Google Drive impossible. Réessayez en autorisant la fenêtre Google.", "Importation annulée. Vous pouvez choisir un autre fichier.", "Google a refusé l’exportation. Choisissez à nouveau et autorisez l’accès au fichier.", "Ce fichier dépasse la limite d’importation de Google. Essayez un fichier plus petit.", "Exportation impossible. Choisissez un document ou une feuille Google téléchargeable. Si le problème persiste, faites vérifier la configuration Google.", "Google Drive nécessite JavaScript. Vous pouvez télécharger un fichier depuis Google et l’importer avec le formulaire.", "Connectez-vous à Google pour choisir un fichier. Oficina importe une copie et laisse l’original intact. Cette page contacte Google sans enregistrer votre jeton d’accès."},
+ "it": {"Scegli da Google Drive", "Annulla", "Caricamento di Google Drive…", "Scegli un file da Google Drive.", "Connessione a Google…", "Preparazione del file…", "Impossibile connettersi a Google Drive. Riprova consentendo la finestra popup di Google.", "Importazione annullata. Puoi scegliere un altro file.", "Google non ha consentito l’esportazione. Scegli di nuovo e autorizza l’accesso al file.", "Il file supera il limite di importazione di Google. Prova un file più piccolo.", "Impossibile esportare. Scegli un documento o un foglio Google scaricabile. Se il problema persiste, chiedi di verificare la configurazione Google.", "Google Drive richiede JavaScript. Puoi scaricare un file da Google e caricarlo con il modulo.", "Connettiti a Google per scegliere un file. Oficina importa una copia e lascia invariato l’originale. Questa pagina contatta Google senza salvare il token di accesso."},
+ "pt": {"Escolher do Google Drive", "Cancelar", "A carregar o Google Drive…", "Escolha um ficheiro do Google Drive.", "A ligar ao Google…", "A preparar o ficheiro…", "Não foi possível ligar ao Google Drive. Tente novamente e permita a janela do Google.", "Importação cancelada. Pode escolher outro ficheiro.", "O Google não permitiu a exportação. Escolha novamente e autorize o acesso ao ficheiro.", "O ficheiro excede o limite de importação do Google. Tente um ficheiro mais pequeno.", "Não foi possível exportar. Escolha um documento ou folha Google que possa transferir. Se persistir, peça para verificarem a configuração do Google.", "O Google Drive precisa de JavaScript. Pode transferir um ficheiro do Google e carregá-lo através do formulário.", "Ligue-se ao Google para escolher um ficheiro. A Oficina importa uma cópia e mantém o original intacto. Esta página contacta o Google sem guardar o seu token de acesso."},
+ "nl": {"Kiezen uit Google Drive", "Annuleren", "Google Drive laden…", "Kies een bestand uit Google Drive.", "Verbinden met Google…", "Bestand voorbereiden…", "Verbinding met Google Drive mislukt. Probeer opnieuw en sta de Google-pop-up toe.", "Import geannuleerd. Je kunt een ander bestand kiezen.", "Google heeft de export geweigerd. Kies opnieuw en geef toegang tot het bestand.", "Het bestand overschrijdt de importlimiet van Google. Probeer een kleiner bestand.", "Export mislukt. Kies een Google-document of spreadsheet dat je kunt downloaden. Laat bij aanhoudende problemen de Google-instellingen controleren.", "Google Drive heeft JavaScript nodig. Je kunt een bestand van Google downloaden en via het formulier uploaden.", "Verbind met Google om één bestand te kiezen. Oficina importeert een kopie en laat het origineel ongewijzigd. Deze pagina maakt contact met Google en slaat je toegangstoken niet op."},
+ "pl": {"Wybierz z Dysku Google", "Anuluj", "Ładowanie Dysku Google…", "Wybierz plik z Dysku Google.", "Łączenie z Google…", "Przygotowywanie pliku…", "Nie udało się połączyć z Dyskiem Google. Spróbuj ponownie i zezwól na wyskakujące okno Google.", "Import anulowany. Możesz wybrać inny plik.", "Google odmówił eksportu. Wybierz ponownie i udziel dostępu do pliku.", "Plik przekracza limit importu Google. Spróbuj z mniejszym plikiem.", "Nie udało się wyeksportować. Wybierz dokument lub arkusz Google, który można pobrać. Jeśli problem się powtarza, poproś o sprawdzenie konfiguracji Google.", "Dysk Google wymaga JavaScript. Możesz pobrać plik z Google i przesłać go za pomocą formularza.", "Połącz się z Google, aby wybrać jeden plik. Oficina importuje kopię i pozostawia oryginał bez zmian. Ta strona łączy się z Google, ale nie zapisuje tokenu dostępu."},
+ "ar": {"اختيار من Google Drive", "إلغاء", "جارٍ تحميل Google Drive…", "اختر ملفًا من Google Drive.", "جارٍ الاتصال بـ Google…", "جارٍ تجهيز الملف…", "تعذر الاتصال بـ Google Drive. حاول مجددًا واسمح لنافذة Google بالظهور.", "أُلغي الاستيراد. يمكنك اختيار ملف آخر.", "لم يسمح Google بالتصدير. اختر مجددًا وامنح الإذن بالوصول إلى الملف.", "يتجاوز الملف حد الاستيراد لدى Google. جرّب ملفًا أصغر.", "تعذر تصدير الملف. اختر مستندًا أو جدول بيانات من Google يمكنك تنزيله. إذا استمرت المشكلة، اطلب مراجعة إعدادات Google.", "يتطلب Google Drive تفعيل JavaScript. يمكنك تنزيل ملف من Google ورفعه باستخدام النموذج.", "اتصل بـ Google لاختيار ملف واحد. تستورد Oficina نسخة وتترك الملف الأصلي دون تغيير. تتصل هذه الصفحة بـ Google ولا تحفظ رمز الوصول."},
+ "ja": {"Google ドライブから選択", "キャンセル", "Google ドライブを読み込み中…", "Google ドライブからファイルを選んでください。", "Google に接続中…", "ファイルを準備中…", "Google ドライブに接続できませんでした。Google のポップアップを許可して再試行してください。", "インポートをキャンセルしました。別のファイルを選べます。", "Google がエクスポートを許可しませんでした。再度選択してファイルへのアクセスを許可してください。", "ファイルが Google のインポート上限を超えています。小さいファイルをお試しください。", "エクスポートできませんでした。ダウンロード可能な Google ドキュメントまたはスプレッドシートを選んでください。問題が続く場合は管理者に設定の確認を依頼してください。", "Google ドライブには JavaScript が必要です。Google からファイルをダウンロードし、フォームでアップロードすることもできます。", "Google に接続してファイルを1つ選択します。Oficina はコピーをインポートし、元のファイルは変更しません。このページは Google に接続しますが、アクセストークンを保存しません。"},
+ "zh": {"从 Google 云端硬盘选择", "取消", "正在加载 Google 云端硬盘…", "请选择 Google 云端硬盘中的文件。", "正在连接 Google…", "正在准备文件…", "无法连接 Google 云端硬盘。请允许 Google 弹出窗口后重试。", "导入已取消。您可以选择其他文件。", "Google 未允许导出。请重新选择并授予文件访问权限。", "文件超出 Google 导入大小限制。请尝试较小的文件。", "无法导出文件。请选择可下载的 Google 文档或表格。如果问题持续,请联系管理员检查 Google 配置。", "Google 云端硬盘需要 JavaScript。您也可以从 Google 下载文件,然后通过表单上传。", "连接 Google 以选择一个文件。Oficina 会导入副本,不会修改原始文件。此页面会连接 Google,但不会保存您的访问令牌。"},
+ "ko": {"Google Drive에서 선택", "취소", "Google Drive 로딩 중…", "Google Drive에서 파일을 선택하세요.", "Google에 연결 중…", "파일 준비 중…", "Google Drive에 연결할 수 없습니다. Google 팝업을 허용한 후 다시 시도하세요.", "가져오기가 취소되었습니다. 다른 파일을 선택할 수 있습니다.", "Google이 내보내기를 허용하지 않았습니다. 다시 선택하고 파일 접근을 허용하세요.", "파일이 Google 가져오기 크기 제한을 초과합니다. 더 작은 파일을 시도하세요.", "파일을 내보낼 수 없습니다. 다운로드할 수 있는 Google 문서 또는 스프레드시트를 선택하세요. 문제가 계속되면 관리자에게 Google 설정 확인을 요청하세요.", "Google Drive에는 JavaScript가 필요합니다. Google에서 파일을 다운로드한 후 양식으로 업로드할 수도 있습니다.", "Google에 연결하여 파일 하나를 선택합니다. Oficina는 사본을 가져오며 원본은 변경하지 않습니다. 이 페이지는 Google에 연결하지만 접근 토큰을 저장하지 않습니다."},
+}
diff --git a/googleimport/policy.go b/googleimport/policy.go
new file mode 100644
index 0000000..b63dabe
--- /dev/null
+++ b/googleimport/policy.go
@@ -0,0 +1,81 @@
+package googleimport
+
+import (
+ "errors"
+ "net/http"
+ "strings"
+)
+
+// Policy extends one app policy for its import page. It never relaxes form
+// targets, framing protection, base URLs, inline scripts or eval. Multiple
+// policies/duplicate directives are refused rather than ambiguously merged.
+func Policy(base string) (string, error) {
+ if strings.ContainsAny(base, ",\r\n") {
+ return "", errors.New("googleimport: expected one content security policy")
+ }
+ order := []string{}
+ directives := map[string][]string{}
+ for _, part := range strings.Split(base, ";") {
+ fields := strings.Fields(part)
+ if len(fields) == 0 {
+ continue
+ }
+ name := strings.ToLower(fields[0])
+ if _, exists := directives[name]; exists {
+ return "", errors.New("googleimport: duplicate policy directive")
+ }
+ order = append(order, name)
+ directives[name] = fields[1:]
+ }
+ if len(directives["default-src"]) == 0 {
+ return "", errors.New("googleimport: policy needs default-src")
+ }
+ add := func(name string, sources ...string) {
+ values, exists := directives[name]
+ if !exists {
+ order = append(order, name)
+ fallback := directives["default-src"]
+ if name == "frame-src" && len(directives["child-src"]) > 0 {
+ fallback = directives["child-src"]
+ }
+ values = append([]string(nil), fallback...)
+ }
+ out := []string{}
+ seen := map[string]bool{}
+ for _, source := range append(values, sources...) {
+ if source != "'none'" && !seen[source] {
+ seen[source] = true
+ out = append(out, source)
+ }
+ }
+ directives[name] = out
+ }
+ // The chooser module is served by the app itself, even if its original
+ // policy disallowed scripts entirely.
+ add("script-src", "'self'", "https://accounts.google.com", "https://apis.google.com")
+ if _, exists := directives["script-src-elem"]; exists {
+ add("script-src-elem", "'self'", "https://accounts.google.com", "https://apis.google.com")
+ }
+ add("connect-src", "https://accounts.google.com", "https://apis.google.com", "https://www.googleapis.com")
+ add("frame-src", "https://accounts.google.com", "https://docs.google.com")
+ parts := make([]string, 0, len(order))
+ for _, name := range order {
+ parts = append(parts, strings.Join(append([]string{name}, directives[name]...), " "))
+ }
+ return strings.Join(parts, "; "), nil
+}
+
+// Headers must run before rendering the opted-in import page, including a
+// refused upload re-render. base is the app's existing policy constant.
+func Headers(w http.ResponseWriter, base string) error {
+ if len(w.Header().Values("Content-Security-Policy")) > 1 {
+ return errors.New("googleimport: multiple content security policies")
+ }
+ policy, err := Policy(base)
+ if err != nil {
+ return err
+ }
+ w.Header().Set("Content-Security-Policy", policy)
+ w.Header().Set("Cache-Control", "no-store")
+ return nil
+}
diff --git a/googleimport/templates/google-import.html b/googleimport/templates/google-import.html
new file mode 100644
index 0000000..d53598f
--- /dev/null
+++ b/googleimport/templates/google-import.html
@@ -0,0 +1,9 @@
+{{define "estilo-google-import"}}{{if .Enabled}}
+<div estilo-google-import data-google-kind="{{.Kind}}" data-google-client="{{.Config.ClientID}}" data-google-key="{{.Config.APIKey}}" data-google-app="{{.Config.AppID}}" data-google-form="{{.FormID}}" data-google-input="{{.InputID}}" data-google-labels="{{.Labels.JSON}}">
+<p>{{.Labels.Disclosure}}</p>
+<span data-google-choose-wrap hidden><button rst-btn type="button" data-google-choose>{{.Labels.Choose}}</button></span>
+<span data-google-cancel-wrap hidden><button rst-btn type="button" data-google-cancel>{{.Labels.Cancel}}</button></span>
+<p data-google-status role="status" aria-live="polite"></p>
+<noscript><p>{{.Labels.NoScript}}</p></noscript>
+</div>
+{{end}}{{end}}
diff --git a/implementation/google-drive-import.md b/implementation/google-drive-import.md
new file mode 100644
index 0000000..2c8117a
--- /dev/null
+++ b/implementation/google-drive-import.md
@@ -0,0 +1,169 @@
+# Google Drive import, first slice
+
+2026-11-01. Requested by Paul: connect Google Drive, choose Docs and Sheets,
+import useful editable copies, and improve formatting fidelity incrementally.
+Status: reviewed by Claude Fable 5.1 (claude-fable-5-1), 2026-11-01;
+implementation permitted with B1–B5/R1–R5 corrections, incorporated below.
+Corrected spec APPROVED by the same reviewer on 2026-11-01, separately from
+the initial changes-required verdict. Implementation is authorized by the conversation.
+
+## Outcome
+
+Each app has an Import from Google Drive action on its import page. A person
+connects their Google account, chooses one file, and imports a new Oficina copy.
+The original stays in Google Drive. This is a one-time copy, with no sync,
+automatic sharing migration, or background access to Google.
+
+Google integration is optional, configured per deployment with a public OAuth
+web client ID, Picker API key and Google Cloud project number. All three must
+be set together; unset leaves normal app use and file imports available.
+The setup guide records API enablement, exact authorized JavaScript origins,
+API key restrictions, consent-screen/test-user setup and production publishing.
+The project number must belong to the OAuth client's project and is passed to
+Picker.setAppId; a mismatch can cause export to answer 404. drive.file is a
+non-sensitive scope; follow the console's publishing and branding requirements,
+and explicitly list test users while the OAuth app is in Testing.
+No client secret or refresh token is required. The API key is public browser
+configuration, restricted in Google Cloud, never described as a secret.
+
+## Transport and ownership
+
+Use Google's supported GIS browser token model and Google Picker with only
+drive.file scope and a view filtered to the app's Google-native file MIME type.
+Google authorization is separate from Oficina sign-in and grants no Oficina
+membership. Require the existing signed-in create permission on every import
+endpoint and recheck membership at the write. Never derive membership from
+the Google account address.
+
+The short-lived access token lives only in the import page's memory. Use it
+to export the selected native Google file through Google's fixed Drive API
+origin (Docs as DOCX, Sheets as XLSX). Validate selected IDs and MIME types;
+never fetch a URL supplied by Picker, a document, or a request parameter.
+Fetch with Authorization header, never a query token. Reject shortcut selections
+even if the view was MIME-filtered. Bound exported response bytes at 10 MiB and
+use AbortController timeouts. Google's own export-size refusal has a distinct
+actionable message. Name the File from the selected name with path separators
+removed and always append .docx/.xlsx. Transfer the resulting File through the
+normal same-origin multipart upload form; server limits and validation remain
+authoritative. No Google tokens go to Oficina, storage, logs or error text.
+Cancellation, blocked popups, denied scopes, expired credentials, export
+refusals/limits, networking failures and picker-load failures leave a usable
+retry action and no new document. Do not expose Google's raw errors.
+
+Shared browser behavior and public configuration validation live in Estilo's
+googleimport package, built for the Docs integration and then adopted by
+Sheets. Render strings come from a twelve-locale catalog; app-specific copy
+describes the import fidelity. JavaScript is required for Google Picker;
+ordinary file upload remains the scriptless path.
+
+Load Google scripts only on the opted-in import page. Extend CSP only on
+that page for the specific Google script, frame and connection origins needed;
+retain form-action self, frame-ancestors none and base-uri self. Derive it from
+the app's existing policy, set one CSP header, and extend the policy drift tests.
+Preserve the existing app policy elsewhere. No wildcard origins or unsafe-eval.
+The apps set no COOP header; do not add one, and test that it remains absent. Document
+the disclosed Google connection on the page and in operator documentation.
+
+## Docs conversion
+
+Add GET /import and POST /import to Docs' signed-in group, guarded by
+requireMemberRequest. Add a dedicated import template, ordinary scriptless
+multipart form, 10 MiB file cap plus multipart framing slack, .docx extension
+check and ZIP validation. Use MultipartReader without disk spill. Docs'
+app-specific copy uses its existing English catalog; the shared chooser has
+twelve locales.
+
+Replace the existing paragraph/font reader with a bounded token walk that
+preserves nested text in hyperlink, table/row/cell, insertion, sdt and smartTag
+containers. Omit deletion text and report it; honour w:val on bold/italic toggles.
+Map tabs and line breaks to spaces or paragraph breaks and report normalization.
+Count XML depth explicitly; encoding/xml does not enforce it on our behalf.
+Preserve paragraph text, headings, bold and italic, and supported fonts/sizes.
+Unsupported links retain their visible text; the first slice does not invent
+a clickable-link feature missing from the editor. Lists and table cells retain
+their text in reading order as paragraphs. Report lost structure/formatting
+and omitted non-text content, headers/footers, comments and tracked changes.
+Reject malformed/empty-only unsupported documents with an actionable error.
+Bound ZIP entries, total uncompressed data, XML depth and text/output size;
+never extract to disk, fetch external relationships, or log source content.
+
+Produce a genuine Yjs document using a bounded builder in the existing Rust
+yrs core (ABI version 5), not a second handwritten Yjs wire encoder. Go passes
+only the closed set of supported paragraph/heading/text/mark operations; validate
+the entire input before writing to a fresh handle. Replay the generated update
+in a second handle and compare its rendered structure with the converter's
+intended structure before saving. Test compatibility with the editor's own
+y-prosemirror bridge; opening the import must not cause schema-cleanup edits.
+This keeps ordinary file upload usable with JavaScript disabled. Creation
+and content publication use one CreateImported transaction: document row,
+sealed initial update and sealed report, with membership checked inside it,
+creation-token idempotence and a distinct report contentAAD kind byte. Cancellation or conversion/write failure
+must not publish an empty or partial document. Persist import report codes
+and coordinates with the created document under existing encryption rules;
+show the report on arrival, with a way to reopen it. No report may imply full
+fidelity. Preserve the existing sharing default for new documents.
+
+## Sheets conversion
+
+Reuse the existing XLSX job lifecycle and hidden-until-success sheet creation.
+For this slice explicitly import only the first worksheet, because the current
+UI has no tab switching (Sheets spec deferral). State this before import and
+report how many worksheets were omitted. Preserve existing supported values
+and formatting. Unsupported formulas must fall back to an available cached
+value and be reported by coordinate; never silently turn a value into a broken
+formula. Google's __xludf.DUMMYFUNCTION wrappers (even within IFERROR), array
+formulas, qualified sheet references and external references are unsupported.
+A bounded ZIP/XML scan of the first worksheet verifies actual cached <v>
+presence, agreeing with excelize's formula cells: finite numeric n, boolean
+exactly 0/1, or string str (empty allowed). Missing caches, cached errors and
+unexpected cached types refuse the import. Known formulas remain formulas;
+report differences from saved values, using a relative numeric tolerance.
+
+Preserve typed text, including strings beginning with '=' or looking like
+numbers. Ambiguous strings, including empty strings and TRUE/FALSE/NaN/Inf,
+become constant string expressions ="..." with doubled quotes through the
+existing parser, reported by coordinate; refuse wrapped input over 8 KiB.
+No new apostrophe semantics or input codec; existing records keep their meaning.
+If no trustworthy cached value exists, flag the affected coordinate
+and refuse that import rather than manufacture a value. Cross-sheet references
+are unsupported in a single-worksheet import, even if the evaluator parses them.
+Any additional supported-formula fidelity cannot be claimed without fixtures.
+
+Persist a report attached to the sheet using the sealed-content conventions;
+show it at completion and allow reopening. Report unsupported charts, images,
+merges, comments, validation and layout where detectable, with an always-visible
+statement of the supported subset. Data and filenames never enter logs.
+
+## Proof and release
+
+Tests cover actual converted text/marks/cell values and omission reports,
+ZIP/resource limits, malicious link targets, unknown formulas and missing
+caches, permission/CSRF refusal, failed imports not appearing, and sealed-at-rest
+storage including SQLite WAL. Browser tests exercise picker/token/export success
+and failure with controlled Google responses; run through production headers.
+Check keyboard use, cancellation, retry, 320px reflow and scriptless upload.
+
+Repository review rules apply to this spec and to each final branch. Work in
+isolated worktrees and push reviewable commits. Complete local/CI checks before
+shipping; real Google OAuth verification additionally needs configured Google
+Cloud credentials and a person exercising consent on an authorized origin.
+Never call a mocked Google test proof of live consent. Until real verification,
+keep Google configuration off on production and report the remaining setup.
+
+## Later fidelity, with triggers
+
+- More Docx structure and clickable links: editor support and a representative
+ failing fixture exist; promote each fixture into the regression corpus.
+- Additional worksheets: the Sheets UI can create, name and switch tabs.
+- Multiple selected files: single-file imports are reliable and batch progress,
+ cancellation and per-file retry have a defined lifecycle.
+- Google comments, permissions, history and ongoing sync: separately requested
+ product work with explicit ownership semantics.
+
+## References
+
+- https://developers.google.com/identity/oauth2/web/guides/use-token-model
+- https://developers.google.com/workspace/drive/picker/guides/overview
+- https://developers.google.com/workspace/drive/api/guides/ref-export-formats
+- https://developers.google.com/workspace/drive/api/reference/rest/v3/files/export
+- Docs design section 11.2; Sheets design sections 11 and 14.