diff --git a/src/App.svelte b/src/App.svelte index b032f8e..82b38f4 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -13,6 +13,7 @@ import { supportsFsAccess, saveOdt, saveAsOdt, saveDocx, saveAsDocx, saveAsTemplate, openOdt } from './lib/export/saveFile'; import { loadRecentFiles, rememberRecentFile, readRecentFile, forgetRecentFile, forgetRecentFiles, pruneRecentFiles, type RecentFile } from './lib/storage/recentFiles'; import { importOdt } from './lib/import/odt'; + import { isProtected, decryptPackage, WRONG_PASSWORD } from './lib/crypto/protect'; import { importDocx } from './lib/import/docx'; import { convertUnsupportedImages } from './lib/import/imageFormats'; import { getPageBreakDebug } from './lib/editor/extensions/pageBreaks'; @@ -56,6 +57,7 @@ import TemplateGalleryDialog from './lib/components/TemplateGalleryDialog.svelte'; import type { TemplateEntry } from './lib/templates/types'; import DocPropertiesDialog from './lib/components/DocPropertiesDialog.svelte'; + import PasswordDialog from './lib/components/PasswordDialog.svelte'; import CommentsPane from './lib/components/CommentsPane.svelte'; import RevisionsPane from './lib/components/RevisionsPane.svelte'; import ConnectorLayer from './lib/components/ConnectorLayer.svelte'; @@ -481,6 +483,13 @@ // The file the document is saved to (File System Access API). Session-only: a // reload restores the doc from localStorage but the first Save re-prompts. let fileHandle: FileSystemFileHandle | null = $state(null); + // The password the document is saved with. Session-only: it is never written to + // localStorage, and the autosaved copy there stays unencrypted. + let docPassword: string | null = $state(null); + let passwordSetOpen = $state(false); + let passwordAskOpen = $state(false); + let passwordWrong = $state(false); + let askResolve: ((password: string | null) => void) | null = null; // Word's and LibreOffice's recent-documents list; a click reopens the file itself. // Only a browser with the File System Access API has handles to reopen from, so // elsewhere the list stays empty; a startup prune drops entries whose handle is gone. @@ -581,6 +590,7 @@ saveDocProperties(docProps); fileHandle = null; documentFormat = 'odt'; + docPassword = null; // Styles and note settings live in the document, so a new one starts from the built-ins setStyleSheet(builtinStyleSheet()); setNoteSettings(DEFAULT_NOTE_SETTINGS); @@ -634,9 +644,41 @@ if (Array.isArray(n.content)) for (const c of n.content) collectFontFamilies(c, out); } + function settleAsk(password: string | null): void { + const resolve = askResolve; + askResolve = null; + resolve?.(password); + } + + // Ask until the password fits or the user gives up; null means give up. + async function unprotect(bytes: Uint8Array): Promise { + for (;;) { + const password = await new Promise((resolve) => { + askResolve = resolve; + passwordAskOpen = true; + }); + if (password === null) return null; + try { + const plain = await decryptPackage(bytes, password); + docPassword = password; + passwordWrong = false; + return plain; + } catch (err) { + if ((err as Error)?.message !== WRONG_PASSWORD) throw err; + passwordWrong = true; + } + } + } + async function applyImport(bytes: Uint8Array, handle: FileSystemFileHandle | null, sourceName?: string) { if (!editor) return; try { + // Before anything reads the archive: an encrypted file is not one yet. + if (isProtected(bytes)) { + const opened = await unprotect(bytes); + if (!opened) return; + bytes = opened; + } const name = sourceName?.toLowerCase() ?? ''; let isDocx = name.endsWith('.docx') || name.endsWith('.dotx'); // A template is loaded for its content but never bound as the handle, so the @@ -822,17 +864,18 @@ if (documentFormat === 'docx') { const { buildDocx } = await import('./lib/export/docx'); const bytes = await buildDocx(json, pageMargins, pageOrientation, hfOpts(), odfFromLanguage(documentLanguage), pageFormat, styleSheet(), tabIntervalCm, spacingModel, pageRtl, noteSettings(), docProps, hyphenate, pageNumbering, pageDecor, lineNumbering, recordChanges(), foldMarks); - fileHandle = await saveDocx(bytes, suggestedFilenameDocx(json), fileHandle); + fileHandle = await saveDocx(bytes, suggestedFilenameDocx(json), fileHandle, docPassword); recentFiles = await rememberRecentFile(fileHandle?.name ?? suggestedFilenameDocx(json), fileHandle); return; } const bytes = await buildOdt(json, pageMargins, pageOrientation, hfOpts(), odfFromLanguage(documentLanguage), pageFormat, styleSheet(), tabIntervalCm, spacingModel, pageRtl, noteSettings(), docProps, hyphenate, pageNumbering, pageDecor, lineNumbering, recordChanges(), foldMarks); - fileHandle = await saveOdt(bytes, suggestedFilename(json), fileHandle); + fileHandle = await saveOdt(bytes, suggestedFilename(json), fileHandle, docPassword); recentFiles = await rememberRecentFile(fileHandle?.name ?? suggestedFilename(json), fileHandle); } catch (err) { if ((err as DOMException)?.name === 'AbortError') return; - // A stored handle may have lost permission; re-prompt via Save As. - if (fileHandle) { fileHandle = null; await handleSaveAs(); return; } + // A stored handle may have lost permission; re-prompt via Save As. Encryption + // failing is not that case — it would silently save the document unprotected. + if (fileHandle && (err as Error)?.name !== 'EncryptionError') { fileHandle = null; await handleSaveAs(); return; } console.error('[save] Failed to save file:', err); failed(t().dialogs.couldNotSave, err); } @@ -844,7 +887,7 @@ const json = editor.getJSON() as Parameters[0]; try { const bytes = await buildOdt(json, pageMargins, pageOrientation, hfOpts(), odfFromLanguage(documentLanguage), pageFormat, styleSheet(), tabIntervalCm, spacingModel, pageRtl, noteSettings(), docProps, hyphenate, pageNumbering, pageDecor, lineNumbering, recordChanges(), foldMarks); - fileHandle = await saveAsOdt(bytes, suggestedFilename(json)); + fileHandle = await saveAsOdt(bytes, suggestedFilename(json), docPassword); documentFormat = 'odt'; // Save As is odt-only, so a docx-opened document switches format here. recentFiles = await rememberRecentFile(fileHandle?.name ?? suggestedFilename(json), fileHandle); } catch (err) { @@ -870,7 +913,7 @@ return docxToDotx(await buildDocx(json, ...args)); } return odtToOtt(await buildOdt(json, ...args)); - }, stripOdtExtension(suggestedFilename(json))); + }, stripOdtExtension(suggestedFilename(json)), docPassword); } catch (err) { if ((err as DOMException)?.name === 'AbortError') return; console.error('[save] Failed to save template:', err); @@ -917,7 +960,7 @@ const json = editor.getJSON() as Parameters[0]; const { buildDocx } = await import('./lib/export/docx'); const bytes = await buildDocx(json, pageMargins, pageOrientation, hfOpts(), odfFromLanguage(documentLanguage), pageFormat, styleSheet(), tabIntervalCm, spacingModel, pageRtl, noteSettings(), docProps, hyphenate, pageNumbering, pageDecor, lineNumbering, recordChanges(), foldMarks); - await saveAsDocx(bytes, suggestedFilenameDocx(json)); + await saveAsDocx(bytes, suggestedFilenameDocx(json), docPassword); } catch (err) { if ((err as DOMException)?.name === 'AbortError') return; console.error('[docx] Export failed:', err); @@ -1182,6 +1225,8 @@ onPrint={handlePrint} onAbout={() => (aboutOpen = true)} onDocProperties={() => (docPropsOpen = true)} + onProtect={() => (passwordSetOpen = true)} + hasPassword={docPassword !== null} onAutoCorrect={() => (autoCorrectOpen = true)} onAutoText={() => (autoTextOpen = true)} onNewComment={addComment} @@ -1307,6 +1352,10 @@ {t().app.clearRecentFiles} {/if} +
{t().docProps.title}
+ {/if} + + + + + + + + diff --git a/src/lib/components/ribbon/Ribbon.svelte b/src/lib/components/ribbon/Ribbon.svelte index 9ad40aa..174ac58 100644 --- a/src/lib/components/ribbon/Ribbon.svelte +++ b/src/lib/components/ribbon/Ribbon.svelte @@ -68,7 +68,8 @@ onSelectTheme, docxBusy = false, pdfBusy = false, - onNew, onNewFromTemplate, onOpen, onSave, onSaveAs, onSaveDocx, onSaveTemplate, onExportPdf, onPrintPdf, onPrint, onAbout, onDocProperties, onAutoCorrect, onAutoText, onNewComment, + hasPassword = false, + onNew, onNewFromTemplate, onOpen, onSave, onSaveAs, onSaveDocx, onSaveTemplate, onExportPdf, onPrintPdf, onPrint, onAbout, onDocProperties, onProtect, onAutoCorrect, onAutoText, onNewComment, navigatorOpen = false, onToggleNavigator, recentFiles = [], onOpenRecent, onForgetRecent, }: { @@ -122,6 +123,8 @@ onPrint?: () => void; onAbout?: () => void; onDocProperties?: () => void; + onProtect?: () => void; + hasPassword?: boolean; onAutoCorrect?: () => void; onAutoText?: () => void; onNewComment?: () => void; @@ -247,6 +250,10 @@ {t().app.print} {withShortcut('Ctrl+P')} + diff --git a/src/lib/components/ribbon/icons.ts b/src/lib/components/ribbon/icons.ts index 82d3598..6989f4a 100644 --- a/src/lib/components/ribbon/icons.ts +++ b/src/lib/components/ribbon/icons.ts @@ -30,6 +30,7 @@ export const STROKED = { undo: ['M2.5 6.5h6.75a3.75 3.75 0 0 1 0 7.5H5.5', 'M5.25 3.5 2.5 6.5l2.75 3'], redo: ['M13.5 6.5H6.75a3.75 3.75 0 0 0 0 7.5H10.5', 'M10.75 3.5 13.5 6.5l-2.75 3'], info: ['M8 14.5A6.5 6.5 0 1 0 8 1.5a6.5 6.5 0 0 0 0 13z', 'M8 7.25v4'], + lock: ['M3.75 7.25h8.5v6.25h-8.5z', 'M5.75 7.25V5a2.25 2.25 0 0 1 4.5 0v2.25'], ribbon: ['M2 3.25h12v3.5H2z', 'M2 9.5h4v3.25H2z', 'M7.5 9.5h2.5v3.25H7.5z', 'M11.5 9.5H14v3.25h-2.5z'], cut: ['M4 2.5 11 12', 'M12 2.5 5 12', 'M3.6 13.9a1.6 1.6 0 1 0 0-3.2 1.6 1.6 0 0 0 0 3.2z', 'M12.4 13.9a1.6 1.6 0 1 0 0-3.2 1.6 1.6 0 0 0 0 3.2z'], diff --git a/src/lib/export/saveFile.ts b/src/lib/export/saveFile.ts index a0b845e..8f2d9be 100644 --- a/src/lib/export/saveFile.ts +++ b/src/lib/export/saveFile.ts @@ -69,6 +69,15 @@ async function writeHandle(handle: FileSystemFileHandle, bytes: Uint8Array): Pro await writable.close(); } +// Password protection is the last thing that happens to the bytes, after every +// post-processing pass and after the template conversion. The crypto module loads +// only when a password is actually set. +async function protect(bytes: Uint8Array, password: string | null): Promise { + if (!password) return bytes; + const { encryptPackage } = await import('../crypto/protect'); + return encryptPackage(bytes, password); +} + // Save to the given handle if we have one; otherwise prompt for a location (i.e. // the first save acts as Save As). Returns the handle written to, or null when // falling back to a plain download. Throws AbortError if the user cancels. @@ -76,13 +85,15 @@ export async function saveOdt( bytes: Uint8Array, suggestedName: string, handle: FileSystemFileHandle | null, + password: string | null = null, ): Promise { + const out = await protect(bytes, password); if (!supportsFsAccess()) { - download(bytes, suggestedName); + download(out, suggestedName); return null; } const target = handle ?? (await (window as WinFs).showSaveFilePicker!({ suggestedName, types: PICKER_TYPES })); - await writeHandle(target, bytes); + await writeHandle(target, out); return target; } @@ -90,13 +101,15 @@ export async function saveOdt( export async function saveAsOdt( bytes: Uint8Array, suggestedName: string, + password: string | null = null, ): Promise { + const out = await protect(bytes, password); if (!supportsFsAccess()) { - download(bytes, suggestedName); + download(out, suggestedName); return null; } const handle = await (window as WinFs).showSaveFilePicker!({ suggestedName, types: PICKER_TYPES }); - await writeHandle(handle, bytes); + await writeHandle(handle, out); return handle; } @@ -106,20 +119,26 @@ export async function saveDocx( bytes: Uint8Array, suggestedName: string, handle: FileSystemFileHandle | null, + password: string | null = null, ): Promise { + const out = await protect(bytes, password); if (!supportsFsAccess()) { - download(bytes, suggestedName, DOCX_MIME); + download(out, suggestedName, DOCX_MIME); return null; } const target = handle ?? (await (window as WinFs).showSaveFilePicker!({ suggestedName, types: DOCX_PICKER_TYPES })); - await writeHandle(target, bytes); + await writeHandle(target, out); return target; } // Export a .docx: always prompt for a location (no handle is tracked — this is the // explicit "Export" action, like PDF). Returns null. Throws AbortError if cancelled. -export async function saveAsDocx(bytes: Uint8Array, suggestedName: string): Promise { - await saveDocx(bytes, suggestedName, null); +export async function saveAsDocx( + bytes: Uint8Array, + suggestedName: string, + password: string | null = null, +): Promise { + await saveDocx(bytes, suggestedName, null, password); } // Save a template. The picker offers both formats, so the bytes can only be built @@ -128,15 +147,17 @@ export async function saveAsDocx(bytes: Uint8Array, suggestedName: string): Prom export async function saveAsTemplate( build: (kind: 'ott' | 'dotx') => Promise, baseName: string, + password: string | null = null, ): Promise { if (!supportsFsAccess()) { - download(await build('ott'), `${baseName}.ott`, OTT_MIME); + download(await protect(await build('ott'), password), `${baseName}.ott`, OTT_MIME); return; } const handle = await (window as WinFs).showSaveFilePicker!({ suggestedName: `${baseName}.ott`, types: TEMPLATE_PICKER_TYPES, }); - await writeHandle(handle, await build(handle.name.toLowerCase().endsWith('.dotx') ? 'dotx' : 'ott')); + const kind = handle.name.toLowerCase().endsWith('.dotx') ? 'dotx' : 'ott'; + await writeHandle(handle, await protect(await build(kind), password)); } // Prompt for an .odt/.ott/.docx to open, capturing its handle so a later save can diff --git a/src/lib/i18n/locales/de.ts b/src/lib/i18n/locales/de.ts index 27356c8..d0f5c0b 100644 --- a/src/lib/i18n/locales/de.ts +++ b/src/lib/i18n/locales/de.ts @@ -1104,6 +1104,18 @@ const de: Messages = { comments: 'Kommentare wurden entfernt', missingFonts: (fonts) => `Diese Schriftarten sind nicht installiert und wurden durch Ersatzschriften dargestellt: ${fonts}`, }, + password: { + menu: 'Mit Passwort schützen…', + menuOn: 'Geschützt', + setTitle: 'Mit Passwort schützen', + askTitle: 'Dieses Dokument ist geschützt', + password: 'Passwort', + repeat: 'Wiederholen', + mismatch: 'Die beiden Eingaben unterscheiden sich.', + wrong: 'Falsches Passwort.', + note: 'Schützt die gespeicherte Datei. Die Kopie, die der Editor im Browser hält, bleibt unverschlüsselt.', + remove: 'Schutz entfernen', + }, importError: { odtArchive: 'Keine gültige .odt-Datei (Archiv konnte nicht gelesen werden).', odtContentMissing: 'Keine gültige .odt-Datei (content.xml fehlt).', @@ -1113,6 +1125,7 @@ const de: Messages = { docxArchive: 'Keine gültige .docx-Datei (Archiv konnte nicht gelesen werden).', docxMissing: 'Keine gültige .docx-Datei (word/document.xml fehlt).', docxNoBody: 'Kein Word-Dokument (kein w:body).', + encryptionUnsupported: 'Dieses Dokument benutzt ein Verschlüsselungsverfahren, das nicht unterstützt wird.', }, }; diff --git a/src/lib/i18n/locales/en.ts b/src/lib/i18n/locales/en.ts index e286f3c..c7ba416 100644 --- a/src/lib/i18n/locales/en.ts +++ b/src/lib/i18n/locales/en.ts @@ -1112,6 +1112,18 @@ const en = { comments: 'Comments were removed', missingFonts: (fonts: string) => `These fonts aren't installed and were shown with a substitute: ${fonts}`, }, + password: { + menu: 'Protect with a password…', + menuOn: 'Protected', + setTitle: 'Protect with a password', + askTitle: 'This document is protected', + password: 'Password', + repeat: 'Repeat', + mismatch: 'The two entries differ.', + wrong: 'Wrong password.', + note: 'Protects the saved file. The copy this editor keeps in the browser stays unencrypted.', + remove: 'Remove protection', + }, importError: { odtArchive: 'Not a valid .odt file (could not read the archive).', odtContentMissing: 'Not a valid .odt file (content.xml is missing).', @@ -1121,6 +1133,7 @@ const en = { docxArchive: 'Not a valid .docx file (could not read the archive).', docxMissing: 'Not a valid .docx file (word/document.xml is missing).', docxNoBody: 'Not a Word document (no w:body).', + encryptionUnsupported: 'This document uses an encryption method that is not supported.', }, };