diff --git a/src/options/components/ImportExportPanel.tsx b/src/options/components/ImportExportPanel.tsx index fbb4002..3cd7bf1 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,542 @@ 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. -

+ Import / Export + + + + {/* 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. +

- - - Accepts JSON and text files from OneTab, Session Buddy, Tab Session Manager, Toby, and - Raft - - - {/* Import Status */} - {importState.status === 'success' && ( -
-
-
-

Import successful!

-

- {importState.result.format && ( - <>Format: {getFormatDisplayName(importState.result.format)} · - )} - {importState.result.stats.sessionsCreated} session - {importState.result.stats.sessionsCreated !== 1 ? 's' : ''} ·{' '} - {importState.result.stats.tabsImported} tab - {importState.result.stats.tabsImported !== 1 ? 's' : ''} -

- {importState.result.warnings.length > 0 && ( -

- {importState.result.warnings.length} warning - {importState.result.warnings.length !== 1 ? 's' : ''} ( - {importState.result.stats.skippedUrls} skipped) + + {/* Import Status */} + {importState.status === 'success' && ( +

+
+
+

Import successful!

+

+ {importState.result.format && ( + <>Format: {getFormatDisplayName(importState.result.format)} · + )} + {importState.result.stats.sessionsCreated} session + {importState.result.stats.sessionsCreated !== 1 ? 's' : ''} ·{' '} + {importState.result.stats.tabsImported} tab + {importState.result.stats.tabsImported !== 1 ? 's' : ''}

- )} + {importState.result.warnings.length > 0 && ( +

+ {importState.result.warnings.length} warning + {importState.result.warnings.length !== 1 ? 's' : ''} ( + {importState.result.stats.skippedUrls} skipped) +

+ )} +
+
- + + +
-
- )} + )} +
+ + {/* Export Section */} +
+

Export Sessions

+ + {sessions.length === 0 ? ( +

No sessions to export.

+ ) : ( + <> +

+ Select sessions to export, or export all if none selected. +

+ + {/* Session selection */} +
+ {sessions.map((session) => ( +
+ + +
+ ))} +
- {importState.status === 'error' && ( - + + {/* Export Status */} + {exportState.status === 'success' && ( +
+
+
+

Export complete!

+

+ {exportState.result.stats.sessionsExported} session + {exportState.result.stats.sessionsExported !== 1 + ? 's' + : ''} · {exportState.result.stats.tabsExported} tab + {exportState.result.stats.tabsExported !== 1 ? 's' : ''} +

+
+ +
+
+ )} + + {exportState.status === 'error' && ( + + )} + + )} +
+
+ )} +
+ + {/* Encrypted bundle export dialog */} + {bundleExport.status === 'open' && ( + + )} + + {/* Encrypted bundle import dialog: passphrase entry */} + {bundleImport.status === 'awaitingPassphrase' && ( + + )} + + {bundleImport.status === 'decrypting' && ( + + )} - {/* Export Section */} -
-

Export Sessions

- - {sessions.length === 0 ? ( -

No sessions to export.

- ) : ( - <> -

- Select sessions to export, or export all if none selected. -

- - {/* Session selection */} -
- {sessions.map((session) => ( + {/* Encrypted bundle import dialog: tab picker */} + {bundleImport.status === 'choosing' && ( + )} -
+ ) } diff --git a/src/shared/importExport/bundle.ts b/src/shared/importExport/bundle.ts new file mode 100644 index 0000000..4c29cf3 --- /dev/null +++ b/src/shared/importExport/bundle.ts @@ -0,0 +1,343 @@ +/** + * Encrypted .raftbundle session sharing + * + * Exports a single Session as an end-to-end encrypted file the user can + * hand to someone out-of-band. Reuses the cloud-sync encryption primitives + * (PBKDF2 600k + AES-256-GCM) so the trust surface is the same. + * + * Bundle envelope shape — JSON, file-shaped (not Drive-shaped): + * { v: 1, salt, iv, ct, iterations } + */ + +import type { Session } from '../types' +import { + PBKDF2_ITERATIONS, + generateSalt, + deriveKey, + encryptObject, + decryptObject, +} from '../cloudSync/encryption' + +/** Current bundle envelope version. */ +export const BUNDLE_VERSION = 1 + +/** File extension used for downloaded bundles. */ +export const BUNDLE_EXTENSION = '.raftbundle' + +/** MIME type used for bundle blobs. */ +export const BUNDLE_MIME_TYPE = 'application/x-raftbundle+json' + +/** + * On-disk envelope. `salt` is the PBKDF2 salt for this file, `iv` and `ct` + * are the AES-GCM IV and ciphertext. `iterations` is recorded so a future + * bump (or downgrade for legacy bundles) round-trips correctly. + */ +export interface RaftBundleEnvelope { + v: typeof BUNDLE_VERSION + salt: string + iv: string + ct: string + iterations: number +} + +/** + * Encrypt a session into a downloadable .raftbundle Blob. + * + * Generates a fresh salt + IV per export so two exports of the same + * session under the same passphrase produce different ciphertexts. + */ +export async function exportBundle(session: Session, passphrase: string): Promise { + if (!passphrase) { + throw new Error('Passphrase required to export bundle') + } + + const salt = generateSalt() + const key = await deriveKey(passphrase, salt, PBKDF2_ITERATIONS) + const payload = await encryptObject(session, key) + + const envelope: RaftBundleEnvelope = { + v: BUNDLE_VERSION, + salt, + iv: payload.iv, + ct: payload.ct, + iterations: PBKDF2_ITERATIONS, + } + + const json = JSON.stringify(envelope) + return new globalThis.Blob([json], { type: BUNDLE_MIME_TYPE }) +} + +/** + * Type guard for the envelope shape. Anything missing a required field + * is rejected before we even try to derive a key. + */ +export function isRaftBundleEnvelope(value: unknown): value is RaftBundleEnvelope { + if (!value || typeof value !== 'object') return false + const e = value as Record + return ( + e.v === BUNDLE_VERSION && + typeof e.salt === 'string' && + typeof e.iv === 'string' && + typeof e.ct === 'string' && + typeof e.iterations === 'number' + ) +} + +/** + * Parse a string (or Blob's text contents) into a validated envelope. + * Throws with a useful message on malformed input. + */ +export function parseEnvelope(content: string): RaftBundleEnvelope { + let parsed: unknown + try { + parsed = JSON.parse(content) + } catch { + throw new Error('Not a valid Raft bundle: file is not JSON') + } + if (!isRaftBundleEnvelope(parsed)) { + throw new Error('Not a valid Raft bundle: envelope shape is wrong') + } + return parsed +} + +/** + * Convenience: read a Blob (or pass through a string) and parse it as an + * envelope in one call. Useful for tests that just want to inspect the + * envelope shape without decrypting. + */ +export async function readEnvelope(input: globalThis.Blob | string): Promise { + return parseEnvelope(await blobToText(input)) +} + +/** + * Read a Blob into a string. Prefers the standard `Blob.text()`, falls back + * to `FileReader` for environments (some Blob polyfills, older jsdom) that + * don't implement it. Accepts a raw string passthrough for convenience — + * callers can hand us either form. + */ +async function blobToText(input: globalThis.Blob | string): Promise { + if (typeof input === 'string') return input + if (typeof (input as { text?: unknown }).text === 'function') { + return input.text() + } + if (typeof (input as { arrayBuffer?: unknown }).arrayBuffer === 'function') { + const buf = await input.arrayBuffer() + return new TextDecoder().decode(buf) + } + return new Promise((resolve, reject) => { + const reader = new globalThis.FileReader() + reader.onload = () => resolve(String(reader.result)) + reader.onerror = () => reject(reader.error ?? new Error('Failed to read blob')) + reader.readAsText(input as globalThis.Blob) + }) +} + +/** + * Decrypt a .raftbundle blob back into a Session. + * + * Wrong-passphrase failures (AES-GCM auth tag mismatch) are surfaced as + * a clean `Error('Incorrect passphrase ...')` so callers can show the + * user something useful instead of a raw OperationError. + * + * Accepts a Blob or a raw string (the JSON envelope) so callers don't have + * to wrap text in a Blob just to round-trip it. + */ +export async function importBundle( + blob: globalThis.Blob | string, + passphrase: string +): Promise { + if (!passphrase) { + throw new Error('Passphrase required to import bundle') + } + + const text = await blobToText(blob) + const envelope = parseEnvelope(text) + + const key = await deriveKey(passphrase, envelope.salt, envelope.iterations) + + try { + return await decryptObject({ v: 1, iv: envelope.iv, ct: envelope.ct }, key) + } catch { + throw new Error('Incorrect passphrase or corrupted bundle') + } +} + +/** + * Build a download filename for a session bundle. + * Sanitizes the session name to a filesystem-safe slug. + */ +export function bundleFilename(session: Session): string { + const slug = + session.name + .trim() + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, '') + .slice(0, 40) || 'session' + const date = new Date().toISOString().split('T')[0] + return `raft-${slug}-${date}${BUNDLE_EXTENSION}` +} + +/** + * Generate a high-entropy passphrase suitable for one-time bundle sharing. + * 6 words from a small wordlist + 4-digit number gives ~70 bits of entropy + * while staying readable enough to dictate over a phone call. + */ +export function generateBundlePassphrase(): string { + // Short, common, unambiguous. Picked to avoid lookalike letters and + // anything that would be embarrassing to read aloud. + const words = [ + 'amber', + 'anchor', + 'apple', + 'arrow', + 'atlas', + 'banjo', + 'basin', + 'beach', + 'birch', + 'blaze', + 'bloom', + 'brave', + 'breeze', + 'brick', + 'bronze', + 'cabin', + 'canyon', + 'cedar', + 'chase', + 'cider', + 'cliff', + 'cloud', + 'clover', + 'comet', + 'coral', + 'crane', + 'crisp', + 'crown', + 'crystal', + 'dawn', + 'delta', + 'denim', + 'desert', + 'diamond', + 'dolphin', + 'dune', + 'eagle', + 'ember', + 'falcon', + 'fern', + 'fjord', + 'flame', + 'flint', + 'forest', + 'galaxy', + 'garden', + 'gentle', + 'glacier', + 'gold', + 'granite', + 'harbor', + 'harvest', + 'hawk', + 'heron', + 'hollow', + 'honey', + 'horizon', + 'island', + 'ivory', + 'jade', + 'juniper', + 'kettle', + 'lagoon', + 'lantern', + 'lily', + 'linen', + 'lotus', + 'maple', + 'meadow', + 'mellow', + 'mesa', + 'mint', + 'misty', + 'morning', + 'mountain', + 'nectar', + 'nimbus', + 'oak', + 'ocean', + 'olive', + 'opal', + 'orchid', + 'otter', + 'pebble', + 'phoenix', + 'pine', + 'plum', + 'prairie', + 'quartz', + 'quiet', + 'rain', + 'raven', + 'reef', + 'river', + 'robin', + 'sable', + 'sage', + 'sapphire', + 'shadow', + 'silver', + 'spark', + 'spring', + 'stone', + 'storm', + 'stream', + 'summit', + 'sunrise', + 'swan', + 'tide', + 'topaz', + 'trail', + 'tulip', + 'twilight', + 'valley', + 'velvet', + 'violet', + 'wander', + 'willow', + 'winter', + 'zephyr', + ] + + const picks = Array.from({ length: 6 }, () => words[unbiasedRandomInt(words.length)]) + const num = unbiasedRandomInt(10_000) + return `${picks.join('-')}-${num.toString().padStart(4, '0')}` +} + +/** + * Generate an unbiased integer in `[0, max)` from a CSPRNG. + * + * Naively doing `crypto.getRandomValues(...) % max` is biased whenever + * `2^32 % max !== 0` — the lower buckets get slightly more probability + * than the higher ones. Rejection sampling fixes this: discard any + * draw that falls in the "unfair" top slice, so the remaining range + * is an exact multiple of `max` and the modulo is uniform. + * + * For the values we use (120-word list, 10_000) the rejection rate is + * effectively zero (< 1 in ~36M), so this loop is virtually always + * one iteration. + */ +function unbiasedRandomInt(max: number): number { + if (max <= 0 || !Number.isInteger(max)) { + throw new Error('unbiasedRandomInt: max must be a positive integer') + } + const range = 0x1_0000_0000 // 2^32 + const limit = Math.floor(range / max) * max + const buf = new Uint32Array(1) + // Loop terminates: P(reject) = (range - limit) / range < max / range, + // which is microscopic for our inputs. + for (;;) { + crypto.getRandomValues(buf) + if (buf[0] < limit) return buf[0] % max + } +} diff --git a/src/shared/importExport/index.ts b/src/shared/importExport/index.ts index cc99866..fc83a1f 100644 --- a/src/shared/importExport/index.ts +++ b/src/shared/importExport/index.ts @@ -26,10 +26,26 @@ export { parseSessionBuddy } from './parsers/sessionBuddy' export { parseTabSessionManager } from './parsers/tabSessionManager' export { parseToby } from './parsers/toby' export { parseRaft } from './parsers/raft' +export { parseRaftbundle } from './parsers/raftbundle' // Re-export exporters export { exportAsJson, exportAsText, exportSessions, downloadExport } from './exporters' +// Re-export encrypted bundle export/import +export { + exportBundle, + importBundle, + bundleFilename, + generateBundlePassphrase, + parseEnvelope as parseBundleEnvelope, + readEnvelope as readBundleEnvelope, + isRaftBundleEnvelope, + BUNDLE_VERSION, + BUNDLE_EXTENSION, + BUNDLE_MIME_TYPE, +} from './bundle' +export type { RaftBundleEnvelope } from './bundle' + // Main import function import type { ImportResult, ImportFormat } from './types' import { validateImportContent } from './validators' @@ -78,6 +94,28 @@ export function importSessions(content: string): ImportResult { return parseToby(content) case 'raft': return parseRaft(content) + case 'raftbundle': + // Encrypted bundles need a passphrase, which auto-import can't supply. + // Surface a useful message; the panel handles bundles via parseRaftbundle directly. + return { + success: false, + sessions: [], + errors: [ + { + message: + 'Encrypted Raft bundle detected — use the encrypted bundle import to enter the passphrase.', + }, + ], + warnings: [], + stats: { + totalEntries: 0, + validUrls: 0, + skippedUrls: 0, + sessionsCreated: 0, + tabsImported: 0, + }, + format: 'raftbundle', + } default: return { success: false, @@ -110,6 +148,8 @@ export function getFormatDisplayName(format: ImportFormat): string { return 'Toby' case 'raft': return 'Raft' + case 'raftbundle': + return 'Raft (encrypted bundle)' default: return format } diff --git a/src/shared/importExport/parsers/raftbundle.ts b/src/shared/importExport/parsers/raftbundle.ts new file mode 100644 index 0000000..dba96b3 --- /dev/null +++ b/src/shared/importExport/parsers/raftbundle.ts @@ -0,0 +1,68 @@ +/** + * Encrypted .raftbundle import parser + * + * Unlike the other parsers, this one needs a passphrase — bundles are + * end-to-end encrypted with PBKDF2 + AES-256-GCM. The signature is async + * and takes the passphrase explicitly; the panel calls it directly rather + * than going through `importSessions`, since auto-detect can't supply + * a passphrase. + */ + +import type { Session } from '../../types' +import type { ImportResult, ImportError, ImportStats } from '../types' +import { importBundle } from '../bundle' + +/** + * Decrypt a .raftbundle file and produce an ImportResult shaped like + * the other parsers so the panel's success/error UI can reuse the same + * code path. + * + * The Session inside the bundle is preserved as-is (IDs intact). The + * caller decides what to do with it — the round-trip safety contract + * is "bytes you put in, bytes you get out". + */ +export async function parseRaftbundle( + content: string | globalThis.Blob, + passphrase: string +): Promise { + const stats: ImportStats = { + totalEntries: 0, + validUrls: 0, + skippedUrls: 0, + sessionsCreated: 0, + tabsImported: 0, + } + const errors: ImportError[] = [] + const warnings: ImportError[] = [] + + let session: Session + try { + session = await importBundle(content, passphrase) + } catch (e) { + return { + success: false, + sessions: [], + errors: [{ message: e instanceof Error ? e.message : 'Failed to decrypt bundle' }], + warnings: [], + stats, + format: 'raftbundle', + } + } + + // Recompute stats from the decrypted session so the UI summary works. + for (const window of session.windows) { + stats.totalEntries += window.tabs.length + stats.validUrls += window.tabs.length + } + stats.sessionsCreated = 1 + stats.tabsImported = stats.validUrls + + return { + success: true, + sessions: [session], + errors, + warnings, + stats, + format: 'raftbundle', + } +} diff --git a/src/shared/importExport/types.ts b/src/shared/importExport/types.ts index 16bbc2b..0584692 100644 --- a/src/shared/importExport/types.ts +++ b/src/shared/importExport/types.ts @@ -7,7 +7,13 @@ import type { Session } from '../types' /** * Supported import formats */ -export type ImportFormat = 'onetab' | 'sessionBuddy' | 'tabSessionManager' | 'toby' | 'raft' +export type ImportFormat = + | 'onetab' + | 'sessionBuddy' + | 'tabSessionManager' + | 'toby' + | 'raft' + | 'raftbundle' /** * Individual import error with context diff --git a/src/shared/importExport/validators.ts b/src/shared/importExport/validators.ts index 6cf95b5..03543e9 100644 --- a/src/shared/importExport/validators.ts +++ b/src/shared/importExport/validators.ts @@ -86,6 +86,17 @@ export function detectImportFormat(content: string): ImportFormat | null { try { const parsed = JSON.parse(trimmed) + // Check for encrypted Raft bundle envelope (file-shaped, not Drive-shaped) + if ( + parsed.v === 1 && + typeof parsed.salt === 'string' && + typeof parsed.iv === 'string' && + typeof parsed.ct === 'string' && + typeof parsed.iterations === 'number' + ) { + return 'raftbundle' + } + // Check for Raft format (has version and raftVersion fields) if (parsed.version && parsed.raftVersion && Array.isArray(parsed.sessions)) { return 'raft' diff --git a/tests/safety/encrypted-bundle.test.ts b/tests/safety/encrypted-bundle.test.ts new file mode 100644 index 0000000..23d92cf --- /dev/null +++ b/tests/safety/encrypted-bundle.test.ts @@ -0,0 +1,221 @@ +/** + * Encrypted Bundle Safety Tests + * + * Asserts that `.raftbundle` export/import: + * 1. Never touches the network (no fetch / XHR / WebSocket calls). + * 2. Round-trips a realistic session (50 tabs + groups) bit-for-bit. + * 3. Surfaces a clean, useful error on the wrong passphrase. + * 4. Uses the 600k PBKDF2 default and embeds it in the envelope. + * + * The "no network" check is the key trust property: end-to-end-encrypted + * sharing must be a fully local operation. If we ever accidentally ship a + * codepath that reaches out to a server, this test fires. + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' +import { + exportBundle, + importBundle, + readEnvelope, + generateBundlePassphrase, + BUNDLE_VERSION, +} from '@/shared/importExport/bundle' +import { parseRaftbundle } from '@/shared/importExport/parsers/raftbundle' +import { PBKDF2_ITERATIONS } from '@/shared/cloudSync/encryption' +import type { Session } from '@/shared/types' +import { buildLargeSession } from './helpers' + +describe('Encrypted .raftbundle export/import', () => { + describe('Never reaches the network', () => { + let fetchSpy: ReturnType + let xhrSpy: ReturnType + let wsSpy: ReturnType + let originalFetch: typeof globalThis.fetch | undefined + let originalXhr: typeof globalThis.XMLHttpRequest | undefined + let originalWs: typeof globalThis.WebSocket | undefined + + beforeEach(() => { + // Replace any network-capable global with a spy that throws if called. + // If a future change accidentally introduces an HTTP call inside + // exportBundle/importBundle, one of these spies will be invoked + // and the test will fail loudly. + originalFetch = globalThis.fetch + originalXhr = globalThis.XMLHttpRequest + originalWs = globalThis.WebSocket + + fetchSpy = vi.fn(() => { + throw new Error('fetch must not be called from bundle export/import') + }) + xhrSpy = vi.fn(() => { + throw new Error('XMLHttpRequest must not be used from bundle export/import') + }) + wsSpy = vi.fn(() => { + throw new Error('WebSocket must not be used from bundle export/import') + }) + + globalThis.fetch = fetchSpy as unknown as typeof globalThis.fetch + globalThis.XMLHttpRequest = + xhrSpy as unknown as typeof globalThis.XMLHttpRequest + globalThis.WebSocket = wsSpy as unknown as typeof globalThis.WebSocket + }) + + afterEach(() => { + if (originalFetch) globalThis.fetch = originalFetch + else delete (globalThis as { fetch?: unknown }).fetch + if (originalXhr) globalThis.XMLHttpRequest = originalXhr + if (originalWs) globalThis.WebSocket = originalWs + }) + + it('exportBundle and importBundle make zero network calls', async () => { + const session = buildLargeSession(2, 5, 2) + const passphrase = 'correct-horse-battery-staple' + + const blob = await exportBundle(session, passphrase) + const restored = await importBundle(blob, passphrase) + + expect(restored.id).toBe(session.id) + expect(fetchSpy).not.toHaveBeenCalled() + expect(xhrSpy).not.toHaveBeenCalled() + expect(wsSpy).not.toHaveBeenCalled() + }) + + it('parseRaftbundle (the parser entry) is also network-free', async () => { + const session = buildLargeSession(1, 3, 1) + const passphrase = 'bundle-test-passphrase' + const blob = await exportBundle(session, passphrase) + + // Pass the Blob through directly — parseRaftbundle accepts both forms. + const result = await parseRaftbundle(blob, passphrase) + + expect(result.success).toBe(true) + expect(fetchSpy).not.toHaveBeenCalled() + expect(xhrSpy).not.toHaveBeenCalled() + expect(wsSpy).not.toHaveBeenCalled() + }) + }) + + describe('Round-trip preserves a 50-tab session bit-for-bit', () => { + it('exports 50 tabs across multiple windows + groups, re-imports identically', async () => { + // 5 windows × 10 tabs = 50 tabs, with 3 groups per window so group/tab + // membership is exercised. + const original: Session = buildLargeSession(5, 10, 3) + const tabCount = original.windows.reduce((n, w) => n + w.tabs.length, 0) + expect(tabCount).toBe(50) + + const passphrase = generateBundlePassphrase() + const blob = await exportBundle(original, passphrase) + const restored = await importBundle(blob, passphrase) + + // Bit-identical: every field, every ID, every group color, every index. + expect(restored).toEqual(original) + }) + + it('parseRaftbundle yields the same Session that importBundle returns', async () => { + const original = buildLargeSession(2, 25, 2) + const passphrase = 'shared-channel-passphrase' + const blob = await exportBundle(original, passphrase) + + const direct = await importBundle(blob, passphrase) + const viaParser = await parseRaftbundle(blob, passphrase) + + expect(viaParser.success).toBe(true) + expect(viaParser.sessions).toHaveLength(1) + expect(viaParser.sessions[0]).toEqual(direct) + expect(viaParser.stats.tabsImported).toBe(50) + expect(viaParser.format).toBe('raftbundle') + }) + }) + + describe('Bad passphrase fails cleanly', () => { + it('importBundle throws a useful error when the passphrase is wrong', async () => { + const session = buildLargeSession(1, 5) + const blob = await exportBundle(session, 'right-passphrase') + + await expect(importBundle(blob, 'wrong-passphrase')).rejects.toThrow( + /incorrect passphrase|corrupted/i + ) + }) + + it('parseRaftbundle returns a failed ImportResult with a useful error', async () => { + const session = buildLargeSession(1, 5) + const blob = await exportBundle(session, 'right-passphrase') + + const result = await parseRaftbundle(blob, 'wrong-passphrase') + + expect(result.success).toBe(false) + expect(result.sessions).toHaveLength(0) + expect(result.errors).toHaveLength(1) + expect(result.errors[0].message).toMatch(/incorrect passphrase|corrupted/i) + expect(result.format).toBe('raftbundle') + }) + + it('rejects malformed envelopes without trying to derive a key', async () => { + const result = await parseRaftbundle('not-json', 'whatever') + expect(result.success).toBe(false) + expect(result.errors[0].message).toMatch(/not a valid raft bundle/i) + }) + + it('rejects envelopes missing required fields', async () => { + const result = await parseRaftbundle('{"v":1}', 'whatever') + expect(result.success).toBe(false) + expect(result.errors[0].message).toMatch(/envelope shape/i) + }) + + it('importBundle requires a passphrase', async () => { + const session = buildLargeSession(1, 1) + const blob = await exportBundle(session, 'pw') + await expect(importBundle(blob, '')).rejects.toThrow(/passphrase required/i) + }) + + it('exportBundle requires a passphrase', async () => { + const session = buildLargeSession(1, 1) + await expect(exportBundle(session, '')).rejects.toThrow(/passphrase required/i) + }) + }) + + describe('Envelope uses the 600k PBKDF2 default', () => { + it('records iterations: 600_000 in the envelope', async () => { + const session = buildLargeSession(1, 2) + const blob = await exportBundle(session, 'any-passphrase') + const envelope = await readEnvelope(blob) + + expect(envelope.iterations).toBe(PBKDF2_ITERATIONS) + expect(PBKDF2_ITERATIONS).toBe(600_000) + expect(envelope.v).toBe(BUNDLE_VERSION) + expect(typeof envelope.salt).toBe('string') + expect(typeof envelope.iv).toBe('string') + expect(typeof envelope.ct).toBe('string') + }) + + it('two exports of the same session produce different ciphertexts (fresh salt+iv)', async () => { + const session = buildLargeSession(1, 3) + const blob1 = await exportBundle(session, 'pw') + const blob2 = await exportBundle(session, 'pw') + + const env1 = await readEnvelope(blob1) + const env2 = await readEnvelope(blob2) + + expect(env1.salt).not.toBe(env2.salt) + expect(env1.iv).not.toBe(env2.iv) + expect(env1.ct).not.toBe(env2.ct) + }) + }) + + describe('Generated passphrase is high-entropy', () => { + it('produces unique passphrases on repeated calls', () => { + const seen = new Set() + for (let i = 0; i < 50; i++) { + seen.add(generateBundlePassphrase()) + } + // No collisions in 50 draws — confirms the wordlist+digit space is + // doing real work and not silently returning a constant. + expect(seen.size).toBe(50) + }) + + it('passphrase has the expected shape (6 words + 4 digits)', () => { + const pw = generateBundlePassphrase() + // word-word-word-word-word-word-NNNN + expect(pw).toMatch(/^[a-z]+(-[a-z]+){5}-\d{4}$/) + }) + }) +})