From 6fa94b8d82782ad3dc13c9cf5e456a12c00fdb1f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 27 Apr 2026 09:02:32 +0000 Subject: [PATCH 1/5] Add encrypted .raftbundle session sharing Lets users export a saved session as an end-to-end-encrypted file with a one-time passphrase, then re-import on another machine. Reuses the PBKDF2 (600k) + AES-256-GCM primitives from cloud sync, file-shaped envelope { v, salt, iv, ct, iterations }. Trust surface: passphrase + bundle travel out-of-band, both halves are needed to read it. The new safety suite asserts the export/import path makes zero network calls and round-trips a 50-tab session bit-for-bit. --- src/options/components/ImportExportPanel.tsx | 1014 ++++++++++++----- src/shared/importExport/bundle.ts | 316 +++++ src/shared/importExport/index.ts | 40 + src/shared/importExport/parsers/raftbundle.ts | 68 ++ src/shared/importExport/types.ts | 8 +- src/shared/importExport/validators.ts | 11 + tests/safety/encrypted-bundle.test.ts | 221 ++++ 7 files changed, 1406 insertions(+), 272 deletions(-) create mode 100644 src/shared/importExport/bundle.ts create mode 100644 src/shared/importExport/parsers/raftbundle.ts create mode 100644 tests/safety/encrypted-bundle.test.ts diff --git a/src/options/components/ImportExportPanel.tsx b/src/options/components/ImportExportPanel.tsx index fbb4002..b539d4f 100644 --- a/src/options/components/ImportExportPanel.tsx +++ b/src/options/components/ImportExportPanel.tsx @@ -7,13 +7,20 @@ */ import { useState, useRef } from 'preact/hooks' -import type { Session } from '@/shared/types' +import { nanoid } from 'nanoid' +import type { Session, Tab, Window } from '@/shared/types' import { importSessions, exportSessions, downloadExport, getFormatDisplayName, MAX_IMPORT_SIZE, + exportBundle, + importBundle, + bundleFilename, + generateBundlePassphrase, + BUNDLE_EXTENSION, + detectImportFormat, type ImportResult, type ExportResult, } from '@/shared/importExport' @@ -36,6 +43,31 @@ type ExportState = | { status: 'success'; result: ExportResult } | { status: 'error'; message: string } +/** Modal for the encrypted-bundle export flow. Shows passphrase + download. */ +type BundleExportDialog = + | { status: 'closed' } + | { + status: 'open' + session: Session + passphrase: string + blob: globalThis.Blob + filename: string + passphraseCopied: boolean + downloaded: boolean + } + +/** Modal for the encrypted-bundle import flow. Passphrase entry → tab picker. */ +type BundleImportDialog = + | { status: 'closed' } + | { status: 'awaitingPassphrase'; file: globalThis.File; passphrase: string; error?: string } + | { status: 'decrypting'; file: globalThis.File } + | { + status: 'choosing' + session: Session + // tab id -> selected + selected: Set + } + export function ImportExportPanel({ sessions, onImportComplete, @@ -45,6 +77,8 @@ export function ImportExportPanel({ const [importState, setImportState] = useState({ status: 'idle' }) const [exportState, setExportState] = useState({ status: 'idle' }) const [selectedSessionIds, setSelectedSessionIds] = useState>(new Set()) + const [bundleExport, setBundleExport] = useState({ status: 'closed' }) + const [bundleImport, setBundleImport] = useState({ status: 'closed' }) const fileInputRef = useRef(null) const handleFileSelect = async (e: globalThis.Event) => { @@ -64,10 +98,26 @@ export function ImportExportPanel({ return } + // Encrypted bundles need a passphrase before they can be parsed. Detect by + // extension or by sniffing the JSON envelope shape and route to the + // bundle-import flow instead of the auto-detect parser. + if (file.name.toLowerCase().endsWith(BUNDLE_EXTENSION)) { + setBundleImport({ status: 'awaitingPassphrase', file, passphrase: '' }) + if (fileInputRef.current) fileInputRef.current.value = '' + return + } + setImportState({ status: 'loading' }) try { const content = await file.text() + + if (detectImportFormat(content) === 'raftbundle') { + setBundleImport({ status: 'awaitingPassphrase', file, passphrase: '' }) + setImportState({ status: 'idle' }) + return + } + const result = importSessions(content) if (!result.success && result.errors.length > 0) { @@ -109,6 +159,177 @@ export function ImportExportPanel({ } } + const handleEncryptedExport = async (sessionId: string) => { + const sessionWithStats = sessions.find((s) => s.id === sessionId) + if (!sessionWithStats) return + + // Strip the UI-only stats wrapper before serializing. + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { stats: _stats, ...session } = sessionWithStats + const target = session as Session + + try { + const passphrase = generateBundlePassphrase() + const blob = await exportBundle(target, passphrase) + setBundleExport({ + status: 'open', + session: target, + passphrase, + blob, + filename: bundleFilename(target), + passphraseCopied: false, + downloaded: false, + }) + } catch (err) { + setExportState({ + status: 'error', + message: err instanceof Error ? err.message : 'Failed to encrypt bundle', + }) + } + } + + const handleCopyPassphrase = async () => { + if (bundleExport.status !== 'open') return + try { + await globalThis.navigator.clipboard.writeText(bundleExport.passphrase) + setBundleExport({ ...bundleExport, passphraseCopied: true }) + } catch { + // Clipboard can fail in restricted contexts; the passphrase is still on screen. + } + } + + const handleDownloadBundle = () => { + if (bundleExport.status !== 'open') return + const url = URL.createObjectURL(bundleExport.blob) + const link = document.createElement('a') + link.href = url + link.download = bundleExport.filename + document.body.appendChild(link) + link.click() + document.body.removeChild(link) + URL.revokeObjectURL(url) + setBundleExport({ ...bundleExport, downloaded: true }) + onExportComplete?.() + } + + const closeBundleExport = () => setBundleExport({ status: 'closed' }) + + const handleBundleDecrypt = async () => { + if (bundleImport.status !== 'awaitingPassphrase') return + const { file, passphrase } = bundleImport + + if (!passphrase) { + setBundleImport({ ...bundleImport, error: 'Enter the passphrase to continue.' }) + return + } + + setBundleImport({ status: 'decrypting', file }) + + try { + const session = await importBundle(file, passphrase) + const allTabIds = new Set(session.windows.flatMap((w) => w.tabs.map((t) => t.id))) + setBundleImport({ status: 'choosing', session, selected: allTabIds }) + } catch (err) { + setBundleImport({ + status: 'awaitingPassphrase', + file, + passphrase, + error: err instanceof Error ? err.message : 'Failed to decrypt bundle', + }) + } + } + + const toggleBundleTab = (tabId: string) => { + if (bundleImport.status !== 'choosing') return + const next = new Set(bundleImport.selected) + if (next.has(tabId)) next.delete(tabId) + else next.add(tabId) + setBundleImport({ ...bundleImport, selected: next }) + } + + const toggleAllBundleTabs = (select: boolean) => { + if (bundleImport.status !== 'choosing') return + if (select) { + const all = new Set( + bundleImport.session.windows.flatMap((w) => w.tabs.map((t) => t.id)) + ) + setBundleImport({ ...bundleImport, selected: all }) + } else { + setBundleImport({ ...bundleImport, selected: new Set() }) + } + } + + const handleConfirmBundleImport = async () => { + if (bundleImport.status !== 'choosing') return + const { session, selected } = bundleImport + + // Filter the decrypted session down to selected tabs. Drop empty windows + // and tab groups whose tabs were all deselected so the imported session + // doesn't carry orphan groups. + const newWindows: Window[] = [] + for (const window of session.windows) { + const keptTabs: Tab[] = window.tabs + .filter((t) => selected.has(t.id)) + .map((t, i) => ({ ...t, index: i })) + if (keptTabs.length === 0) continue + + const usedGroupIds = new Set(keptTabs.map((t) => t.groupId).filter(Boolean) as string[]) + const keptGroups = window.tabGroups.filter((g) => usedGroupIds.has(g.id)) + newWindows.push({ ...window, id: nanoid(), tabs: keptTabs, tabGroups: keptGroups }) + } + + if (newWindows.length === 0) { + setBundleImport({ + status: 'choosing', + session, + selected, + }) + setImportState({ status: 'error', message: 'Select at least one tab to import.' }) + return + } + + // Always assign a fresh session ID so a recipient with an existing copy + // doesn't get their version silently overwritten. + const importedSession: Session = { + ...session, + id: nanoid(), + windows: newWindows, + source: 'import', + updatedAt: Date.now(), + } + + try { + const existing = await sessionsStorage.getAll() + await sessionsStorage.saveAll([...existing, importedSession]) + + const tabsImported = newWindows.reduce((sum, w) => sum + w.tabs.length, 0) + const result: ImportResult = { + success: true, + sessions: [importedSession], + errors: [], + warnings: [], + stats: { + totalEntries: tabsImported, + validUrls: tabsImported, + skippedUrls: 0, + sessionsCreated: 1, + tabsImported, + }, + format: 'raftbundle', + } + setImportState({ status: 'success', result }) + setBundleImport({ status: 'closed' }) + onImportComplete() + } catch (err) { + setImportState({ + status: 'error', + message: err instanceof Error ? err.message : 'Failed to save imported session', + }) + } + } + + const closeBundleImport = () => setBundleImport({ status: 'closed' }) + const handleExport = (format: 'json' | 'text') => { const sessionIds = selectedSessionIds.size > 0 ? Array.from(selectedSessionIds) : undefined const sessionsToExport = sessions.map((s) => { @@ -156,300 +377,551 @@ export function ImportExportPanel({ } return ( -
- {/* Header - always visible */} - - - {/* Expandable content */} - {isExpanded && ( -
- {/* Import Section */} -
-

Import Sessions

-

- Supports OneTab, Session Buddy, Tab Session Manager, Toby, and Raft backups. Import - formats are based on best available documentation. If your import doesn't work, please{' '} - - let us know - {' '} - and we'll prioritize a fix. -

- -