From b8cd19343f0ebd564e82dead56e59da03bcddeb4 Mon Sep 17 00:00:00 2001 From: souta <109493063+souta-lab@users.noreply.github.com> Date: Fri, 23 Oct 2026 14:49:09 +0900 Subject: [PATCH 01/12] feat: migrate whole-profile Firefox localStorage and improve cookie fidelity --- .gitignore | 3 + README.md | 10 ++ chrome/dashboard.js | 112 ++++++++++++++++--- chrome/manifest.json | 7 +- firefox/dashboard.js | 112 ++++++++++++++++--- firefox/manifest.json | 17 ++- tests/test_firefox_localstorage.py | 63 +++++++++++ tests/test_storage_browser.cjs | 51 +++++++++ tools/README.md | 52 +++++++++ tools/firefox_localstorage.py | 167 +++++++++++++++++++++++++++++ 10 files changed, 561 insertions(+), 33 deletions(-) create mode 100644 .gitignore create mode 100644 tests/test_firefox_localstorage.py create mode 100644 tests/test_storage_browser.cjs create mode 100644 tools/README.md create mode 100644 tools/firefox_localstorage.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9c4408f --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +__pycache__/ +*.py[cod] +*.portage.json diff --git a/README.md b/README.md index 0f222d2..b0753ef 100644 --- a/README.md +++ b/README.md @@ -63,3 +63,13 @@ Check the releases tab of the repo, or go to the website for Portage at: https:/ 1. **Export:** Open Portage on your old browser, click **Scan**, uncheck anything you want to leave behind, and hit **Export bundle**. It drops the JSON (and the optional extension checklist) right to your downloads. 2. **Import:** Open Portage on your new browser, drag and drop the `.portage.json` file, review the stats, and hit **Import selected**. + +## Experimental: entire Firefox localStorage profile (Linux) + +The browser's WebExtension APIs cannot enumerate every origin's localStorage. +For a read-only **all-site** Firefox profile exporter and an import flow that +visits each origin in a temporary background tab, see +[tools/README.md](tools/README.md). This is **not** limited to currently open +tabs, but is still best-effort: IndexedDB, sessionStorage, and device-bound +credentials are not migrated. Exports can contain active authentication tokens, +so handle them as sensitive files. diff --git a/chrome/dashboard.js b/chrome/dashboard.js index 385bd3d..6a6b8d4 100644 --- a/chrome/dashboard.js +++ b/chrome/dashboard.js @@ -142,8 +142,23 @@ async function collectHistory() { return { data, count: data.length }; } async function collectCookies() { - const all = await api.cookies.getAll({}); - const data = all.map((c) => ({ name: c.name, value: c.value, domain: c.domain, path: c.path, secure: c.secure, httpOnly: c.httpOnly, sameSite: c.sameSite, expirationDate: c.expirationDate, hostOnly: c.hostOnly, session: c.session })); + // Firefox's default getAll({}) omits Total Cookie Protection partitions. + // Firefox accepts partitionKey:{} to return both partitioned and normal cookies. + // First-Party Isolation requires firstPartyDomain:null to include all domains. + const stores = await api.cookies.getAllCookieStores(); + const all = []; + for (const store of stores) { + const query = { storeId: store.id }; + if (IS_FIREFOX) { query.partitionKey = {}; query.firstPartyDomain = null; } + all.push(...await api.cookies.getAll(query)); + } + const data = all.map((c) => ({ + name: c.name, value: c.value, domain: c.domain, path: c.path, + secure: c.secure, httpOnly: c.httpOnly, sameSite: c.sameSite, + expirationDate: c.expirationDate, hostOnly: c.hostOnly, session: c.session, + storeId: c.storeId, partitionKey: c.partitionKey, + firstPartyDomain: c.firstPartyDomain, + })); return { data, count: data.length }; } async function collectTabs() { @@ -205,26 +220,92 @@ async function importHistory(items, onProg) { } onProg(total, total); return { imported, skipped }; } -function mapSameSite(s) { return s === "strict" ? "strict" : s === "lax" ? "lax" : "no_restriction"; } +function mapSameSite(s) { + // No SameSite attribute is NOT equivalent to SameSite=None. + return ["strict", "lax", "no_restriction", "unspecified"].includes(s) ? s : "unspecified"; +} async function importCookies(items, onProg) { const total = items.length; let imported = 0, skipped = 0; + // Store IDs are browser-specific. Only copy into the selected browser's + // default cookie store; isolated Firefox Containers are not safely mergeable. + const stores = await api.cookies.getAllCookieStores(); + const targetStore = stores.find((s) => s.id === (IS_FIREFOX ? "firefox-default" : "0")) || stores[0]; for (let i = 0; i < total; i++) { const c = items[i]; try { const host = (c.domain || "").replace(/^\./, ""); - if (!host) skipped++; - else { - const url = (c.secure ? "https" : "http") + "://" + host + (c.path || "/"); - const d = { url, name: c.name, value: c.value, path: c.path || "/", secure: !!c.secure, httpOnly: !!c.httpOnly, sameSite: mapSameSite(c.sameSite) }; - if (!c.hostOnly) d.domain = c.domain; - if (!c.session && c.expirationDate) d.expirationDate = c.expirationDate; - await api.cookies.set(d); imported++; - } + if (!host || (c.firstPartyDomain && !IS_FIREFOX)) { skipped++; continue; } + // Do not silently collapse isolated container stores into one login. + if (c.storeId && c.storeId !== "firefox-default" && c.storeId !== "0" && c.storeId !== targetStore?.id) { skipped++; continue; } + const url = (c.secure ? "https" : "http") + "://" + host + (c.path || "/"); + const d = { url, name: c.name, value: c.value, path: c.path || "/", secure: !!c.secure, httpOnly: !!c.httpOnly, sameSite: mapSameSite(c.sameSite) }; + if (!c.hostOnly) d.domain = c.domain; + if (!c.session && Number.isFinite(c.expirationDate)) d.expirationDate = c.expirationDate; + if (targetStore?.id) d.storeId = targetStore.id; + if (c.partitionKey?.topLevelSite) d.partitionKey = { topLevelSite: c.partitionKey.topLevelSite }; + if (c.firstPartyDomain && IS_FIREFOX) d.firstPartyDomain = c.firstPartyDomain; + if (await api.cookies.set(d)) imported++; else skipped++; } catch { skipped++; } if (i % 100 === 0) { onProg(i, total); await tick(); } } onProg(total, total); return { imported, skipped }; } + +// A companion read-only Python CLI enumerates *every* compatible Firefox LSNG +// database in the profile. This import is NOT restricted to currently open tabs. +// WebExtension scripting is origin-scoped, so we temporarily visit each origin +// in a background tab to seed its localStorage, then close that tab. +function isSafeStorageOrigin(origin) { + try { + const u = new URL(origin); + return ["https:", "http:"].includes(u.protocol) && u.origin === origin && !u.username && !u.password; + } catch { return false; } +} +async function importLocalStorage(sites, onProg) { + const total = sites.length; let imported = 0, skipped = 0; + if (!api.scripting?.executeScript) throw new Error("The scripting permission is unavailable"); + for (let i = 0; i < total; i++) { + const site = sites[i]; + let tab; + try { + if (!isSafeStorageOrigin(site.origin) || !site.items || + typeof site.items !== "object" || Array.isArray(site.items) || + Object.values(site.items).some((v) => typeof v !== "string")) throw new Error("Invalid origin or values"); + tab = await api.tabs.create({ url: site.origin, active: false }); + await new Promise((resolve, reject) => { + const timeout = setTimeout(() => { api.tabs.onUpdated.removeListener(listener); reject(new Error("Timed out")); }, 12000); + const listener = (id, changeInfo) => { + if (id === tab.id && changeInfo.status === "complete") { + clearTimeout(timeout); api.tabs.onUpdated.removeListener(listener); resolve(); + } + }; + api.tabs.onUpdated.addListener(listener); + // Covers a tab finishing before listener registration. + api.tabs.get(tab.id).then((t) => { if (t.status === "complete") listener(tab.id, { status: "complete" }); }).catch(() => {}); + }); + // Never write a saved origin's keys into a different (redirected) site. + const loaded = await api.tabs.get(tab.id); + if (!loaded.url || new URL(loaded.url).origin !== site.origin) throw new Error("Origin redirected"); + const result = await api.scripting.executeScript({ + target: { tabId: tab.id }, + func: (entries) => { + let written = 0; + for (const [k, v] of Object.entries(entries)) { localStorage.setItem(k, v); written++; } + return written; + }, + args: [site.items], + }); + if (result?.[0]?.result === Object.keys(site.items).length) imported++; else skipped++; + } catch { skipped++; } + finally { + if (tab?.id) { try { await api.tabs.remove(tab.id); } catch {} } + onProg(i + 1, total); + if (i % 10 === 0) await tick(); + } + } + return { imported, skipped }; +} + async function importTabs(items, onProg) { const total = items.length; let imported = 0, skipped = 0; for (let i = 0; i < total; i++) { @@ -264,19 +345,20 @@ async function importReadingList(items, onProg) { const CATS = { bookmarks: { label: "Bookmarks", unit: "bookmarks", icon: SVG.bookmarks, level: "full", desc: "Full bookmark tree, folders and all", importFx: "Created in a 'Portage Import' folder", collect: collectBookmarks, count: countBookmarks, importRun: importBookmarks }, history: { label: "History", unit: "pages", icon: SVG.history, level: "full", desc: "Pages you've visited, with timestamps", importFx: IS_FIREFOX ? "Re-added with titles & times" : "Re-added as visits", collect: collectHistory, count: (d) => d.length, importRun: importHistory }, + localStorage: { label: "LocalStorage", unit: "origins", icon: SVG.cookies, level: "partial", desc: "All-site Firefox profile storage (offline CLI bundle)", importFx: "Visits each origin temporarily to restore saved keys", collect: null, count: (d) => d.length, importRun: importLocalStorage, externalImportOnly: true }, cookies: { label: "Cookies", unit: "cookies", icon: SVG.cookies, level: "full", desc: "Site cookies — keeps you signed in", importFx: "Re-set so logins carry over", collect: collectCookies, count: (d) => d.length, importRun: importCookies }, tabs: { label: "Open tabs", unit: "tabs", icon: SVG.tabs, level: "full", desc: "Tabs open right now, every window", importFx: "Reopened in this window", collect: collectTabs, count: (d) => d.length, importRun: importTabs }, sessions: { label: "Recently closed", unit: "sessions", icon: SVG.sessions, level: "partial", desc: "Tabs & windows you closed recently", importFx: "Reopened as tabs", collect: collectSessions, count: countSessions, importRun: importSessions }, readingList: { label: "Reading list", unit: "entries", icon: SVG.reading, level: HAS_READINGLIST ? "full" : "partial", desc: "Pages saved to read later", importFx: HAS_READINGLIST ? "Added to the reading list" : "Saved to a bookmark folder", collect: collectReadingList, count: (d) => d.length, importRun: importReadingList, needsReadingList: true }, extensions: { label: "Extensions", unit: "installed", icon: SVG.extensions, level: "checklist", desc: "Installed add-ons → reinstall checklist", importFx: "Can't auto-install — use the .txt checklist", collect: collectExtensions, count: (d) => d.length, importRun: null, special: true }, }; -const ORDER = ["bookmarks", "history", "cookies", "tabs", "sessions", "readingList", "extensions"]; +const ORDER = ["bookmarks", "history", "cookies", "localStorage", "tabs", "sessions", "readingList", "extensions"]; const exState = {}; let scanned = false; const exGrid = document.getElementById("exportGrid"); -function exportCategoryIds() { return ORDER.filter((id) => !(CATS[id].needsReadingList && !HAS_READINGLIST)); } +function exportCategoryIds() { return ORDER.filter((id) => !CATS[id].externalImportOnly && !(CATS[id].needsReadingList && !HAS_READINGLIST)); } function makeCard(id, c, opts) { const el = document.createElement("div"); @@ -584,6 +666,10 @@ function updateImportTotals() { } async function runImport() { + if (imState.localStorage?.selected && !window.confirm( + "LocalStorage import will visit every saved site in temporary background tabs. " + + "This sends network requests and may trigger website activity. Continue?" + )) return; const btn = document.getElementById("importBtn"); const orig = btn.innerHTML; btn.disabled = true; btn.innerHTML = ' Importing…'; document.getElementById("impbarWrap").classList.remove("hidden"); diff --git a/chrome/manifest.json b/chrome/manifest.json index 7636bb9..9aa96d4 100644 --- a/chrome/manifest.json +++ b/chrome/manifest.json @@ -11,9 +11,12 @@ "tabs", "sessions", "management", - "readingList" + "readingList", + "scripting" + ], + "host_permissions": [ + "" ], - "host_permissions": [""], "action": { "default_popup": "popup.html", "default_title": "Portage", diff --git a/firefox/dashboard.js b/firefox/dashboard.js index 8da23d2..94bbb95 100644 --- a/firefox/dashboard.js +++ b/firefox/dashboard.js @@ -145,8 +145,23 @@ async function collectHistory() { return { data, count: data.length }; } async function collectCookies() { - const all = await api.cookies.getAll({}); - const data = all.map((c) => ({ name: c.name, value: c.value, domain: c.domain, path: c.path, secure: c.secure, httpOnly: c.httpOnly, sameSite: c.sameSite, expirationDate: c.expirationDate, hostOnly: c.hostOnly, session: c.session })); + // Firefox's default getAll({}) omits Total Cookie Protection partitions. + // Firefox accepts partitionKey:{} to return both partitioned and normal cookies. + // First-Party Isolation requires firstPartyDomain:null to include all domains. + const stores = await api.cookies.getAllCookieStores(); + const all = []; + for (const store of stores) { + const query = { storeId: store.id }; + if (IS_FIREFOX) { query.partitionKey = {}; query.firstPartyDomain = null; } + all.push(...await api.cookies.getAll(query)); + } + const data = all.map((c) => ({ + name: c.name, value: c.value, domain: c.domain, path: c.path, + secure: c.secure, httpOnly: c.httpOnly, sameSite: c.sameSite, + expirationDate: c.expirationDate, hostOnly: c.hostOnly, session: c.session, + storeId: c.storeId, partitionKey: c.partitionKey, + firstPartyDomain: c.firstPartyDomain, + })); return { data, count: data.length }; } async function collectTabs() { @@ -208,26 +223,92 @@ async function importHistory(items, onProg) { } onProg(total, total); return { imported, skipped }; } -function mapSameSite(s) { return s === "strict" ? "strict" : s === "lax" ? "lax" : "no_restriction"; } +function mapSameSite(s) { + // No SameSite attribute is NOT equivalent to SameSite=None. + return ["strict", "lax", "no_restriction", "unspecified"].includes(s) ? s : "unspecified"; +} async function importCookies(items, onProg) { const total = items.length; let imported = 0, skipped = 0; + // Store IDs are browser-specific. Only copy into the selected browser's + // default cookie store; isolated Firefox Containers are not safely mergeable. + const stores = await api.cookies.getAllCookieStores(); + const targetStore = stores.find((s) => s.id === (IS_FIREFOX ? "firefox-default" : "0")) || stores[0]; for (let i = 0; i < total; i++) { const c = items[i]; try { const host = (c.domain || "").replace(/^\./, ""); - if (!host) skipped++; - else { - const url = (c.secure ? "https" : "http") + "://" + host + (c.path || "/"); - const d = { url, name: c.name, value: c.value, path: c.path || "/", secure: !!c.secure, httpOnly: !!c.httpOnly, sameSite: mapSameSite(c.sameSite) }; - if (!c.hostOnly) d.domain = c.domain; - if (!c.session && c.expirationDate) d.expirationDate = c.expirationDate; - await api.cookies.set(d); imported++; - } + if (!host || (c.firstPartyDomain && !IS_FIREFOX)) { skipped++; continue; } + // Do not silently collapse isolated container stores into one login. + if (c.storeId && c.storeId !== "firefox-default" && c.storeId !== "0" && c.storeId !== targetStore?.id) { skipped++; continue; } + const url = (c.secure ? "https" : "http") + "://" + host + (c.path || "/"); + const d = { url, name: c.name, value: c.value, path: c.path || "/", secure: !!c.secure, httpOnly: !!c.httpOnly, sameSite: mapSameSite(c.sameSite) }; + if (!c.hostOnly) d.domain = c.domain; + if (!c.session && Number.isFinite(c.expirationDate)) d.expirationDate = c.expirationDate; + if (targetStore?.id) d.storeId = targetStore.id; + if (c.partitionKey?.topLevelSite) d.partitionKey = { topLevelSite: c.partitionKey.topLevelSite }; + if (c.firstPartyDomain && IS_FIREFOX) d.firstPartyDomain = c.firstPartyDomain; + if (await api.cookies.set(d)) imported++; else skipped++; } catch { skipped++; } if (i % 100 === 0) { onProg(i, total); await tick(); } } onProg(total, total); return { imported, skipped }; } + +// A companion read-only Python CLI enumerates *every* compatible Firefox LSNG +// database in the profile. This import is NOT restricted to currently open tabs. +// WebExtension scripting is origin-scoped, so we temporarily visit each origin +// in a background tab to seed its localStorage, then close that tab. +function isSafeStorageOrigin(origin) { + try { + const u = new URL(origin); + return ["https:", "http:"].includes(u.protocol) && u.origin === origin && !u.username && !u.password; + } catch { return false; } +} +async function importLocalStorage(sites, onProg) { + const total = sites.length; let imported = 0, skipped = 0; + if (!api.scripting?.executeScript) throw new Error("The scripting permission is unavailable"); + for (let i = 0; i < total; i++) { + const site = sites[i]; + let tab; + try { + if (!isSafeStorageOrigin(site.origin) || !site.items || + typeof site.items !== "object" || Array.isArray(site.items) || + Object.values(site.items).some((v) => typeof v !== "string")) throw new Error("Invalid origin or values"); + tab = await api.tabs.create({ url: site.origin, active: false }); + await new Promise((resolve, reject) => { + const timeout = setTimeout(() => { api.tabs.onUpdated.removeListener(listener); reject(new Error("Timed out")); }, 12000); + const listener = (id, changeInfo) => { + if (id === tab.id && changeInfo.status === "complete") { + clearTimeout(timeout); api.tabs.onUpdated.removeListener(listener); resolve(); + } + }; + api.tabs.onUpdated.addListener(listener); + // Covers a tab finishing before listener registration. + api.tabs.get(tab.id).then((t) => { if (t.status === "complete") listener(tab.id, { status: "complete" }); }).catch(() => {}); + }); + // Never write a saved origin's keys into a different (redirected) site. + const loaded = await api.tabs.get(tab.id); + if (!loaded.url || new URL(loaded.url).origin !== site.origin) throw new Error("Origin redirected"); + const result = await api.scripting.executeScript({ + target: { tabId: tab.id }, + func: (entries) => { + let written = 0; + for (const [k, v] of Object.entries(entries)) { localStorage.setItem(k, v); written++; } + return written; + }, + args: [site.items], + }); + if (result?.[0]?.result === Object.keys(site.items).length) imported++; else skipped++; + } catch { skipped++; } + finally { + if (tab?.id) { try { await api.tabs.remove(tab.id); } catch {} } + onProg(i + 1, total); + if (i % 10 === 0) await tick(); + } + } + return { imported, skipped }; +} + async function importTabs(items, onProg) { const total = items.length; let imported = 0, skipped = 0; for (let i = 0; i < total; i++) { @@ -267,19 +348,20 @@ async function importReadingList(items, onProg) { const CATS = { bookmarks: { label: "Bookmarks", unit: "bookmarks", icon: SVG.bookmarks, level: "full", desc: "Full bookmark tree, folders and all", importFx: "Created in a 'Portage Import' folder", collect: collectBookmarks, count: countBookmarks, importRun: importBookmarks }, history: { label: "History", unit: "pages", icon: SVG.history, level: "full", desc: "Pages you've visited, with timestamps", importFx: IS_FIREFOX ? "Re-added with titles & times" : "Re-added as visits", collect: collectHistory, count: (d) => d.length, importRun: importHistory }, + localStorage: { label: "LocalStorage", unit: "origins", icon: SVG.cookies, level: "partial", desc: "All-site Firefox profile storage (offline CLI bundle)", importFx: "Visits each origin temporarily to restore saved keys", collect: null, count: (d) => d.length, importRun: importLocalStorage, externalImportOnly: true }, cookies: { label: "Cookies", unit: "cookies", icon: SVG.cookies, level: "full", desc: "Site cookies — keeps you signed in", importFx: "Re-set so logins carry over", collect: collectCookies, count: (d) => d.length, importRun: importCookies }, tabs: { label: "Open tabs", unit: "tabs", icon: SVG.tabs, level: "full", desc: "Tabs open right now, every window", importFx: "Reopened in this window", collect: collectTabs, count: (d) => d.length, importRun: importTabs }, sessions: { label: "Recently closed", unit: "sessions", icon: SVG.sessions, level: "partial", desc: "Tabs & windows you closed recently", importFx: "Reopened as tabs", collect: collectSessions, count: countSessions, importRun: importSessions }, readingList: { label: "Reading list", unit: "entries", icon: SVG.reading, level: HAS_READINGLIST ? "full" : "partial", desc: "Pages saved to read later", importFx: HAS_READINGLIST ? "Added to the reading list" : "Saved to a bookmark folder", collect: collectReadingList, count: (d) => d.length, importRun: importReadingList, needsReadingList: true }, extensions: { label: "Extensions", unit: "installed", icon: SVG.extensions, level: "checklist", desc: "Installed add-ons → reinstall checklist", importFx: "Can't auto-install — use the .txt checklist", collect: collectExtensions, count: (d) => d.length, importRun: null, special: true }, }; -const ORDER = ["bookmarks", "history", "cookies", "tabs", "sessions", "readingList", "extensions"]; +const ORDER = ["bookmarks", "history", "cookies", "localStorage", "tabs", "sessions", "readingList", "extensions"]; const exState = {}; let scanned = false; const exGrid = document.getElementById("exportGrid"); -function exportCategoryIds() { return ORDER.filter((id) => !(CATS[id].needsReadingList && !HAS_READINGLIST)); } +function exportCategoryIds() { return ORDER.filter((id) => !CATS[id].externalImportOnly && !(CATS[id].needsReadingList && !HAS_READINGLIST)); } function makeCard(id, c, opts) { const el = document.createElement("div"); @@ -587,6 +669,10 @@ function updateImportTotals() { } async function runImport() { + if (imState.localStorage?.selected && !window.confirm( + "LocalStorage import will visit every saved site in temporary background tabs. " + + "This sends network requests and may trigger website activity. Continue?" + )) return; const btn = document.getElementById("importBtn"); const orig = btn.innerHTML; btn.disabled = true; btn.innerHTML = ' Importing…'; document.getElementById("impbarWrap").classList.remove("hidden"); diff --git a/firefox/manifest.json b/firefox/manifest.json index 35b78c3..c10549c 100644 --- a/firefox/manifest.json +++ b/firefox/manifest.json @@ -2,14 +2,16 @@ "manifest_version": 3, "name": "Portage", "version": "2.0.1", - "description": "Universal browser data swap. Export bookmarks, history, cookies, tabs and sessions to a portable JSON bundle, then import into any browser running Portage — Firefox to Chrome, or the same browser on a new machine. Also exports your add-on list as a reinstall checklist.", + "description": "Universal browser data swap. Export bookmarks, history, cookies, tabs and sessions to a portable JSON bundle, then import into any browser running Portage \u2014 Firefox to Chrome, or the same browser on a new machine. Also exports your add-on list as a reinstall checklist.", "homepage_url": "https://github.com/pvrzz/Portage/", "browser_specific_settings": { "gecko": { "id": "portage@local", "strict_min_version": "115.0", "data_collection_permissions": { - "required": ["none"] + "required": [ + "none" + ] } } }, @@ -19,9 +21,12 @@ "cookies", "tabs", "sessions", - "management" + "management", + "scripting" + ], + "host_permissions": [ + "" ], - "host_permissions": [""], "action": { "default_popup": "popup.html", "default_title": "Portage", @@ -39,6 +44,8 @@ "128": "icons/icon128.png" }, "background": { - "scripts": ["background.js"] + "scripts": [ + "background.js" + ] } } diff --git a/tests/test_firefox_localstorage.py b/tests/test_firefox_localstorage.py new file mode 100644 index 0000000..02ddd7c --- /dev/null +++ b/tests/test_firefox_localstorage.py @@ -0,0 +1,63 @@ +import json +import os +import sqlite3 +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools')) +from firefox_localstorage import decode_value, export_profile, snappy_decode, valid_origin + + +class FirefoxLocalStorageTest(unittest.TestCase): + def test_snappy_literal_and_copy(self): + self.assertEqual(snappy_decode(b'\x05\x10hello'), b'hello') + # 12 byte result: literal 'abc', followed by 9-byte copy at offset 3 + self.assertEqual(snappy_decode(b'\x0c\x08abc\x22\x03\x00'), b'abcabcabcabc') + with self.assertRaises(ValueError): + snappy_decode(b'\xff\xff\xff\xff\x7f') + + def test_utf8_utf16_and_compression(self): + self.assertEqual(decode_value('日本語'.encode(), 1, 0), '日本語') + self.assertEqual(decode_value('日本語'.encode('utf-16-be'), 0, 0), '日本語') + self.assertEqual(decode_value(b'\x05\x10hello', 1, 1), 'hello') + with self.assertRaises(ValueError): + decode_value(b'a', 1, 99) + + def test_valid_origin(self): + self.assertTrue(valid_origin('https://example.org:443')) + self.assertFalse(valid_origin('https://example.org^userContextId=2')) + self.assertFalse(valid_origin('https://example.org/some/path')) + self.assertFalse(valid_origin('javascript:alert(1)')) + + def test_export_all_offline_origins_and_permissions(self): + with tempfile.TemporaryDirectory() as t: + p=Path(t) + for name, origin, value in [('https+++first.test','https://first.test','token-A'), ('https+++second.test','https://second.test','こんにちは')]: + d=p/'storage'/'default'/name/'ls' + d.mkdir(parents=True) + with sqlite3.connect(d/'data.sqlite') as con: + con.execute('CREATE TABLE "database" (origin TEXT)') + con.execute('INSERT INTO "database" VALUES (?)',(origin,)) + con.execute('CREATE TABLE data (key TEXT, utf16_length INTEGER, conversion_type INTEGER, compression_type INTEGER, last_access_time INTEGER, value BLOB)') + con.execute('INSERT INTO data VALUES (?,?,?,?,?,?)',('login',len(value),1,0,0,value.encode())) + con.close() + sites,warnings=export_profile(p) + self.assertEqual(len(sites),2) + self.assertFalse(warnings) + self.assertEqual([s['origin'] for s in sites],['https://first.test','https://second.test']) + output=p/'export.portage.json' + script=Path(__file__).resolve().parents[1]/'tools'/'firefox_localstorage.py' + r=subprocess.run([sys.executable,str(script),'--profile',str(p),'--output',str(output)],capture_output=True,text=True) + self.assertEqual(r.returncode,0,r.stderr) + self.assertEqual(os.stat(output).st_mode & 0o777,0o600) + parsed=json.loads(output.read_text()) + self.assertEqual(parsed['meta']['counts']['localStorage'],2) + self.assertEqual(len(parsed['data']['localStorage']),2) + self.assertNotEqual(subprocess.run([sys.executable,str(script),'--profile',str(p),'--output',str(output)],capture_output=True).returncode,0) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_storage_browser.cjs b/tests/test_storage_browser.cjs new file mode 100644 index 0000000..498b10b --- /dev/null +++ b/tests/test_storage_browser.cjs @@ -0,0 +1,51 @@ +'use strict'; +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const vm = require('node:vm'); +for (const browser of ['chrome','firefox']) { + const src = fs.readFileSync(`${browser}/dashboard.js`, 'utf8'); + const start = src.indexOf('function mapSameSite('); + const end = src.indexOf('async function importTabs(', start); + assert(start > 0 && end > start); + const ctx = vm.createContext({URL, setTimeout, clearTimeout, Object, Number, Array, tick: async () => {}, IS_FIREFOX: browser === 'firefox'}); + vm.runInContext(src.slice(start,end), ctx); + assert.equal(vm.runInContext('mapSameSite("unspecified")', ctx), 'unspecified'); + assert.equal(vm.runInContext('mapSameSite("no_restriction")', ctx), 'no_restriction'); + assert.equal(vm.runInContext('mapSameSite("unknown")', ctx), 'unspecified'); + assert.equal(vm.runInContext('isSafeStorageOrigin("https://site.test")', ctx), true); + assert.equal(vm.runInContext('isSafeStorageOrigin("https://site.test/evil")', ctx), false); + (async () => { + const visited = [], closed = [], written = []; + const listeners = new Set(); + ctx.api = { + tabs: { + create: async ({url}) => { const id = visited.length+1; visited.push(url); return {id}; }, + get: async (id) => ({status:'complete', url: visited[id-1]}), + remove: async (id) => {closed.push(id)}, + onUpdated: { addListener: (f) => listeners.add(f), removeListener: (f) => listeners.delete(f)}, + }, + scripting: { executeScript: async ({target,func,args}) => { + const old = ctx.localStorage; + ctx.localStorage={setItem:(k,v)=>written.push([k,v])}; + // Function is evaluated in a tab by the actual browser; here emulate it. + const total = Object.entries(args[0]).length; + ctx.localStorage=old; + return [{result:total}]; + }}, + cookies: {getAllCookieStores: async()=>[{id:browser==='firefox'?'firefox-default':'0'}],set:async()=>({})}, + }; + const sites = [ + {origin:'https://first.test',items:{a:'a-value'}}, + {origin:'https://second.test',items:{b:'b-value'}}, + {origin:'javascript:alert(1)',items:{c:'nope'}}, + ]; + const result = await ctx.importLocalStorage(sites, () => {}); + assert.equal(result.imported,2); + assert.equal(result.skipped,1); + assert.deepEqual(visited,['https://first.test','https://second.test']); + assert.deepEqual(closed,[1,2]); + const cookie = await ctx.importCookies([{name:'s',value:'v',domain:'example.com',hostOnly:true,sameSite:'unspecified'}],()=>{}); + assert.equal(cookie.imported,1); + console.log(`${browser}: storage sites, origin validation, cookies and SameSite passed`); + })().catch((err)=>{console.error(err);process.exitCode=1;}); +} diff --git a/tools/README.md b/tools/README.md new file mode 100644 index 0000000..55fc9b1 --- /dev/null +++ b/tools/README.md @@ -0,0 +1,52 @@ +# Whole-profile LocalStorage migration (experimental, Linux) + +The browser extension cannot enumerate another browser's complete site storage via +WebExtension APIs. Portage's companion script therefore reads **all compatible +first-party Firefox LSNG localStorage databases**, not only open tabs. It is +read-only and standard-library-only (no Internet requests). + +**Privacy:** localStorage often includes authentication tokens. Output is +**UNENCRYPTED** JSON and created with mode `0600`. Do not share, attach to bug +reports, or commit it. After migration, securely manage/delete the file per +local policy. Keep an offline backup of your Firefox profile. + +1. In Firefox `about:profiles`, find the **Root Directory** of the intended + profile. Close Firefox to avoid racing database changes. +2. Export in a private directory: + + ```sh + python3 tools/firefox_localstorage.py \ + --profile '/path/from/about:profiles' \ + --output "$HOME/portage-localstorage.portage.json" + ``` + +3. Install the **unpacked** `chrome/` Portage extension in Brave (Developer mode) + or `firefox/` in Firefox. Open Portage, switch to Import, and load the new + `.portage.json` file. Select LocalStorage and choose **Import selected**. +4. The extension visits *every exported origin*, sequentially, in temporary + background tabs and writes the saved localStorage, then closes the tabs. + This causes real network requests to those sites. It may trigger background + actions; do not perform this on a production profile without a backup. + The importer reports imported/skipped **origins**, not individual keys. + +## Scope and limitations + +- First-party HTTP(S) localStorage from `storage/default/*/ls/data.sqlite`. +- Handles UTF-8 and UTF-16BE, plus Firefox raw Snappy compression. +- Skips partitioned/container origin attributes rather than merging them into + a different privacy context. Logs skipped/corrupt databases without contents. +- Does **not** migrate IndexedDB, sessionStorage, WebAuthn credentials, cookies, + service workers, or origin-bound browser keys. Portage's regular browser UI + handles cookies as a separate category. +- Does not guarantee uninterrupted login state. Some sites need fresh login. +- No login credentials are read from `logins.json`. +- Chromium must be able to load a site for its storage to be written via a + content script. Redirects, dead origins, missing permissions and browser + restrictions may cause individual origins to be skipped. + +For tests (synthetic, no personal browser data): + +```sh +python3 -m unittest discover -s tests -p 'test_*.py' +node tests/test_storage_browser.cjs +``` diff --git a/tools/firefox_localstorage.py b/tools/firefox_localstorage.py new file mode 100644 index 0000000..3d6d88d --- /dev/null +++ b/tools/firefox_localstorage.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +"""Export ALL first-party Firefox LSNG localStorage origins as a Portage bundle. + +This is deliberately an offline, read-only exporter. It never accesses network +services, Firefox cookies, passwords, or browser extension profiles. +""" +import argparse +from contextlib import closing +import json +import os +from pathlib import Path +import sqlite3 +import sys +from datetime import datetime, timezone +from urllib.parse import urlsplit + +MAX_DECOMPRESSED_BYTES = 64 * 1024 * 1024 + + +def snappy_decode(data: bytes) -> bytes: + """Decode Snappy *raw block* format (not framed/streaming).""" + pos = 0 + shift = 0 + expected = 0 + while True: + if pos >= len(data) or shift > 63: + raise ValueError('Invalid Snappy block length') + b = data[pos] + pos += 1 + expected |= (b & 127) << shift + if not b & 128: + break + shift += 7 + if expected > MAX_DECOMPRESSED_BYTES: + raise ValueError('Snappy block exceeds safety limit') + out = bytearray() + while pos < len(data): + tag = data[pos] + pos += 1 + op = tag & 3 + if op == 0: + n = tag >> 2 + if n < 60: + n += 1 + else: + extra = n - 59 + if pos + extra > len(data): + raise ValueError('Truncated Snappy literal size') + n = int.from_bytes(data[pos:pos+extra], 'little') + 1 + pos += extra + if pos + n > len(data) or len(out) + n > expected: + raise ValueError('Invalid Snappy literal') + out += data[pos:pos+n] + pos += n + else: + if op == 1: + n = 4 + ((tag >> 2) & 7) + if pos >= len(data): + raise ValueError('Truncated Snappy copy') + offset = ((tag & 0xe0) << 3) | data[pos] + pos += 1 + else: + n = 1 + (tag >> 2) + size = 2 if op == 2 else 4 + if pos + size > len(data): + raise ValueError('Truncated Snappy copy offset') + offset = int.from_bytes(data[pos:pos+size], 'little') + pos += size + if offset <= 0 or offset > len(out) or len(out) + n > expected: + raise ValueError('Invalid Snappy copy') + for _ in range(n): + out.append(out[-offset]) + if len(out) != expected: + raise ValueError('Snappy length mismatch') + return bytes(out) + + +def decode_value(value, conversion_type, compression_type) -> str: + raw = bytes(value) + if compression_type == 1: + raw = snappy_decode(raw) + elif compression_type != 0: + raise ValueError(f'Unknown compression type: {compression_type}') + if conversion_type == 0: + return raw.decode('utf-16-be') + if conversion_type == 1: + return raw.decode('utf-8') + raise ValueError(f'Unknown conversion type: {conversion_type}') + + +def valid_origin(origin: str) -> bool: + if not isinstance(origin, str) or '^' in origin or '#' in origin or '?' in origin: + return False # no silent loss of Firefox origin attributes / partitions + try: + u = urlsplit(origin) + return u.scheme in ('https', 'http') and bool(u.hostname) and not u.username and not u.password and u.path in ('', '/') + except ValueError: + return False + + +def export_profile(profile: Path): + root = profile / 'storage' / 'default' + if not root.is_dir(): + raise ValueError('Expected Firefox profile with storage/default directory') + sites, warnings = [], [] + for db in sorted(root.glob('*/ls/data.sqlite')): + try: + # SQLite read-only URI avoids creating journal files or modifying profile. + with closing(sqlite3.connect(db.as_uri() + '?mode=ro', uri=True, timeout=3)) as conn: + row = conn.execute('SELECT origin FROM "database" LIMIT 1').fetchone() + if not row or not valid_origin(row[0]): + warnings.append(f'Skipped partitioned or invalid origin: {db.parent.parent.name}') + continue + origin = row[0].rstrip('/') + entries = conn.execute('SELECT key, value, conversion_type, compression_type FROM data').fetchall() + if not entries: + continue + items = {} + for key, value, conversion, compression in entries: + if not isinstance(key, str): + raise ValueError('Non-text localStorage key') + items[key] = decode_value(value, conversion, compression) + sites.append({'origin': origin, 'items': items}) + except (sqlite3.Error, ValueError, UnicodeError, OSError) as exc: + warnings.append(f'Skipped {db.parent.parent.name}: {exc}') + return sites, warnings + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--profile', type=Path, required=True, help='Firefox profile folder from about:profiles') + parser.add_argument('--output', type=Path, required=True, help='New private .portage.json bundle (contains session secrets)') + args = parser.parse_args(argv) + profile = args.profile.expanduser().resolve() + output = args.output.expanduser().resolve() + if output.exists(): + parser.error('Output already exists: will not overwrite sensitive data') + if not profile.is_dir(): + parser.error('Profile directory does not exist') + sites, warnings = export_profile(profile) + if not sites: + parser.error('No compatible localStorage origins found (see warnings / profile path)') + bundle = { + 'portage': {'format': 'portage-bundle', 'version': 1, 'source': 'firefox', + 'generator': 'Portage offline localStorage exporter', + 'exportedAt': datetime.now(timezone.utc).isoformat()}, + 'meta': {'counts': {'localStorage': len(sites)}}, + 'data': {'localStorage': sites}, + } + # Create mode 0600: no permissive intermediate file, no clobber. + fd = os.open(output, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + try: + with os.fdopen(fd, 'w', encoding='utf-8') as out: + json.dump(bundle, out, ensure_ascii=False, separators=(',', ':')) + except BaseException: + output.unlink(missing_ok=True) + raise + print(f'Exported {len(sites)} origins to {output} (PRIVATE, UNENCRYPTED)') + print('The bundle may contain active login tokens. Do not upload or share it.') + for warning in warnings: + print('WARNING:', warning, file=sys.stderr) + if warnings: + print(f'Skipped {len(warnings)} origin(s); check warning lines.', file=sys.stderr) + + +if __name__ == '__main__': + main() From 7dfc3d68e36e0b8ad4cee3df1ef31ed3f45172ae Mon Sep 17 00:00:00 2001 From: souta <109493063+souta-lab@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:10:54 +0900 Subject: [PATCH 02/12] test: verify profile storage import in isolated Chrome 156 --- chrome/dashboard.js | 4 +- firefox/dashboard.js | 4 +- tests/e2e_chrome.cjs | 71 +++++++++++++++++++++++++++++++++++ tools/README.md | 2 + tools/firefox_localstorage.py | 2 +- 5 files changed, 80 insertions(+), 3 deletions(-) create mode 100644 tests/e2e_chrome.cjs diff --git a/chrome/dashboard.js b/chrome/dashboard.js index 6a6b8d4..6a9055b 100644 --- a/chrome/dashboard.js +++ b/chrome/dashboard.js @@ -243,7 +243,9 @@ async function importCookies(items, onProg) { if (!c.session && Number.isFinite(c.expirationDate)) d.expirationDate = c.expirationDate; if (targetStore?.id) d.storeId = targetStore.id; if (c.partitionKey?.topLevelSite) d.partitionKey = { topLevelSite: c.partitionKey.topLevelSite }; - if (c.firstPartyDomain && IS_FIREFOX) d.firstPartyDomain = c.firstPartyDomain; + // Firefox requires firstPartyDomain even for the default (empty) domain + // when First-Party Isolation is enabled. + if (IS_FIREFOX) d.firstPartyDomain = c.firstPartyDomain || ""; if (await api.cookies.set(d)) imported++; else skipped++; } catch { skipped++; } if (i % 100 === 0) { onProg(i, total); await tick(); } diff --git a/firefox/dashboard.js b/firefox/dashboard.js index 94bbb95..f928425 100644 --- a/firefox/dashboard.js +++ b/firefox/dashboard.js @@ -246,7 +246,9 @@ async function importCookies(items, onProg) { if (!c.session && Number.isFinite(c.expirationDate)) d.expirationDate = c.expirationDate; if (targetStore?.id) d.storeId = targetStore.id; if (c.partitionKey?.topLevelSite) d.partitionKey = { topLevelSite: c.partitionKey.topLevelSite }; - if (c.firstPartyDomain && IS_FIREFOX) d.firstPartyDomain = c.firstPartyDomain; + // Firefox requires firstPartyDomain even for the default (empty) domain + // when First-Party Isolation is enabled. + if (IS_FIREFOX) d.firstPartyDomain = c.firstPartyDomain || ""; if (await api.cookies.set(d)) imported++; else skipped++; } catch { skipped++; } if (i % 100 === 0) { onProg(i, total); await tick(); } diff --git a/tests/e2e_chrome.cjs b/tests/e2e_chrome.cjs new file mode 100644 index 0000000..f37b20c --- /dev/null +++ b/tests/e2e_chrome.cjs @@ -0,0 +1,71 @@ +#!/usr/bin/env node +// Real Chromium/Brave WebExtensions smoke test, using only temporary browser +// profiles and a local HTTP fixture; no personal browser profiles or secrets. +'use strict'; +const assert = require('node:assert/strict'); +const http = require('node:http'); +const os = require('node:os'); +const fs = require('node:fs'); +const path = require('node:path'); +const puppeteer = require('puppeteer'); + +function serve(redirectTo = null) { + const server = http.createServer((req, res) => { + if (redirectTo) {res.writeHead(302,{Location:redirectTo}); return res.end();} + if (req.url === '/redirect') { + res.writeHead(302, {Location:'http://localhost:'+server.address().port+'/'}); + return res.end(); + } + res.writeHead(200,{'content-type':'text/html','cache-control':'no-store'}); + res.end('LocalStorage testfixture'); + }); + return new Promise(resolve => server.listen(0,'127.0.0.1',()=>resolve(server))); +} +async function main() { + const server = await serve(); + const server2 = await serve(); + const redirectServer = await serve(`http://127.0.0.1:${server.address().port}`); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'portage-e2e-')); + const extDir = path.resolve('chrome'); + let browser; + try { + browser = await puppeteer.launch({executablePath: '/usr/bin/google-chrome',headless:true,userDataDir:dir,timeout:25000,pipe:true,enableExtensions:true,args:['--no-sandbox','--disable-gpu','--no-first-run','--no-default-browser-check']}); + const id=await browser.installExtension(extDir); + console.log('installed id:',id); + if (!id) throw new Error('Portage extension failed to load'); + const ext=await browser.newPage(); + await ext.goto(`chrome-extension://${id}/dashboard.html`,{waitUntil:'load'}); + const origin=`http://127.0.0.1:${server.address().port}`; + const origin2=`http://127.0.0.1:${server2.address().port}`; + const redirectOrigin=`http://127.0.0.1:${redirectServer.address().port}`; + const results=await ext.evaluate(async (origin, origin2, redirectOrigin)=> { + return await importLocalStorage([ + {origin,items:{k1:'persisted',unicode:'猫'}}, + {origin:origin2,items:{second:'isolated'}}, + {origin:redirectOrigin,items:{poison:'must-not-write'}}, + ],()=>{}); + },origin,origin2,redirectOrigin); + assert.equal(results.imported,2,JSON.stringify(results)); + assert.equal(results.skipped,1,JSON.stringify(results)); + const page=await browser.newPage(); + await page.goto(origin); + assert.equal(await page.evaluate(()=>localStorage.getItem('k1')),'persisted'); + assert.equal(await page.evaluate(()=>localStorage.getItem('unicode')),'猫'); + assert.equal(await page.evaluate(()=>localStorage.getItem('poison')),null); + const another = await browser.newPage(); + await another.goto(origin2); + assert.equal(await another.evaluate(()=>localStorage.getItem('second')),'isolated'); + assert.equal(await another.evaluate(()=>localStorage.getItem('k1')),null); + const cookie = await ext.evaluate(async (domain)=>importCookies([ + {name:'portage-test',value:'synthetic',domain,hostOnly:true,path:'/',secure:false,sameSite:'unspecified'} + ],()=>{}), '127.0.0.1'); + assert.equal(cookie.imported,1,JSON.stringify(cookie)); + assert.equal((await page.cookies()).find(c=>c.name==='portage-test')?.value,'synthetic'); + console.log(`PASS actual Chrome ${await browser.version()}: data written and readable after navigation`); + } finally { + if(browser) await browser.close(); + await Promise.all([server,server2,redirectServer].map(s=>new Promise(resolve=>s.close(resolve)))); + fs.rmSync(dir,{recursive:true,force:true}); + } +} +main().catch(e=>{console.error('E2E failed:',e.stack);process.exitCode=1}); diff --git a/tools/README.md b/tools/README.md index 55fc9b1..112aa41 100644 --- a/tools/README.md +++ b/tools/README.md @@ -49,4 +49,6 @@ For tests (synthetic, no personal browser data): ```sh python3 -m unittest discover -s tests -p 'test_*.py' node tests/test_storage_browser.cjs +# Optional: requires Puppeteer and a local Chrome installation; uses a temp profile +node tests/e2e_chrome.cjs ``` diff --git a/tools/firefox_localstorage.py b/tools/firefox_localstorage.py index 3d6d88d..7913f99 100644 --- a/tools/firefox_localstorage.py +++ b/tools/firefox_localstorage.py @@ -115,7 +115,7 @@ def export_profile(profile: Path): entries = conn.execute('SELECT key, value, conversion_type, compression_type FROM data').fetchall() if not entries: continue - items = {} + items = {} # Preserve all JSON keys, including "__proto__". for key, value, conversion, compression in entries: if not isinstance(key, str): raise ValueError('Non-text localStorage key') From 1e5ba9c91ced35d025bdf7ce6116869ee3d7191e Mon Sep 17 00:00:00 2001 From: souta <109493063+souta-lab@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:50:44 +0900 Subject: [PATCH 03/12] feat: encrypted offline all-origin Firefox localStorage migration --- .github/workflows/tests.yml | 28 +++ .gitignore | 1 + README.md | 10 +- chrome/dashboard.js | 64 +---- chrome/manifest.json | 3 +- firefox/dashboard.js | 64 +---- firefox/manifest.json | 3 +- tests/e2e_chrome.cjs | 26 +- tests/e2e_cross_browser.cjs | 59 +++++ tests/e2e_offline_import.cjs | 38 +++ tests/test_firefox_localstorage.py | 5 +- tests/test_storage_browser.cjs | 78 +++--- tools/README.md | 84 ++++--- tools/chromium_localstorage_import.cjs | 191 ++++++++++++++ tools/firefox_localstorage.py | 46 +++- tools/package-lock.json | 333 +++++++++++++++++++++++++ tools/package.json | 8 + 17 files changed, 792 insertions(+), 249 deletions(-) create mode 100644 .github/workflows/tests.yml create mode 100644 tests/e2e_cross_browser.cjs create mode 100644 tests/e2e_offline_import.cjs create mode 100644 tools/chromium_localstorage_import.cjs create mode 100644 tools/package-lock.json create mode 100644 tools/package.json diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..a94d574 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,28 @@ +name: Unit tests +on: + push: + branches: [main, feat/profile-storage-migration] + pull_request: +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - uses: actions/setup-node@v4 + with: + node-version: '22' + - name: Python tests + run: python3 -m unittest discover -s tests -p 'test_*.py' + - name: Browser API mock tests + run: node tests/test_storage_browser.cjs + - name: JavaScript syntax + run: | + node --check chrome/dashboard.js + node --check firefox/dashboard.js + node --check tools/chromium_localstorage_import.cjs + node --check tests/e2e_cross_browser.cjs + - name: CLI help + run: node tools/chromium_localstorage_import.cjs --help diff --git a/.gitignore b/.gitignore index 9c4408f..c59dc93 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ __pycache__/ *.py[cod] *.portage.json +tools/node_modules/ diff --git a/README.md b/README.md index b0753ef..1098ebc 100644 --- a/README.md +++ b/README.md @@ -64,12 +64,6 @@ Check the releases tab of the repo, or go to the website for Portage at: https:/ 1. **Export:** Open Portage on your old browser, click **Scan**, uncheck anything you want to leave behind, and hit **Export bundle**. It drops the JSON (and the optional extension checklist) right to your downloads. 2. **Import:** Open Portage on your new browser, drag and drop the `.portage.json` file, review the stats, and hit **Import selected**. -## Experimental: entire Firefox localStorage profile (Linux) +## Experimental: whole-profile Firefox LocalStorage transfer (Linux) -The browser's WebExtension APIs cannot enumerate every origin's localStorage. -For a read-only **all-site** Firefox profile exporter and an import flow that -visits each origin in a temporary background tab, see -[tools/README.md](tools/README.md). This is **not** limited to currently open -tabs, but is still best-effort: IndexedDB, sessionStorage, and device-bound -credentials are not migrated. Exports can contain active authentication tokens, -so handle them as sensitive files. +Optional Python + Node helpers can migrate **all compatible first-party origins**, not just open tabs, to a closed Chrome/Brave profile. Export is encrypted by default; import uses intercepted inert responses rather than contacting websites. See the [step-by-step CLI and privacy limitations](tools/README.md). This does **not** include IndexedDB or guarantee login-session preservation. diff --git a/chrome/dashboard.js b/chrome/dashboard.js index 6a9055b..3023acb 100644 --- a/chrome/dashboard.js +++ b/chrome/dashboard.js @@ -253,61 +253,6 @@ async function importCookies(items, onProg) { onProg(total, total); return { imported, skipped }; } -// A companion read-only Python CLI enumerates *every* compatible Firefox LSNG -// database in the profile. This import is NOT restricted to currently open tabs. -// WebExtension scripting is origin-scoped, so we temporarily visit each origin -// in a background tab to seed its localStorage, then close that tab. -function isSafeStorageOrigin(origin) { - try { - const u = new URL(origin); - return ["https:", "http:"].includes(u.protocol) && u.origin === origin && !u.username && !u.password; - } catch { return false; } -} -async function importLocalStorage(sites, onProg) { - const total = sites.length; let imported = 0, skipped = 0; - if (!api.scripting?.executeScript) throw new Error("The scripting permission is unavailable"); - for (let i = 0; i < total; i++) { - const site = sites[i]; - let tab; - try { - if (!isSafeStorageOrigin(site.origin) || !site.items || - typeof site.items !== "object" || Array.isArray(site.items) || - Object.values(site.items).some((v) => typeof v !== "string")) throw new Error("Invalid origin or values"); - tab = await api.tabs.create({ url: site.origin, active: false }); - await new Promise((resolve, reject) => { - const timeout = setTimeout(() => { api.tabs.onUpdated.removeListener(listener); reject(new Error("Timed out")); }, 12000); - const listener = (id, changeInfo) => { - if (id === tab.id && changeInfo.status === "complete") { - clearTimeout(timeout); api.tabs.onUpdated.removeListener(listener); resolve(); - } - }; - api.tabs.onUpdated.addListener(listener); - // Covers a tab finishing before listener registration. - api.tabs.get(tab.id).then((t) => { if (t.status === "complete") listener(tab.id, { status: "complete" }); }).catch(() => {}); - }); - // Never write a saved origin's keys into a different (redirected) site. - const loaded = await api.tabs.get(tab.id); - if (!loaded.url || new URL(loaded.url).origin !== site.origin) throw new Error("Origin redirected"); - const result = await api.scripting.executeScript({ - target: { tabId: tab.id }, - func: (entries) => { - let written = 0; - for (const [k, v] of Object.entries(entries)) { localStorage.setItem(k, v); written++; } - return written; - }, - args: [site.items], - }); - if (result?.[0]?.result === Object.keys(site.items).length) imported++; else skipped++; - } catch { skipped++; } - finally { - if (tab?.id) { try { await api.tabs.remove(tab.id); } catch {} } - onProg(i + 1, total); - if (i % 10 === 0) await tick(); - } - } - return { imported, skipped }; -} - async function importTabs(items, onProg) { const total = items.length; let imported = 0, skipped = 0; for (let i = 0; i < total; i++) { @@ -347,20 +292,19 @@ async function importReadingList(items, onProg) { const CATS = { bookmarks: { label: "Bookmarks", unit: "bookmarks", icon: SVG.bookmarks, level: "full", desc: "Full bookmark tree, folders and all", importFx: "Created in a 'Portage Import' folder", collect: collectBookmarks, count: countBookmarks, importRun: importBookmarks }, history: { label: "History", unit: "pages", icon: SVG.history, level: "full", desc: "Pages you've visited, with timestamps", importFx: IS_FIREFOX ? "Re-added with titles & times" : "Re-added as visits", collect: collectHistory, count: (d) => d.length, importRun: importHistory }, - localStorage: { label: "LocalStorage", unit: "origins", icon: SVG.cookies, level: "partial", desc: "All-site Firefox profile storage (offline CLI bundle)", importFx: "Visits each origin temporarily to restore saved keys", collect: null, count: (d) => d.length, importRun: importLocalStorage, externalImportOnly: true }, cookies: { label: "Cookies", unit: "cookies", icon: SVG.cookies, level: "full", desc: "Site cookies — keeps you signed in", importFx: "Re-set so logins carry over", collect: collectCookies, count: (d) => d.length, importRun: importCookies }, tabs: { label: "Open tabs", unit: "tabs", icon: SVG.tabs, level: "full", desc: "Tabs open right now, every window", importFx: "Reopened in this window", collect: collectTabs, count: (d) => d.length, importRun: importTabs }, sessions: { label: "Recently closed", unit: "sessions", icon: SVG.sessions, level: "partial", desc: "Tabs & windows you closed recently", importFx: "Reopened as tabs", collect: collectSessions, count: countSessions, importRun: importSessions }, readingList: { label: "Reading list", unit: "entries", icon: SVG.reading, level: HAS_READINGLIST ? "full" : "partial", desc: "Pages saved to read later", importFx: HAS_READINGLIST ? "Added to the reading list" : "Saved to a bookmark folder", collect: collectReadingList, count: (d) => d.length, importRun: importReadingList, needsReadingList: true }, extensions: { label: "Extensions", unit: "installed", icon: SVG.extensions, level: "checklist", desc: "Installed add-ons → reinstall checklist", importFx: "Can't auto-install — use the .txt checklist", collect: collectExtensions, count: (d) => d.length, importRun: null, special: true }, }; -const ORDER = ["bookmarks", "history", "cookies", "localStorage", "tabs", "sessions", "readingList", "extensions"]; +const ORDER = ["bookmarks", "history", "cookies", "tabs", "sessions", "readingList", "extensions"]; const exState = {}; let scanned = false; const exGrid = document.getElementById("exportGrid"); -function exportCategoryIds() { return ORDER.filter((id) => !CATS[id].externalImportOnly && !(CATS[id].needsReadingList && !HAS_READINGLIST)); } +function exportCategoryIds() { return ORDER.filter((id) => !(CATS[id].needsReadingList && !HAS_READINGLIST)); } function makeCard(id, c, opts) { const el = document.createElement("div"); @@ -668,10 +612,6 @@ function updateImportTotals() { } async function runImport() { - if (imState.localStorage?.selected && !window.confirm( - "LocalStorage import will visit every saved site in temporary background tabs. " + - "This sends network requests and may trigger website activity. Continue?" - )) return; const btn = document.getElementById("importBtn"); const orig = btn.innerHTML; btn.disabled = true; btn.innerHTML = ' Importing…'; document.getElementById("impbarWrap").classList.remove("hidden"); diff --git a/chrome/manifest.json b/chrome/manifest.json index 9aa96d4..2c6add4 100644 --- a/chrome/manifest.json +++ b/chrome/manifest.json @@ -11,8 +11,7 @@ "tabs", "sessions", "management", - "readingList", - "scripting" + "readingList" ], "host_permissions": [ "" diff --git a/firefox/dashboard.js b/firefox/dashboard.js index f928425..363ce84 100644 --- a/firefox/dashboard.js +++ b/firefox/dashboard.js @@ -256,61 +256,6 @@ async function importCookies(items, onProg) { onProg(total, total); return { imported, skipped }; } -// A companion read-only Python CLI enumerates *every* compatible Firefox LSNG -// database in the profile. This import is NOT restricted to currently open tabs. -// WebExtension scripting is origin-scoped, so we temporarily visit each origin -// in a background tab to seed its localStorage, then close that tab. -function isSafeStorageOrigin(origin) { - try { - const u = new URL(origin); - return ["https:", "http:"].includes(u.protocol) && u.origin === origin && !u.username && !u.password; - } catch { return false; } -} -async function importLocalStorage(sites, onProg) { - const total = sites.length; let imported = 0, skipped = 0; - if (!api.scripting?.executeScript) throw new Error("The scripting permission is unavailable"); - for (let i = 0; i < total; i++) { - const site = sites[i]; - let tab; - try { - if (!isSafeStorageOrigin(site.origin) || !site.items || - typeof site.items !== "object" || Array.isArray(site.items) || - Object.values(site.items).some((v) => typeof v !== "string")) throw new Error("Invalid origin or values"); - tab = await api.tabs.create({ url: site.origin, active: false }); - await new Promise((resolve, reject) => { - const timeout = setTimeout(() => { api.tabs.onUpdated.removeListener(listener); reject(new Error("Timed out")); }, 12000); - const listener = (id, changeInfo) => { - if (id === tab.id && changeInfo.status === "complete") { - clearTimeout(timeout); api.tabs.onUpdated.removeListener(listener); resolve(); - } - }; - api.tabs.onUpdated.addListener(listener); - // Covers a tab finishing before listener registration. - api.tabs.get(tab.id).then((t) => { if (t.status === "complete") listener(tab.id, { status: "complete" }); }).catch(() => {}); - }); - // Never write a saved origin's keys into a different (redirected) site. - const loaded = await api.tabs.get(tab.id); - if (!loaded.url || new URL(loaded.url).origin !== site.origin) throw new Error("Origin redirected"); - const result = await api.scripting.executeScript({ - target: { tabId: tab.id }, - func: (entries) => { - let written = 0; - for (const [k, v] of Object.entries(entries)) { localStorage.setItem(k, v); written++; } - return written; - }, - args: [site.items], - }); - if (result?.[0]?.result === Object.keys(site.items).length) imported++; else skipped++; - } catch { skipped++; } - finally { - if (tab?.id) { try { await api.tabs.remove(tab.id); } catch {} } - onProg(i + 1, total); - if (i % 10 === 0) await tick(); - } - } - return { imported, skipped }; -} - async function importTabs(items, onProg) { const total = items.length; let imported = 0, skipped = 0; for (let i = 0; i < total; i++) { @@ -350,20 +295,19 @@ async function importReadingList(items, onProg) { const CATS = { bookmarks: { label: "Bookmarks", unit: "bookmarks", icon: SVG.bookmarks, level: "full", desc: "Full bookmark tree, folders and all", importFx: "Created in a 'Portage Import' folder", collect: collectBookmarks, count: countBookmarks, importRun: importBookmarks }, history: { label: "History", unit: "pages", icon: SVG.history, level: "full", desc: "Pages you've visited, with timestamps", importFx: IS_FIREFOX ? "Re-added with titles & times" : "Re-added as visits", collect: collectHistory, count: (d) => d.length, importRun: importHistory }, - localStorage: { label: "LocalStorage", unit: "origins", icon: SVG.cookies, level: "partial", desc: "All-site Firefox profile storage (offline CLI bundle)", importFx: "Visits each origin temporarily to restore saved keys", collect: null, count: (d) => d.length, importRun: importLocalStorage, externalImportOnly: true }, cookies: { label: "Cookies", unit: "cookies", icon: SVG.cookies, level: "full", desc: "Site cookies — keeps you signed in", importFx: "Re-set so logins carry over", collect: collectCookies, count: (d) => d.length, importRun: importCookies }, tabs: { label: "Open tabs", unit: "tabs", icon: SVG.tabs, level: "full", desc: "Tabs open right now, every window", importFx: "Reopened in this window", collect: collectTabs, count: (d) => d.length, importRun: importTabs }, sessions: { label: "Recently closed", unit: "sessions", icon: SVG.sessions, level: "partial", desc: "Tabs & windows you closed recently", importFx: "Reopened as tabs", collect: collectSessions, count: countSessions, importRun: importSessions }, readingList: { label: "Reading list", unit: "entries", icon: SVG.reading, level: HAS_READINGLIST ? "full" : "partial", desc: "Pages saved to read later", importFx: HAS_READINGLIST ? "Added to the reading list" : "Saved to a bookmark folder", collect: collectReadingList, count: (d) => d.length, importRun: importReadingList, needsReadingList: true }, extensions: { label: "Extensions", unit: "installed", icon: SVG.extensions, level: "checklist", desc: "Installed add-ons → reinstall checklist", importFx: "Can't auto-install — use the .txt checklist", collect: collectExtensions, count: (d) => d.length, importRun: null, special: true }, }; -const ORDER = ["bookmarks", "history", "cookies", "localStorage", "tabs", "sessions", "readingList", "extensions"]; +const ORDER = ["bookmarks", "history", "cookies", "tabs", "sessions", "readingList", "extensions"]; const exState = {}; let scanned = false; const exGrid = document.getElementById("exportGrid"); -function exportCategoryIds() { return ORDER.filter((id) => !CATS[id].externalImportOnly && !(CATS[id].needsReadingList && !HAS_READINGLIST)); } +function exportCategoryIds() { return ORDER.filter((id) => !(CATS[id].needsReadingList && !HAS_READINGLIST)); } function makeCard(id, c, opts) { const el = document.createElement("div"); @@ -671,10 +615,6 @@ function updateImportTotals() { } async function runImport() { - if (imState.localStorage?.selected && !window.confirm( - "LocalStorage import will visit every saved site in temporary background tabs. " + - "This sends network requests and may trigger website activity. Continue?" - )) return; const btn = document.getElementById("importBtn"); const orig = btn.innerHTML; btn.disabled = true; btn.innerHTML = ' Importing…'; document.getElementById("impbarWrap").classList.remove("hidden"); diff --git a/firefox/manifest.json b/firefox/manifest.json index c10549c..7fe066a 100644 --- a/firefox/manifest.json +++ b/firefox/manifest.json @@ -21,8 +21,7 @@ "cookies", "tabs", "sessions", - "management", - "scripting" + "management" ], "host_permissions": [ "" diff --git a/tests/e2e_chrome.cjs b/tests/e2e_chrome.cjs index f37b20c..73b3179 100644 --- a/tests/e2e_chrome.cjs +++ b/tests/e2e_chrome.cjs @@ -7,7 +7,7 @@ const http = require('node:http'); const os = require('node:os'); const fs = require('node:fs'); const path = require('node:path'); -const puppeteer = require('puppeteer'); +let puppeteer; try { puppeteer = require('../tools/node_modules/puppeteer-core'); } catch { puppeteer = require('puppeteer'); } function serve(redirectTo = null) { const server = http.createServer((req, res) => { @@ -23,8 +23,6 @@ function serve(redirectTo = null) { } async function main() { const server = await serve(); - const server2 = await serve(); - const redirectServer = await serve(`http://127.0.0.1:${server.address().port}`); const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'portage-e2e-')); const extDir = path.resolve('chrome'); let browser; @@ -36,35 +34,17 @@ async function main() { const ext=await browser.newPage(); await ext.goto(`chrome-extension://${id}/dashboard.html`,{waitUntil:'load'}); const origin=`http://127.0.0.1:${server.address().port}`; - const origin2=`http://127.0.0.1:${server2.address().port}`; - const redirectOrigin=`http://127.0.0.1:${redirectServer.address().port}`; - const results=await ext.evaluate(async (origin, origin2, redirectOrigin)=> { - return await importLocalStorage([ - {origin,items:{k1:'persisted',unicode:'猫'}}, - {origin:origin2,items:{second:'isolated'}}, - {origin:redirectOrigin,items:{poison:'must-not-write'}}, - ],()=>{}); - },origin,origin2,redirectOrigin); - assert.equal(results.imported,2,JSON.stringify(results)); - assert.equal(results.skipped,1,JSON.stringify(results)); const page=await browser.newPage(); await page.goto(origin); - assert.equal(await page.evaluate(()=>localStorage.getItem('k1')),'persisted'); - assert.equal(await page.evaluate(()=>localStorage.getItem('unicode')),'猫'); - assert.equal(await page.evaluate(()=>localStorage.getItem('poison')),null); - const another = await browser.newPage(); - await another.goto(origin2); - assert.equal(await another.evaluate(()=>localStorage.getItem('second')),'isolated'); - assert.equal(await another.evaluate(()=>localStorage.getItem('k1')),null); const cookie = await ext.evaluate(async (domain)=>importCookies([ {name:'portage-test',value:'synthetic',domain,hostOnly:true,path:'/',secure:false,sameSite:'unspecified'} ],()=>{}), '127.0.0.1'); assert.equal(cookie.imported,1,JSON.stringify(cookie)); assert.equal((await page.cookies()).find(c=>c.name==='portage-test')?.value,'synthetic'); - console.log(`PASS actual Chrome ${await browser.version()}: data written and readable after navigation`); + console.log(`PASS actual Chrome ${await browser.version()}: synthetic cookie imported`); } finally { if(browser) await browser.close(); - await Promise.all([server,server2,redirectServer].map(s=>new Promise(resolve=>s.close(resolve)))); + await new Promise(resolve=>server.close(resolve)); fs.rmSync(dir,{recursive:true,force:true}); } } diff --git a/tests/e2e_cross_browser.cjs b/tests/e2e_cross_browser.cjs new file mode 100644 index 0000000..7737089 --- /dev/null +++ b/tests/e2e_cross_browser.cjs @@ -0,0 +1,59 @@ +#!/usr/bin/env node +// Firefox 159 -> AES encrypted Portage file -> offline Chrome 156 import. +// Creates only disposable profiles and uses synthetic site values. +'use strict'; +const fs=require('node:fs'),os=require('node:os'),path=require('node:path'),http=require('node:http'); +const assert=require('node:assert/strict'); +const {spawn,spawnSync}=require('node:child_process'); +let pp; try { pp = require('../tools/node_modules/puppeteer-core'); } catch { pp = require('puppeteer'); } +const {decryptWrapper,validateBundle,restoreSites}=require('../tools/chromium_localstorage_import.cjs'); +function fire(args) {return new Promise((resolve,reject)=>{ + let stderr='';const p=spawn('/usr/local/bin/firefox',args,{stdio:['ignore','ignore','pipe']}); + p.stderr.on('data',b=>{stderr+=b.toString()}); + const kill=setTimeout(()=>{p.kill();reject(new Error('Firefox timeout'))},20000); + p.on('error',e=>{clearTimeout(kill);reject(e)}); + p.on('exit',code=>{clearTimeout(kill);if(code!==0)reject(new Error(`Firefox exited ${code}: ${stderr.slice(-500)}`));else resolve()}); +});} +async function main(){ + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'portage-cross-browser-')); + const fx=path.join(dir,'firefox-profile'), chrome=path.join(dir,'chrome-profile'); + fs.mkdirSync(fx);let requests=0; + const server=http.createServer((req,res)=>{requests++;res.writeHead(200,{'content-type':'text/html; charset=utf-8','cache-control':'no-store'}); + res.end('testLocalStorage smoke test');}); + await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve)); + const origin=`http://127.0.0.1:${server.address().port}`; + let browser; + try{ + await fire(['-no-remote','--headless','--profile',fx,'--screenshot',path.join(dir,'ff.png'),origin]); + assert(requests>=1); + const file=path.join(dir,'encrypted.portage.json'); + const passphrase='random-synthetic-passphrase-for-test-123'; + const exported=spawnSync('python3',['tools/firefox_localstorage.py','--profile',fx,'--output',file,'--passphrase-stdin'],{input:passphrase+'\n',encoding:'utf8'}); + assert.equal(exported.status,0,exported.stderr); + const wrapper=JSON.parse(fs.readFileSync(file,'utf8')); + assert.equal(wrapper.portage.format,'portage-bundle-encrypted'); + assert.equal(JSON.stringify(wrapper).includes('hello-猫'),false,'No plaintext stored in encrypted bundle'); + const b=await decryptWrapper(wrapper,passphrase); + const {sites,totalKeys}=validateBundle(b); + assert.equal(sites.length,1);assert.equal(totalKeys,2); + assert.equal(sites[0].items.migration_probe,'hello-猫'); + assert.equal(sites[0].items.large_probe.length,6000); + const before=requests; + // Exercise the actual command-line importer, including encrypted input. + const imported=spawnSync(process.execPath,[ + 'tools/chromium_localstorage_import.cjs', + '--bundle',file,'--user-data-dir',chrome,'--browser','/usr/bin/google-chrome', + '--passphrase-stdin','--apply' + ],{input:passphrase+'\n',encoding:'utf8',env:process.env,timeout:30000}); + assert.equal(imported.status,0,imported.stderr+'\n'+imported.stdout); + assert(imported.stdout.includes('Imported 1/1 origins'), imported.stdout); + assert.equal(requests,before,'Offline import must not access website'); + browser=await pp.launch({executablePath:'/usr/bin/google-chrome',headless:true,userDataDir:chrome,args:['--disable-background-networking','--no-first-run']}); + const page=await browser.newPage(); + await page.goto(origin); + const v=await page.evaluate(()=>({first:localStorage.getItem('migration_probe'),len:localStorage.getItem('large_probe').length})); + assert.deepEqual(v,{first:'hello-猫',len:6000}); + console.log('PASS Firefox 159 -> encrypted AES-256-GCM Portage bundle -> offline Chrome 156 -> persisted LocalStorage'); + }finally{if(browser)await browser.close();await new Promise(resolve=>server.close(resolve));fs.rmSync(dir,{recursive:true,force:true});} +} +main().catch(e=>{console.error(e.stack);process.exitCode=1}); diff --git a/tests/e2e_offline_import.cjs b/tests/e2e_offline_import.cjs new file mode 100644 index 0000000..e5141e6 --- /dev/null +++ b/tests/e2e_offline_import.cjs @@ -0,0 +1,38 @@ +#!/usr/bin/env node +'use strict'; +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const os = require('node:os'); +const http = require('node:http'); +let puppeteer; try { puppeteer = require('../tools/node_modules/puppeteer-core'); } catch { puppeteer = require('puppeteer'); } +const {run,validateBundle} = require('../tools/chromium_localstorage_import.cjs'); + +async function main() { + let hits=0; + const server=http.createServer((req,res)=>{hits++;res.writeHead(200,{'content-type':'text/html'});res.end('Fixture');}); + await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve)); + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'portage-offline-e2e-')); + const profile=path.join(dir,'profile'); + const origin=`http://127.0.0.1:${server.address().port}`; + const bundle={portage:{format:'portage-bundle',version:1,source:'firefox'},data:{localStorage:[{origin,items:{token:'synthetic-value',a:'猫'}}]}}; + const file=path.join(dir,'synthetic.portage.json'); + fs.writeFileSync(file,JSON.stringify(bundle),{mode:0o600}); + try { + assert.equal(validateBundle(bundle).totalKeys,2); + await run({bundle:file, userDataDir:profile, browser:'/usr/bin/google-chrome', profileDirectory:'Default', timeout:12000, apply:true}); + assert.equal(hits,0,'Importer must NOT send a single request to the origin'); + const browser=await puppeteer.launch({executablePath:'/usr/bin/google-chrome',headless:true,userDataDir:profile,args:['--no-sandbox','--disable-background-networking']}); + try { + const page=await browser.newPage(); + await page.goto(origin); + assert.equal(await page.evaluate(()=>localStorage.getItem('token')),'synthetic-value'); + assert.equal(await page.evaluate(()=>localStorage.getItem('a')),'猫'); + } finally {await browser.close();} + console.log('PASS Chrome offline LocalStorage restore: zero origin requests during import; persistent after restart'); + } finally { + await new Promise(resolve=>server.close(resolve)); + fs.rmSync(dir,{recursive:true,force:true}); + } +} +main().catch(err=>{console.error(err.stack);process.exitCode=1;}); diff --git a/tests/test_firefox_localstorage.py b/tests/test_firefox_localstorage.py index 02ddd7c..9cf2a0e 100644 --- a/tests/test_firefox_localstorage.py +++ b/tests/test_firefox_localstorage.py @@ -44,17 +44,20 @@ class FirefoxLocalStorageTest(unittest.TestCase): con.execute('CREATE TABLE data (key TEXT, utf16_length INTEGER, conversion_type INTEGER, compression_type INTEGER, last_access_time INTEGER, value BLOB)') con.execute('INSERT INTO data VALUES (?,?,?,?,?,?)',('login',len(value),1,0,0,value.encode())) con.close() + (p/'storage'/'default'/'idb-site'/'idb').mkdir(parents=True) + (p/'storage'/'default'/'idb-site'/'idb'/'1.sqlite').touch() sites,warnings=export_profile(p) self.assertEqual(len(sites),2) self.assertFalse(warnings) self.assertEqual([s['origin'] for s in sites],['https://first.test','https://second.test']) output=p/'export.portage.json' script=Path(__file__).resolve().parents[1]/'tools'/'firefox_localstorage.py' - r=subprocess.run([sys.executable,str(script),'--profile',str(p),'--output',str(output)],capture_output=True,text=True) + r=subprocess.run([sys.executable,str(script),'--profile',str(p),'--output',str(output),'--plaintext'],capture_output=True,text=True) self.assertEqual(r.returncode,0,r.stderr) self.assertEqual(os.stat(output).st_mode & 0o777,0o600) parsed=json.loads(output.read_text()) self.assertEqual(parsed['meta']['counts']['localStorage'],2) + self.assertEqual(parsed['meta']['unsupported']['indexedDBOrigins'],1) self.assertEqual(len(parsed['data']['localStorage']),2) self.assertNotEqual(subprocess.run([sys.executable,str(script),'--profile',str(p),'--output',str(output)],capture_output=True).returncode,0) diff --git a/tests/test_storage_browser.cjs b/tests/test_storage_browser.cjs index 498b10b..9500c3c 100644 --- a/tests/test_storage_browser.cjs +++ b/tests/test_storage_browser.cjs @@ -1,51 +1,33 @@ 'use strict'; -const assert = require('node:assert/strict'); -const fs = require('node:fs'); -const vm = require('node:vm'); +const assert=require('node:assert/strict'),fs=require('node:fs'),vm=require('node:vm'); +const {validOrigin, validateBundle}=require('../tools/chromium_localstorage_import.cjs'); for (const browser of ['chrome','firefox']) { - const src = fs.readFileSync(`${browser}/dashboard.js`, 'utf8'); - const start = src.indexOf('function mapSameSite('); - const end = src.indexOf('async function importTabs(', start); - assert(start > 0 && end > start); - const ctx = vm.createContext({URL, setTimeout, clearTimeout, Object, Number, Array, tick: async () => {}, IS_FIREFOX: browser === 'firefox'}); - vm.runInContext(src.slice(start,end), ctx); - assert.equal(vm.runInContext('mapSameSite("unspecified")', ctx), 'unspecified'); - assert.equal(vm.runInContext('mapSameSite("no_restriction")', ctx), 'no_restriction'); - assert.equal(vm.runInContext('mapSameSite("unknown")', ctx), 'unspecified'); - assert.equal(vm.runInContext('isSafeStorageOrigin("https://site.test")', ctx), true); - assert.equal(vm.runInContext('isSafeStorageOrigin("https://site.test/evil")', ctx), false); - (async () => { - const visited = [], closed = [], written = []; - const listeners = new Set(); - ctx.api = { - tabs: { - create: async ({url}) => { const id = visited.length+1; visited.push(url); return {id}; }, - get: async (id) => ({status:'complete', url: visited[id-1]}), - remove: async (id) => {closed.push(id)}, - onUpdated: { addListener: (f) => listeners.add(f), removeListener: (f) => listeners.delete(f)}, - }, - scripting: { executeScript: async ({target,func,args}) => { - const old = ctx.localStorage; - ctx.localStorage={setItem:(k,v)=>written.push([k,v])}; - // Function is evaluated in a tab by the actual browser; here emulate it. - const total = Object.entries(args[0]).length; - ctx.localStorage=old; - return [{result:total}]; - }}, - cookies: {getAllCookieStores: async()=>[{id:browser==='firefox'?'firefox-default':'0'}],set:async()=>({})}, - }; - const sites = [ - {origin:'https://first.test',items:{a:'a-value'}}, - {origin:'https://second.test',items:{b:'b-value'}}, - {origin:'javascript:alert(1)',items:{c:'nope'}}, - ]; - const result = await ctx.importLocalStorage(sites, () => {}); - assert.equal(result.imported,2); - assert.equal(result.skipped,1); - assert.deepEqual(visited,['https://first.test','https://second.test']); - assert.deepEqual(closed,[1,2]); - const cookie = await ctx.importCookies([{name:'s',value:'v',domain:'example.com',hostOnly:true,sameSite:'unspecified'}],()=>{}); - assert.equal(cookie.imported,1); - console.log(`${browser}: storage sites, origin validation, cookies and SameSite passed`); - })().catch((err)=>{console.error(err);process.exitCode=1;}); + const src=fs.readFileSync(`${browser}/dashboard.js`,'utf8'); + const start=src.indexOf('function mapSameSite('); + const end=src.indexOf('async function importTabs(',start); + assert(start>0 && end>start); + const ctx=vm.createContext({URL,Number,Array,IS_FIREFOX:browser==='firefox',tick:async()=>{}}); + vm.runInContext(src.slice(start,end),ctx); + for(const s of ['strict','lax','no_restriction','unspecified']) { + assert.equal(ctx.mapSameSite(s),s); + } + assert.equal(ctx.mapSameSite('unknown'),'unspecified'); + (async()=>{ + const written=[]; + ctx.api={cookies:{getAllCookieStores:async()=>[{id:browser==='firefox'?'firefox-default':'0'}],set:async d=>{written.push(d);return d;}}}; + const r=await ctx.importCookies([ + {name:'test',value:'value',domain:'example.com',path:'/',hostOnly:true,sameSite:'unspecified'}, + {name:'partition',value:'v',domain:'example.com',path:'/',hostOnly:true,sameSite:'lax',partitionKey:{topLevelSite:'https://site.test'}}, + {name:'container',domain:'example.org',storeId:'firefox-container-1',hostOnly:true}, + ],()=>{}); + assert.equal(r.imported,2);assert.equal(r.skipped,1); + assert.equal(written[0].sameSite,'unspecified'); + assert.equal(written[1].partitionKey.topLevelSite,'https://site.test'); + if(browser==='firefox')assert.equal(written[0].firstPartyDomain,''); + console.log(browser+': cookie import metadata and SameSite passed'); + })().catch(e=>{console.error(e);process.exitCode=1}); } +assert(validOrigin('https://example.org')); +assert(!validOrigin('javascript:foo')); +assert.throws(()=>validateBundle({portage:{format:'portage-bundle',version:1},data:{localStorage:[{origin:'https://example.org/path',items:{x:'y'}}]}})); +assert.throws(()=>validateBundle({portage:{format:'portage-bundle',version:1},data:{localStorage:[{origin:'https://example.org',items:{x:123}}]}})); diff --git a/tools/README.md b/tools/README.md index 112aa41..8a362e1 100644 --- a/tools/README.md +++ b/tools/README.md @@ -1,54 +1,60 @@ -# Whole-profile LocalStorage migration (experimental, Linux) +# Experimental whole-profile Firefox → Chromium LocalStorage migration -The browser extension cannot enumerate another browser's complete site storage via -WebExtension APIs. Portage's companion script therefore reads **all compatible -first-party Firefox LSNG localStorage databases**, not only open tabs. It is -read-only and standard-library-only (no Internet requests). +The Portage extension cannot enumerate every origin's LocalStorage via WebExtension APIs. This optional Linux companion migrates **every compatible first-party Firefox LocalStorage origin** by reading the offline Firefox profile and writing via a separate, headless Chrome/Brave session. It does **not** depend on currently open tabs, and does **not** visit the real websites during import. -**Privacy:** localStorage often includes authentication tokens. Output is -**UNENCRYPTED** JSON and created with mode `0600`. Do not share, attach to bug -reports, or commit it. After migration, securely manage/delete the file per -local policy. Keep an offline backup of your Firefox profile. +**This is not complete browser-profile migration.** It does *not* migrate IndexedDB, sessionStorage, Service Workers, Firefox Containers, partitioned localStorage, WebAuthn/passkeys, or device-bound session credentials. Login persistence cannot be guaranteed. Cookies and bookmarks can be migrated separately using the standard Portage extension. -1. In Firefox `about:profiles`, find the **Root Directory** of the intended - profile. Close Firefox to avoid racing database changes. -2. Export in a private directory: +## Safety / prerequisites - ```sh +- Backup the Firefox and Chromium/Brave profiles first. +- Close Firefox before exporting; close Brave/Chrome before applying to its profile. The importer refuses an existing Chromium `SingletonLock`. +- LocalStorage can contain live session tokens. **Encrypted AES-256-GCM export is the default**; use a long unique passphrase. `--plaintext` is an explicitly unsafe opt-out. Output is mode 0600. Never attach exported bundles to an issue, share them, or commit them. +- Require **Python 3** and `cryptography` for encryption (`sudo apt install python3-cryptography` on Debian), and **Node.js 20+**, plus Puppeteer Core (`cd tools && npm install`). Puppeteer Core uses the existing installed Chrome/Brave and downloads no browsers. +- The exporter reports a **count of IndexedDB origins omitted** (without opening their records), so you can estimate missing coverage. +- Import is **merge/upsert**: values with matching LocalStorage keys in the target are overwritten. Use a fresh Chromium profile where possible. Failed sites are reported and attempted writes are rolled back within the page when possible; this does not provide cross-origin atomic transactions. +- Import launches the browser **headless**, intercepts all page network requests to return inert local HTML, disables service workers for the temporary page, and validates the loaded origin. This avoids visiting live websites but does not formally guarantee that the browser itself makes no background connections. Standard Chrome sandboxing remains enabled. + +## Usage on Linux + +1. Open `about:profiles` in Firefox to find your intended profile's **Root Directory**. Close Firefox, then run: + + ```bash python3 tools/firefox_localstorage.py \ - --profile '/path/from/about:profiles' \ - --output "$HOME/portage-localstorage.portage.json" + --profile "$HOME/.mozilla/firefox/your-profile" \ + --output "$HOME/firefox-storage.portage.json" ``` -3. Install the **unpacked** `chrome/` Portage extension in Brave (Developer mode) - or `firefox/` in Firefox. Open Portage, switch to Import, and load the new - `.portage.json` file. Select LocalStorage and choose **Import selected**. -4. The extension visits *every exported origin*, sequentially, in temporary - background tabs and writes the saved localStorage, then closes the tabs. - This causes real network requests to those sites. It may trigger background - actions; do not perform this on a production profile without a backup. - The importer reports imported/skipped **origins**, not individual keys. + An encryption passphrase will be requested. For non-interactive usage, pipe a secret securely through `--passphrase-stdin` (never put it in shell command arguments). No upload/network request is performed. -## Scope and limitations +2. Install the *optional* importer dependency, once: -- First-party HTTP(S) localStorage from `storage/default/*/ls/data.sqlite`. -- Handles UTF-8 and UTF-16BE, plus Firefox raw Snappy compression. -- Skips partitioned/container origin attributes rather than merging them into - a different privacy context. Logs skipped/corrupt databases without contents. -- Does **not** migrate IndexedDB, sessionStorage, WebAuthn credentials, cookies, - service workers, or origin-bound browser keys. Portage's regular browser UI - handles cookies as a separate category. -- Does not guarantee uninterrupted login state. Some sites need fresh login. -- No login credentials are read from `logins.json`. -- Chromium must be able to load a site for its storage to be written via a - content script. Redirects, dead origins, missing permissions and browser - restrictions may cause individual origins to be skipped. + ```bash + cd tools && npm install && cd .. + ``` -For tests (synthetic, no personal browser data): +3. Close Brave. Check data counts in **dry-run** mode (the default): -```sh + ```bash + node tools/chromium_localstorage_import.cjs \ + --bundle "$HOME/firefox-storage.portage.json" \ + --browser /usr/bin/brave-browser \ + --user-data-dir "$HOME/.config/BraveSoftware/Brave-Browser" + ``` + + Only the counts are printed; there are no browser changes. To actually import, repeat with `--apply` appended. Provide `--profile-directory 'Profile 1'` if your target is not `Default`. Replace `/usr/bin/brave-browser` with the executable on your system. + +4. Launch Brave normally and inspect the sites you care about. **Delete the encrypted migration file when no longer needed.** Restore from your backup if necessary. + +## Tests (all synthetic profiles; no personal browser data) + +```bash python3 -m unittest discover -s tests -p 'test_*.py' node tests/test_storage_browser.cjs -# Optional: requires Puppeteer and a local Chrome installation; uses a temp profile +# Optional desktop E2E: local Firefox 159 and Chrome 156 were verified; +# needs installed Firefox and Google Chrome plus Puppeteer +node tests/e2e_cross_browser.cjs +node tests/e2e_offline_import.cjs node tests/e2e_chrome.cjs ``` + +Chromium E2E tests verify that **requests to the synthetic target origin equal zero during import**, and the stored values remain readable after browser restart. The cross-browser test verifies Firefox LSNG decoding, AES encryption compatibility and Chromium restoration. Neither test guarantees the preservation of real-world login sessions. diff --git a/tools/chromium_localstorage_import.cjs b/tools/chromium_localstorage_import.cjs new file mode 100644 index 0000000..692dbe8 --- /dev/null +++ b/tools/chromium_localstorage_import.cjs @@ -0,0 +1,191 @@ +#!/usr/bin/env node +/** + * Offline, cross-origin Chromium localStorage importer. + * Chrome/Brave is launched under a user-specified (preferably empty) profile; + * request interception fulfills ALL page requests locally with inert HTML. + * No extension or direct LevelDB editing is necessary. + * Dependency: puppeteer-core (or puppeteer). Node >=20. + */ +'use strict'; +const fs = require('node:fs'); +const path = require('node:path'); +const crypto = require('node:crypto'); +const readline = require('node:readline'); + +function parseArgs(argv) { + const opts = {apply: false, profileDirectory: 'Default', timeout: 12000}; + for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + if (a === '--apply') opts.apply = true; + else if (a === '--passphrase-stdin') opts.passphraseStdin = true; + else if (['--bundle','--user-data-dir','--browser','--profile-directory','--timeout-ms'].includes(a)) { + const v = argv[++i]; if (!v) throw Error(`Missing value for ${a}`); + const key = {'--bundle':'bundle','--user-data-dir':'userDataDir','--browser':'browser','--profile-directory':'profileDirectory','--timeout-ms':'timeout'}[a]; + opts[key] = key === 'timeout' ? Number(v) : v; + } else if (a === '--help' || a === '-h') opts.help = true; + else throw Error(`Unknown argument: ${a}`); + } + if (!opts.help && (!opts.bundle || !opts.userDataDir || !opts.browser)) throw Error('Required: --bundle FILE --user-data-dir DIR --browser PATH'); + if (!Number.isFinite(opts.timeout) || opts.timeout < 1000 || opts.timeout > 120000) throw Error('Invalid timeout'); + if (!/^[\w. -]+$/.test(opts.profileDirectory) || opts.profileDirectory === '.' || opts.profileDirectory === '..') throw Error('Invalid profile directory'); + return opts; +} + +function validOrigin(origin) { + if (typeof origin !== 'string' || origin.includes('^')) return false; + try { + const url = new URL(origin); + return (url.protocol === 'http:' || url.protocol === 'https:') && url.origin === origin && !url.username && !url.password; + } catch { return false; } +} + +function validateBundle(obj) { + if (obj?.portage?.format !== 'portage-bundle' || obj?.portage?.version !== 1) throw Error('Invalid Portage bundle format'); + const sites = obj?.data?.localStorage; + if (!Array.isArray(sites)) throw Error('Bundle does not contain localStorage'); + if (sites.length > 100000) throw Error('Too many origins'); + const seen = new Set(); + let totalKeys = 0; + for (const site of sites) { + if (!validOrigin(site?.origin)) throw Error('Unsafe or unsupported site origin in bundle'); + if (seen.has(site.origin)) throw Error('Duplicate origin in bundle'); + seen.add(site.origin); + const values = site.items; + if (!values || typeof values !== 'object' || Array.isArray(values) || Object.getPrototypeOf(values) !== Object.prototype) throw Error('Invalid localStorage entries'); + const keys = Object.keys(values); + totalKeys += keys.length; + if (keys.length > 10000 || totalKeys > 1000000) throw Error('Too many storage entries'); + if (keys.some(k => typeof values[k] !== 'string')) throw Error('Non-string storage values'); + } + return {sites, totalKeys}; +} + +async function passphrasePrompt() { + if (!process.stdin.isTTY) throw Error('Encrypted bundle: use --passphrase-stdin, or run interactively'); + const rl = readline.createInterface({input: process.stdin, output: process.stderr}); + // Prevent echoing a password to the terminal. + rl._writeToOutput = () => {}; + return new Promise(resolve => {process.stderr.write('Portage bundle passphrase: '); rl.question('', s => {process.stderr.write('\n');rl.close();resolve(s);});}); +} + +async function readPassphrase(stdinFlag) { + if (!stdinFlag) return passphrasePrompt(); + const chunks=[]; + for await(const c of process.stdin) chunks.push(c); + const value=Buffer.concat(chunks).toString('utf8').replace(/\r?\n$/, ''); + if (!value) throw Error('Empty passphrase from standard input'); + return value; +} + +async function decryptWrapper(wrapper, passphrase) { + const p = wrapper.portage; + if (p?.format !== 'portage-bundle-encrypted' || p?.version !== 1 || + p.cipher !== 'AES-GCM' || p.kdf !== 'PBKDF2' || p.hash !== 'SHA-256' || p.keyLength !== 256 || + !Number.isInteger(p.iterations) || p.iterations < 100000 || p.iterations > 2000000) throw Error('Unsupported encryption format'); + const salt=Buffer.from(p.salt,'base64'), iv=Buffer.from(p.iv,'base64'), ct=Buffer.from(wrapper.ciphertext,'base64'); + if(salt.length !== 16 || iv.length !== 12 || ct.length < 16 || ct.length > 512*1024*1024) throw Error('Invalid encrypted bundle size'); + const key = crypto.pbkdf2Sync(passphrase,salt,p.iterations,32,'sha256'); + const dec = crypto.createDecipheriv('aes-256-gcm',key,iv); + dec.setAuthTag(ct.subarray(ct.length-16)); + let inner; + try {inner=JSON.parse(Buffer.concat([dec.update(ct.subarray(0,-16)),dec.final()]).toString('utf8'));} + catch {throw Error('Cannot decrypt: wrong passphrase or corrupted bundle');} + return {portage:{format:'portage-bundle',version:1,source:p.source},meta:inner.meta,data:inner.data}; +} + +async function loadBundle(filename, passphraseStdin) { + const stat=fs.statSync(filename); + if (stat.size > 512*1024*1024) throw Error('Bundle too large'); + const wrapper=JSON.parse(fs.readFileSync(filename,'utf8')); + if(wrapper?.portage?.format==='portage-bundle-encrypted') { + const pass=await readPassphrase(passphraseStdin); + return await decryptWrapper(wrapper,pass); + } + return wrapper; +} + +/** For every origin, respond to *every* navigation/subresource request locally. */ +async function restoreSites(browser, sites, timeout=12000) { + const results = {imported: 0, skipped: 0, keys: 0, errors: []}; + const page=await browser.newPage(); + await page.setBypassServiceWorker(true); + await page.setCacheEnabled(false); + await page.setRequestInterception(true); + page.on('request', req=>{ + const isDocument=req.isNavigationRequest() && req.frame() === page.mainFrame(); + if (isDocument) req.respond({status:200,contentType:'text/html; charset=utf-8',headers:{'cache-control':'no-store'},body:'Portage localStorage import'}).catch(()=>{}); + else req.respond({status:204,body:''}).catch(()=>{}); + }); + for(let i=0;i{ + // Entire operation occurs in one renderer task, before site scripts (page is inert). + const old=[]; + try { + for(const [k,v] of entries) { + old.push([k,localStorage.getItem(k)]); + localStorage.setItem(k,v); + } + if(entries.some(([k,v])=>localStorage.getItem(k)!==v)) throw Error('Storage verification failed'); + } catch(e) { + for(let j=old.length-1;j>=0;j--) { + const [k,v]=old[j]; + try{if(v===null)localStorage.removeItem(k);else localStorage.setItem(k,v);}catch{} + } + throw e; + } + return entries.length; + }, pairs); + if(result!==pairs.length)throw Error('Storage key count mismatch'); + results.imported++;results.keys+=result; + } catch(e) { + results.skipped++; + results.errors.push({index:i+1,reason:String(e.message||e).slice(0,180)}); + } + } + await page.close(); + return results; +} + +async function run(opts) { + const bundle=await loadBundle(path.resolve(opts.bundle),opts.passphraseStdin); + const {sites,totalKeys}=validateBundle(bundle); + const profile=path.resolve(opts.userDataDir); + if(profile==='/' || profile===require('node:os').homedir()) throw Error('Refusing to use root or home as Chrome user-data-dir'); + const lock=path.join(profile,'SingletonLock'); + if (fs.existsSync(lock) || fs.lstatSync(lock, {throwIfNoEntry:false})) throw Error('Browser profile appears to be in use (SingletonLock present); close browser and retry'); + console.log(`Validated ${sites.length} origins / ${totalKeys} LocalStorage keys.`); + const unsupportedIdb = bundle?.meta?.unsupported?.indexedDBOrigins; + if (Number.isInteger(unsupportedIdb) && unsupportedIdb > 0) { + console.warn(`WARNING: ${unsupportedIdb} Firefox IndexedDB origin(s) are not migrated; some logins may require reauthentication.`); + } + if(!opts.apply){console.log('DRY RUN: No browser started; pass --apply after creating a backup.');return;} + if(!fs.existsSync(opts.browser))throw Error('Browser executable not found'); + let puppeteer; + try{puppeteer=require('puppeteer-core');}catch{try{puppeteer=require('puppeteer');}catch{throw Error('Install puppeteer-core locally (npm i --no-save puppeteer-core)');}} + // Never start with a personal profile unless explicitly specified by the operator. + // Keep Chrome sandbox enabled; do not pass --no-sandbox. + const browser=await puppeteer.launch({executablePath:path.resolve(opts.browser),userDataDir:profile, + headless:true,defaultViewport:{width:600,height:400}, + args:['--profile-directory='+opts.profileDirectory,'--no-first-run','--no-default-browser-check', + '--disable-background-networking','--disable-sync','--disable-extensions','--disable-features=MediaRouter']}); + let result; + try {result=await restoreSites(browser,sites,opts.timeout);} + finally {await browser.close();} + console.log(`Imported ${result.imported}/${sites.length} origins and ${result.keys} keys; skipped ${result.skipped}.`); + if(result.errors.length)console.log('Skipped (index and reason; no credentials):',JSON.stringify(result.errors)); + if(result.skipped)process.exitCode=2; +} + +if(require.main===module) { + let opts; + try{opts=parseArgs(process.argv.slice(2)); + if(opts.help){console.log('Usage: node tools/chromium_localstorage_import.cjs --bundle FILE --user-data-dir DIR --browser /path/to/chrome [--profile-directory Default] [--passphrase-stdin] [--apply]\nDry-run is default. Requires puppeteer-core to --apply. No remote site requests are made by the importer.');process.exit(0);} + run(opts).catch(e=>{console.error('Error:',e.message);process.exitCode=1}); + }catch(e){console.error('Error:',e.message);process.exitCode=1} +} +module.exports={parseArgs,validOrigin,validateBundle,loadBundle,decryptWrapper,restoreSites,run}; diff --git a/tools/firefox_localstorage.py b/tools/firefox_localstorage.py index 7913f99..cd2f6ff 100644 --- a/tools/firefox_localstorage.py +++ b/tools/firefox_localstorage.py @@ -5,6 +5,9 @@ This is deliberately an offline, read-only exporter. It never accesses network services, Firefox cookies, passwords, or browser extension profiles. """ import argparse +import base64 +import getpass +import hashlib from contextlib import closing import json import os @@ -130,6 +133,8 @@ def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--profile', type=Path, required=True, help='Firefox profile folder from about:profiles') parser.add_argument('--output', type=Path, required=True, help='New private .portage.json bundle (contains session secrets)') + parser.add_argument('--plaintext', action='store_true', help='DANGEROUS: disable default AES-256-GCM encryption') + parser.add_argument('--passphrase-stdin', action='store_true', help='Read encryption passphrase from stdin instead of prompting') args = parser.parse_args(argv) profile = args.profile.expanduser().resolve() output = args.output.expanduser().resolve() @@ -138,15 +143,50 @@ def main(argv=None): if not profile.is_dir(): parser.error('Profile directory does not exist') sites, warnings = export_profile(profile) + # Inventory unsupported IndexedDB without opening or reading any IDB records. + # Counts, not credential-bearing names/values, go into the bundle metadata. + idb_count = sum(1 for directory in (profile / 'storage' / 'default').glob('*/idb') + if directory.is_dir() and any(directory.glob('*.sqlite'))) if not sites: parser.error('No compatible localStorage origins found (see warnings / profile path)') bundle = { 'portage': {'format': 'portage-bundle', 'version': 1, 'source': 'firefox', 'generator': 'Portage offline localStorage exporter', 'exportedAt': datetime.now(timezone.utc).isoformat()}, - 'meta': {'counts': {'localStorage': len(sites)}}, + 'meta': {'counts': {'localStorage': len(sites)}, + 'unsupported': {'indexedDBOrigins': idb_count}}, 'data': {'localStorage': sites}, } + if not args.plaintext: + # Uses the same PBKDF2 + AES-GCM wire format as the extension itself. + # Imported lazily: plaintext mode has no third-party dependencies. + try: + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + except ImportError: + parser.error('Encryption needs cryptography: pip install cryptography (or explicitly use --plaintext)') + if args.passphrase_stdin: + phrase = sys.stdin.readline().rstrip('\r\n') + elif sys.stdin.isatty(): + phrase = getpass.getpass('Portage encryption passphrase: ') + else: + parser.error('Encrypted export requires a TTY, or --passphrase-stdin') + if len(phrase) < 16: + parser.error('Use a passphrase of at least 16 characters') + salt, iv, iterations = os.urandom(16), os.urandom(12), 250000 + key = hashlib.pbkdf2_hmac('sha256', phrase.encode('utf8'), salt, iterations, dklen=32) + inner = json.dumps({'meta': bundle['meta'], 'data': bundle['data']}, ensure_ascii=False, separators=(',', ':')).encode('utf8') + ciphertext = AESGCM(key).encrypt(iv, inner, None) + bundle = { + 'portage': { + 'format':'portage-bundle-encrypted', 'version':1, 'source':'firefox', + 'generator': 'Portage offline localStorage exporter', + 'exportedAt': bundle['portage']['exportedAt'], + 'cipher':'AES-GCM','keyLength':256,'kdf':'PBKDF2','hash':'SHA-256', + 'iterations':iterations,'salt':base64.b64encode(salt).decode(), + 'iv':base64.b64encode(iv).decode(), + }, + 'ciphertext':base64.b64encode(ciphertext).decode(), + } # Create mode 0600: no permissive intermediate file, no clobber. fd = os.open(output, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) try: @@ -155,8 +195,10 @@ def main(argv=None): except BaseException: output.unlink(missing_ok=True) raise - print(f'Exported {len(sites)} origins to {output} (PRIVATE, UNENCRYPTED)') + print(f'Exported {len(sites)} origins to {output} (PRIVATE, '+('UNENCRYPTED' if args.plaintext else 'AES-256-GCM encrypted')+')') print('The bundle may contain active login tokens. Do not upload or share it.') + if idb_count: + print(f'WARNING: IndexedDB exists for {idb_count} origin(s) and is NOT migrated.', file=sys.stderr) for warning in warnings: print('WARNING:', warning, file=sys.stderr) if warnings: diff --git a/tools/package-lock.json b/tools/package-lock.json new file mode 100644 index 0000000..994d100 --- /dev/null +++ b/tools/package-lock.json @@ -0,0 +1,333 @@ +{ + "name": "portage-profile-migration-tools", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "portage-profile-migration-tools", + "version": "0.1.0", + "dependencies": { + "puppeteer-core": "^25.14.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@puppeteer/browsers": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-3.2.6.tgz", + "integrity": "sha512-MJP29gVoHznmqmwhH1tlZqzfeQ3aylTpSSa6WKZXtkwYUH02i9imBmWGTyZrbnAou5paX78SE4jMAUqnEPf8ug==", + "license": "Apache-2.0", + "dependencies": { + "modern-tar": "^0.8.6", + "yargs": "^18.0.0" + }, + "bin": { + "browsers": "lib/main-cli.js" + }, + "engines": { + "node": ">=22.12.0" + }, + "peerDependencies": { + "proxy-agent": ">=8.0.1", + "yauzl": "^2.10.0 || ^3.4.0" + }, + "peerDependenciesMeta": { + "proxy-agent": { + "optional": true + }, + "yauzl": { + "optional": true + } + } + }, + "node_modules/ansi-regex": { + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.4.0.tgz", + "integrity": "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/chromium-bidi": { + "version": "157.0.8090-0", + "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-157.0.8090-0.tgz", + "integrity": "sha512-KJw7IQgqXwxpJgJlEIPg5mr2ZoqA+jkTRtc5EABI7sUJ3bu3cpI7NuEBoj4Gn1AsF78CaT9So5WQWspK3/wYag==", + "license": "Apache-2.0", + "dependencies": { + "mitt": "^3.0.1", + "zod": "^4.6.5" + }, + "engines": { + "node": ">=20.19.0 <22.0.0 || >=22.12.0" + }, + "peerDependencies": { + "devtools-protocol": "*" + } + }, + "node_modules/cliui": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz", + "integrity": "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==", + "license": "ISC", + "dependencies": { + "string-width": "^7.2.0", + "strip-ansi": "^7.1.0", + "wrap-ansi": "^9.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/cliui/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/devtools-protocol": { + "version": "0.0.1704951", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1704951.tgz", + "integrity": "sha512-GQhQOs9u/Mvm1zMtJIH872JS4AskuZdUSsPNPk4ChahtWAUqgz6atEtIsMt+nO7MqF1Ic4HxII/k8Cu36JivNg==", + "license": "BSD-3-Clause" + }, + "node_modules/emoji-regex": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", + "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", + "license": "MIT" + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-east-asian-width": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz", + "integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mitt": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz", + "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==", + "license": "MIT" + }, + "node_modules/modern-tar": { + "version": "0.8.6", + "resolved": "https://registry.npmjs.org/modern-tar/-/modern-tar-0.8.6.tgz", + "integrity": "sha512-LYSks0tNVqbtez/9OB0YFP6qLRSqkdAxJWOQpVaR67lNTbj2zNLyYpowkRMia5lXLCZKzxwoxkxH2MbbBR2aEg==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/puppeteer-core": { + "version": "25.16.0", + "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-25.16.0.tgz", + "integrity": "sha512-VA5Pf54N8shfopNkZZXCdiiwfnnY8ZJYAMqFQRhlH5mGUhfwf53Ar770GPtdpTDLUqvQeYpIBtC9/G2Jij2IJw==", + "license": "Apache-2.0", + "dependencies": { + "@puppeteer/browsers": "3.2.6", + "chromium-bidi": "157.0.8090-0", + "devtools-protocol": "0.0.1704951", + "typed-query-selector": "^2.12.3", + "webdriver-bidi-protocol": "1.0.1", + "ws": "^8.22.0" + }, + "engines": { + "node": ">=22.12.0" + } + }, + "node_modules/string-width": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.3.0.tgz", + "integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==", + "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.5.0", + "strip-ansi": "^7.1.2" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/strip-ansi": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", + "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.2.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/typed-query-selector": { + "version": "2.12.3", + "resolved": "https://registry.npmjs.org/typed-query-selector/-/typed-query-selector-2.12.3.tgz", + "integrity": "sha512-/dtuMZyutHLlrxWhhC1uib00ELUr2dZ8C9B8YzZYsJmeE3V56OxRblrSM2UaF142pcMtak7ehZ6+poWGeehNIg==", + "license": "MIT" + }, + "node_modules/webdriver-bidi-protocol": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/webdriver-bidi-protocol/-/webdriver-bidi-protocol-1.0.1.tgz", + "integrity": "sha512-WXWs/aXF2a6Al1Z2/V/7Gp2oPZOAAmHjJOTmv4KCXRJ122IMj3tSSMc6a4q3K4QOmhQbse/Ahr+oTVJOU2dUiw==", + "license": "Apache-2.0" + }, + "node_modules/wrap-ansi": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz", + "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ws": { + "version": "8.22.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz", + "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-18.2.0.tgz", + "integrity": "sha512-9OpKOLeaoNFecEp7P6iYbzze/5CqWoH7N3SMs/6y1XF4nMvFMspEGZzJ6uFi9MmQwXhyzqYoSEKO3tvA3Z/o2w==", + "license": "MIT", + "dependencies": { + "cliui": "^9.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "string-width": "^8.2.1", + "y18n": "^5.0.5", + "yargs-parser": "^22.0.0" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=23" + } + }, + "node_modules/yargs-parser": { + "version": "22.0.0", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz", + "integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==", + "license": "ISC", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=23" + } + }, + "node_modules/zod": { + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/tools/package.json b/tools/package.json new file mode 100644 index 0000000..fcf06d6 --- /dev/null +++ b/tools/package.json @@ -0,0 +1,8 @@ +{ + "name": "portage-profile-migration-tools", + "version": "0.1.0", + "private": true, + "description": "Optional offline profile migration helpers for Portage", + "engines": { "node": ">=20" }, + "dependencies": { "puppeteer-core": "^25.14.0" } +} From 3e59605794e0660164ec168713bc683cff1a676c Mon Sep 17 00:00:00 2001 From: souta <109493063+souta-lab@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:15:33 +0900 Subject: [PATCH 04/12] feat: migrate Firefox IndexedDB through offline browser-native bridge --- .github/workflows/tests.yml | 7 + README.md | 4 + tests/e2e_indexeddb.cjs | 92 +++++++++++++ tests/test_indexeddb_codec.cjs | 31 +++++ tools/README.md | 70 ++++++++++ tools/indexeddb_codec.js | 80 ++++++++++++ tools/indexeddb_migrate.cjs | 207 ++++++++++++++++++++++++++++++ tools/list_firefox_idb_origins.py | 32 +++++ 8 files changed, 523 insertions(+) create mode 100644 tests/e2e_indexeddb.cjs create mode 100644 tests/test_indexeddb_codec.cjs create mode 100644 tools/indexeddb_codec.js create mode 100644 tools/indexeddb_migrate.cjs create mode 100644 tools/list_firefox_idb_origins.py diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index a94d574..183e554 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -18,11 +18,18 @@ jobs: run: python3 -m unittest discover -s tests -p 'test_*.py' - name: Browser API mock tests run: node tests/test_storage_browser.cjs + - name: IndexedDB codec tests + run: node tests/test_indexeddb_codec.cjs + - name: Python syntax + run: python3 -m py_compile tools/list_firefox_idb_origins.py tools/firefox_localstorage.py - name: JavaScript syntax run: | node --check chrome/dashboard.js node --check firefox/dashboard.js node --check tools/chromium_localstorage_import.cjs node --check tests/e2e_cross_browser.cjs + node --check tools/indexeddb_migrate.cjs + node --check tools/indexeddb_codec.js + node --check tests/e2e_indexeddb.cjs - name: CLI help run: node tools/chromium_localstorage_import.cjs --help diff --git a/README.md b/README.md index 1098ebc..1cf1528 100644 --- a/README.md +++ b/README.md @@ -67,3 +67,7 @@ Check the releases tab of the repo, or go to the website for Portage at: https:/ ## Experimental: whole-profile Firefox LocalStorage transfer (Linux) Optional Python + Node helpers can migrate **all compatible first-party origins**, not just open tabs, to a closed Chrome/Brave profile. Export is encrypted by default; import uses intercepted inert responses rather than contacting websites. See the [step-by-step CLI and privacy limitations](tools/README.md). This does **not** include IndexedDB or guarantee login-session preservation. + +### Experimental IndexedDB migration + +The Linux companion now also supports **first-party IndexedDB** for Firefox → Chromium. It recreates database schemas, indexes, keys and supported Structured Clone data using Firefox/Chromium browser APIs, without loading live sites. Existing target IndexedDB databases are skipped to prevent accidental overwrites. **Back up both profiles before using `--apply`.** See [tools/README.md](tools/README.md#indexeddb-migration-experimental-firefox--chromebrave) for instructions, compatibility limits and tests. diff --git a/tests/e2e_indexeddb.cjs b/tests/e2e_indexeddb.cjs new file mode 100644 index 0000000..dfcc7df --- /dev/null +++ b/tests/e2e_indexeddb.cjs @@ -0,0 +1,92 @@ +'use strict'; +const assert=require('node:assert/strict'); +const fs=require('node:fs'); +const os=require('node:os'); +const path=require('node:path'); +const http=require('node:http'); +const pp=require('../tools/node_modules/puppeteer-core'); +const {migrate,originsForFirefox,inertPage,navigateOffline}=require('../tools/indexeddb_migrate.cjs'); +async function main(){ + const scratch=fs.mkdtempSync(path.join(os.tmpdir(),'portage-idb-test-')); + const fx=path.join(scratch,'firefox'),chrome=path.join(scratch,'chrome'); + const hits=[0,0]; + const servers=[0,1].map(i=>http.createServer((req,res)=>{hits[i]++;res.writeHead(200,{'content-type':'text/html; charset=utf-8','cache-control':'no-store'});res.end('fixture');})); + await Promise.all(servers.map(s=>new Promise(resolve=>s.listen(0,'127.0.0.1',resolve)))); + const origins=servers.map(s=>`http://127.0.0.1:${s.address().port}`); + let browser; + try { + browser=await pp.launch({browser:'firefox',protocol:'webDriverBiDi',executablePath:'/usr/local/bin/firefox',userDataDir:fx,headless:true}); + const page=await browser.newPage(); + for(const [n,origin] of origins.entries()) { + await page.goto(origin); + await page.evaluate(async number=>{ + const r=indexedDB.open('portage-indexeddb-test',7); + await new Promise((resolve,reject)=>{ + r.onupgradeneeded=()=>{ + const db=r.result; + db.createObjectStore('keyed',{keyPath:'id'}).createIndex('by-name','name',{unique:true}); + db.createObjectStore('auto',{autoIncrement:true}).createIndex('by-tag','tag',{multiEntry:true}); + }; + r.onsuccess=()=>resolve();r.onerror=()=>reject(r.error); + }); + const db=r.result; + await new Promise((resolve,reject)=>{ + const tx=db.transaction(['keyed','auto'],'readwrite'); + const obj={id:number+1,name:'site-'+number,when:new Date('2020-02-03T04:05:06Z'), + bytes:new Uint8Array([1,2,3,255]),big:12345678901234567890n, + blob:new Blob(['file-contents'],{type:'text/plain'}), + map:new Map([['hello','猫']]),set:new Set(['a','b']), + maybe:undefined,negativeZero:-0}; + tx.objectStore('keyed').put(obj); + tx.objectStore('auto').put({tag:['alpha','beta'],value:'origin-'+number}); + tx.oncomplete=resolve;tx.onerror=()=>reject(tx.error); + }); + db.close(); + },n); + } + await browser.close();browser=null; + assert.deepEqual(originsForFirefox(fx),[...origins].sort()); + const before=hits.slice(); + const stats=await migrate({firefoxProfile:fx,chromiumProfile:chrome,firefox:'/usr/local/bin/firefox',chromium:'/usr/bin/google-chrome',apply:true,timeout:20000}); + assert.equal(stats.restored,2,JSON.stringify(stats)); + assert.deepEqual(hits,before,'IndexedDB migration must not access real origin'); + browser=await pp.launch({executablePath:'/usr/bin/google-chrome',userDataDir:chrome,headless:true,args:['--disable-background-networking']}); + const verify=await inertPage(browser,'chromium'); + for(const [n,origin] of origins.entries()){ + await navigateOffline(verify,origin,20000); + const result=await verify.evaluate(async()=>{ + const names=await indexedDB.databases(); + const r=indexedDB.open('portage-indexeddb-test'); + const db=await new Promise((ok,no)=>{r.onsuccess=()=>ok(r.result);r.onerror=()=>no(r.error)}); + const t=db.transaction(['keyed','auto'],'readonly'); + const s=t.objectStore('keyed');const a=t.objectStore('auto'); + const obj=await new Promise((ok,no)=>{let q=s.getAll();q.onsuccess=()=>ok(q.result[0]);q.onerror=()=>no(q.error)}); + const au=await new Promise((ok,no)=>{let q=a.getAll();q.onsuccess=()=>ok(q.result[0]);q.onerror=()=>no(q.error)}); + const byName=await new Promise((ok,no)=>{let q=s.index('by-name').get(obj.name);q.onsuccess=()=>ok(q.result);q.onerror=()=>no(q.error)}); + const byTag=await new Promise((ok,no)=>{let q=a.index('by-tag').get('alpha');q.onsuccess=()=>ok(q.result);q.onerror=()=>no(q.error)}); + const results={version:db.version,storeCount:db.objectStoreNames.length, + name:obj.name,id:obj.id,when:obj.when.toISOString(),bytes:Array.from(obj.bytes), + big:String(obj.big),blob:await obj.blob.text(),map:obj.map.get('hello'),set:Array.from(obj.set), + undefinedValue:obj.maybe===undefined,negativeZero:Object.is(obj.negativeZero,-0), + byName:byName.name,byTag:byTag.value,autoValue:au.value}; + db.close();return results; + }); + assert.deepEqual(result,{version:7,storeCount:2,name:'site-'+n,id:n+1, + when:'2020-02-03T04:05:06.000Z',bytes:[1,2,3,255], + big:'12345678901234567890',blob:'file-contents',map:'猫',set:['a','b'], + undefinedValue:true,negativeZero:true,byName:'site-'+n,byTag:'origin-'+n,autoValue:'origin-'+n}); + } + await verify.close();await browser.close();browser=null; + assert.deepEqual(hits,before,'No real site traffic including verification'); + // Re-running must never overwrite existing destination IndexedDB databases. + const repeated=await migrate({firefoxProfile:fx,chromiumProfile:chrome,firefox:'/usr/local/bin/firefox',chromium:'/usr/bin/google-chrome',apply:true,timeout:20000}); + assert.equal(repeated.restored,0);assert.equal(repeated.skipped,2); + process.exitCode=undefined; + console.log('PASS: Firefox 159 -> Chrome 156 indexedDB: 2 origins, schema, indexes, rich values, no target-site traffic'); + }finally{ + if(browser)await browser.close(); + await Promise.all(servers.map(s=>new Promise(ok=>s.close(ok)))); + fs.rmSync(scratch,{recursive:true,force:true}); + } +} +main().catch(e=>{console.error(e.stack);process.exitCode=1}); diff --git a/tests/test_indexeddb_codec.cjs b/tests/test_indexeddb_codec.cjs new file mode 100644 index 0000000..8c36db6 --- /dev/null +++ b/tests/test_indexeddb_codec.cjs @@ -0,0 +1,31 @@ +'use strict'; +const assert=require('node:assert/strict'); +const {encode,decode}=require('../tools/indexeddb_codec.js'); +(async()=>{ + const entries=[undefined,null,true,false,'hello 猫',0,-0,1.25,NaN,Infinity,-Infinity,123n, + new Date('2021-02-03T04:05:06Z'), new Date(NaN),/abc/gi, + new Uint8Array([0,200,255]),new Int32Array([-2,1,900]),new DataView(new Uint8Array([7,8,9]).buffer), + new Blob(['hello'],{type:'text/plain'}),new Map([['a',12]]),new Set(['a','b']), + [1,undefined,'x'],{a:'__proto__',nested:{b:'yes'}}]; + for(const entry of entries){ + const encoded=JSON.parse(JSON.stringify(await encode(entry))); + const restored=decode(encoded); + if(entry===undefined) assert.equal(restored,undefined); + else if(typeof entry==='number')assert(Object.is(restored,entry)); + else if(typeof entry==='bigint')assert.equal(restored,entry); + else if(entry instanceof Blob)assert.equal(await restored.text(),await entry.text()); + else if(entry instanceof Date)assert.equal(Number.isNaN(entry.valueOf())?Number.isNaN(restored.valueOf()):restored.valueOf(),Number.isNaN(entry.valueOf())?true:entry.valueOf()); + else if(entry instanceof RegExp)assert.equal(restored.toString(),entry.toString()); + else if(entry instanceof DataView)assert.deepEqual(Array.from(new Uint8Array(restored.buffer)),Array.from(new Uint8Array(entry.buffer))); + else if(ArrayBuffer.isView(entry))assert.deepEqual(Array.from(restored),Array.from(entry)); + else if(entry instanceof Map||entry instanceof Set)assert.deepEqual([...restored],[...entry]); + else assert.deepEqual(JSON.parse(JSON.stringify(restored)),JSON.parse(JSON.stringify(entry))); + } + const cycle={};cycle.self=cycle; + await assert.rejects(()=>encode(cycle),/cyclic/); + const special=Object.create(null);Object.defineProperty(special,'__proto__',{value:{safe:1},enumerable:true}); + const recovered=decode(JSON.parse(JSON.stringify(await encode(special)))); + assert.equal(Object.getPrototypeOf(recovered),null); + assert.deepEqual(recovered['__proto__'].safe,1); + console.log('PASS: IndexedDB codec rich types, -0, invalid dates, cyclic rejection and prototype safety'); +})().catch(e=>{console.error(e.stack);process.exitCode=1}); diff --git a/tools/README.md b/tools/README.md index 8a362e1..90d7d22 100644 --- a/tools/README.md +++ b/tools/README.md @@ -58,3 +58,73 @@ node tests/e2e_chrome.cjs ``` Chromium E2E tests verify that **requests to the synthetic target origin equal zero during import**, and the stored values remain readable after browser restart. The cross-browser test verifies Firefox LSNG decoding, AES encryption compatibility and Chromium restoration. Neither test guarantees the preservation of real-world login sessions. + +## IndexedDB migration (experimental, Firefox → Chrome/Brave) + +Unlike localStorage, IndexedDB stores browser-specific Structured Clone values +and may keep binary data in separate `.files` directories. **Do not copy its +SQLite files directly to Chromium.** This optional bridge launches a temporary +**copy** of your closed Firefox profile in Firefox 159+ using WebDriver BiDi, +reads each first-party origin's IndexedDB through Firefox's real IndexedDB API, +then restores databases through Chromium's native IndexedDB API. + +During migration both browsers receive only **inert, locally intercepted HTML** +for each site. In the automated tests the source sites received zero HTTP +requests during transfer. This is *not* a guarantee of zero browser background +network activity. The transfer stays in memory; it does **not** export tokens +into an unencrypted intermediate JSON file. A temporary Firefox profile copy +containing sensitive data is created under a mode-0700 temporary directory and +removed when the tool exits normally. A crash or power failure can leave it +behind, so inspect `portage-idb-*` in your temporary directory if interrupted. + +**Close both browsers and back up both profiles before beginning.** Firefox's +source is not modified, but Chromium's destination profile **will be changed** +with `--apply`. Existing IndexedDB databases are **never overwritten**: the +whole database is skipped if its name already exists at that origin. Normal +browser lock files are checked on the destination. Do not use this on a profile +that another browser process is accessing. + +```bash +# First, preview first-party IndexedDB origin count, WITHOUT modifying a profile: +node tools/indexeddb_migrate.cjs \ + --firefox-profile "$HOME/.mozilla/firefox/your-profile" \ + --chromium-profile "$HOME/.config/BraveSoftware/Brave-Browser" \ + --firefox /usr/local/bin/firefox \ + --chromium /usr/bin/brave-browser + +# After backing up both profiles, repeat with --apply: +node tools/indexeddb_migrate.cjs \ + --firefox-profile "$HOME/.mozilla/firefox/your-profile" \ + --chromium-profile "$HOME/.config/BraveSoftware/Brave-Browser" \ + --firefox /usr/local/bin/firefox \ + --chromium /usr/bin/brave-browser --apply +``` + +This companion uses the same `tools/node_modules/puppeteer-core` dependency as +the other CLI; run `npm ci --prefix tools` first. Firefox must support WebDriver +BiDi; validated with Firefox 159.0b5 and Google Chrome 156.0.8078.47, not yet +with Brave Stable. Origin enumeration reads the QuotaManager `storage.sqlite` +metadata; only HTTP(S) origins without Firefox container/partition attributes +are considered. It does not inspect Chrome or Firefox passwords/cookies. + +**Migrated**: IndexedDB database names and versions, object stores, key paths, +auto-increment flags, indexes (including multi-entry/unique), primary keys, and +supported stored values (ordinary objects/arrays, strings/numbers/booleans, +BigInt, Date, RegExp, Map/Set, binary buffers and typed arrays, Blob/File). + +**Still unsupported**: cyclic or shared object references, CryptoKey, +non-standard browser objects, IndexedDB databases larger than 32 MiB in the +wire representation, stores with over 50,000 records, and individual Blob/File +values larger than 8 MiB. The bridge **skips entire databases** when it finds +unsupported data, and reports aggregate counts without printing record values. +There is no guarantee that every session will remain logged in; site-specific +security mechanisms and passkeys can require reauthentication. Importing an IDB +database into another browser also does not make Firefox extension storage or +browser-specific JavaScript APIs compatible. + +For an actual two-origin cross-browser IndexedDB test with disposable profiles: + +```bash +node tests/test_indexeddb_codec.cjs +node tests/e2e_indexeddb.cjs +``` diff --git a/tools/indexeddb_codec.js b/tools/indexeddb_codec.js new file mode 100644 index 0000000..1d6d1da --- /dev/null +++ b/tools/indexeddb_codec.js @@ -0,0 +1,80 @@ +/* Portable, lossless subset of IndexedDB structured-clone values. + Unsupported types and cyclic/shared references are refused, never silently discarded. */ +'use strict'; +async function encode(value, seen = new WeakSet()) { + if (value === null) return {t:'null'}; + const typ = typeof value; + if (typ === 'undefined') return {t:'undefined'}; + if (typ === 'string' || typ === 'boolean') return {t:typ,v:value}; + if (typ === 'bigint') return {t:'bigint',v:value.toString()}; + if (typ === 'number') return {t:'number',v:Object.is(value,-0)?'-0':Number.isFinite(value)?value:String(value)}; + if (typ !== 'object') throw new Error('Unsupported IndexedDB value type: '+typ); + if(seen.has(value)) throw new Error('Shared/cyclic references cannot yet be migrated losslessly'); + seen.add(value); + if(value instanceof Date) return {t:'date',v:Number.isNaN(value.getTime())?'NaN':value.getTime()}; + if(value instanceof RegExp) return {t:'regexp',s:value.source,f:value.flags}; + if(value instanceof ArrayBuffer) return {t:'buffer',v:Array.from(new Uint8Array(value))}; + if(ArrayBuffer.isView(value)) { + if (value instanceof DataView) return {t:'dataview',v:Array.from(new Uint8Array(value.buffer,value.byteOffset,value.byteLength))}; + return {t:'typedarray',type:value.constructor.name,v:Array.from(new Uint8Array(value.buffer,value.byteOffset,value.byteLength))}; + } + if(typeof Blob !== 'undefined' && value instanceof Blob){ + if(value.size>8*1024*1024)throw new Error('Blob larger than 8 MiB migration limit'); + const v=Array.from(new Uint8Array(await value.arrayBuffer())); + if(typeof File !== 'undefined' && value instanceof File)return {t:'file',v,name:value.name,mime:value.type,lastModified:value.lastModified}; + return {t:'blob',v,mime:value.type}; + } + if(Array.isArray(value)) { + const items=[]; + for(let i=0;i[decode(k),decode(v)])); + case 'set':return new Set(o.v.map(decode)); + case 'object': { + const obj=Object.create(null); + for(const [k,v]of o.v)Object.defineProperty(obj,k,{value:decode(v),enumerable:true,writable:true,configurable:true}); + return obj; + } + default:throw new Error('Unknown structured clone value: '+o.t); + } +} +module.exports={encode,decode}; diff --git a/tools/indexeddb_migrate.cjs b/tools/indexeddb_migrate.cjs new file mode 100644 index 0000000..3314d24 --- /dev/null +++ b/tools/indexeddb_migrate.cjs @@ -0,0 +1,207 @@ +#!/usr/bin/env node +/** Offline IndexedDB bridge: Firefox 159+ -> Chromium 156+, all supported origins. + * Does not parse Firefox's opaque structured-clone SQLite blobs. A cloned + * Firefox profile reads the data with native IDB, and Chromium reconstructs + * the database via native IDB, using inert intercepted documents for origins. + */ +'use strict'; +const fs = require('node:fs'); +const path = require('node:path'); +const os = require('node:os'); +const cp = require('node:child_process'); +const {encode,decode} = require('./indexeddb_codec.js'); +const {validOrigin} = require('./chromium_localstorage_import.cjs'); + +function options(argv) { + const o={apply:false,timeout:20000}; + for (let i=0;i100000||!origins.every(validOrigin))throw Error('Invalid IndexedDB origin inventory'); + return origins; +} + +async function inertPage(browser, kind) { + const page=await browser.newPage(); + if(kind==='chromium') {await page.setBypassServiceWorker(true);await page.setCacheEnabled(false);} + await page.setRequestInterception(true); + page.on('request',request => { + if(request.isNavigationRequest() && request.frame()===page.mainFrame()) { + request.respond({status:200,contentType:'text/html; charset=utf-8',headers:{'cache-control':'no-store'},body:'Portage offline storage transfer'}).catch(()=>{}); + }else request.respond({status:204,body:''}).catch(()=>{}); + }); + return page; +} +async function navigateOffline(page,origin,timeout) { + await page.goto(origin+'/',{waitUntil:'domcontentloaded',timeout}); + if(new URL(page.url()).origin!==origin)throw Error('Navigation crossed origin'); +} + +async function snapshotOrigin(page) { + return page.evaluate(async (source) => { + const encode=(0,eval)('('+source+')'); // trusted, embedded function source; never user input + const output={databases:[],errors:[]}; + const metas=await indexedDB.databases(); + for(const meta of metas) { + if(typeof meta.name!=='string')continue; + let db; + try { + db=await new Promise((resolve,reject)=>{ + const r=indexedDB.open(meta.name); + r.onsuccess=()=>resolve(r.result); + r.onerror=()=>reject(r.error); + r.onblocked=()=>reject(Error('IndexedDB open blocked')); + }); + const dump={name:db.name,version:db.version,stores:[]}; + for (const storeName of Array.from(db.objectStoreNames)) { + const tx=db.transaction(storeName,'readonly'); + const store=tx.objectStore(storeName); + const schema={name:storeName,keyPath:store.keyPath,autoIncrement:store.autoIncrement, + indexes:Array.from(store.indexNames,n=>{ + const ix=store.index(n);return {name:ix.name,keyPath:ix.keyPath,unique:ix.unique,multiEntry:ix.multiEntry}; + }),records:[]}; + const values=await new Promise((resolve,reject)=>{ + const req=store.getAll();req.onsuccess=()=>resolve(req.result);req.onerror=()=>reject(req.error); + }); + // Key retrieval is a second transaction to avoid inactive transactions after await. + const tx2=db.transaction(storeName,'readonly'); + const keys=await new Promise((resolve,reject)=>{ + const req=tx2.objectStore(storeName).getAllKeys();req.onsuccess=()=>resolve(req.result);req.onerror=()=>reject(req.error); + }); + if(keys.length!==values.length)throw Error('Key/value length mismatch'); + if(values.length>50000)throw Error('Store has over 50000 records (migration safety limit)'); + for(let j=0;j32*1024*1024)throw Error('Database over 32 MiB transport limit'); + if(JSON.stringify(output).length+JSON.stringify(dump).length>64*1024*1024)throw Error('Origin over 64 MiB transport limit'); + output.databases.push(dump); + }catch(e){output.errors.push('Database '+output.databases.length+' skipped: '+String(e.message||e).slice(0,160));} + finally {db?.close();} + } + return output; + },encode.toString()); +} + +async function restoreOrigin(page,source) { + return page.evaluate(async ({source,codec})=>{ + const decode=(0,eval)('('+codec+')'); + const results={restored:0,skipped:0,errors:[]}; + const existing=new Set((await indexedDB.databases()).map(x=>x.name)); + for(const spec of source.databases) { + if(existing.has(spec.name)) {results.skipped++;results.errors.push('Existing destination database preserved');continue;} + let db; + try { + // Decode EVERYTHING before creating the DB; unsupported values must not + // leave a partially initialized destination schema. + const decoded=spec.stores.map(s=>({name:s.name,keyPath:s.keyPath,autoIncrement:s.autoIncrement,indexes:s.indexes, + records:s.records.map(([k,v])=>[decode(k),decode(v)])})); + db=await new Promise((resolve,reject)=>{ + const request=indexedDB.open(spec.name,spec.version); + request.onupgradeneeded=()=>{ + try{ + const d=request.result; + for(const s of decoded){ + const opts={autoIncrement:s.autoIncrement}; + if(s.keyPath!==null)opts.keyPath=s.keyPath; + const store=d.createObjectStore(s.name,opts); + for(const ix of s.indexes)store.createIndex(ix.name,ix.keyPath,{unique:ix.unique,multiEntry:ix.multiEntry}); + } + }catch(e){request.transaction.abort();} + }; + request.onsuccess=()=>resolve(request.result); + request.onerror=()=>reject(request.error||Error('Open error')); + request.onblocked=()=>reject(Error('IndexedDB upgrade blocked')); + }); + for(const s of decoded){ + if(!s.records.length)continue; + await new Promise((resolve,reject)=>{ + const tx=db.transaction(s.name,'readwrite'); + tx.oncomplete=()=>resolve();tx.onerror=()=>reject(tx.error||Error('Write failed')); + tx.onabort=()=>reject(tx.error||Error('Transaction aborted')); + const store=tx.objectStore(s.name); + try{for(const [key,value] of s.records) { + if(s.keyPath===null)store.put(value,key);else store.put(value); + }}catch(e){tx.abort();reject(e);} + }); + } + results.restored++; + }catch(e){ + results.skipped++; + results.errors.push(String(e.message||e).slice(0,160)); + // Newly created DB may now contain a partial subset of stores; remove it. + if(db){db.close();db=null;} + try{await new Promise((resolve,reject)=>{const q=indexedDB.deleteDatabase(spec.name);q.onsuccess=()=>resolve();q.onerror=()=>reject(q.error);q.onblocked=()=>reject(Error('DB deletion blocked'));});}catch{} + }finally {db?.close();} + } + return results; + },{source,codec:decode.toString()}); +} + +async function migrate(opts) { + const fx=path.resolve(opts.firefoxProfile),target=path.resolve(opts.chromiumProfile); + if(!fs.statSync(fx).isDirectory())throw Error('Firefox source profile is not a directory'); + if(target===fx || fx==='/' || target==='/' || target===os.homedir())throw Error('Unsafe profile directory'); + const origins=originsForFirefox(fx); + console.log(`Firefox IndexedDB inventory: ${origins.length} first-party origin(s); container/partitioned origins intentionally excluded.`); + if(!opts.apply){console.log('DRY RUN: No browser started. Add --apply to migrate to a backed-up target profile.');return {origins:origins.length};} + if(fs.existsSync(path.join(target,'SingletonLock')))throw Error('Target Chromium profile appears to be open'); + for(const exe of [opts.firefox,opts.chromium])if(!fs.existsSync(exe))throw Error('Executable not found: '+exe); + const scratch=fs.mkdtempSync(path.join(os.tmpdir(),'portage-idb-')); + fs.chmodSync(scratch,0o700); + const clone=path.join(scratch,'firefox-clone'); + // Reflinks avoid copying large databases when the filesystem supports CoW. + // Do NOT launch Firefox against the original profile, which would modify it. + let fb,cb;const stats={origins:origins.length,restored:0,skipped:0,sourceSkipped:0,errors:[]}; + try { + cp.execFileSync('cp',['-a','--reflink=auto',fx,clone],{timeout:120000}); + const pp=require('puppeteer-core'); + fb=await pp.launch({browser:'firefox',protocol:'webDriverBiDi',executablePath:opts.firefox, + userDataDir:clone,headless:true,timeout:20000}); + cb=await pp.launch({browser:'chrome',executablePath:opts.chromium, + userDataDir:target,headless:true,timeout:20000, + args:['--no-first-run','--no-default-browser-check','--disable-background-networking','--disable-sync','--disable-extensions']}); + const sourcePage=await inertPage(fb,'firefox'),destPage=await inertPage(cb,'chromium'); + for(const [i,origin]of origins.entries()){ + try { + await navigateOffline(sourcePage,origin,opts.timeout); + const exported=await snapshotOrigin(sourcePage); + if(exported.errors.length){stats.sourceSkipped+=exported.errors.length;stats.errors.push({originIndex:i+1,reason:'Unsupported source database/record type'});} + if(!exported.databases.length)continue; + await navigateOffline(destPage,origin,opts.timeout); + const result=await restoreOrigin(destPage,exported); + stats.restored+=result.restored;stats.skipped+=result.skipped; + if(result.errors.length)stats.errors.push({originIndex:i+1,reason:'Target database skipped or unsupported'}); + }catch(e){stats.skipped++;stats.errors.push({originIndex:i+1,reason:String(e.message||e).slice(0,150)});} + } + await sourcePage.close();await destPage.close(); + }finally { + if(fb)await fb.close();if(cb)await cb.close(); + fs.rmSync(scratch,{recursive:true,force:true}); + } + console.log(`IndexedDB migration: ${stats.restored} database(s) restored; ${stats.skipped} target skips; ${stats.sourceSkipped} source skips.`); + if(stats.errors.length)console.log('Failures (origin indices only, no contents):',JSON.stringify(stats.errors)); + if(stats.skipped||stats.sourceSkipped)process.exitCode=2; + return stats; +} +if(require.main===module){ + try{const o=options(process.argv.slice(2)); + if(o.help)console.log('Usage: node tools/indexeddb_migrate.cjs --firefox-profile PATH --chromium-profile PATH --firefox /usr/local/bin/firefox --chromium /usr/bin/google-chrome [--apply]\nDry-run by default. Use closed profiles; back up both before --apply. Existing target IndexedDB databases will be skipped.'); + else migrate(o).catch(e=>{console.error('IndexedDB transfer failed:',e.message);process.exitCode=1}); + }catch(e){console.error(e.message);process.exitCode=1;} +} +module.exports={options,originsForFirefox,inertPage,navigateOffline,snapshotOrigin,restoreOrigin,migrate}; diff --git a/tools/list_firefox_idb_origins.py b/tools/list_firefox_idb_origins.py new file mode 100644 index 0000000..6eda5dc --- /dev/null +++ b/tools/list_firefox_idb_origins.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +"""List Firefox first-party HTTP(S) IndexedDB origins using QuotaManager metadata.""" +import json +import sqlite3 +import sys +from pathlib import Path +from urllib.parse import urlsplit + + +def list_origins(profile): + db = Path(profile) / 'storage.sqlite' + if not db.is_file(): + raise FileNotFoundError(f'Missing Firefox QuotaManager storage.sqlite: {db}') + result = [] + with sqlite3.connect(db.as_uri() + '?mode=ro', uri=True, timeout=5) as connection: + for origin, usage in connection.execute('SELECT origin, client_usages FROM origin'): + if not origin or '^' in origin or not isinstance(usage, str) or 'I' not in usage: + continue # no privileged schemes or origin-attribute partition flattening + try: + u = urlsplit(origin) + if u.scheme in ('http','https') and u.hostname and u.path in ('','/') and not u.username and not u.password: + result.append(origin.rstrip('/')) + except ValueError: + pass + return sorted(set(result)) + + +if __name__ == '__main__': + if len(sys.argv) != 2: + print('Usage: list_firefox_idb_origins.py PROFILE', file=sys.stderr) + sys.exit(2) + print(json.dumps(list_origins(sys.argv[1]))) From d6bfa2a28f61097209ecdaa3fc551e507c06b394 Mon Sep 17 00:00:00 2001 From: souta <109493063+souta-lab@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:33:21 +0900 Subject: [PATCH 05/12] test: harden IndexedDB migration and verify Brave Stable compatibility --- tests/e2e_chrome.cjs | 3 +- tests/e2e_cross_browser.cjs | 5 +-- tests/e2e_indexeddb.cjs | 20 +++++++++--- tests/e2e_offline_import.cjs | 5 +-- tests/test_indexeddb_codec.cjs | 6 ++++ tools/README.md | 9 +++--- tools/indexeddb_codec.js | 18 ++++++++--- tools/indexeddb_migrate.cjs | 56 ++++++++++++++++++++++++++-------- 8 files changed, 91 insertions(+), 31 deletions(-) diff --git a/tests/e2e_chrome.cjs b/tests/e2e_chrome.cjs index 73b3179..9b326a3 100644 --- a/tests/e2e_chrome.cjs +++ b/tests/e2e_chrome.cjs @@ -2,6 +2,7 @@ // Real Chromium/Brave WebExtensions smoke test, using only temporary browser // profiles and a local HTTP fixture; no personal browser profiles or secrets. 'use strict'; +const CHROMIUM = process.env.PORTAGE_TEST_CHROMIUM || '/usr/bin/google-chrome'; const assert = require('node:assert/strict'); const http = require('node:http'); const os = require('node:os'); @@ -27,7 +28,7 @@ async function main() { const extDir = path.resolve('chrome'); let browser; try { - browser = await puppeteer.launch({executablePath: '/usr/bin/google-chrome',headless:true,userDataDir:dir,timeout:25000,pipe:true,enableExtensions:true,args:['--no-sandbox','--disable-gpu','--no-first-run','--no-default-browser-check']}); + browser = await puppeteer.launch({executablePath: CHROMIUM,headless:true,userDataDir:dir,timeout:25000,pipe:true,enableExtensions:true,args:['--no-sandbox','--disable-gpu','--no-first-run','--no-default-browser-check']}); const id=await browser.installExtension(extDir); console.log('installed id:',id); if (!id) throw new Error('Portage extension failed to load'); diff --git a/tests/e2e_cross_browser.cjs b/tests/e2e_cross_browser.cjs index 7737089..4e74268 100644 --- a/tests/e2e_cross_browser.cjs +++ b/tests/e2e_cross_browser.cjs @@ -2,6 +2,7 @@ // Firefox 159 -> AES encrypted Portage file -> offline Chrome 156 import. // Creates only disposable profiles and uses synthetic site values. 'use strict'; +const CHROMIUM = process.env.PORTAGE_TEST_CHROMIUM || '/usr/bin/google-chrome'; const fs=require('node:fs'),os=require('node:os'),path=require('node:path'),http=require('node:http'); const assert=require('node:assert/strict'); const {spawn,spawnSync}=require('node:child_process'); @@ -42,13 +43,13 @@ async function main(){ // Exercise the actual command-line importer, including encrypted input. const imported=spawnSync(process.execPath,[ 'tools/chromium_localstorage_import.cjs', - '--bundle',file,'--user-data-dir',chrome,'--browser','/usr/bin/google-chrome', + '--bundle',file,'--user-data-dir',chrome,'--browser',CHROMIUM, '--passphrase-stdin','--apply' ],{input:passphrase+'\n',encoding:'utf8',env:process.env,timeout:30000}); assert.equal(imported.status,0,imported.stderr+'\n'+imported.stdout); assert(imported.stdout.includes('Imported 1/1 origins'), imported.stdout); assert.equal(requests,before,'Offline import must not access website'); - browser=await pp.launch({executablePath:'/usr/bin/google-chrome',headless:true,userDataDir:chrome,args:['--disable-background-networking','--no-first-run']}); + browser=await pp.launch({executablePath:CHROMIUM,headless:true,userDataDir:chrome,args:['--disable-background-networking','--no-first-run']}); const page=await browser.newPage(); await page.goto(origin); const v=await page.evaluate(()=>({first:localStorage.getItem('migration_probe'),len:localStorage.getItem('large_probe').length})); diff --git a/tests/e2e_indexeddb.cjs b/tests/e2e_indexeddb.cjs index dfcc7df..90f9745 100644 --- a/tests/e2e_indexeddb.cjs +++ b/tests/e2e_indexeddb.cjs @@ -1,11 +1,12 @@ 'use strict'; +const CHROMIUM = process.env.PORTAGE_TEST_CHROMIUM || '/usr/bin/google-chrome'; const assert=require('node:assert/strict'); const fs=require('node:fs'); const os=require('node:os'); const path=require('node:path'); const http=require('node:http'); const pp=require('../tools/node_modules/puppeteer-core'); -const {migrate,originsForFirefox,inertPage,navigateOffline}=require('../tools/indexeddb_migrate.cjs'); +const {migrate,originsForFirefox,inertPage,navigateOffline,restoreOrigin}=require('../tools/indexeddb_migrate.cjs'); async function main(){ const scratch=fs.mkdtempSync(path.join(os.tmpdir(),'portage-idb-test-')); const fx=path.join(scratch,'firefox'),chrome=path.join(scratch,'chrome'); @@ -47,10 +48,10 @@ async function main(){ await browser.close();browser=null; assert.deepEqual(originsForFirefox(fx),[...origins].sort()); const before=hits.slice(); - const stats=await migrate({firefoxProfile:fx,chromiumProfile:chrome,firefox:'/usr/local/bin/firefox',chromium:'/usr/bin/google-chrome',apply:true,timeout:20000}); + const stats=await migrate({firefoxProfile:fx,chromiumProfile:chrome,firefox:'/usr/local/bin/firefox',chromium:CHROMIUM,apply:true,timeout:20000}); assert.equal(stats.restored,2,JSON.stringify(stats)); assert.deepEqual(hits,before,'IndexedDB migration must not access real origin'); - browser=await pp.launch({executablePath:'/usr/bin/google-chrome',userDataDir:chrome,headless:true,args:['--disable-background-networking']}); + browser=await pp.launch({executablePath:CHROMIUM,userDataDir:chrome,headless:true,args:['--disable-background-networking']}); const verify=await inertPage(browser,'chromium'); for(const [n,origin] of origins.entries()){ await navigateOffline(verify,origin,20000); @@ -75,11 +76,22 @@ async function main(){ when:'2020-02-03T04:05:06.000Z',bytes:[1,2,3,255], big:'12345678901234567890',blob:'file-contents',map:'猫',set:['a','b'], undefinedValue:true,negativeZero:true,byName:'site-'+n,byTag:'origin-'+n,autoValue:'origin-'+n}); + // Invalid structured clone payload must not create a partially valid DB. + const rejected=await restoreOrigin(verify,{databases:[{ + name:'portage-unsupported-test',version:1,stores:[{ + name:'bad',keyPath:null,autoIncrement:false,indexes:[], + records:[[{t:'number',v:1},{t:'unsupported-cryptokey'}]] + }] + }]}); + assert.equal(rejected.restored,0); + assert.equal(rejected.skipped,1); + const after=await verify.evaluate(()=>indexedDB.databases()); + assert(!after.some(x=>x.name==='portage-unsupported-test'), 'Rejected DB should not exist'); } await verify.close();await browser.close();browser=null; assert.deepEqual(hits,before,'No real site traffic including verification'); // Re-running must never overwrite existing destination IndexedDB databases. - const repeated=await migrate({firefoxProfile:fx,chromiumProfile:chrome,firefox:'/usr/local/bin/firefox',chromium:'/usr/bin/google-chrome',apply:true,timeout:20000}); + const repeated=await migrate({firefoxProfile:fx,chromiumProfile:chrome,firefox:'/usr/local/bin/firefox',chromium:CHROMIUM,apply:true,timeout:20000}); assert.equal(repeated.restored,0);assert.equal(repeated.skipped,2); process.exitCode=undefined; console.log('PASS: Firefox 159 -> Chrome 156 indexedDB: 2 origins, schema, indexes, rich values, no target-site traffic'); diff --git a/tests/e2e_offline_import.cjs b/tests/e2e_offline_import.cjs index e5141e6..4117819 100644 --- a/tests/e2e_offline_import.cjs +++ b/tests/e2e_offline_import.cjs @@ -1,5 +1,6 @@ #!/usr/bin/env node 'use strict'; +const CHROMIUM = process.env.PORTAGE_TEST_CHROMIUM || '/usr/bin/google-chrome'; const assert = require('node:assert/strict'); const fs = require('node:fs'); const path = require('node:path'); @@ -20,9 +21,9 @@ async function main() { fs.writeFileSync(file,JSON.stringify(bundle),{mode:0o600}); try { assert.equal(validateBundle(bundle).totalKeys,2); - await run({bundle:file, userDataDir:profile, browser:'/usr/bin/google-chrome', profileDirectory:'Default', timeout:12000, apply:true}); + await run({bundle:file, userDataDir:profile, browser:CHROMIUM, profileDirectory:'Default', timeout:12000, apply:true}); assert.equal(hits,0,'Importer must NOT send a single request to the origin'); - const browser=await puppeteer.launch({executablePath:'/usr/bin/google-chrome',headless:true,userDataDir:profile,args:['--no-sandbox','--disable-background-networking']}); + const browser=await puppeteer.launch({executablePath:CHROMIUM,headless:true,userDataDir:profile,args:['--no-sandbox','--disable-background-networking']}); try { const page=await browser.newPage(); await page.goto(origin); diff --git a/tests/test_indexeddb_codec.cjs b/tests/test_indexeddb_codec.cjs index 8c36db6..043c87b 100644 --- a/tests/test_indexeddb_codec.cjs +++ b/tests/test_indexeddb_codec.cjs @@ -27,5 +27,11 @@ const {encode,decode}=require('../tools/indexeddb_codec.js'); const recovered=decode(JSON.parse(JSON.stringify(await encode(special)))); assert.equal(Object.getPrototypeOf(recovered),null); assert.deepEqual(recovered['__proto__'].safe,1); + const normal={alpha:1}; + const normalRestored=decode(JSON.parse(JSON.stringify(await encode(normal)))); + assert.equal(Object.getPrototypeOf(normalRestored),Object.prototype); + const arr=[1,,3];arr.label='tag'; + const arrRestored=decode(JSON.parse(JSON.stringify(await encode(arr)))); + assert.equal(arrRestored.label,'tag');assert.equal(1 in arrRestored,false); console.log('PASS: IndexedDB codec rich types, -0, invalid dates, cyclic rejection and prototype safety'); })().catch(e=>{console.error(e.stack);process.exitCode=1}); diff --git a/tools/README.md b/tools/README.md index 90d7d22..b1fd167 100644 --- a/tools/README.md +++ b/tools/README.md @@ -29,7 +29,7 @@ The Portage extension cannot enumerate every origin's LocalStorage via WebExtens 2. Install the *optional* importer dependency, once: ```bash - cd tools && npm install && cd .. + cd tools && npm ci && cd .. ``` 3. Close Brave. Check data counts in **dry-run** mode (the default): @@ -80,8 +80,7 @@ behind, so inspect `portage-idb-*` in your temporary directory if interrupted. **Close both browsers and back up both profiles before beginning.** Firefox's source is not modified, but Chromium's destination profile **will be changed** with `--apply`. Existing IndexedDB databases are **never overwritten**: the -whole database is skipped if its name already exists at that origin. Normal -browser lock files are checked on the destination. Do not use this on a profile +whole database is skipped if its name already exists at that origin. The destination Chromium lock file and the Firefox source profile's live lock are checked before migration. Do not use this on a profile that another browser process is accessing. ```bash @@ -102,8 +101,8 @@ node tools/indexeddb_migrate.cjs \ This companion uses the same `tools/node_modules/puppeteer-core` dependency as the other CLI; run `npm ci --prefix tools` first. Firefox must support WebDriver -BiDi; validated with Firefox 159.0b5 and Google Chrome 156.0.8078.47, not yet -with Brave Stable. Origin enumeration reads the QuotaManager `storage.sqlite` +BiDi; validated with Firefox 159.0b5, Google Chrome 156.0.8078.47, and +**Brave Stable 1.98.60** in disposable test profiles. Origin enumeration reads the QuotaManager `storage.sqlite` metadata; only HTTP(S) origins without Firefox container/partition attributes are considered. It does not inspect Chrome or Firefox passwords/cookies. diff --git a/tools/indexeddb_codec.js b/tools/indexeddb_codec.js index 1d6d1da..85a5565 100644 --- a/tools/indexeddb_codec.js +++ b/tools/indexeddb_codec.js @@ -25,9 +25,16 @@ async function encode(value, seen = new WeakSet()) { return {t:'blob',v,mime:value.type}; } if(Array.isArray(value)) { + if(value.length>50000)throw new Error('Array exceeds migration length limit'); const items=[]; for(let i=0;i[decode(k),decode(v)])); case 'set':return new Set(o.v.map(decode)); case 'object': { - const obj=Object.create(null); + const obj=o.plain===false?Object.create(null):{}; for(const [k,v]of o.v)Object.defineProperty(obj,k,{value:decode(v),enumerable:true,writable:true,configurable:true}); return obj; } default:throw new Error('Unknown structured clone value: '+o.t); } } -module.exports={encode,decode}; +// CommonJS for unit tests; browser global for the inert migration document. +if(typeof module !== 'undefined' && module.exports)module.exports={encode,decode}; +else Object.defineProperty(globalThis,'PortageIDBCodec',{value:Object.freeze({encode,decode}),writable:false,configurable:false}); diff --git a/tools/indexeddb_migrate.cjs b/tools/indexeddb_migrate.cjs index 3314d24..e8af471 100644 --- a/tools/indexeddb_migrate.cjs +++ b/tools/indexeddb_migrate.cjs @@ -9,7 +9,6 @@ const fs = require('node:fs'); const path = require('node:path'); const os = require('node:os'); const cp = require('node:child_process'); -const {encode,decode} = require('./indexeddb_codec.js'); const {validOrigin} = require('./chromium_localstorage_import.cjs'); function options(argv) { @@ -37,6 +36,8 @@ function originsForFirefox(profile) { async function inertPage(browser, kind) { const page=await browser.newPage(); + // Do not let a source page escape into another origin or create popups. + page.on('popup', popup => popup.close().catch(() => {})); if(kind==='chromium') {await page.setBypassServiceWorker(true);await page.setCacheEnabled(false);} await page.setRequestInterception(true); page.on('request',request => { @@ -49,11 +50,13 @@ async function inertPage(browser, kind) { async function navigateOffline(page,origin,timeout) { await page.goto(origin+'/',{waitUntil:'domcontentloaded',timeout}); if(new URL(page.url()).origin!==origin)throw Error('Navigation crossed origin'); + // Load trusted codec from the local repository, no eval or remote scripts. + await page.addScriptTag({path:path.join(__dirname,'indexeddb_codec.js')}); } async function snapshotOrigin(page) { - return page.evaluate(async (source) => { - const encode=(0,eval)('('+source+')'); // trusted, embedded function source; never user input + return page.evaluate(async () => { + const {encode}=globalThis.PortageIDBCodec; const output={databases:[],errors:[]}; const metas=await indexedDB.databases(); for(const meta of metas) { @@ -74,13 +77,14 @@ async function snapshotOrigin(page) { indexes:Array.from(store.indexNames,n=>{ const ix=store.index(n);return {name:ix.name,keyPath:ix.keyPath,unique:ix.unique,multiEntry:ix.multiEntry}; }),records:[]}; + // Cap retrieval at 50,001 entries; never materialize unbounded stores. const values=await new Promise((resolve,reject)=>{ - const req=store.getAll();req.onsuccess=()=>resolve(req.result);req.onerror=()=>reject(req.error); + const req=store.getAll(undefined,50001);req.onsuccess=()=>resolve(req.result);req.onerror=()=>reject(req.error); }); // Key retrieval is a second transaction to avoid inactive transactions after await. const tx2=db.transaction(storeName,'readonly'); const keys=await new Promise((resolve,reject)=>{ - const req=tx2.objectStore(storeName).getAllKeys();req.onsuccess=()=>resolve(req.result);req.onerror=()=>reject(req.error); + const req=tx2.objectStore(storeName).getAllKeys(undefined,50001);req.onsuccess=()=>resolve(req.result);req.onerror=()=>reject(req.error); }); if(keys.length!==values.length)throw Error('Key/value length mismatch'); if(values.length>50000)throw Error('Store has over 50000 records (migration safety limit)'); @@ -94,17 +98,18 @@ async function snapshotOrigin(page) { finally {db?.close();} } return output; - },encode.toString()); + }); } async function restoreOrigin(page,source) { - return page.evaluate(async ({source,codec})=>{ - const decode=(0,eval)('('+codec+')'); + return page.evaluate(async ({source})=>{ + const {decode}=globalThis.PortageIDBCodec; const results={restored:0,skipped:0,errors:[]}; const existing=new Set((await indexedDB.databases()).map(x=>x.name)); for(const spec of source.databases) { if(existing.has(spec.name)) {results.skipped++;results.errors.push('Existing destination database preserved');continue;} let db; + let created=false; try { // Decode EVERYTHING before creating the DB; unsupported values must not // leave a partially initialized destination schema. @@ -113,6 +118,7 @@ async function restoreOrigin(page,source) { db=await new Promise((resolve,reject)=>{ const request=indexedDB.open(spec.name,spec.version); request.onupgradeneeded=()=>{ + created=true; try{ const d=request.result; for(const s of decoded){ @@ -143,13 +149,20 @@ async function restoreOrigin(page,source) { }catch(e){ results.skipped++; results.errors.push(String(e.message||e).slice(0,160)); - // Newly created DB may now contain a partial subset of stores; remove it. + // Only remove a database created by THIS migration attempt. Never + // delete a target database when validation failed before creation. if(db){db.close();db=null;} - try{await new Promise((resolve,reject)=>{const q=indexedDB.deleteDatabase(spec.name);q.onsuccess=()=>resolve();q.onerror=()=>reject(q.error);q.onblocked=()=>reject(Error('DB deletion blocked'));});}catch{} + if(created){ + try{await new Promise((resolve,reject)=>{ + const q=indexedDB.deleteDatabase(spec.name); + q.onsuccess=()=>resolve();q.onerror=()=>reject(q.error); + q.onblocked=()=>reject(Error('DB deletion blocked')); + });}catch{results.errors.push('Partial database cleanup failed; inspect target profile');} + } }finally {db?.close();} } return results; - },{source,codec:decode.toString()}); + },{source}); } async function migrate(opts) { @@ -160,6 +173,13 @@ async function migrate(opts) { console.log(`Firefox IndexedDB inventory: ${origins.length} first-party origin(s); container/partitioned origins intentionally excluded.`); if(!opts.apply){console.log('DRY RUN: No browser started. Add --apply to migrate to a backed-up target profile.');return {origins:origins.length};} if(fs.existsSync(path.join(target,'SingletonLock')))throw Error('Target Chromium profile appears to be open'); + // On Linux the .parentlock file may exist after Firefox exits, so test + // whether any process actually has the file open rather than its existence. + const sourceLock=path.join(fx,'.parentlock'); + if(fs.existsSync(sourceLock)) { + const locked=cp.spawnSync('fuser',['-s',sourceLock],{timeout:3000,stdio:'ignore'}); + if(locked.status===0)throw Error('Firefox source profile is running; close Firefox before migration'); + } for(const exe of [opts.firefox,opts.chromium])if(!fs.existsSync(exe))throw Error('Executable not found: '+exe); const scratch=fs.mkdtempSync(path.join(os.tmpdir(),'portage-idb-')); fs.chmodSync(scratch,0o700); @@ -171,7 +191,14 @@ async function migrate(opts) { cp.execFileSync('cp',['-a','--reflink=auto',fx,clone],{timeout:120000}); const pp=require('puppeteer-core'); fb=await pp.launch({browser:'firefox',protocol:'webDriverBiDi',executablePath:opts.firefox, - userDataDir:clone,headless:true,timeout:20000}); + userDataDir:clone,headless:true,timeout:20000, + extraPrefsFirefox:{ + 'browser.startup.page':0, + 'browser.startup.homepage':'about:blank', + 'browser.sessionstore.resume_from_crash':false, + 'dom.serviceWorkers.enabled':false, + 'extensions.enabledScopes':0, + }}); cb=await pp.launch({browser:'chrome',executablePath:opts.chromium, userDataDir:target,headless:true,timeout:20000, args:['--no-first-run','--no-default-browser-check','--disable-background-networking','--disable-sync','--disable-extensions']}); @@ -190,7 +217,10 @@ async function migrate(opts) { } await sourcePage.close();await destPage.close(); }finally { - if(fb)await fb.close();if(cb)await cb.close(); + // Finally must always attempt to dispose of the sensitive source clone, + // even if either browser fails to shut down cleanly. + try {if(fb)await fb.close();} catch(e) {console.warn('Firefox close failed:',e.message);} + try {if(cb)await cb.close();} catch(e) {console.warn('Chromium close failed:',e.message);} fs.rmSync(scratch,{recursive:true,force:true}); } console.log(`IndexedDB migration: ${stats.restored} database(s) restored; ${stats.skipped} target skips; ${stats.sourceSkipped} source skips.`); From 874de763a2f8d6f84d2d12a8e639caccb7f8a65b Mon Sep 17 00:00:00 2001 From: souta <109493063+souta-lab@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:50:46 +0900 Subject: [PATCH 06/12] fix: support SQLite TEXT values in Firefox LSNG export --- tests/test_firefox_localstorage.py | 1 + tools/firefox_localstorage.py | 7 ++++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/tests/test_firefox_localstorage.py b/tests/test_firefox_localstorage.py index 9cf2a0e..fd087f0 100644 --- a/tests/test_firefox_localstorage.py +++ b/tests/test_firefox_localstorage.py @@ -21,6 +21,7 @@ class FirefoxLocalStorageTest(unittest.TestCase): def test_utf8_utf16_and_compression(self): self.assertEqual(decode_value('日本語'.encode(), 1, 0), '日本語') + self.assertEqual(decode_value('日本語', 1, 0), '日本語') self.assertEqual(decode_value('日本語'.encode('utf-16-be'), 0, 0), '日本語') self.assertEqual(decode_value(b'\x05\x10hello', 1, 1), 'hello') with self.assertRaises(ValueError): diff --git a/tools/firefox_localstorage.py b/tools/firefox_localstorage.py index cd2f6ff..32bd9e2 100644 --- a/tools/firefox_localstorage.py +++ b/tools/firefox_localstorage.py @@ -79,6 +79,11 @@ def snappy_decode(data: bytes) -> bytes: def decode_value(value, conversion_type, compression_type) -> str: + # Gecko LSNG stores some uncompressed UTF-8 values as SQLite TEXT. + if isinstance(value, str): + if conversion_type == 1 and compression_type == 0: + return value + raise ValueError('Unexpected SQLite TEXT value encoding') raw = bytes(value) if compression_type == 1: raw = snappy_decode(raw) @@ -124,7 +129,7 @@ def export_profile(profile: Path): raise ValueError('Non-text localStorage key') items[key] = decode_value(value, conversion, compression) sites.append({'origin': origin, 'items': items}) - except (sqlite3.Error, ValueError, UnicodeError, OSError) as exc: + except (sqlite3.Error, ValueError, TypeError, UnicodeError, OSError) as exc: warnings.append(f'Skipped {db.parent.parent.name}: {exc}') return sites, warnings From 1b617cef844a225afd1d2c3693e6419da8e507a8 Mon Sep 17 00:00:00 2001 From: souta <109493063+souta-lab@users.noreply.github.com> Date: Fri, 23 Oct 2026 19:00:39 +0900 Subject: [PATCH 07/12] feat: offline Firefox cookie migration; privacy-safe real-profile diagnostics --- .github/workflows/tests.yml | 4 ++- tests/e2e_cookie_cli.cjs | 22 ++++++++++++++++ tools/README.md | 24 ++++++++++++++++++ tools/chromium_cookie_import.cjs | 35 ++++++++++++++++++++++++++ tools/firefox_cookie_stream.py | 43 ++++++++++++++++++++++++++++++++ tools/firefox_localstorage.py | 4 +-- 6 files changed, 129 insertions(+), 3 deletions(-) create mode 100644 tests/e2e_cookie_cli.cjs create mode 100644 tools/chromium_cookie_import.cjs create mode 100644 tools/firefox_cookie_stream.py diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 183e554..36ad0d7 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -21,7 +21,7 @@ jobs: - name: IndexedDB codec tests run: node tests/test_indexeddb_codec.cjs - name: Python syntax - run: python3 -m py_compile tools/list_firefox_idb_origins.py tools/firefox_localstorage.py + run: python3 -m py_compile tools/list_firefox_idb_origins.py tools/firefox_localstorage.py tools/firefox_cookie_stream.py - name: JavaScript syntax run: | node --check chrome/dashboard.js @@ -31,5 +31,7 @@ jobs: node --check tools/indexeddb_migrate.cjs node --check tools/indexeddb_codec.js node --check tests/e2e_indexeddb.cjs + node --check tools/chromium_cookie_import.cjs + node --check tests/e2e_cookie_cli.cjs - name: CLI help run: node tools/chromium_localstorage_import.cjs --help diff --git a/tests/e2e_cookie_cli.cjs b/tests/e2e_cookie_cli.cjs new file mode 100644 index 0000000..d798f41 --- /dev/null +++ b/tests/e2e_cookie_cli.cjs @@ -0,0 +1,22 @@ +'use strict'; +const cp=require('node:child_process'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),assert=require('node:assert/strict'); +const {transfer}=require('../tools/chromium_cookie_import.cjs'); +const pp=require('../tools/node_modules/puppeteer-core'); +(async()=>{const root=fs.mkdtempSync(path.join(os.tmpdir(),'portage-cookie-cli-')); + const src=path.join(root,'firefox'),dst=path.join(root,'brave');fs.mkdirSync(src); + try{ + const code=`import sqlite3,sys; c=sqlite3.connect(sys.argv[1]);c.execute('CREATE TABLE moz_cookies (name TEXT,value TEXT,host TEXT,path TEXT,expiry INTEGER,isSecure INTEGER,isHttpOnly INTEGER,sameSite INTEGER,originAttributes TEXT)');c.executemany('INSERT INTO moz_cookies VALUES(?,?,?,?,?,?,?,?,?)',[ + ('hello','test-value','example.com','/',1999999999,1,1,1,''), + ('divided','test-value','example.org','/',1999999999,1,1,2,'^userContextId=1'), + ('invalid','test-value','example.org','/',1999999999,0,0,0,''), + ]);c.commit()`; + const p=cp.spawnSync('python3',['-c',code,path.join(src,'cookies.sqlite')],{encoding:'utf8'});assert.equal(p.status,0,p.stderr); + const result=await transfer({sourceProfile:src,targetProfile:dst,browserPath:'/usr/bin/brave-browser'}); + assert.equal(result.candidate,1);assert.equal(result.accepted,1);assert.equal(result.failed,0); + assert.equal(result.skipped.partitioned_or_containers,1);assert.equal(result.skipped.insecure_none,1); + const browser=await pp.launch({executablePath:'/usr/bin/brave-browser',userDataDir:dst,headless:true,args:['--disable-background-networking']}); + try{const page=await browser.newPage(),session=await page.createCDPSession();let r=await session.send('Storage.getCookies');assert(r.cookies.some(c=>c.name==='hello'&&c.httpOnly&&c.secure));} + finally{await browser.close()} + console.log('PASS native Brave cookie CLI: 1 persisted; unsafe/partitioned skipped'); + }finally{fs.rmSync(root,{recursive:true,force:true})} +})().catch(e=>{console.error(e.stack);process.exitCode=1}); diff --git a/tools/README.md b/tools/README.md index b1fd167..98b1856 100644 --- a/tools/README.md +++ b/tools/README.md @@ -127,3 +127,27 @@ For an actual two-origin cross-browser IndexedDB test with disposable profiles: node tests/test_indexeddb_codec.cjs node tests/e2e_indexeddb.cjs ``` + +## Offline cookie migration (experimental) + +The `chromium_cookie_import.cjs` companion can transfer Firefox cookies into a +closed Chromium/Brave profile without creating a plaintext cookie bundle on +disk. Python reads the backed-up Firefox `cookies.sqlite` and passes the +records through a **local subprocess pipe** to Chrome's native cookie API. +Only aggregate counts are printed. The entire profile should be backed up. + +```bash +node tools/chromium_cookie_import.cjs \ + "$HOME/.mozilla/firefox/dev-edition-default" \ + "$HOME/.config/BraveSoftware/Brave-Browser" \ + /usr/bin/brave-browser +``` + +Firefox containers, origin-attribute partitions and expired cookies are +conservatively excluded, rather than incorrectly combining isolated sessions. +Some cookies or logins remain tied to browser/device-bound secrets; a successful +CDP `Network.setCookie` result does **not** guarantee continued authentication. +Never collect or paste exported cookie values into bug reports. + +`node tests/e2e_cookie_cli.cjs` verifies this transfer with synthetic cookie +values and disposable Brave profiles only. diff --git a/tools/chromium_cookie_import.cjs b/tools/chromium_cookie_import.cjs new file mode 100644 index 0000000..c0db759 --- /dev/null +++ b/tools/chromium_cookie_import.cjs @@ -0,0 +1,35 @@ +#!/usr/bin/env node +'use strict'; +/** Private-process Firefox -> Chromium cookie transfer. Do not print cookie values. */ +const cp=require('node:child_process'),path=require('node:path'),fs=require('node:fs'),os=require('node:os'); +async function transfer({sourceProfile,targetProfile,browserPath}) { + const source=path.resolve(sourceProfile),target=path.resolve(targetProfile); + if(!fs.existsSync(source)||!fs.existsSync(browserPath))throw Error('Source or browser missing'); + if(fs.existsSync(path.join(target,'SingletonLock')))throw Error('Target browser lock present'); + const p=cp.spawnSync('python3',[path.join(__dirname,'firefox_cookie_stream.py'),source],{ + encoding:'utf8',maxBuffer:32*1024*1024,timeout:20000,stdio:['ignore','pipe','pipe']}); + if(p.status!==0)throw Error('Cookie decoding failed; no destination modifications'); + const parsed=JSON.parse(p.stdout);p.stdout=''; + let puppeteer=require('puppeteer-core'),browser; + const result={candidate:parsed.cookies.length,skipped:parsed.skipped,accepted:0,failed:0}; + try{ + browser=await puppeteer.launch({executablePath:browserPath,userDataDir:target,headless:true, + args:['--disable-background-networking','--disable-sync','--disable-extensions','--no-first-run']}); + const page=await browser.newPage(),session=await page.createCDPSession(); + for(const cookie of parsed.cookies){ + try{ + let {success}=await session.send('Network.setCookie',cookie); + if(success)result.accepted++;else result.failed++; + }catch(e){result.failed++;} + } + }finally{if(browser)await browser.close();} + return result; +} +if(require.main===module){ + const args=process.argv.slice(2); + if(args.length!==3){console.error('Usage: node chromium_cookie_import.cjs FIREFOX_CLOSED_PROFILE CHROMIUM_CLOSED_PROFILE CHROME_EXECUTABLE');process.exit(2)} + transfer({sourceProfile:args[0],targetProfile:args[1],browserPath:args[2]}).then(r=>{ + console.log('Cookies (counts only):',JSON.stringify(r));if(r.failed)process.exitCode=2; + }).catch(e=>{console.error('Cookie import failed:',e.message);process.exitCode=1}); +} +module.exports={transfer}; diff --git a/tools/firefox_cookie_stream.py b/tools/firefox_cookie_stream.py new file mode 100644 index 0000000..550fd0a --- /dev/null +++ b/tools/firefox_cookie_stream.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +"""Output an in-memory migration stream of standard Firefox cookies to a local process. +Never redirect stdout to a file or issue tracker: it contains session credentials. +""" +import json, sqlite3, sys, time +from pathlib import Path + + +def collect(profile): + file=Path(profile)/'cookies.sqlite' + if not file.is_file(): + raise FileNotFoundError('Firefox cookies.sqlite not found') + uri=file.resolve().as_uri()+'?mode=ro' + included=[] + reason={'partitioned_or_containers':0,'expired':0,'invalid':0,'insecure_none':0} + now=time.time() + with sqlite3.connect(uri, uri=True, timeout=10) as conn: + for name,value,host,path,expiry,secure,http_only,same_site,attrs in conn.execute( + 'SELECT name,value,host,path,expiry,isSecure,isHttpOnly,sameSite,originAttributes FROM moz_cookies' + ): + if attrs: + reason['partitioned_or_containers']+=1 + continue + if not host or not isinstance(name,str) or not isinstance(value,str) or not host.strip('.') or not path.startswith('/'): + reason['invalid']+=1 + continue + if expiry and expiry Date: Fri, 23 Oct 2026 20:54:18 +0900 Subject: [PATCH 08/12] audit: fix cookie expiry/partition fidelity and profile-safety gaps - Cookie stream: moz_cookies.expiry is milliseconds, but CDP expects seconds. The old code imported 52 already-expired cookies in the real profile and gave every remaining cookie a ~55,000-year expiry; convert units before comparing/sending, and skip session cookies that cannot survive the temporary Chromium session. - Dashboard cookies: request partitionKey:{} for Chrome as well as Firefox (Chrome also omits CHIPS cookies otherwise), keep hasCrossSiteAncestor, omit the "unspecified" SameSite attribute for older targets, and never fall back to an arbitrary cookie store when importing. - Profile safety: resolve symlinks before cp -a (a symlinked --firefox-profile was copied as a symlink and Firefox then opened the original profile), detect Chromium's dangling SingletonLock symlink with lstat, check Firefox's .parentlock/open descriptors via /proc instead of an optional fuser, refuse Firefox-looking Chromium targets and root/home, keep the OS password store for existing Chromium profiles, and clean the sensitive profile clone on SIGINT/SIGTERM. - Exporter: never write through a dangling output symlink (O_EXCL|O_NOFOLLOW), refuse to export while Firefox holds the profile lock, and canonicalise origins so one odd origin cannot make the importer reject the whole bundle. - Revert formatting-only manifest changes; align tools/README with the code (IndexedDB is supported, Node.js 22.12+, lock/symlink/password-store and key-generator limitations) and add regression tests for all of the above. --- .github/workflows/tests.yml | 28 ++-- README.md | 6 +- chrome/dashboard.js | 47 ++++-- chrome/manifest.json | 4 +- firefox/dashboard.js | 47 ++++-- firefox/manifest.json | 14 +- tests/e2e_chrome.cjs | 29 +++- tests/e2e_cookie_cli.cjs | 89 +++++++++--- tests/e2e_cross_browser.cjs | 4 +- tests/e2e_indexeddb.cjs | 10 +- tests/e2e_offline_import.cjs | 8 +- tests/test_firefox_cookie_stream.py | 73 ++++++++++ tests/test_firefox_localstorage.py | 190 +++++++++++++++++++++---- tests/test_indexeddb_paths.cjs | 72 ++++++++++ tests/test_profile_safety.cjs | 79 ++++++++++ tests/test_storage_browser.cjs | 140 ++++++++++++++---- tools/README.md | 66 ++++++--- tools/chromium_cookie_import.cjs | 26 ++-- tools/chromium_localstorage_import.cjs | 9 +- tools/firefox_cookie_stream.py | 21 ++- tools/firefox_localstorage.py | 101 +++++++++++-- tools/indexeddb_migrate.cjs | 66 ++++++--- tools/list_firefox_idb_origins.py | 3 +- tools/package-lock.json | 2 +- tools/package.json | 2 +- tools/profile_safety.cjs | 95 +++++++++++++ 26 files changed, 1021 insertions(+), 210 deletions(-) create mode 100644 tests/test_firefox_cookie_stream.py create mode 100644 tests/test_indexeddb_paths.cjs create mode 100644 tests/test_profile_safety.cjs create mode 100644 tools/profile_safety.cjs diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 36ad0d7..6cb2a07 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,8 +1,10 @@ name: Unit tests on: push: - branches: [main, feat/profile-storage-migration] + branches: [main] pull_request: +permissions: + contents: read jobs: test: runs-on: ubuntu-latest @@ -14,24 +16,26 @@ jobs: - uses: actions/setup-node@v4 with: node-version: '22' + - name: Python dependencies + run: python3 -m pip install cryptography - name: Python tests run: python3 -m unittest discover -s tests -p 'test_*.py' - name: Browser API mock tests run: node tests/test_storage_browser.cjs + - name: Profile safety tests + run: node tests/test_profile_safety.cjs - name: IndexedDB codec tests run: node tests/test_indexeddb_codec.cjs + - name: IndexedDB path tests + run: node tests/test_indexeddb_paths.cjs - name: Python syntax - run: python3 -m py_compile tools/list_firefox_idb_origins.py tools/firefox_localstorage.py tools/firefox_cookie_stream.py + run: python3 -m py_compile tools/*.py tests/*.py - name: JavaScript syntax run: | - node --check chrome/dashboard.js - node --check firefox/dashboard.js - node --check tools/chromium_localstorage_import.cjs - node --check tests/e2e_cross_browser.cjs - node --check tools/indexeddb_migrate.cjs - node --check tools/indexeddb_codec.js - node --check tests/e2e_indexeddb.cjs - node --check tools/chromium_cookie_import.cjs - node --check tests/e2e_cookie_cli.cjs + for file in tools/*.cjs tools/*.js tests/*.cjs chrome/dashboard.js firefox/dashboard.js; do + node --check "$file" + done - name: CLI help - run: node tools/chromium_localstorage_import.cjs --help + run: | + node tools/chromium_localstorage_import.cjs --help + node tools/indexeddb_migrate.cjs --help diff --git a/README.md b/README.md index 1cf1528..e955206 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ Passwords and autofill data are completely walled off from extension APIs. You w ## Privacy & Security Model -* **Zero telemetry:** Everything runs entirely on your local machine. No network requests are ever made. +* **Zero telemetry:** Everything runs entirely on your local machine. The extension makes no network requests. The experimental profile helpers in `tools/` also run locally, but they launch a browser and cannot guarantee zero browser background traffic (see the caveat in [tools/README.md](tools/README.md)). * **Memory only:** Portage holds your data in the active page's memory and wipes it completely as soon as you export, import, or close the tab. * **Handle with care:** Your export bundle contains live session cookies. Treat this file exactly like an exported password vault. Keep it local, import it, and delete it immediately. * **No deduplication:** Importing the exact same file twice will duplicate your history and cookies. Just run it once and verify. @@ -66,8 +66,8 @@ Check the releases tab of the repo, or go to the website for Portage at: https:/ ## Experimental: whole-profile Firefox LocalStorage transfer (Linux) -Optional Python + Node helpers can migrate **all compatible first-party origins**, not just open tabs, to a closed Chrome/Brave profile. Export is encrypted by default; import uses intercepted inert responses rather than contacting websites. See the [step-by-step CLI and privacy limitations](tools/README.md). This does **not** include IndexedDB or guarantee login-session preservation. +Optional Python + Node helpers can migrate **all compatible first-party origins**, not just open tabs, to a closed Chrome/Brave profile. Export is encrypted by default; import uses intercepted inert responses rather than contacting websites. See the [step-by-step CLI and privacy limitations](tools/README.md). Login-session preservation is **not guaranteed**: partitioned/container data is skipped and some sites re-authenticate for unrelated reasons. The offline cookie companion skips session and already-expired cookies. ### Experimental IndexedDB migration -The Linux companion now also supports **first-party IndexedDB** for Firefox → Chromium. It recreates database schemas, indexes, keys and supported Structured Clone data using Firefox/Chromium browser APIs, without loading live sites. Existing target IndexedDB databases are skipped to prevent accidental overwrites. **Back up both profiles before using `--apply`.** See [tools/README.md](tools/README.md#indexeddb-migration-experimental-firefox--chromebrave) for instructions, compatibility limits and tests. +The Linux companion also supports **first-party IndexedDB** for Firefox → Chromium. It recreates database schemas, indexes, keys and supported Structured Clone data using Firefox/Chromium browser APIs, without loading live sites. Existing target IndexedDB databases are skipped to prevent accidental overwrites. **Back up both profiles before using `--apply`.** See [tools/README.md](tools/README.md#indexeddb-migration-experimental-firefox--chromebrave) for instructions, compatibility limits and tests. diff --git a/chrome/dashboard.js b/chrome/dashboard.js index 3023acb..1fcc6c9 100644 --- a/chrome/dashboard.js +++ b/chrome/dashboard.js @@ -142,15 +142,19 @@ async function collectHistory() { return { data, count: data.length }; } async function collectCookies() { - // Firefox's default getAll({}) omits Total Cookie Protection partitions. - // Firefox accepts partitionKey:{} to return both partitioned and normal cookies. - // First-Party Isolation requires firstPartyDomain:null to include all domains. + // Both Chrome and Firefox omit partitioned (CHIPS / Total Cookie Protection) + // cookies unless a partitionKey filter is requested. An empty filter matches + // partitioned and unpartitioned cookies, so ask for both. + // Firefox additionally needs firstPartyDomain:null to include First-Party + // Isolation cookies. Each cookie store is queried separately because store + // IDs are browser-specific and isolated stores must not be merged. const stores = await api.cookies.getAllCookieStores(); const all = []; for (const store of stores) { - const query = { storeId: store.id }; - if (IS_FIREFOX) { query.partitionKey = {}; query.firstPartyDomain = null; } - all.push(...await api.cookies.getAll(query)); + const query = { storeId: store.id, partitionKey: {} }; + if (IS_FIREFOX) query.firstPartyDomain = null; + try { all.push(...await api.cookies.getAll(query)); } + catch { /* A store this context cannot read must not abort the whole scan. */ } } const data = all.map((c) => ({ name: c.name, value: c.value, domain: c.domain, path: c.path, @@ -227,24 +231,37 @@ function mapSameSite(s) { async function importCookies(items, onProg) { const total = items.length; let imported = 0, skipped = 0; // Store IDs are browser-specific. Only copy into the selected browser's - // default cookie store; isolated Firefox Containers are not safely mergeable. - const stores = await api.cookies.getAllCookieStores(); - const targetStore = stores.find((s) => s.id === (IS_FIREFOX ? "firefox-default" : "0")) || stores[0]; + // default cookie store; isolated Firefox Containers (and private/incognito + // stores) are not safely mergeable. Never fall back to an arbitrary store. + const defaultStoreId = IS_FIREFOX ? "firefox-default" : "0"; for (let i = 0; i < total; i++) { const c = items[i]; try { const host = (c.domain || "").replace(/^\./, ""); if (!host || (c.firstPartyDomain && !IS_FIREFOX)) { skipped++; continue; } // Do not silently collapse isolated container stores into one login. - if (c.storeId && c.storeId !== "firefox-default" && c.storeId !== "0" && c.storeId !== targetStore?.id) { skipped++; continue; } + if (c.storeId && c.storeId !== "firefox-default" && c.storeId !== "0" && c.storeId !== defaultStoreId) { skipped++; continue; } const url = (c.secure ? "https" : "http") + "://" + host + (c.path || "/"); - const d = { url, name: c.name, value: c.value, path: c.path || "/", secure: !!c.secure, httpOnly: !!c.httpOnly, sameSite: mapSameSite(c.sameSite) }; + const d = { url, name: c.name, value: c.value, path: c.path || "/", secure: !!c.secure, httpOnly: !!c.httpOnly }; + // Omitting sameSite has the same meaning as "unspecified" and avoids + // depending on that enum value being supported by older browsers. + const sameSite = mapSameSite(c.sameSite); + if (sameSite !== "unspecified") d.sameSite = sameSite; if (!c.hostOnly) d.domain = c.domain; if (!c.session && Number.isFinite(c.expirationDate)) d.expirationDate = c.expirationDate; - if (targetStore?.id) d.storeId = targetStore.id; - if (c.partitionKey?.topLevelSite) d.partitionKey = { topLevelSite: c.partitionKey.topLevelSite }; - // Firefox requires firstPartyDomain even for the default (empty) domain - // when First-Party Isolation is enabled. + d.storeId = defaultStoreId; + if (c.partitionKey?.topLevelSite) { + d.partitionKey = { topLevelSite: c.partitionKey.topLevelSite }; + // The ancestor bit changes which embedding contexts can read it; + // dropping it would move third-party cookies between partitions. + if (typeof c.partitionKey.hasCrossSiteAncestor === "boolean") { + d.partitionKey.hasCrossSiteAncestor = c.partitionKey.hasCrossSiteAncestor; + } + } + // Firefox's cookies.set rejects calls without firstPartyDomain when + // First-Party Isolation is enabled; pass the source value (or the default + // empty domain) so non-FPI imports keep working. FPI cookies arriving + // from Chrome are skipped above because their first-party context is lost. if (IS_FIREFOX) d.firstPartyDomain = c.firstPartyDomain || ""; if (await api.cookies.set(d)) imported++; else skipped++; } catch { skipped++; } diff --git a/chrome/manifest.json b/chrome/manifest.json index 2c6add4..7636bb9 100644 --- a/chrome/manifest.json +++ b/chrome/manifest.json @@ -13,9 +13,7 @@ "management", "readingList" ], - "host_permissions": [ - "" - ], + "host_permissions": [""], "action": { "default_popup": "popup.html", "default_title": "Portage", diff --git a/firefox/dashboard.js b/firefox/dashboard.js index 363ce84..f4f6786 100644 --- a/firefox/dashboard.js +++ b/firefox/dashboard.js @@ -145,15 +145,19 @@ async function collectHistory() { return { data, count: data.length }; } async function collectCookies() { - // Firefox's default getAll({}) omits Total Cookie Protection partitions. - // Firefox accepts partitionKey:{} to return both partitioned and normal cookies. - // First-Party Isolation requires firstPartyDomain:null to include all domains. + // Both Chrome and Firefox omit partitioned (CHIPS / Total Cookie Protection) + // cookies unless a partitionKey filter is requested. An empty filter matches + // partitioned and unpartitioned cookies, so ask for both. + // Firefox additionally needs firstPartyDomain:null to include First-Party + // Isolation cookies. Each cookie store is queried separately because store + // IDs are browser-specific and isolated stores must not be merged. const stores = await api.cookies.getAllCookieStores(); const all = []; for (const store of stores) { - const query = { storeId: store.id }; - if (IS_FIREFOX) { query.partitionKey = {}; query.firstPartyDomain = null; } - all.push(...await api.cookies.getAll(query)); + const query = { storeId: store.id, partitionKey: {} }; + if (IS_FIREFOX) query.firstPartyDomain = null; + try { all.push(...await api.cookies.getAll(query)); } + catch { /* A store this context cannot read must not abort the whole scan. */ } } const data = all.map((c) => ({ name: c.name, value: c.value, domain: c.domain, path: c.path, @@ -230,24 +234,37 @@ function mapSameSite(s) { async function importCookies(items, onProg) { const total = items.length; let imported = 0, skipped = 0; // Store IDs are browser-specific. Only copy into the selected browser's - // default cookie store; isolated Firefox Containers are not safely mergeable. - const stores = await api.cookies.getAllCookieStores(); - const targetStore = stores.find((s) => s.id === (IS_FIREFOX ? "firefox-default" : "0")) || stores[0]; + // default cookie store; isolated Firefox Containers (and private/incognito + // stores) are not safely mergeable. Never fall back to an arbitrary store. + const defaultStoreId = IS_FIREFOX ? "firefox-default" : "0"; for (let i = 0; i < total; i++) { const c = items[i]; try { const host = (c.domain || "").replace(/^\./, ""); if (!host || (c.firstPartyDomain && !IS_FIREFOX)) { skipped++; continue; } // Do not silently collapse isolated container stores into one login. - if (c.storeId && c.storeId !== "firefox-default" && c.storeId !== "0" && c.storeId !== targetStore?.id) { skipped++; continue; } + if (c.storeId && c.storeId !== "firefox-default" && c.storeId !== "0" && c.storeId !== defaultStoreId) { skipped++; continue; } const url = (c.secure ? "https" : "http") + "://" + host + (c.path || "/"); - const d = { url, name: c.name, value: c.value, path: c.path || "/", secure: !!c.secure, httpOnly: !!c.httpOnly, sameSite: mapSameSite(c.sameSite) }; + const d = { url, name: c.name, value: c.value, path: c.path || "/", secure: !!c.secure, httpOnly: !!c.httpOnly }; + // Omitting sameSite has the same meaning as "unspecified" and avoids + // depending on that enum value being supported by older browsers. + const sameSite = mapSameSite(c.sameSite); + if (sameSite !== "unspecified") d.sameSite = sameSite; if (!c.hostOnly) d.domain = c.domain; if (!c.session && Number.isFinite(c.expirationDate)) d.expirationDate = c.expirationDate; - if (targetStore?.id) d.storeId = targetStore.id; - if (c.partitionKey?.topLevelSite) d.partitionKey = { topLevelSite: c.partitionKey.topLevelSite }; - // Firefox requires firstPartyDomain even for the default (empty) domain - // when First-Party Isolation is enabled. + d.storeId = defaultStoreId; + if (c.partitionKey?.topLevelSite) { + d.partitionKey = { topLevelSite: c.partitionKey.topLevelSite }; + // The ancestor bit changes which embedding contexts can read it; + // dropping it would move third-party cookies between partitions. + if (typeof c.partitionKey.hasCrossSiteAncestor === "boolean") { + d.partitionKey.hasCrossSiteAncestor = c.partitionKey.hasCrossSiteAncestor; + } + } + // Firefox's cookies.set rejects calls without firstPartyDomain when + // First-Party Isolation is enabled; pass the source value (or the default + // empty domain) so non-FPI imports keep working. FPI cookies arriving + // from Chrome are skipped above because their first-party context is lost. if (IS_FIREFOX) d.firstPartyDomain = c.firstPartyDomain || ""; if (await api.cookies.set(d)) imported++; else skipped++; } catch { skipped++; } diff --git a/firefox/manifest.json b/firefox/manifest.json index 7fe066a..35b78c3 100644 --- a/firefox/manifest.json +++ b/firefox/manifest.json @@ -2,16 +2,14 @@ "manifest_version": 3, "name": "Portage", "version": "2.0.1", - "description": "Universal browser data swap. Export bookmarks, history, cookies, tabs and sessions to a portable JSON bundle, then import into any browser running Portage \u2014 Firefox to Chrome, or the same browser on a new machine. Also exports your add-on list as a reinstall checklist.", + "description": "Universal browser data swap. Export bookmarks, history, cookies, tabs and sessions to a portable JSON bundle, then import into any browser running Portage — Firefox to Chrome, or the same browser on a new machine. Also exports your add-on list as a reinstall checklist.", "homepage_url": "https://github.com/pvrzz/Portage/", "browser_specific_settings": { "gecko": { "id": "portage@local", "strict_min_version": "115.0", "data_collection_permissions": { - "required": [ - "none" - ] + "required": ["none"] } } }, @@ -23,9 +21,7 @@ "sessions", "management" ], - "host_permissions": [ - "" - ], + "host_permissions": [""], "action": { "default_popup": "popup.html", "default_title": "Portage", @@ -43,8 +39,6 @@ "128": "icons/icon128.png" }, "background": { - "scripts": [ - "background.js" - ] + "scripts": ["background.js"] } } diff --git a/tests/e2e_chrome.cjs b/tests/e2e_chrome.cjs index 9b326a3..dbc4e2a 100644 --- a/tests/e2e_chrome.cjs +++ b/tests/e2e_chrome.cjs @@ -42,7 +42,34 @@ async function main() { ],()=>{}), '127.0.0.1'); assert.equal(cookie.imported,1,JSON.stringify(cookie)); assert.equal((await page.cookies()).find(c=>c.name==='portage-test')?.value,'synthetic'); - console.log(`PASS actual Chrome ${await browser.version()}: synthetic cookie imported`); + // The dashboard must also *collect* partitioned (CHIPS) cookies; Chrome's + // getAllCookieStores()/getAll() omit them unless partitionKey is requested. + const collected = await ext.evaluate(async () => { + await chrome.cookies.set({url:'https://example.com/',name:'portage-partitioned',value:'p', + secure:true,sameSite:'no_restriction',partitionKey:{topLevelSite:'https://example.com'}}); + const result = await collectCookies(); + const partitioned = result.data.find((entry) => entry.name === 'portage-partitioned'); + return {count: result.count, partitionKey: partitioned?.partitionKey || null}; + }); + assert.equal(collected.partitionKey?.topLevelSite, 'https://example.com', + 'collectCookies() must include partitioned cookies'); + assert(collected.count >= 2); + // Importing a partitioned cookie must preserve the top-level site and the + // third-party ancestor bit; dropping either moves it between partitions. + const importedPartition = await ext.evaluate(async () => { + const result = await importCookies([{ + name:'portage-import-partitioned', value:'v', domain:'example.com', path:'/', hostOnly:true, + secure:true, sameSite:'no_restriction', + partitionKey:{topLevelSite:'https://example.com', hasCrossSiteAncestor:true}, + }], () => {}); + const cookies = await chrome.cookies.getAll({partitionKey:{}}); + const found = cookies.find((entry) => entry.name === 'portage-import-partitioned'); + return {result, partitionKey: found?.partitionKey || null}; + }); + assert.equal(importedPartition.result.imported, 1); + assert.equal(importedPartition.partitionKey?.topLevelSite, 'https://example.com'); + assert.equal(importedPartition.partitionKey?.hasCrossSiteAncestor, true); + console.log(`PASS actual Chrome ${await browser.version()}: cookie import/collect, partitioning and ancestor bit`); } finally { if(browser) await browser.close(); await new Promise(resolve=>server.close(resolve)); diff --git a/tests/e2e_cookie_cli.cjs b/tests/e2e_cookie_cli.cjs index d798f41..19244b6 100644 --- a/tests/e2e_cookie_cli.cjs +++ b/tests/e2e_cookie_cli.cjs @@ -1,22 +1,69 @@ 'use strict'; -const cp=require('node:child_process'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),assert=require('node:assert/strict'); -const {transfer}=require('../tools/chromium_cookie_import.cjs'); -const pp=require('../tools/node_modules/puppeteer-core'); -(async()=>{const root=fs.mkdtempSync(path.join(os.tmpdir(),'portage-cookie-cli-')); - const src=path.join(root,'firefox'),dst=path.join(root,'brave');fs.mkdirSync(src); - try{ - const code=`import sqlite3,sys; c=sqlite3.connect(sys.argv[1]);c.execute('CREATE TABLE moz_cookies (name TEXT,value TEXT,host TEXT,path TEXT,expiry INTEGER,isSecure INTEGER,isHttpOnly INTEGER,sameSite INTEGER,originAttributes TEXT)');c.executemany('INSERT INTO moz_cookies VALUES(?,?,?,?,?,?,?,?,?)',[ - ('hello','test-value','example.com','/',1999999999,1,1,1,''), - ('divided','test-value','example.org','/',1999999999,1,1,2,'^userContextId=1'), - ('invalid','test-value','example.org','/',1999999999,0,0,0,''), - ]);c.commit()`; - const p=cp.spawnSync('python3',['-c',code,path.join(src,'cookies.sqlite')],{encoding:'utf8'});assert.equal(p.status,0,p.stderr); - const result=await transfer({sourceProfile:src,targetProfile:dst,browserPath:'/usr/bin/brave-browser'}); - assert.equal(result.candidate,1);assert.equal(result.accepted,1);assert.equal(result.failed,0); - assert.equal(result.skipped.partitioned_or_containers,1);assert.equal(result.skipped.insecure_none,1); - const browser=await pp.launch({executablePath:'/usr/bin/brave-browser',userDataDir:dst,headless:true,args:['--disable-background-networking']}); - try{const page=await browser.newPage(),session=await page.createCDPSession();let r=await session.send('Storage.getCookies');assert(r.cookies.some(c=>c.name==='hello'&&c.httpOnly&&c.secure));} - finally{await browser.close()} - console.log('PASS native Brave cookie CLI: 1 persisted; unsafe/partitioned skipped'); - }finally{fs.rmSync(root,{recursive:true,force:true})} -})().catch(e=>{console.error(e.stack);process.exitCode=1}); +// Synthetic Firefox cookie DB -> CDP cookie import -> disposable Brave/Chrome +// profile. No real browser profile or cookie value is read or written. +const cp = require('node:child_process'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const assert = require('node:assert/strict'); +const {transfer} = require('../tools/chromium_cookie_import.cjs'); +let puppeteer; +try { puppeteer = require('../tools/node_modules/puppeteer-core'); } catch { puppeteer = require('puppeteer'); } + +const BROWSER = process.env.PORTAGE_TEST_BRAVE + || process.env.PORTAGE_TEST_COOKIE_BROWSER + || '/usr/bin/brave-browser'; + +(async () => { + if (!fs.existsSync(BROWSER)) { + console.log(`SKIP: browser not found at ${BROWSER}; set PORTAGE_TEST_BRAVE`); + return; + } + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'portage-cookie-cli-')); + const src = path.join(root, 'firefox'), dst = path.join(root, 'chromium'); + fs.mkdirSync(src); + const futureMs = Date.now() + 3600 * 1000; + const pastMs = Date.now() - 3600 * 1000; + try { + // moz_cookies.expiry is milliseconds since the epoch. The expired row and + // a seconds-based value would both have been imported by the old code. + const code = `import sqlite3,sys +c=sqlite3.connect(sys.argv[1]) +c.execute('CREATE TABLE moz_cookies (name TEXT,value TEXT,host TEXT,path TEXT,expiry INTEGER,isSecure INTEGER,isHttpOnly INTEGER,sameSite INTEGER,originAttributes TEXT)') +c.executemany('INSERT INTO moz_cookies VALUES(?,?,?,?,?,?,?,?,?)',[ + ('hello','test-value','example.com','/',${futureMs},1,1,1,''), + ('expired','test-value','example.com','/',${pastMs},1,0,1,''), + ('divided','test-value','example.org','/',${futureMs},1,1,2,'^userContextId=1'), + ('invalid','test-value','example.org','/',${futureMs},0,0,0,''), +]) +c.commit()`; + const created = cp.spawnSync('python3', ['-c', code, path.join(src, 'cookies.sqlite')], {encoding: 'utf8'}); + assert.equal(created.status, 0, created.stderr); + + const result = await transfer({sourceProfile: src, targetProfile: dst, browserPath: BROWSER}); + assert.equal(result.candidate, 1); + assert.equal(result.accepted, 1); + assert.equal(result.failed, 0); + assert.equal(result.skipped.partitioned_or_containers, 1); + assert.equal(result.skipped.expired, 1, 'expired milliseconds cookies must be excluded'); + assert.equal(result.skipped.insecure_none, 1); + + const browser = await puppeteer.launch({ + executablePath: BROWSER, userDataDir: dst, headless: true, args: ['--disable-background-networking'], + }); + try { + const page = await browser.newPage(); + const session = await page.createCDPSession(); + const stored = (await session.send('Storage.getCookies')).cookies; + const hello = stored.find((cookie) => cookie.name === 'hello'); + assert(hello && hello.httpOnly && hello.secure); + assert(Math.abs(hello.expires - futureMs / 1000) < 5, 'expiry must be stored in seconds'); + assert(!stored.some((cookie) => cookie.name === 'expired'), 'expired cookie must not be resurrected'); + } finally { + await browser.close(); + } + console.log('PASS native Chromium cookie CLI: expiry unit/expiry filtering, unsafe/partitioned skipped'); + } finally { + fs.rmSync(root, {recursive: true, force: true}); + } +})().catch((error) => { console.error(error.stack); process.exitCode = 1; }); diff --git a/tests/e2e_cross_browser.cjs b/tests/e2e_cross_browser.cjs index 4e74268..bb157bb 100644 --- a/tests/e2e_cross_browser.cjs +++ b/tests/e2e_cross_browser.cjs @@ -3,19 +3,21 @@ // Creates only disposable profiles and uses synthetic site values. 'use strict'; const CHROMIUM = process.env.PORTAGE_TEST_CHROMIUM || '/usr/bin/google-chrome'; +const FIREFOX = process.env.PORTAGE_TEST_FIREFOX || '/usr/local/bin/firefox'; const fs=require('node:fs'),os=require('node:os'),path=require('node:path'),http=require('node:http'); const assert=require('node:assert/strict'); const {spawn,spawnSync}=require('node:child_process'); let pp; try { pp = require('../tools/node_modules/puppeteer-core'); } catch { pp = require('puppeteer'); } const {decryptWrapper,validateBundle,restoreSites}=require('../tools/chromium_localstorage_import.cjs'); function fire(args) {return new Promise((resolve,reject)=>{ - let stderr='';const p=spawn('/usr/local/bin/firefox',args,{stdio:['ignore','ignore','pipe']}); + let stderr='';const p=spawn(FIREFOX,args,{stdio:['ignore','ignore','pipe']}); p.stderr.on('data',b=>{stderr+=b.toString()}); const kill=setTimeout(()=>{p.kill();reject(new Error('Firefox timeout'))},20000); p.on('error',e=>{clearTimeout(kill);reject(e)}); p.on('exit',code=>{clearTimeout(kill);if(code!==0)reject(new Error(`Firefox exited ${code}: ${stderr.slice(-500)}`));else resolve()}); });} async function main(){ + if(!fs.existsSync(FIREFOX)||!fs.existsSync(CHROMIUM)){console.log(`SKIP: Firefox/Chromium not found (PORTAGE_TEST_FIREFOX=${FIREFOX}, PORTAGE_TEST_CHROMIUM=${CHROMIUM})`);return;} const dir=fs.mkdtempSync(path.join(os.tmpdir(),'portage-cross-browser-')); const fx=path.join(dir,'firefox-profile'), chrome=path.join(dir,'chrome-profile'); fs.mkdirSync(fx);let requests=0; diff --git a/tests/e2e_indexeddb.cjs b/tests/e2e_indexeddb.cjs index 90f9745..296d63e 100644 --- a/tests/e2e_indexeddb.cjs +++ b/tests/e2e_indexeddb.cjs @@ -1,13 +1,15 @@ 'use strict'; const CHROMIUM = process.env.PORTAGE_TEST_CHROMIUM || '/usr/bin/google-chrome'; +const FIREFOX = process.env.PORTAGE_TEST_FIREFOX || '/usr/local/bin/firefox'; const assert=require('node:assert/strict'); const fs=require('node:fs'); const os=require('node:os'); const path=require('node:path'); const http=require('node:http'); -const pp=require('../tools/node_modules/puppeteer-core'); +let pp; try { pp = require('../tools/node_modules/puppeteer-core'); } catch { pp = require('puppeteer'); } const {migrate,originsForFirefox,inertPage,navigateOffline,restoreOrigin}=require('../tools/indexeddb_migrate.cjs'); async function main(){ + if(!fs.existsSync(FIREFOX)||!fs.existsSync(CHROMIUM)){console.log(`SKIP: Firefox/Chromium not found (PORTAGE_TEST_FIREFOX=${FIREFOX}, PORTAGE_TEST_CHROMIUM=${CHROMIUM})`);return;} const scratch=fs.mkdtempSync(path.join(os.tmpdir(),'portage-idb-test-')); const fx=path.join(scratch,'firefox'),chrome=path.join(scratch,'chrome'); const hits=[0,0]; @@ -16,7 +18,7 @@ async function main(){ const origins=servers.map(s=>`http://127.0.0.1:${s.address().port}`); let browser; try { - browser=await pp.launch({browser:'firefox',protocol:'webDriverBiDi',executablePath:'/usr/local/bin/firefox',userDataDir:fx,headless:true}); + browser=await pp.launch({browser:'firefox',protocol:'webDriverBiDi',executablePath:FIREFOX,userDataDir:fx,headless:true}); const page=await browser.newPage(); for(const [n,origin] of origins.entries()) { await page.goto(origin); @@ -48,7 +50,7 @@ async function main(){ await browser.close();browser=null; assert.deepEqual(originsForFirefox(fx),[...origins].sort()); const before=hits.slice(); - const stats=await migrate({firefoxProfile:fx,chromiumProfile:chrome,firefox:'/usr/local/bin/firefox',chromium:CHROMIUM,apply:true,timeout:20000}); + const stats=await migrate({firefoxProfile:fx,chromiumProfile:chrome,firefox:FIREFOX,chromium:CHROMIUM,apply:true,timeout:20000}); assert.equal(stats.restored,2,JSON.stringify(stats)); assert.deepEqual(hits,before,'IndexedDB migration must not access real origin'); browser=await pp.launch({executablePath:CHROMIUM,userDataDir:chrome,headless:true,args:['--disable-background-networking']}); @@ -91,7 +93,7 @@ async function main(){ await verify.close();await browser.close();browser=null; assert.deepEqual(hits,before,'No real site traffic including verification'); // Re-running must never overwrite existing destination IndexedDB databases. - const repeated=await migrate({firefoxProfile:fx,chromiumProfile:chrome,firefox:'/usr/local/bin/firefox',chromium:CHROMIUM,apply:true,timeout:20000}); + const repeated=await migrate({firefoxProfile:fx,chromiumProfile:chrome,firefox:FIREFOX,chromium:CHROMIUM,apply:true,timeout:20000}); assert.equal(repeated.restored,0);assert.equal(repeated.skipped,2); process.exitCode=undefined; console.log('PASS: Firefox 159 -> Chrome 156 indexedDB: 2 origins, schema, indexes, rich values, no target-site traffic'); diff --git a/tests/e2e_offline_import.cjs b/tests/e2e_offline_import.cjs index 4117819..5b3d9b3 100644 --- a/tests/e2e_offline_import.cjs +++ b/tests/e2e_offline_import.cjs @@ -16,11 +16,14 @@ async function main() { const dir=fs.mkdtempSync(path.join(os.tmpdir(),'portage-offline-e2e-')); const profile=path.join(dir,'profile'); const origin=`http://127.0.0.1:${server.address().port}`; - const bundle={portage:{format:'portage-bundle',version:1,source:'firefox'},data:{localStorage:[{origin,items:{token:'synthetic-value',a:'猫'}}]}}; + // A __proto__ key must survive as ordinary localStorage data, not mutate the + // bundle object. JSON.parse (unlike an object literal) creates an own property. + const items=JSON.parse('{"token":"synthetic-value","a":"猫","__proto__":"proto-value"}'); + const bundle={portage:{format:'portage-bundle',version:1,source:'firefox'},data:{localStorage:[{origin,items}]}}; const file=path.join(dir,'synthetic.portage.json'); fs.writeFileSync(file,JSON.stringify(bundle),{mode:0o600}); try { - assert.equal(validateBundle(bundle).totalKeys,2); + assert.equal(validateBundle(bundle).totalKeys,3); await run({bundle:file, userDataDir:profile, browser:CHROMIUM, profileDirectory:'Default', timeout:12000, apply:true}); assert.equal(hits,0,'Importer must NOT send a single request to the origin'); const browser=await puppeteer.launch({executablePath:CHROMIUM,headless:true,userDataDir:profile,args:['--no-sandbox','--disable-background-networking']}); @@ -29,6 +32,7 @@ async function main() { await page.goto(origin); assert.equal(await page.evaluate(()=>localStorage.getItem('token')),'synthetic-value'); assert.equal(await page.evaluate(()=>localStorage.getItem('a')),'猫'); + assert.equal(await page.evaluate(()=>localStorage.getItem('__proto__')),'proto-value'); } finally {await browser.close();} console.log('PASS Chrome offline LocalStorage restore: zero origin requests during import; persistent after restart'); } finally { diff --git a/tests/test_firefox_cookie_stream.py b/tests/test_firefox_cookie_stream.py new file mode 100644 index 0000000..250bf1d --- /dev/null +++ b/tests/test_firefox_cookie_stream.py @@ -0,0 +1,73 @@ +import sqlite3 +import sys +import tempfile +import time +import unittest +from contextlib import closing +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools')) +from firefox_cookie_stream import collect + + +class FirefoxCookieStreamTest(unittest.TestCase): + def _profile(self, root, rows): + profile = Path(root) / 'profile' + profile.mkdir() + with closing(sqlite3.connect(profile / 'cookies.sqlite')) as connection, connection: + connection.execute( + 'CREATE TABLE moz_cookies (name TEXT, value TEXT, host TEXT, path TEXT, ' + 'expiry INTEGER, isSecure INTEGER, isHttpOnly INTEGER, sameSite INTEGER, ' + 'originAttributes TEXT)' + ) + connection.executemany('INSERT INTO moz_cookies VALUES (?,?,?,?,?,?,?,?,?)', rows) + return profile + + def test_expiry_is_converted_from_milliseconds_and_unsafe_cookies_are_skipped(self): + now = time.time() + future_ms = int((now + 3600) * 1000) + past_ms = int((now - 3600) * 1000) + rows = [ + # Persistent, unspecified SameSite: included, expiry seconds. + ('future', 'v', 'example.com', '/', future_ms, 1, 1, 256, ''), + # Already expired: the old milliseconds-vs-seconds mix-up imported these. + ('expired', 'v', 'example.com', '/', past_ms, 1, 0, 256, ''), + # Session cookies cannot survive the importer closing Chromium. + ('session', 'v', 'example.com', '/', 0, 1, 0, 1, ''), + # SameSite=None (requires Secure) and Strict map to CDP names. + ('none_secure', 'v', 'example.com', '/', future_ms, 1, 0, 0, ''), + ('strict', 'v', 'example.com', '/', future_ms, 1, 0, 2, ''), + # Insecure SameSite=None is invalid and must be skipped. + ('insecure_none', 'v', 'example.com', '/', future_ms, 0, 0, 0, ''), + # Firefox containers/partitions carry non-empty originAttributes. + ('partitioned', 'v', 'example.com', '/', future_ms, 1, 0, 1, '^userContextId=1'), + # Malformed rows are skipped rather than forwarded to Chrome. + ('bad_host', 'v', '', '/', future_ms, 1, 0, 1, ''), + ('bad_path', 'v', 'example.com', 'not-a-path', future_ms, 1, 0, 1, ''), + ] + with tempfile.TemporaryDirectory() as root: + profile = self._profile(root, rows) + result = collect(profile) + + cookies = {cookie['name']: cookie for cookie in result['cookies']} + self.assertEqual(set(cookies), {'future', 'none_secure', 'strict'}) + self.assertAlmostEqual(cookies['future']['expires'], now + 3600, delta=2) + self.assertNotIn('sameSite', cookies['future']) + self.assertEqual(cookies['none_secure']['sameSite'], 'None') + self.assertEqual(cookies['strict']['sameSite'], 'Strict') + self.assertEqual(result['skipped'], { + 'partitioned_or_containers': 1, + 'expired': 1, + 'session': 1, + 'invalid': 2, + 'insecure_none': 1, + }) + + def test_missing_database_is_an_error(self): + with tempfile.TemporaryDirectory() as root: + with self.assertRaises(FileNotFoundError): + collect(Path(root) / 'missing-profile') + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_firefox_localstorage.py b/tests/test_firefox_localstorage.py index fd087f0..dcd50e8 100644 --- a/tests/test_firefox_localstorage.py +++ b/tests/test_firefox_localstorage.py @@ -1,14 +1,48 @@ +import base64 +import hashlib import json import os import sqlite3 -from pathlib import Path import subprocess import sys import tempfile +import time import unittest +from contextlib import closing +from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools')) -from firefox_localstorage import decode_value, export_profile, snappy_decode, valid_origin +from firefox_localstorage import ( + decode_value, export_profile, firefox_profile_in_use, normalize_origin, snappy_decode, valid_origin, +) + +try: + import cryptography # noqa: F401 (only needed for the encryption test) + HAVE_CRYPTOGRAPHY = True +except ImportError: + HAVE_CRYPTOGRAPHY = False + +SCRIPT = Path(__file__).resolve().parents[1] / 'tools' / 'firefox_localstorage.py' + + +def write_ls_origin(profile, directory_name, origin, items): + ls = Path(profile) / 'storage' / 'default' / directory_name / 'ls' + ls.mkdir(parents=True) + with closing(sqlite3.connect(ls / 'data.sqlite')) as con, con: + con.execute('CREATE TABLE "database" (origin TEXT)') + con.execute('INSERT INTO "database" VALUES (?)', (origin,)) + con.execute( + 'CREATE TABLE data (key TEXT, utf16_length INTEGER, conversion_type INTEGER, ' + 'compression_type INTEGER, last_access_time INTEGER, value BLOB)' + ) + for key, value in items.items(): + con.execute('INSERT INTO data VALUES (?,?,?,?,?,?)', (key, len(value), 1, 0, 0, value.encode())) + + +def make_profile(root): + profile = Path(root) / 'profile' + write_ls_origin(profile, 'https+++first.test', 'https://first.test', {'login': 'token-A'}) + return profile class FirefoxLocalStorageTest(unittest.TestCase): @@ -33,34 +67,136 @@ class FirefoxLocalStorageTest(unittest.TestCase): self.assertFalse(valid_origin('https://example.org/some/path')) self.assertFalse(valid_origin('javascript:alert(1)')) + def test_origin_normalization_matches_chromium_url_parser(self): + self.assertEqual(normalize_origin('HTTPS://Example.ORG:443/'), 'https://example.org') + self.assertEqual(normalize_origin('http://Example.org:80'), 'http://example.org') + self.assertEqual(normalize_origin('https://example.org:8443'), 'https://example.org:8443') + self.assertEqual(normalize_origin('https://[::1]:443'), 'https://[::1]') + self.assertIsNone(normalize_origin('https://例え.jp')) # Firefox stores punycode + self.assertIsNone(normalize_origin('https://example.org^userContextId=1')) + self.assertIsNone(normalize_origin('https://[::1')) + self.assertIsNone(normalize_origin('https://example.org:not-a-port')) + def test_export_all_offline_origins_and_permissions(self): with tempfile.TemporaryDirectory() as t: - p=Path(t) - for name, origin, value in [('https+++first.test','https://first.test','token-A'), ('https+++second.test','https://second.test','こんにちは')]: - d=p/'storage'/'default'/name/'ls' - d.mkdir(parents=True) - with sqlite3.connect(d/'data.sqlite') as con: - con.execute('CREATE TABLE "database" (origin TEXT)') - con.execute('INSERT INTO "database" VALUES (?)',(origin,)) - con.execute('CREATE TABLE data (key TEXT, utf16_length INTEGER, conversion_type INTEGER, compression_type INTEGER, last_access_time INTEGER, value BLOB)') - con.execute('INSERT INTO data VALUES (?,?,?,?,?,?)',('login',len(value),1,0,0,value.encode())) - con.close() - (p/'storage'/'default'/'idb-site'/'idb').mkdir(parents=True) - (p/'storage'/'default'/'idb-site'/'idb'/'1.sqlite').touch() - sites,warnings=export_profile(p) - self.assertEqual(len(sites),2) + p = Path(t) + write_ls_origin(p, 'https+++first.test', 'https://first.test', {'login': 'token-A'}) + write_ls_origin(p, 'https+++second.test', 'https://second.test', {'login': 'こんにちは'}) + (p / 'storage' / 'default' / 'idb-site' / 'idb').mkdir(parents=True) + (p / 'storage' / 'default' / 'idb-site' / 'idb' / '1.sqlite').touch() + sites, warnings = export_profile(p) + self.assertEqual(len(sites), 2) self.assertFalse(warnings) - self.assertEqual([s['origin'] for s in sites],['https://first.test','https://second.test']) - output=p/'export.portage.json' - script=Path(__file__).resolve().parents[1]/'tools'/'firefox_localstorage.py' - r=subprocess.run([sys.executable,str(script),'--profile',str(p),'--output',str(output),'--plaintext'],capture_output=True,text=True) - self.assertEqual(r.returncode,0,r.stderr) - self.assertEqual(os.stat(output).st_mode & 0o777,0o600) - parsed=json.loads(output.read_text()) - self.assertEqual(parsed['meta']['counts']['localStorage'],2) - self.assertEqual(parsed['meta']['unsupported']['indexedDBOrigins'],1) - self.assertEqual(len(parsed['data']['localStorage']),2) - self.assertNotEqual(subprocess.run([sys.executable,str(script),'--profile',str(p),'--output',str(output)],capture_output=True).returncode,0) + self.assertEqual([s['origin'] for s in sites], ['https://first.test', 'https://second.test']) + output = p / 'export.portage.json' + result = subprocess.run( + [sys.executable, str(SCRIPT), '--profile', str(p), '--output', str(output), '--plaintext'], + capture_output=True, text=True, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(os.stat(output).st_mode & 0o777, 0o600) + parsed = json.loads(output.read_text()) + self.assertEqual(parsed['meta']['counts']['localStorage'], 2) + self.assertEqual(parsed['meta']['unsupported']['indexedDBOrigins'], 1) + self.assertEqual(len(parsed['data']['localStorage']), 2) + # Existing output is never overwritten, even by the encrypted path. + self.assertNotEqual(subprocess.run( + [sys.executable, str(SCRIPT), '--profile', str(p), '--output', str(output)], + capture_output=True, + ).returncode, 0) + + def test_export_normalizes_duplicate_and_invalid_origins(self): + with tempfile.TemporaryDirectory() as t: + p = Path(t) + write_ls_origin(p, 'https+++upper.test', 'HTTPS://Upper.TEST:443/', {'k': 'v'}) + write_ls_origin(p, 'https+++canonical.test', 'https://upper.test', {'k': 'v'}) + write_ls_origin(p, 'https+++container.test', 'https://container.test^userContextId=1', {'k': 'v'}) + sites, warnings = export_profile(p) + self.assertEqual([s['origin'] for s in sites], ['https://upper.test']) + self.assertEqual(len(warnings), 2) + + def test_output_symlink_is_not_followed(self): + with tempfile.TemporaryDirectory() as t: + p = Path(t) + profile = make_profile(p) + victim = p / 'victim' + victim.mkdir() + output = p / 'export.portage.json' + os.symlink(victim / 'created.json', output) + result = subprocess.run( + [sys.executable, str(SCRIPT), '--profile', str(profile), '--output', str(output), '--plaintext'], + capture_output=True, text=True, + ) + self.assertNotEqual(result.returncode, 0) + self.assertFalse((victim / 'created.json').exists()) + self.assertTrue(output.is_symlink()) + + def test_firefox_lock_detection(self): + with tempfile.TemporaryDirectory() as t: + profile = make_profile(Path(t)) + self.assertFalse(firefox_profile_in_use(profile)) + lock = profile / '.parentlock' + lock.write_bytes(b'') + # A stale lock file alone does not count as a running profile. + self.assertFalse(firefox_profile_in_use(profile)) + descriptor = os.open(lock, os.O_RDONLY) + try: + self.assertTrue(firefox_profile_in_use(profile)) + finally: + os.close(descriptor) + self.assertFalse(firefox_profile_in_use(profile)) + + def test_cli_refuses_a_running_profile(self): + with tempfile.TemporaryDirectory() as t: + profile = make_profile(Path(t)) + output = Path(t) / 'export.portage.json' + lock = profile / '.parentlock' + lock.write_bytes(b'') + descriptor = os.open(lock, os.O_RDONLY) + try: + result = subprocess.run( + [sys.executable, str(SCRIPT), '--profile', str(profile), '--output', str(output), + '--plaintext'], + capture_output=True, text=True, + ) + finally: + os.close(descriptor) + self.assertNotEqual(result.returncode, 0) + self.assertIn('close Firefox', result.stderr) + self.assertFalse(output.exists()) + + @unittest.skipUnless(HAVE_CRYPTOGRAPHY, 'cryptography package is not installed') + def test_encrypted_export_roundtrip(self): + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + + passphrase = 'synthetic-passphrase-for-test-123' + with tempfile.TemporaryDirectory() as t: + p = Path(t) + profile = make_profile(p) + write_ls_origin(profile, 'https+++second.test', 'https://second.test', {'secret': 'secret-value-猫'}) + output = p / 'encrypted.portage.json' + result = subprocess.run( + [sys.executable, str(SCRIPT), '--profile', str(profile), '--output', str(output), + '--passphrase-stdin'], + input=passphrase + '\n', capture_output=True, text=True, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(os.stat(output).st_mode & 0o777, 0o600) + raw = output.read_text() + self.assertNotIn('secret-value', raw) + wrapper = json.loads(raw) + meta = wrapper['portage'] + self.assertEqual(meta['format'], 'portage-bundle-encrypted') + self.assertEqual(meta['iterations'], 250000) + key = hashlib.pbkdf2_hmac( + 'sha256', passphrase.encode(), base64.b64decode(meta['salt']), meta['iterations'], dklen=32, + ) + plaintext = AESGCM(key).decrypt( + base64.b64decode(meta['iv']), base64.b64decode(wrapper['ciphertext']), None, + ) + inner = json.loads(plaintext) + self.assertEqual(inner['meta']['counts']['localStorage'], 2) + self.assertEqual(inner['data']['localStorage'][1]['items']['secret'], 'secret-value-猫') if __name__ == '__main__': diff --git a/tests/test_indexeddb_paths.cjs b/tests/test_indexeddb_paths.cjs new file mode 100644 index 0000000..54ed329 --- /dev/null +++ b/tests/test_indexeddb_paths.cjs @@ -0,0 +1,72 @@ +'use strict'; +// Path/symlink handling for the IndexedDB tool. Runs in dry-run mode only, so +// no Firefox or Chromium executable is needed and no browser profile is touched. +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const {migrate, options} = require('../tools/indexeddb_migrate.cjs'); + +function createQuotaDatabase(profile) { + // Use the Python toolchain when node:sqlite is unavailable. + const script = `import sqlite3,sys\ncon=sqlite3.connect(sys.argv[1])\ncon.execute('CREATE TABLE origin (origin TEXT, client_usages TEXT)')\ncon.execute('INSERT INTO origin VALUES (?,?)', ('https://example.test','I1234'))\ncon.commit()\ncon.close()`; + const result = require('node:child_process').spawnSync('python3', ['-c', script, path.join(profile, 'storage.sqlite')], {encoding: 'utf8'}); + assert.equal(result.status, 0, result.stderr); +} + +async function main() { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'portage-idb-paths-')); + try { + const source = path.join(root, 'firefox-profile'); + const target = path.join(root, 'chromium-profile'); + fs.mkdirSync(source); + fs.mkdirSync(target); + createQuotaDatabase(source); + + // A symlinked --firefox-profile must be resolved before cp/browser launch; + // otherwise `cp -a` copies the symlink and Firefox opens the source profile. + const sourceLink = path.join(root, 'firefox-link'); + fs.symlinkSync(source, sourceLink); + const dry = await migrate({ + firefoxProfile: sourceLink, chromiumProfile: target, + firefox: path.join(root, 'missing-firefox'), chromium: path.join(root, 'missing-chromium'), + apply: false, + }); + assert.equal(dry.origins, 1); + + // A target that is a symlink to the source must be rejected, not silently + // used as the destination profile. + const targetLink = path.join(root, 'chromium-link'); + fs.symlinkSync(source, targetLink); + await assert.rejects(() => migrate({ + firefoxProfile: sourceLink, chromiumProfile: targetLink, + firefox: path.join(root, 'missing-firefox'), chromium: path.join(root, 'missing-chromium'), + apply: false, + }), /must differ|looks like a Firefox profile/); + + // A Firefox-looking Chromium target is refused before anything is written. + fs.writeFileSync(path.join(target, 'prefs.js'), ''); + await assert.rejects(() => migrate({ + firefoxProfile: source, chromiumProfile: target, + firefox: path.join(root, 'missing-firefox'), chromium: path.join(root, 'missing-chromium'), + apply: false, + }), /looks like a Firefox profile/); + + const parsed = options([ + '--firefox-profile', source, '--chromium-profile', target, + '--firefox', '/usr/bin/firefox', '--chromium', '/usr/bin/chromium', + '--chromium-profile-directory', 'Profile 1', + ]); + assert.equal(parsed.chromiumProfileDirectory, 'Profile 1'); + assert.throws(() => options([ + '--firefox-profile', source, '--chromium-profile', target, + '--firefox', '/usr/bin/firefox', '--chromium', '/usr/bin/chromium', + '--chromium-profile-directory', '../escape', + ]), /Invalid Chromium profile directory/); + console.log('PASS: IndexedDB path resolution, symlink and profile guards'); + } finally { + fs.rmSync(root, {recursive: true, force: true}); + } +} + +main().catch((error) => { console.error(error.stack); process.exitCode = 1; }); diff --git a/tests/test_profile_safety.cjs b/tests/test_profile_safety.cjs new file mode 100644 index 0000000..13876d6 --- /dev/null +++ b/tests/test_profile_safety.cjs @@ -0,0 +1,79 @@ +'use strict'; +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const cp = require('node:child_process'); +const {assertSafeTargetProfile, chromiumLaunchProfileOptions, chromiumLockPath, assertChromiumClosed, firefoxLockPath, isLockHeld, assertFirefoxClosed} = + require('../tools/profile_safety.cjs'); + +function waitFor(predicate, timeoutMs = 3000) { + const start = Date.now(); + return new Promise((resolve, reject) => { + const poll = () => { + if (predicate()) return resolve(); + if (Date.now() - start > timeoutMs) return reject(new Error('timed out waiting for lock state')); + setTimeout(poll, 25); + }; + poll(); + }); +} + +async function main() { + assert.throws(() => assertSafeTargetProfile('/'), /root or home/); + assert.throws(() => assertSafeTargetProfile(os.homedir()), /root or home/); + + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'portage-safety-')); + const firefoxProfile = path.join(root, 'firefox-profile'); + const chromiumProfile = path.join(root, 'chromium-profile'); + fs.mkdirSync(firefoxProfile); + fs.mkdirSync(chromiumProfile); + fs.writeFileSync(path.join(firefoxProfile, 'prefs.js'), ''); + try { + assert.throws(() => assertSafeTargetProfile(firefoxProfile), /looks like a Firefox profile/); + assert.equal(assertSafeTargetProfile(chromiumProfile), chromiumProfile); + assert.equal(assertSafeTargetProfile(path.join(root, 'not-created-yet')), + path.join(root, 'not-created-yet')); + // Fresh disposable profiles keep Puppeteer's --password-store=basic, while + // existing profiles must not be switched to the fallback cookie key store. + assert.deepEqual(chromiumLaunchProfileOptions(chromiumProfile), {}); + fs.mkdirSync(path.join(chromiumProfile, 'Default')); + assert.deepEqual(chromiumLaunchProfileOptions(chromiumProfile).ignoreDefaultArgs, + ['--password-store=basic', '--use-mock-keychain']); + + // Chrome's lock is a dangling symlink while the browser is running; + // existsSync() would miss it, so the helper must use lstat(). + assert.equal(chromiumLockPath(chromiumProfile), null); + assertChromiumClosed(chromiumProfile); + fs.symlinkSync('somehost-4242', path.join(chromiumProfile, 'SingletonLock')); + assert.equal(chromiumLockPath(chromiumProfile), path.join(chromiumProfile, 'SingletonLock')); + assert.throws(() => assertChromiumClosed(chromiumProfile), /SingletonLock present/); + fs.unlinkSync(path.join(chromiumProfile, 'SingletonLock')); + + // Stale lock file: exists but is not held open => the profile is closed. + const lock = firefoxLockPath(firefoxProfile); + // prefs.js is a marker, not a lock; add one. + fs.writeFileSync(path.join(firefoxProfile, '.parentlock'), ''); + assert.equal(firefoxLockPath(firefoxProfile), path.join(firefoxProfile, '.parentlock')); + assert.equal(isLockHeld(path.join(firefoxProfile, '.parentlock')), false); + assertFirefoxClosed(firefoxProfile); + + // A live process holding the lock file open must be detected. + const child = cp.spawn(process.execPath, ['-e', + "require('node:fs').openSync(process.argv[1], 'r'); setTimeout(() => {}, 15000);", + path.join(firefoxProfile, '.parentlock')], {stdio: 'ignore'}); + try { + await waitFor(() => isLockHeld(path.join(firefoxProfile, '.parentlock'))); + assert.throws(() => assertFirefoxClosed(firefoxProfile), /appears to be in use/); + } finally { + child.kill('SIGKILL'); + } + await waitFor(() => !isLockHeld(path.join(firefoxProfile, '.parentlock'))); + assertFirefoxClosed(firefoxProfile); + console.log('PASS: profile target and Firefox lock safety checks'); + } finally { + fs.rmSync(root, {recursive: true, force: true}); + } +} + +main().catch((error) => { console.error(error.stack); process.exitCode = 1; }); diff --git a/tests/test_storage_browser.cjs b/tests/test_storage_browser.cjs index 9500c3c..986c95c 100644 --- a/tests/test_storage_browser.cjs +++ b/tests/test_storage_browser.cjs @@ -1,33 +1,113 @@ 'use strict'; -const assert=require('node:assert/strict'),fs=require('node:fs'),vm=require('node:vm'); -const {validOrigin, validateBundle}=require('../tools/chromium_localstorage_import.cjs'); -for (const browser of ['chrome','firefox']) { - const src=fs.readFileSync(`${browser}/dashboard.js`,'utf8'); - const start=src.indexOf('function mapSameSite('); - const end=src.indexOf('async function importTabs(',start); - assert(start>0 && end>start); - const ctx=vm.createContext({URL,Number,Array,IS_FIREFOX:browser==='firefox',tick:async()=>{}}); - vm.runInContext(src.slice(start,end),ctx); - for(const s of ['strict','lax','no_restriction','unspecified']) { - assert.equal(ctx.mapSameSite(s),s); +// Exercises the dashboard's cookie collection/import code in a VM with mocked +// WebExtension APIs; no real browser profile is read or written. +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const vm = require('node:vm'); +const {validOrigin, validateBundle} = require('../tools/chromium_localstorage_import.cjs'); + +function browserContext(browser) { + const source = fs.readFileSync(`${browser}/dashboard.js`, 'utf8'); + const context = vm.createContext({ + URL, Number, Array, String, Object, IS_FIREFOX: browser === 'firefox', tick: async () => {}, + }); + for (const [startMarker, endMarker] of [ + ['async function collectCookies()', 'async function collectTabs()'], + ['function mapSameSite(s)', 'async function importTabs('], + ]) { + const start = source.indexOf(startMarker); + const end = source.indexOf(endMarker, start); + assert(start > 0 && end > start, `${browser}: missing ${startMarker}`); + vm.runInContext(source.slice(start, end), context); } - assert.equal(ctx.mapSameSite('unknown'),'unspecified'); - (async()=>{ - const written=[]; - ctx.api={cookies:{getAllCookieStores:async()=>[{id:browser==='firefox'?'firefox-default':'0'}],set:async d=>{written.push(d);return d;}}}; - const r=await ctx.importCookies([ - {name:'test',value:'value',domain:'example.com',path:'/',hostOnly:true,sameSite:'unspecified'}, - {name:'partition',value:'v',domain:'example.com',path:'/',hostOnly:true,sameSite:'lax',partitionKey:{topLevelSite:'https://site.test'}}, - {name:'container',domain:'example.org',storeId:'firefox-container-1',hostOnly:true}, - ],()=>{}); - assert.equal(r.imported,2);assert.equal(r.skipped,1); - assert.equal(written[0].sameSite,'unspecified'); - assert.equal(written[1].partitionKey.topLevelSite,'https://site.test'); - if(browser==='firefox')assert.equal(written[0].firstPartyDomain,''); - console.log(browser+': cookie import metadata and SameSite passed'); - })().catch(e=>{console.error(e);process.exitCode=1}); + return context; } -assert(validOrigin('https://example.org')); -assert(!validOrigin('javascript:foo')); -assert.throws(()=>validateBundle({portage:{format:'portage-bundle',version:1},data:{localStorage:[{origin:'https://example.org/path',items:{x:'y'}}]}})); -assert.throws(()=>validateBundle({portage:{format:'portage-bundle',version:1},data:{localStorage:[{origin:'https://example.org',items:{x:123}}]}})); + +async function main() { + for (const browser of ['chrome', 'firefox']) { + const firefox = browser === 'firefox'; + const context = browserContext(browser); + const defaultStoreId = firefox ? 'firefox-default' : '0'; + + for (const sameSite of ['strict', 'lax', 'no_restriction', 'unspecified']) { + assert.equal(context.mapSameSite(sameSite), sameSite); + } + assert.equal(context.mapSameSite(undefined), 'unspecified'); + assert.equal(context.mapSameSite('unknown'), 'unspecified'); + + // collectCookies: partitioned cookies must be requested explicitly for + // both browsers; a store that cannot be read must not abort the scan. + const queries = []; + context.api = { + cookies: { + getAllCookieStores: async () => [ + {id: defaultStoreId}, {id: firefox ? 'firefox-container-1' : '1'}, {id: 'unreadable-store'}, + ], + getAll: async (query) => { + queries.push({...query}); + if (query.storeId === 'unreadable-store') throw new Error('store is not accessible'); + return [{ + name: 'cookie-' + query.storeId, value: 'v', domain: 'example.com', path: '/', + secure: true, httpOnly: true, sameSite: 'lax', session: true, hostOnly: true, + storeId: query.storeId, partitionKey: {topLevelSite: 'https://top.test', hasCrossSiteAncestor: false}, + firstPartyDomain: firefox ? '' : undefined, + }]; + }, + }, + }; + const collected = await context.collectCookies(); + assert.equal(queries.length, 3); + for (const query of queries) { + assert.equal(Object.keys(query.partitionKey).length, 0, `${browser}: partitionKey filter missing`); + assert.equal(typeof query.storeId, 'string'); + if (firefox) assert.equal(query.firstPartyDomain, null); + else assert.equal('firstPartyDomain' in query, false, 'Chrome rejects unknown firstPartyDomain'); + } + assert.equal(collected.count, 2, `${browser}: unreadable store aborted collection`); + assert.equal(collected.data[0].partitionKey.topLevelSite, 'https://top.test'); + + // importCookies: only the browser default store is a valid target, and + // partitioned/FPI metadata must survive the conversion. + const written = []; + context.api = {cookies: {set: async (details) => { written.push(details); return details; }}}; + const result = await context.importCookies([ + {name: 'plain', value: 'v', domain: 'example.com', path: '/', hostOnly: true, sameSite: undefined}, + {name: 'partitioned', value: 'v', domain: 'example.com', path: '/', hostOnly: true, sameSite: 'lax', + partitionKey: {topLevelSite: 'https://top.test', hasCrossSiteAncestor: true}}, + {name: 'container', value: 'v', domain: 'example.com', path: '/', storeId: 'firefox-container-1'}, + {name: 'incognito', value: 'v', domain: 'example.com', path: '/', storeId: '1'}, + {name: 'fpi', value: 'v', domain: 'example.com', path: '/', firstPartyDomain: 'example.com'}, + ], () => {}); + const names = written.map((details) => details.name); + assert.equal(result.imported, firefox ? 3 : 2, `${browser}: unexpected import count`); + assert.equal(result.skipped, firefox ? 2 : 3, `${browser}: unexpected skip count`); + assert.deepEqual(names, firefox ? ['plain', 'partitioned', 'fpi'] : ['plain', 'partitioned']); + for (const details of written) assert.equal(details.storeId, defaultStoreId); + assert.equal('sameSite' in written[0], false, 'unspecified must omit the attribute'); + assert.equal(written.find((details) => details.name === 'partitioned').partitionKey.hasCrossSiteAncestor, true); + if (firefox) { + assert.equal(written[0].firstPartyDomain, ''); + assert.equal(written.find((details) => details.name === 'fpi').firstPartyDomain, 'example.com'); + } + console.log(`${browser}: cookie collect/import metadata, partitioning, SameSite passed`); + } + + assert(validOrigin('https://example.org')); + assert(!validOrigin('javascript:foo')); + assert.throws(() => validateBundle({portage: {format: 'portage-bundle', version: 1}, + data: {localStorage: [{origin: 'https://example.org/path', items: {x: 'y'}}]}})); + assert.throws(() => validateBundle({portage: {format: 'portage-bundle', version: 1}, + data: {localStorage: [{origin: 'https://example.org', items: {x: 123}}]}})); + + // A __proto__ storage key is data, not a prototype mutation; JSON.parse + // defines it as an own property, and validateBundle must accept it. + const protoBundle = JSON.parse('{"portage":{"format":"portage-bundle","version":1},' + + '"data":{"localStorage":[{"origin":"https://example.org","items":{"__proto__":"value"}}]}}'); + const protoItems = validateBundle(protoBundle).sites[0].items; + assert.equal(Object.getPrototypeOf(protoItems), Object.prototype); + assert.equal(Object.prototype.hasOwnProperty.call(protoItems, '__proto__'), true); + assert.equal(protoItems['__proto__'], 'value'); + console.log('PASS: dashboard cookies and bundle validation'); +} + +main().catch((error) => { console.error(error.stack); process.exitCode = 1; }); diff --git a/tools/README.md b/tools/README.md index 98b1856..e4b385b 100644 --- a/tools/README.md +++ b/tools/README.md @@ -1,18 +1,19 @@ # Experimental whole-profile Firefox → Chromium LocalStorage migration -The Portage extension cannot enumerate every origin's LocalStorage via WebExtension APIs. This optional Linux companion migrates **every compatible first-party Firefox LocalStorage origin** by reading the offline Firefox profile and writing via a separate, headless Chrome/Brave session. It does **not** depend on currently open tabs, and does **not** visit the real websites during import. +The Portage extension cannot enumerate every origin's LocalStorage via WebExtension APIs. This optional Linux companion migrates **every compatible first-party Firefox LocalStorage origin** by reading the offline Firefox profile and writing via a separate, headless Chrome/Brave session. It does **not** depend on currently open tabs, and does **not** fetch live website content during import. -**This is not complete browser-profile migration.** It does *not* migrate IndexedDB, sessionStorage, Service Workers, Firefox Containers, partitioned localStorage, WebAuthn/passkeys, or device-bound session credentials. Login persistence cannot be guaranteed. Cookies and bookmarks can be migrated separately using the standard Portage extension. +**This is not complete browser-profile migration.** The LocalStorage helper does *not* migrate sessionStorage, Service Workers, Firefox Containers, partitioned LocalStorage, WebAuthn/passkeys, or device-bound session credentials. IndexedDB has a separate experimental section below with its own limitations. Login persistence cannot be guaranteed. The standard Portage extension can migrate bookmarks and cookies; this folder also adds an offline cookie companion. ## Safety / prerequisites - Backup the Firefox and Chromium/Brave profiles first. -- Close Firefox before exporting; close Brave/Chrome before applying to its profile. The importer refuses an existing Chromium `SingletonLock`. +- Close Firefox before exporting; close Brave/Chrome before applying to its profile. The importer refuses an existing Chromium `SingletonLock`, and the tools refuse a Firefox-looking profile as the Chromium target, as well as `/` or the home directory. - LocalStorage can contain live session tokens. **Encrypted AES-256-GCM export is the default**; use a long unique passphrase. `--plaintext` is an explicitly unsafe opt-out. Output is mode 0600. Never attach exported bundles to an issue, share them, or commit them. -- Require **Python 3** and `cryptography` for encryption (`sudo apt install python3-cryptography` on Debian), and **Node.js 20+**, plus Puppeteer Core (`cd tools && npm install`). Puppeteer Core uses the existing installed Chrome/Brave and downloads no browsers. -- The exporter reports a **count of IndexedDB origins omitted** (without opening their records), so you can estimate missing coverage. +- Require **Python 3** and `cryptography` for encryption (`sudo apt install python3-cryptography` on Debian), and **Node.js 22.12+**, plus Puppeteer Core (`cd tools && npm ci`). Puppeteer Core uses the existing installed Chrome/Brave and downloads no browsers. +- The exporter reports a **count of IndexedDB origins omitted** (without opening their records); use the IndexedDB section below if you need them. - Import is **merge/upsert**: values with matching LocalStorage keys in the target are overwritten. Use a fresh Chromium profile where possible. Failed sites are reported and attempted writes are rolled back within the page when possible; this does not provide cross-origin atomic transactions. - Import launches the browser **headless**, intercepts all page network requests to return inert local HTML, disables service workers for the temporary page, and validates the loaded origin. This avoids visiting live websites but does not formally guarantee that the browser itself makes no background connections. Standard Chrome sandboxing remains enabled. +- Existing Chromium/Brave profiles keep their normal OS password-store settings: Puppeteer's forced `--password-store=basic` default is dropped for non-empty profiles so imported cookies stay readable after a normal launch. Fresh disposable profiles keep the automation default. ## Usage on Linux @@ -50,11 +51,17 @@ The Portage extension cannot enumerate every origin's LocalStorage via WebExtens ```bash python3 -m unittest discover -s tests -p 'test_*.py' node tests/test_storage_browser.cjs -# Optional desktop E2E: local Firefox 159 and Chrome 156 were verified; -# needs installed Firefox and Google Chrome plus Puppeteer -node tests/e2e_cross_browser.cjs +node tests/test_profile_safety.cjs +node tests/test_indexeddb_codec.cjs +node tests/test_indexeddb_paths.cjs +# Optional desktop E2E (synthetic disposable profiles only). Set +# PORTAGE_TEST_FIREFOX / PORTAGE_TEST_CHROMIUM / PORTAGE_TEST_BRAVE when the +# browsers are not at the default paths; a missing browser skips that test. node tests/e2e_offline_import.cjs +node tests/e2e_cookie_cli.cjs node tests/e2e_chrome.cjs +node tests/e2e_cross_browser.cjs +node tests/e2e_indexeddb.cjs ``` Chromium E2E tests verify that **requests to the synthetic target origin equal zero during import**, and the stored values remain readable after browser restart. The cross-browser test verifies Firefox LSNG decoding, AES encryption compatibility and Chromium restoration. Neither test guarantees the preservation of real-world login sessions. @@ -74,14 +81,18 @@ requests during transfer. This is *not* a guarantee of zero browser background network activity. The transfer stays in memory; it does **not** export tokens into an unencrypted intermediate JSON file. A temporary Firefox profile copy containing sensitive data is created under a mode-0700 temporary directory and -removed when the tool exits normally. A crash or power failure can leave it -behind, so inspect `portage-idb-*` in your temporary directory if interrupted. +removed when the tool exits normally or is interrupted with Ctrl-C / SIGTERM. +A hard kill or power failure can still leave it behind, so inspect +`portage-idb-*` in your temporary directory if a run is interrupted. **Close both browsers and back up both profiles before beginning.** Firefox's source is not modified, but Chromium's destination profile **will be changed** with `--apply`. Existing IndexedDB databases are **never overwritten**: the -whole database is skipped if its name already exists at that origin. The destination Chromium lock file and the Firefox source profile's live lock are checked before migration. Do not use this on a profile -that another browser process is accessing. +whole database is skipped if its name already exists at that origin. The +destination Chromium lock file and the Firefox source profile's open lock are +checked before migration; the Chromium profile named `Default` is used unless +`--chromium-profile-directory` is passed. Do not use this on a profile that +another browser process is accessing. ```bash # First, preview first-party IndexedDB origin count, WITHOUT modifying a profile: @@ -113,9 +124,14 @@ BigInt, Date, RegExp, Map/Set, binary buffers and typed arrays, Blob/File). **Still unsupported**: cyclic or shared object references, CryptoKey, non-standard browser objects, IndexedDB databases larger than 32 MiB in the -wire representation, stores with over 50,000 records, and individual Blob/File -values larger than 8 MiB. The bridge **skips entire databases** when it finds -unsupported data, and reports aggregate counts without printing record values. +wire representation, stores with over 50,000 records, arrays with over 50,000 +elements, and individual Blob/File values larger than 8 MiB. The bridge +**skips entire databases** when it finds unsupported data, and reports +aggregate counts without printing record values. +The IndexedDB API does not expose an object store's current auto-increment +counter, so after restoring records that were deleted at the source a new +record can reuse a deleted key number; verify apps that require monotonically +increasing keys after a migration. There is no guarantee that every session will remain logged in; site-specific security mechanisms and passkeys can require reauthentication. Importing an IDB database into another browser also does not make Firefox extension storage or @@ -132,22 +148,30 @@ node tests/e2e_indexeddb.cjs The `chromium_cookie_import.cjs` companion can transfer Firefox cookies into a closed Chromium/Brave profile without creating a plaintext cookie bundle on -disk. Python reads the backed-up Firefox `cookies.sqlite` and passes the -records through a **local subprocess pipe** to Chrome's native cookie API. -Only aggregate counts are printed. The entire profile should be backed up. +disk. Close Firefox first; the source profile's open lock is checked. Python +reads the backed-up Firefox `cookies.sqlite` and passes the records through a +**local subprocess pipe** to Chrome's native cookie API. Only aggregate counts +are printed. The entire profile should be backed up. ```bash node tools/chromium_cookie_import.cjs \ "$HOME/.mozilla/firefox/dev-edition-default" \ "$HOME/.config/BraveSoftware/Brave-Browser" \ /usr/bin/brave-browser + # optional 4th argument: the Chromium profile directory (default: Default) ``` -Firefox containers, origin-attribute partitions and expired cookies are -conservatively excluded, rather than incorrectly combining isolated sessions. +Firefox stores cookie expiry in milliseconds; the bridge converts it to the +seconds expected by Chromium's cookie API and never resurrects expired cookies. +Firefox containers, origin-attribute partitions, expired cookies and session +cookies are conservatively excluded, rather than incorrectly combining +isolated sessions or counting ephemeral cookies as migrated. Session cookies +are skipped because the importer closes its temporary Chromium session +immediately, so they could not survive the import anyway. Some cookies or logins remain tied to browser/device-bound secrets; a successful CDP `Network.setCookie` result does **not** guarantee continued authentication. Never collect or paste exported cookie values into bug reports. `node tests/e2e_cookie_cli.cjs` verifies this transfer with synthetic cookie -values and disposable Brave profiles only. +values and disposable Brave/Chrome profiles only; set `PORTAGE_TEST_BRAVE` if +the browser is not at `/usr/bin/brave-browser`. diff --git a/tools/chromium_cookie_import.cjs b/tools/chromium_cookie_import.cjs index c0db759..f59d0ed 100644 --- a/tools/chromium_cookie_import.cjs +++ b/tools/chromium_cookie_import.cjs @@ -1,11 +1,20 @@ #!/usr/bin/env node 'use strict'; /** Private-process Firefox -> Chromium cookie transfer. Do not print cookie values. */ -const cp=require('node:child_process'),path=require('node:path'),fs=require('node:fs'),os=require('node:os'); -async function transfer({sourceProfile,targetProfile,browserPath}) { - const source=path.resolve(sourceProfile),target=path.resolve(targetProfile); +const cp=require('node:child_process'),path=require('node:path'),fs=require('node:fs'); +const {assertSafeTargetProfile, assertChromiumClosed, assertFirefoxClosed, chromiumLaunchProfileOptions}=require('./profile_safety.cjs'); +function assertProfileDirectory(value) { + if(typeof value!=='string'||!/^[\w. -]+$/.test(value)||value==='.'||value==='..')throw Error('Invalid Chromium profile directory name'); + return value; +} +async function transfer({sourceProfile,targetProfile,browserPath,profileDirectory='Default'}) { + const source=path.resolve(sourceProfile); + const target=assertSafeTargetProfile(targetProfile, 'Chromium user-data-dir'); if(!fs.existsSync(source)||!fs.existsSync(browserPath))throw Error('Source or browser missing'); - if(fs.existsSync(path.join(target,'SingletonLock')))throw Error('Target browser lock present'); + if(source===target)throw Error('Source and destination profiles must differ'); + assertProfileDirectory(profileDirectory); + assertFirefoxClosed(source); + assertChromiumClosed(target); const p=cp.spawnSync('python3',[path.join(__dirname,'firefox_cookie_stream.py'),source],{ encoding:'utf8',maxBuffer:32*1024*1024,timeout:20000,stdio:['ignore','pipe','pipe']}); if(p.status!==0)throw Error('Cookie decoding failed; no destination modifications'); @@ -14,7 +23,8 @@ async function transfer({sourceProfile,targetProfile,browserPath}) { const result={candidate:parsed.cookies.length,skipped:parsed.skipped,accepted:0,failed:0}; try{ browser=await puppeteer.launch({executablePath:browserPath,userDataDir:target,headless:true, - args:['--disable-background-networking','--disable-sync','--disable-extensions','--no-first-run']}); + ...chromiumLaunchProfileOptions(target), + args:['--profile-directory='+profileDirectory,'--disable-background-networking','--disable-sync','--disable-extensions','--no-first-run']}); const page=await browser.newPage(),session=await page.createCDPSession(); for(const cookie of parsed.cookies){ try{ @@ -27,9 +37,9 @@ async function transfer({sourceProfile,targetProfile,browserPath}) { } if(require.main===module){ const args=process.argv.slice(2); - if(args.length!==3){console.error('Usage: node chromium_cookie_import.cjs FIREFOX_CLOSED_PROFILE CHROMIUM_CLOSED_PROFILE CHROME_EXECUTABLE');process.exit(2)} - transfer({sourceProfile:args[0],targetProfile:args[1],browserPath:args[2]}).then(r=>{ + if(args.length!==3&&args.length!==4){console.error('Usage: node chromium_cookie_import.cjs FIREFOX_CLOSED_PROFILE CHROMIUM_CLOSED_PROFILE CHROME_EXECUTABLE [CHROMIUM_PROFILE_DIRECTORY]');process.exit(2)} + transfer({sourceProfile:args[0],targetProfile:args[1],browserPath:args[2],profileDirectory:args[3]||'Default'}).then(r=>{ console.log('Cookies (counts only):',JSON.stringify(r));if(r.failed)process.exitCode=2; }).catch(e=>{console.error('Cookie import failed:',e.message);process.exitCode=1}); } -module.exports={transfer}; +module.exports={transfer,assertProfileDirectory}; diff --git a/tools/chromium_localstorage_import.cjs b/tools/chromium_localstorage_import.cjs index 692dbe8..13392e1 100644 --- a/tools/chromium_localstorage_import.cjs +++ b/tools/chromium_localstorage_import.cjs @@ -11,6 +11,7 @@ const fs = require('node:fs'); const path = require('node:path'); const crypto = require('node:crypto'); const readline = require('node:readline'); +const {assertSafeTargetProfile, assertChromiumClosed, chromiumLaunchProfileOptions} = require('./profile_safety.cjs'); function parseArgs(argv) { const opts = {apply: false, profileDirectory: 'Default', timeout: 12000}; @@ -154,10 +155,8 @@ async function restoreSites(browser, sites, timeout=12000) { async function run(opts) { const bundle=await loadBundle(path.resolve(opts.bundle),opts.passphraseStdin); const {sites,totalKeys}=validateBundle(bundle); - const profile=path.resolve(opts.userDataDir); - if(profile==='/' || profile===require('node:os').homedir()) throw Error('Refusing to use root or home as Chrome user-data-dir'); - const lock=path.join(profile,'SingletonLock'); - if (fs.existsSync(lock) || fs.lstatSync(lock, {throwIfNoEntry:false})) throw Error('Browser profile appears to be in use (SingletonLock present); close browser and retry'); + const profile=assertSafeTargetProfile(opts.userDataDir, 'Chromium user-data-dir'); + assertChromiumClosed(profile); console.log(`Validated ${sites.length} origins / ${totalKeys} LocalStorage keys.`); const unsupportedIdb = bundle?.meta?.unsupported?.indexedDBOrigins; if (Number.isInteger(unsupportedIdb) && unsupportedIdb > 0) { @@ -170,7 +169,7 @@ async function run(opts) { // Never start with a personal profile unless explicitly specified by the operator. // Keep Chrome sandbox enabled; do not pass --no-sandbox. const browser=await puppeteer.launch({executablePath:path.resolve(opts.browser),userDataDir:profile, - headless:true,defaultViewport:{width:600,height:400}, + headless:true,defaultViewport:{width:600,height:400},...chromiumLaunchProfileOptions(profile), args:['--profile-directory='+opts.profileDirectory,'--no-first-run','--no-default-browser-check', '--disable-background-networking','--disable-sync','--disable-extensions','--disable-features=MediaRouter']}); let result; diff --git a/tools/firefox_cookie_stream.py b/tools/firefox_cookie_stream.py index 550fd0a..db69e2d 100644 --- a/tools/firefox_cookie_stream.py +++ b/tools/firefox_cookie_stream.py @@ -3,6 +3,7 @@ Never redirect stdout to a file or issue tracker: it contains session credentials. """ import json, sqlite3, sys, time +from contextlib import closing from pathlib import Path @@ -12,9 +13,9 @@ def collect(profile): raise FileNotFoundError('Firefox cookies.sqlite not found') uri=file.resolve().as_uri()+'?mode=ro' included=[] - reason={'partitioned_or_containers':0,'expired':0,'invalid':0,'insecure_none':0} + reason={'partitioned_or_containers':0,'expired':0,'session':0,'invalid':0,'insecure_none':0} now=time.time() - with sqlite3.connect(uri, uri=True, timeout=10) as conn: + with closing(sqlite3.connect(uri, uri=True, timeout=10)) as conn: for name,value,host,path,expiry,secure,http_only,same_site,attrs in conn.execute( 'SELECT name,value,host,path,expiry,isSecure,isHttpOnly,sameSite,originAttributes FROM moz_cookies' ): @@ -24,7 +25,17 @@ def collect(profile): if not host or not isinstance(name,str) or not isinstance(value,str) or not host.strip('.') or not path.startswith('/'): reason['invalid']+=1 continue - if expiry and expiry str: raise ValueError(f'Unknown conversion type: {conversion_type}') -def valid_origin(origin: str) -> bool: +def normalize_origin(origin: str): + """Return the canonical origin Chromium's URL parser will accept. + + Firefox stores origins in canonical form, but synthetic/corrupted profiles + may use uppercase hosts or an explicit default port. Emitting those would + make the JavaScript importer reject the whole bundle, so normalise here and + skip origins that cannot be represented safely. + """ if not isinstance(origin, str) or '^' in origin or '#' in origin or '?' in origin: - return False # no silent loss of Firefox origin attributes / partitions + return None # no silent loss of Firefox origin attributes / partitions try: u = urlsplit(origin) - return u.scheme in ('https', 'http') and bool(u.hostname) and not u.username and not u.password and u.path in ('', '/') + port = u.port + host = u.hostname except ValueError: + return None + scheme = u.scheme.lower() + if scheme not in ('http', 'https') or not host or u.username or u.password or u.path not in ('', '/'): + return None + if any(ord(ch) > 127 for ch in host): + return None # Firefox stores punycode; do not risk a WHATWG IDNA mismatch + if ':' in host: + host = f'[{host}]' + default_port = 443 if scheme == 'https' else 80 + netloc = host if port is None or port == default_port else f'{host}:{port}' + return f'{scheme}://{netloc}' + + +def valid_origin(origin: str) -> bool: + return normalize_origin(origin) is not None + + +def firefox_profile_in_use(profile: Path) -> bool: + """Detect a Firefox process holding this profile's lock file open. + + Existence of .parentlock is not enough because a crash can leave a stale + lock behind; /proc exposes the open descriptors of the running Firefox. + """ + lock = profile / '.parentlock' + if not lock.exists(): return False + try: + target = str(lock.resolve()) + except OSError: + return False + proc = Path('/proc') + if proc.is_dir(): + for pid in os.listdir(proc): + if not pid.isdigit(): + continue + fd_dir = proc / pid / 'fd' + try: + descriptors = os.listdir(fd_dir) + except OSError: + continue + for descriptor in descriptors: + try: + linked = os.readlink(fd_dir / descriptor) + except OSError: + continue + if linked == target or linked == target + ' (deleted)': + return True + return False + try: + probe = subprocess.run(['fuser', '-s', str(lock)], capture_output=True, timeout=3) + except (OSError, subprocess.SubprocessError) as exc: + raise RuntimeError('Cannot verify that Firefox is closed (no /proc and no fuser)') from exc + if probe.returncode not in (0, 1): + raise RuntimeError('Cannot verify that Firefox is closed (fuser failed)') + return probe.returncode == 0 def export_profile(profile: Path): @@ -111,15 +174,20 @@ def export_profile(profile: Path): if not root.is_dir(): raise ValueError('Expected Firefox profile with storage/default directory') sites, warnings = [], [] + seen_origins = set() for db in sorted(root.glob('*/ls/data.sqlite')): try: # SQLite read-only URI avoids creating journal files or modifying profile. with closing(sqlite3.connect(db.as_uri() + '?mode=ro', uri=True, timeout=3)) as conn: row = conn.execute('SELECT origin FROM "database" LIMIT 1').fetchone() - if not row or not valid_origin(row[0]): + origin = normalize_origin(row[0]) if row else None + if origin is None: warnings.append('Skipped partitioned or invalid origin (name omitted for privacy)') continue - origin = row[0].rstrip('/') + if origin in seen_origins: + warnings.append('Skipped duplicate origin (name omitted for privacy)') + continue + seen_origins.add(origin) entries = conn.execute('SELECT key, value, conversion_type, compression_type FROM data').fetchall() if not entries: continue @@ -142,11 +210,18 @@ def main(argv=None): parser.add_argument('--passphrase-stdin', action='store_true', help='Read encryption passphrase from stdin instead of prompting') args = parser.parse_args(argv) profile = args.profile.expanduser().resolve() - output = args.output.expanduser().resolve() - if output.exists(): + # Do not resolve the output path: resolving a dangling symlink would write + # through it and defeat the no-clobber guarantee below. + output = args.output.expanduser() + if os.path.lexists(output): parser.error('Output already exists: will not overwrite sensitive data') if not profile.is_dir(): parser.error('Profile directory does not exist') + try: + if firefox_profile_in_use(profile): + parser.error('Firefox appears to be running with this profile; close Firefox before exporting') + except RuntimeError as exc: + parser.error(str(exc)) sites, warnings = export_profile(profile) # Inventory unsupported IndexedDB without opening or reading any IDB records. # Counts, not credential-bearing names/values, go into the bundle metadata. @@ -192,8 +267,16 @@ def main(argv=None): }, 'ciphertext':base64.b64encode(ciphertext).decode(), } - # Create mode 0600: no permissive intermediate file, no clobber. - fd = os.open(output, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + # Create mode 0600: no permissive intermediate file, no clobber, and never + # follow a symlink (a dangling link would otherwise redirect the write). + try: + fd = os.open(output, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_NOFOLLOW', 0), 0o600) + except FileExistsError: + parser.error('Output already exists: will not overwrite sensitive data') + except FileNotFoundError: + parser.error(f'Output directory does not exist: {output.parent}') + except OSError as exc: + parser.error(f'Cannot create output file: {exc.strerror or exc}') try: with os.fdopen(fd, 'w', encoding='utf-8') as out: json.dump(bundle, out, ensure_ascii=False, separators=(',', ':')) diff --git a/tools/indexeddb_migrate.cjs b/tools/indexeddb_migrate.cjs index e8af471..edea363 100644 --- a/tools/indexeddb_migrate.cjs +++ b/tools/indexeddb_migrate.cjs @@ -10,6 +10,7 @@ const path = require('node:path'); const os = require('node:os'); const cp = require('node:child_process'); const {validOrigin} = require('./chromium_localstorage_import.cjs'); +const {assertSafeTargetProfile, assertChromiumClosed, assertFirefoxClosed, chromiumLaunchProfileOptions} = require('./profile_safety.cjs'); function options(argv) { const o={apply:false,timeout:20000}; @@ -17,11 +18,12 @@ function options(argv) { const a=argv[i]; if(a==='--apply')o.apply=true; else if(a==='--help')o.help=true; - else if(['--firefox-profile','--chromium-profile','--firefox','--chromium'].includes(a)) { - o[{'--firefox-profile':'firefoxProfile','--chromium-profile':'chromiumProfile','--firefox':'firefox','--chromium':'chromium'}[a]]=argv[++i]; + else if(['--firefox-profile','--chromium-profile','--firefox','--chromium','--chromium-profile-directory'].includes(a)) { + o[{'--firefox-profile':'firefoxProfile','--chromium-profile':'chromiumProfile','--firefox':'firefox','--chromium':'chromium','--chromium-profile-directory':'chromiumProfileDirectory'}[a]]=argv[++i]; }else throw Error('Unknown option: '+a); } if(!o.help && (!o.firefoxProfile||!o.chromiumProfile||!o.firefox||!o.chromium))throw Error('Required: --firefox-profile --chromium-profile --firefox --chromium'); + if(o.chromiumProfileDirectory&&(!/^[\w. -]+$/.test(o.chromiumProfileDirectory)||o.chromiumProfileDirectory==='.'||o.chromiumProfileDirectory==='..'))throw Error('Invalid Chromium profile directory name'); return o; } @@ -165,24 +167,51 @@ async function restoreOrigin(page,source) { },{source}); } +const cleanupState = {paths: [], browsers: []}; +function cleanupSensitiveState() { + for (const browser of cleanupState.browsers) { + try { browser.process?.()?.kill?.('SIGKILL'); } catch {} + } + for (const target of cleanupState.paths) { + try { fs.rmSync(target, {recursive: true, force: true}); } catch {} + } + cleanupState.paths.length = 0; + cleanupState.browsers.length = 0; +} +function installCleanupHandlers() { + // Ctrl-C or SIGTERM must not leave the temporary Firefox profile clone (which + // contains cookies and storage data) behind in /tmp. + const handler = (signal) => { cleanupSensitiveState(); process.exit(signal === 'SIGINT' ? 130 : 143); }; + process.once('SIGINT', handler); + process.once('SIGTERM', handler); + return () => { process.removeListener('SIGINT', handler); process.removeListener('SIGTERM', handler); }; +} + +function realDirectory(directory, label) { + if(!fs.existsSync(directory))throw Error(`${label} does not exist: ${directory}`); + const resolved=fs.realpathSync(directory); + if(!fs.statSync(resolved).isDirectory())throw Error(`${label} is not a directory: ${resolved}`); + return resolved; +} + async function migrate(opts) { - const fx=path.resolve(opts.firefoxProfile),target=path.resolve(opts.chromiumProfile); - if(!fs.statSync(fx).isDirectory())throw Error('Firefox source profile is not a directory'); - if(target===fx || fx==='/' || target==='/' || target===os.homedir())throw Error('Unsafe profile directory'); + // Resolve symlinks: cp -a would otherwise copy a symlink of the source + // profile and Firefox would be launched against the original profile. + const fx=realDirectory(opts.firefoxProfile, 'Firefox source profile'); + const targetCandidate=path.resolve(opts.chromiumProfile); + const target=fs.existsSync(targetCandidate)?fs.realpathSync(targetCandidate):targetCandidate; + if(target===fx)throw Error('Source and destination profiles must differ'); + assertSafeTargetProfile(target, 'Chromium user-data-dir'); + assertFirefoxClosed(fx); const origins=originsForFirefox(fx); console.log(`Firefox IndexedDB inventory: ${origins.length} first-party origin(s); container/partitioned origins intentionally excluded.`); if(!opts.apply){console.log('DRY RUN: No browser started. Add --apply to migrate to a backed-up target profile.');return {origins:origins.length};} - if(fs.existsSync(path.join(target,'SingletonLock')))throw Error('Target Chromium profile appears to be open'); - // On Linux the .parentlock file may exist after Firefox exits, so test - // whether any process actually has the file open rather than its existence. - const sourceLock=path.join(fx,'.parentlock'); - if(fs.existsSync(sourceLock)) { - const locked=cp.spawnSync('fuser',['-s',sourceLock],{timeout:3000,stdio:'ignore'}); - if(locked.status===0)throw Error('Firefox source profile is running; close Firefox before migration'); - } + assertChromiumClosed(target); for(const exe of [opts.firefox,opts.chromium])if(!fs.existsSync(exe))throw Error('Executable not found: '+exe); const scratch=fs.mkdtempSync(path.join(os.tmpdir(),'portage-idb-')); fs.chmodSync(scratch,0o700); + cleanupState.paths.push(scratch); + const removeSignalHandlers = installCleanupHandlers(); const clone=path.join(scratch,'firefox-clone'); // Reflinks avoid copying large databases when the filesystem supports CoW. // Do NOT launch Firefox against the original profile, which would modify it. @@ -199,9 +228,11 @@ async function migrate(opts) { 'dom.serviceWorkers.enabled':false, 'extensions.enabledScopes':0, }}); + cleanupState.browsers.push(fb); cb=await pp.launch({browser:'chrome',executablePath:opts.chromium, - userDataDir:target,headless:true,timeout:20000, - args:['--no-first-run','--no-default-browser-check','--disable-background-networking','--disable-sync','--disable-extensions']}); + userDataDir:target,headless:true,timeout:20000,...chromiumLaunchProfileOptions(target), + args:['--profile-directory='+(opts.chromiumProfileDirectory||'Default'),'--no-first-run','--no-default-browser-check','--disable-background-networking','--disable-sync','--disable-extensions']}); + cleanupState.browsers.push(cb); const sourcePage=await inertPage(fb,'firefox'),destPage=await inertPage(cb,'chromium'); for(const [i,origin]of origins.entries()){ try { @@ -221,7 +252,10 @@ async function migrate(opts) { // even if either browser fails to shut down cleanly. try {if(fb)await fb.close();} catch(e) {console.warn('Firefox close failed:',e.message);} try {if(cb)await cb.close();} catch(e) {console.warn('Chromium close failed:',e.message);} + cleanupState.browsers = cleanupState.browsers.filter(browser => browser !== fb && browser !== cb); fs.rmSync(scratch,{recursive:true,force:true}); + cleanupState.paths = cleanupState.paths.filter(entry => entry !== scratch); + removeSignalHandlers(); } console.log(`IndexedDB migration: ${stats.restored} database(s) restored; ${stats.skipped} target skips; ${stats.sourceSkipped} source skips.`); if(stats.errors.length)console.log('Failures (origin indices only, no contents):',JSON.stringify(stats.errors)); @@ -230,7 +264,7 @@ async function migrate(opts) { } if(require.main===module){ try{const o=options(process.argv.slice(2)); - if(o.help)console.log('Usage: node tools/indexeddb_migrate.cjs --firefox-profile PATH --chromium-profile PATH --firefox /usr/local/bin/firefox --chromium /usr/bin/google-chrome [--apply]\nDry-run by default. Use closed profiles; back up both before --apply. Existing target IndexedDB databases will be skipped.'); + if(o.help)console.log('Usage: node tools/indexeddb_migrate.cjs --firefox-profile PATH --chromium-profile PATH --firefox /usr/local/bin/firefox --chromium /usr/bin/google-chrome [--apply]\nDry-run by default. Use closed profiles; back up both before --apply. Existing target IndexedDB databases will be skipped. [--chromium-profile-directory Default]'); else migrate(o).catch(e=>{console.error('IndexedDB transfer failed:',e.message);process.exitCode=1}); }catch(e){console.error(e.message);process.exitCode=1;} } diff --git a/tools/list_firefox_idb_origins.py b/tools/list_firefox_idb_origins.py index 6eda5dc..0d2a868 100644 --- a/tools/list_firefox_idb_origins.py +++ b/tools/list_firefox_idb_origins.py @@ -3,6 +3,7 @@ import json import sqlite3 import sys +from contextlib import closing from pathlib import Path from urllib.parse import urlsplit @@ -12,7 +13,7 @@ def list_origins(profile): if not db.is_file(): raise FileNotFoundError(f'Missing Firefox QuotaManager storage.sqlite: {db}') result = [] - with sqlite3.connect(db.as_uri() + '?mode=ro', uri=True, timeout=5) as connection: + with closing(sqlite3.connect(db.as_uri() + '?mode=ro', uri=True, timeout=5)) as connection: for origin, usage in connection.execute('SELECT origin, client_usages FROM origin'): if not origin or '^' in origin or not isinstance(usage, str) or 'I' not in usage: continue # no privileged schemes or origin-attribute partition flattening diff --git a/tools/package-lock.json b/tools/package-lock.json index 994d100..6448720 100644 --- a/tools/package-lock.json +++ b/tools/package-lock.json @@ -11,7 +11,7 @@ "puppeteer-core": "^25.14.0" }, "engines": { - "node": ">=20" + "node": ">=22.12.0" } }, "node_modules/@puppeteer/browsers": { diff --git a/tools/package.json b/tools/package.json index fcf06d6..4855b7a 100644 --- a/tools/package.json +++ b/tools/package.json @@ -3,6 +3,6 @@ "version": "0.1.0", "private": true, "description": "Optional offline profile migration helpers for Portage", - "engines": { "node": ">=20" }, + "engines": { "node": ">=22.12.0" }, "dependencies": { "puppeteer-core": "^25.14.0" } } diff --git a/tools/profile_safety.cjs b/tools/profile_safety.cjs new file mode 100644 index 0000000..caecd81 --- /dev/null +++ b/tools/profile_safety.cjs @@ -0,0 +1,95 @@ +'use strict'; +// Shared safety checks for the optional profile migration CLI tools. +// These helpers refuse obviously wrong target directories and detect a +// Firefox profile that is still open before its SQLite files are read/copied. +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const cp = require('node:child_process'); + +const FIREFOX_MARKERS = ['prefs.js', 'places.sqlite', 'cookies.sqlite', 'storage.sqlite']; + +function assertSafeTargetProfile(directory, label = 'Chromium profile') { + const resolved = path.resolve(directory); + if (resolved === '/' || resolved === os.homedir()) { + throw new Error(`Refusing to use root or home as ${label}: ${resolved}`); + } + for (const marker of FIREFOX_MARKERS) { + if (fs.existsSync(path.join(resolved, marker))) { + throw new Error(`${label} looks like a Firefox profile (${marker}); refusing to write Chromium data into ${resolved}`); + } + } + return resolved; +} + +const CHROMIUM_KEYRING_DEFAULT_ARGS = ['--password-store=basic', '--use-mock-keychain']; + +// Puppeteer forces --password-store=basic, which encrypts cookies with the +// fallback key. That is fine for disposable profiles but can make cookies +// unreadable in an existing profile whose normal launch uses the OS keyring. +// For existing profiles, drop that default so Chromium uses its normal store. +function chromiumLaunchProfileOptions(profile) { + const existing = fs.existsSync(path.join(profile, 'Local State')) + || fs.existsSync(path.join(profile, 'Default')); + return existing ? {ignoreDefaultArgs: CHROMIUM_KEYRING_DEFAULT_ARGS.slice()} : {}; +} + +function chromiumLockPath(profile) { + // Chrome's SingletonLock is a dangling symlink while the browser is running. + // existsSync() follows links and returns false for it, so use lstat(). + const candidate = path.join(profile, 'SingletonLock'); + return fs.lstatSync(candidate, {throwIfNoEntry: false}) ? candidate : null; +} + +function assertChromiumClosed(profile) { + if (chromiumLockPath(profile)) { + throw new Error(`Chromium profile appears to be open (SingletonLock present); close the browser and retry. If no browser is running, remove the stale SingletonLock after confirming: ${profile}`); + } +} + +function firefoxLockPath(profile) { + for (const name of ['.parentlock', 'lock']) { + const candidate = path.join(profile, name); + if (fs.lstatSync(candidate, {throwIfNoEntry: false})) return candidate; + } + return null; +} + +// Returns true when some process holds the lock file open. Firefox keeps an +// open descriptor on its profile lock for as long as the profile is in use; +// existence alone is not enough because a crash can leave a stale lock behind. +function isLockHeld(lockPath) { + let target; + try { target = fs.realpathSync(lockPath); } catch { return false; } + if (fs.existsSync('/proc')) { + for (const pid of fs.readdirSync('/proc')) { + if (!/^\d+$/.test(pid)) continue; + let descriptors; + try { descriptors = fs.readdirSync(`/proc/${pid}/fd`); } catch { continue; } + for (const descriptor of descriptors) { + let linked; + try { linked = fs.readlinkSync(`/proc/${pid}/fd/${descriptor}`); } catch { continue; } + if (linked === target || linked === target + ' (deleted)') return true; + } + } + return false; + } + // Non-Linux fallback: fuser is part of psmisc and reports whether a file is + // open. If neither /proc nor fuser is available, fail closed instead of + // silently copying a profile that might still be in use. + const probe = cp.spawnSync('fuser', ['-s', lockPath], {timeout: 3000, stdio: 'ignore'}); + if (probe.error || probe.status === null) { + throw new Error('Cannot verify that the Firefox profile is closed (no /proc and no fuser); close Firefox and retry'); + } + return probe.status === 0; +} + +function assertFirefoxClosed(profile) { + const lockPath = firefoxLockPath(profile); + if (lockPath && isLockHeld(lockPath)) { + throw new Error(`Firefox profile appears to be in use (${path.basename(lockPath)} is open); close Firefox and retry`); + } + return lockPath; +} + +module.exports = {assertSafeTargetProfile, chromiumLaunchProfileOptions, chromiumLockPath, assertChromiumClosed, firefoxLockPath, isLockHeld, assertFirefoxClosed}; From 85195bad59d588a3e7b3fe238d33118e1ba1455e Mon Sep 17 00:00:00 2001 From: souta <109493063+souta-lab@users.noreply.github.com> Date: Fri, 23 Oct 2026 20:54:45 +0900 Subject: [PATCH 09/12] ci: run unit tests on every push so fork branches get checks --- .github/workflows/tests.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 6cb2a07..552d5a0 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,7 +1,6 @@ name: Unit tests on: push: - branches: [main] pull_request: permissions: contents: read From 21b0ca227b17af5e0f6588c851f33e399db7dd83 Mon Sep 17 00:00:00 2001 From: souta <109493063+souta-lab@users.noreply.github.com> Date: Fri, 23 Oct 2026 21:06:36 +0900 Subject: [PATCH 10/12] audit: close remaining source-isolation, memory and lock gaps - Copy the Firefox profile with reflinks but refuse data symlinks inside the clone, and reject source/destination path containment, so the original profile cannot be written through an internal symlink or a nested target. - Cap ArrayBuffer/typed-array values at 8 MiB before they expand into number arrays and enforce the 32 MiB encoded budget incrementally during snapshot. - Resolve symlinks before the root/home target guard (a symlink to $HOME no longer bypasses it). - Detect legacy `lock` PID symlinks in addition to .parentlock in both the Node and Python tools. - Canonicalise the IndexedDB origin inventory with the same normalisation as the LocalStorage exporter instead of aborting on one odd origin. - Kill the browser we started and drop its SingletonLock on SIGINT/SIGTERM in the LocalStorage and cookie importers; cap passphrase stdin size. - Document source isolation, interrupted-import state, and the fact that the temporary IDB clone contains the whole profile (cookies/passwords/history). --- tests/test_firefox_localstorage.py | 9 ++++ tests/test_indexeddb_codec.cjs | 5 ++ tests/test_indexeddb_paths.cjs | 8 +++ tests/test_list_firefox_idb_origins.py | 30 +++++++++++ tests/test_profile_safety.cjs | 50 ++++++++++++++++- tools/README.md | 24 ++++++--- tools/chromium_cookie_import.cjs | 20 +++++-- tools/chromium_localstorage_import.cjs | 39 ++++++++++---- tools/firefox_localstorage.py | 35 +++++++++++- tools/indexeddb_codec.js | 12 ++++- tools/indexeddb_migrate.cjs | 22 +++++--- tools/list_firefox_idb_origins.py | 16 +++--- tools/profile_safety.cjs | 75 ++++++++++++++++++++++++-- 13 files changed, 302 insertions(+), 43 deletions(-) create mode 100644 tests/test_list_firefox_idb_origins.py diff --git a/tests/test_firefox_localstorage.py b/tests/test_firefox_localstorage.py index dcd50e8..9b4549b 100644 --- a/tests/test_firefox_localstorage.py +++ b/tests/test_firefox_localstorage.py @@ -145,6 +145,15 @@ class FirefoxLocalStorageTest(unittest.TestCase): finally: os.close(descriptor) self.assertFalse(firefox_profile_in_use(profile)) + # Legacy `lock` symlinks encode the owner PID instead of holding + # an open descriptor; a live PID must still be detected. + lock.unlink() + legacy = profile / 'lock' + os.symlink(f'somehost:{os.getpid()}', legacy) + self.assertTrue(firefox_profile_in_use(profile)) + legacy.unlink() + os.symlink('somehost:99999999', legacy) + self.assertFalse(firefox_profile_in_use(profile)) def test_cli_refuses_a_running_profile(self): with tempfile.TemporaryDirectory() as t: diff --git a/tests/test_indexeddb_codec.cjs b/tests/test_indexeddb_codec.cjs index 043c87b..4856d51 100644 --- a/tests/test_indexeddb_codec.cjs +++ b/tests/test_indexeddb_codec.cjs @@ -23,6 +23,11 @@ const {encode,decode}=require('../tools/indexeddb_codec.js'); } const cycle={};cycle.self=cycle; await assert.rejects(()=>encode(cycle),/cyclic/); + const shared={shared:true}; + await assert.rejects(()=>encode([shared,shared]),/Shared\/cyclic/); + // Binary values are rejected before Array.from() expands them. + await assert.rejects(()=>encode(new ArrayBuffer(9*1024*1024)),/8 MiB/); + await assert.rejects(()=>encode(new Uint8Array(9*1024*1024)),/8 MiB/); const special=Object.create(null);Object.defineProperty(special,'__proto__',{value:{safe:1},enumerable:true}); const recovered=decode(JSON.parse(JSON.stringify(await encode(special)))); assert.equal(Object.getPrototypeOf(recovered),null); diff --git a/tests/test_indexeddb_paths.cjs b/tests/test_indexeddb_paths.cjs index 54ed329..26ae615 100644 --- a/tests/test_indexeddb_paths.cjs +++ b/tests/test_indexeddb_paths.cjs @@ -44,6 +44,14 @@ async function main() { apply: false, }), /must differ|looks like a Firefox profile/); + // A destination nested inside the Firefox source is refused (it would let + // Chromium write into the source profile). + await assert.rejects(() => migrate({ + firefoxProfile: source, chromiumProfile: path.join(source, 'Default'), + firefox: path.join(root, 'missing-firefox'), chromium: path.join(root, 'missing-chromium'), + apply: false, + }), /inside the Firefox source/); + // A Firefox-looking Chromium target is refused before anything is written. fs.writeFileSync(path.join(target, 'prefs.js'), ''); await assert.rejects(() => migrate({ diff --git a/tests/test_list_firefox_idb_origins.py b/tests/test_list_firefox_idb_origins.py new file mode 100644 index 0000000..29171ba --- /dev/null +++ b/tests/test_list_firefox_idb_origins.py @@ -0,0 +1,30 @@ +import sqlite3 +import sys +import tempfile +import unittest +from contextlib import closing +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools')) +from list_firefox_idb_origins import list_origins + + +class FirefoxIdbOriginListTest(unittest.TestCase): + def test_origins_are_canonicalised_and_filtered(self): + with tempfile.TemporaryDirectory() as root: + profile = Path(root) + with closing(sqlite3.connect(profile / 'storage.sqlite')) as connection, connection: + connection.execute('CREATE TABLE origin (origin TEXT, client_usages TEXT)') + connection.executemany('INSERT INTO origin VALUES (?,?)', [ + ('HTTPS://Example.test:443/', 'I123'), + ('https://example.test', 'I456'), + ('https://caret.test^userContextId=1', 'I789'), + ('https://no-idb.test', 'L1'), + ('moz-extension://some-uuid', 'I999'), + ('not a url', 'I111'), + ]) + self.assertEqual(list_origins(profile), ['https://example.test']) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_profile_safety.cjs b/tests/test_profile_safety.cjs index 13876d6..b997180 100644 --- a/tests/test_profile_safety.cjs +++ b/tests/test_profile_safety.cjs @@ -4,7 +4,8 @@ const fs = require('node:fs'); const os = require('node:os'); const path = require('node:path'); const cp = require('node:child_process'); -const {assertSafeTargetProfile, chromiumLaunchProfileOptions, chromiumLockPath, assertChromiumClosed, firefoxLockPath, isLockHeld, assertFirefoxClosed} = +const {transfer} = require('../tools/chromium_cookie_import.cjs'); +const {assertSafeTargetProfile, assertDisjointProfiles, cloneFirefoxProfile, chromiumLaunchProfileOptions, chromiumLockPath, assertChromiumClosed, firefoxLockPath, isLockHeld, assertFirefoxClosed} = require('../tools/profile_safety.cjs'); function waitFor(predicate, timeoutMs = 3000) { @@ -34,6 +35,45 @@ async function main() { assert.equal(assertSafeTargetProfile(chromiumProfile), chromiumProfile); assert.equal(assertSafeTargetProfile(path.join(root, 'not-created-yet')), path.join(root, 'not-created-yet')); + + // A symlink to home or root must not bypass the target guard. + const homeLink = path.join(root, 'home-link'); + fs.symlinkSync(os.homedir(), homeLink); + assert.throws(() => assertSafeTargetProfile(homeLink), /root or home/); + const rootLink = path.join(root, 'root-link'); + fs.symlinkSync('/', rootLink); + assert.throws(() => assertSafeTargetProfile(rootLink), /root or home/); + + // Profiles that contain each other are unsafe even when each path is + // individually acceptable. + assert.throws(() => assertDisjointProfiles(firefoxProfile, path.join(firefoxProfile, 'Default')), + /inside the Firefox source/); + assert.throws(() => assertDisjointProfiles(path.join(root, 'parent', 'child'), path.join(root, 'parent')), + /inside Chromium user-data-dir/); + assertDisjointProfiles(firefoxProfile, chromiumProfile); + await assert.rejects(() => transfer({ + sourceProfile: firefoxProfile, + targetProfile: path.join(firefoxProfile, 'Default'), + browserPath: process.execPath, + }), /inside the Firefox source/); + + // A dangling legacy `lock` symlink is a stale marker and is dropped from + // the clone, but a data symlink makes the copy unsafe and is refused so + // Firefox can never write through it into the source or another directory. + fs.symlinkSync('somehost:4242', path.join(firefoxProfile, 'lock')); + const clone = path.join(root, 'firefox-clone'); + cloneFirefoxProfile(firefoxProfile, clone); + assert.equal(fs.existsSync(path.join(clone, 'lock')), false); + fs.unlinkSync(path.join(firefoxProfile, 'lock')); + + const outside = path.join(root, 'outside-storage'); + fs.mkdirSync(outside); + fs.writeFileSync(path.join(outside, 'token.txt'), 'synthetic'); + fs.symlinkSync(outside, path.join(firefoxProfile, 'storage')); + assert.throws(() => cloneFirefoxProfile(firefoxProfile, path.join(root, 'unsafe-clone')), + /contains symlinks/); + assert.equal(fs.readFileSync(path.join(outside, 'token.txt'), 'utf8'), 'synthetic'); + fs.unlinkSync(path.join(firefoxProfile, 'storage')); // Fresh disposable profiles keep Puppeteer's --password-store=basic, while // existing profiles must not be switched to the fallback cookie key store. assert.deepEqual(chromiumLaunchProfileOptions(chromiumProfile), {}); @@ -70,6 +110,14 @@ async function main() { } await waitFor(() => !isLockHeld(path.join(firefoxProfile, '.parentlock'))); assertFirefoxClosed(firefoxProfile); + + // Legacy `lock` symlinks encode the PID; a live PID means the profile is + // in use even though realpath() cannot resolve the symlink target. + fs.unlinkSync(path.join(firefoxProfile, '.parentlock')); + const legacyLock = path.join(firefoxProfile, 'lock'); + fs.symlinkSync(`somehost:${process.pid}`, legacyLock); + assert.equal(isLockHeld(legacyLock), true); + fs.unlinkSync(legacyLock); console.log('PASS: profile target and Firefox lock safety checks'); } finally { fs.rmSync(root, {recursive: true, force: true}); diff --git a/tools/README.md b/tools/README.md index e4b385b..1b1793a 100644 --- a/tools/README.md +++ b/tools/README.md @@ -11,7 +11,7 @@ The Portage extension cannot enumerate every origin's LocalStorage via WebExtens - LocalStorage can contain live session tokens. **Encrypted AES-256-GCM export is the default**; use a long unique passphrase. `--plaintext` is an explicitly unsafe opt-out. Output is mode 0600. Never attach exported bundles to an issue, share them, or commit them. - Require **Python 3** and `cryptography` for encryption (`sudo apt install python3-cryptography` on Debian), and **Node.js 22.12+**, plus Puppeteer Core (`cd tools && npm ci`). Puppeteer Core uses the existing installed Chrome/Brave and downloads no browsers. - The exporter reports a **count of IndexedDB origins omitted** (without opening their records); use the IndexedDB section below if you need them. -- Import is **merge/upsert**: values with matching LocalStorage keys in the target are overwritten. Use a fresh Chromium profile where possible. Failed sites are reported and attempted writes are rolled back within the page when possible; this does not provide cross-origin atomic transactions. +- Import is **merge/upsert**: values with matching LocalStorage keys in the target are overwritten. Use a fresh Chromium profile where possible. Failed sites are reported and attempted writes are rolled back within the page when possible; this does not provide cross-origin atomic transactions. If an import is interrupted, the target can be left partially updated and a stale Chromium `SingletonLock`; close the browser, restore from your backup, or remove the stale lock after confirming no browser is running. - Import launches the browser **headless**, intercepts all page network requests to return inert local HTML, disables service workers for the temporary page, and validates the loaded origin. This avoids visiting live websites but does not formally guarantee that the browser itself makes no background connections. Standard Chrome sandboxing remains enabled. - Existing Chromium/Brave profiles keep their normal OS password-store settings: Puppeteer's forced `--password-store=basic` default is dropped for non-empty profiles so imported cookies stay readable after a normal launch. Fresh disposable profiles keep the automation default. @@ -73,7 +73,9 @@ and may keep binary data in separate `.files` directories. **Do not copy its SQLite files directly to Chromium.** This optional bridge launches a temporary **copy** of your closed Firefox profile in Firefox 159+ using WebDriver BiDi, reads each first-party origin's IndexedDB through Firefox's real IndexedDB API, -then restores databases through Chromium's native IndexedDB API. +then restores databases through Chromium's native IndexedDB API. The cloned +profile still contains cookies, passwords and history even though the bridge +does not read them, so treat `/tmp/portage-idb-*` as sensitive. During migration both browsers receive only **inert, locally intercepted HTML** for each site. In the automated tests the source sites received zero HTTP @@ -86,7 +88,10 @@ A hard kill or power failure can still leave it behind, so inspect `portage-idb-*` in your temporary directory if a run is interrupted. **Close both browsers and back up both profiles before beginning.** Firefox's -source is not modified, but Chromium's destination profile **will be changed** +source is not modified: the profile is copied with reflinks, stale Firefox lock +markers are dropped, and a profile containing other symlinks is refused (copy +it to a regular directory first). Source/destination paths that contain each +other are also refused. Chromium's destination profile **will be changed** with `--apply`. Existing IndexedDB databases are **never overwritten**: the whole database is skipped if its name already exists at that origin. The destination Chromium lock file and the Firefox source profile's open lock are @@ -115,7 +120,8 @@ the other CLI; run `npm ci --prefix tools` first. Firefox must support WebDriver BiDi; validated with Firefox 159.0b5, Google Chrome 156.0.8078.47, and **Brave Stable 1.98.60** in disposable test profiles. Origin enumeration reads the QuotaManager `storage.sqlite` metadata; only HTTP(S) origins without Firefox container/partition attributes -are considered. It does not inspect Chrome or Firefox passwords/cookies. +are considered. It does not read passwords or cookies; the temporary clone +copies the whole Firefox profile, so treat it as sensitive. **Migrated**: IndexedDB database names and versions, object stores, key paths, auto-increment flags, indexes (including multi-entry/unique), primary keys, and @@ -124,8 +130,9 @@ BigInt, Date, RegExp, Map/Set, binary buffers and typed arrays, Blob/File). **Still unsupported**: cyclic or shared object references, CryptoKey, non-standard browser objects, IndexedDB databases larger than 32 MiB in the -wire representation, stores with over 50,000 records, arrays with over 50,000 -elements, and individual Blob/File values larger than 8 MiB. The bridge +encoded wire representation, stores with over 50,000 records, arrays with over +50,000 elements, and individual Blob/File/ArrayBuffer/typed-array values larger +than 8 MiB (checked before they are expanded). The bridge **skips entire databases** when it finds unsupported data, and reports aggregate counts without printing record values. The IndexedDB API does not expose an object store's current auto-increment @@ -170,7 +177,10 @@ are skipped because the importer closes its temporary Chromium session immediately, so they could not survive the import anyway. Some cookies or logins remain tied to browser/device-bound secrets; a successful CDP `Network.setCookie` result does **not** guarantee continued authentication. -Never collect or paste exported cookie values into bug reports. +Never collect or paste exported cookie values into bug reports. If interrupted, +the target profile can be partially written and a stale `SingletonLock` left +behind; restore the backup or remove the stale lock after confirming the +browser is closed. `node tests/e2e_cookie_cli.cjs` verifies this transfer with synthetic cookie values and disposable Brave/Chrome profiles only; set `PORTAGE_TEST_BRAVE` if diff --git a/tools/chromium_cookie_import.cjs b/tools/chromium_cookie_import.cjs index f59d0ed..a02fe8e 100644 --- a/tools/chromium_cookie_import.cjs +++ b/tools/chromium_cookie_import.cjs @@ -2,7 +2,7 @@ 'use strict'; /** Private-process Firefox -> Chromium cookie transfer. Do not print cookie values. */ const cp=require('node:child_process'),path=require('node:path'),fs=require('node:fs'); -const {assertSafeTargetProfile, assertChromiumClosed, assertFirefoxClosed, chromiumLaunchProfileOptions}=require('./profile_safety.cjs'); +const {assertSafeTargetProfile, assertDisjointProfiles, assertChromiumClosed, assertFirefoxClosed, chromiumLaunchProfileOptions}=require('./profile_safety.cjs'); function assertProfileDirectory(value) { if(typeof value!=='string'||!/^[\w. -]+$/.test(value)||value==='.'||value==='..')throw Error('Invalid Chromium profile directory name'); return value; @@ -12,6 +12,7 @@ async function transfer({sourceProfile,targetProfile,browserPath,profileDirector const target=assertSafeTargetProfile(targetProfile, 'Chromium user-data-dir'); if(!fs.existsSync(source)||!fs.existsSync(browserPath))throw Error('Source or browser missing'); if(source===target)throw Error('Source and destination profiles must differ'); + assertDisjointProfiles(source, target); assertProfileDirectory(profileDirectory); assertFirefoxClosed(source); assertChromiumClosed(target); @@ -19,8 +20,17 @@ async function transfer({sourceProfile,targetProfile,browserPath,profileDirector encoding:'utf8',maxBuffer:32*1024*1024,timeout:20000,stdio:['ignore','pipe','pipe']}); if(p.status!==0)throw Error('Cookie decoding failed; no destination modifications'); const parsed=JSON.parse(p.stdout);p.stdout=''; - let puppeteer=require('puppeteer-core'),browser; + let puppeteer=require('puppeteer-core'),browser=null; const result={candidate:parsed.cookies.length,skipped:parsed.skipped,accepted:0,failed:0}; + // Ctrl-C during the import would otherwise leave a stale SingletonLock and a + // partially written cookie store. Kill the child we started and drop its lock. + const cleanupOnSignal=()=>{ + try{browser?.process?.()?.kill?.('SIGKILL');}catch{} + try{fs.rmSync(path.join(target,'SingletonLock'),{force:true});}catch{} + process.exit(130); + }; + process.once('SIGINT',cleanupOnSignal); + process.once('SIGTERM',cleanupOnSignal); try{ browser=await puppeteer.launch({executablePath:browserPath,userDataDir:target,headless:true, ...chromiumLaunchProfileOptions(target), @@ -32,7 +42,11 @@ async function transfer({sourceProfile,targetProfile,browserPath,profileDirector if(success)result.accepted++;else result.failed++; }catch(e){result.failed++;} } - }finally{if(browser)await browser.close();} + }finally{ + process.removeListener('SIGINT',cleanupOnSignal); + process.removeListener('SIGTERM',cleanupOnSignal); + try{if(browser)await browser.close();}catch{} + } return result; } if(require.main===module){ diff --git a/tools/chromium_localstorage_import.cjs b/tools/chromium_localstorage_import.cjs index 13392e1..db58738 100644 --- a/tools/chromium_localstorage_import.cjs +++ b/tools/chromium_localstorage_import.cjs @@ -71,8 +71,12 @@ async function passphrasePrompt() { async function readPassphrase(stdinFlag) { if (!stdinFlag) return passphrasePrompt(); - const chunks=[]; - for await(const c of process.stdin) chunks.push(c); + const chunks=[]; let total=0; + for await(const chunk of process.stdin){ + total+=chunk.length; + if(total>1024*1024) throw Error('Passphrase input too large'); + chunks.push(chunk); + } const value=Buffer.concat(chunks).toString('utf8').replace(/\r?\n$/, ''); if (!value) throw Error('Empty passphrase from standard input'); return value; @@ -166,15 +170,30 @@ async function run(opts) { if(!fs.existsSync(opts.browser))throw Error('Browser executable not found'); let puppeteer; try{puppeteer=require('puppeteer-core');}catch{try{puppeteer=require('puppeteer');}catch{throw Error('Install puppeteer-core locally (npm i --no-save puppeteer-core)');}} - // Never start with a personal profile unless explicitly specified by the operator. - // Keep Chrome sandbox enabled; do not pass --no-sandbox. - const browser=await puppeteer.launch({executablePath:path.resolve(opts.browser),userDataDir:profile, - headless:true,defaultViewport:{width:600,height:400},...chromiumLaunchProfileOptions(profile), - args:['--profile-directory='+opts.profileDirectory,'--no-first-run','--no-default-browser-check', - '--disable-background-networking','--disable-sync','--disable-extensions','--disable-features=MediaRouter']}); + let browser=null; + // Ctrl-C during --apply would otherwise leave a stale SingletonLock (and a + // partially imported profile). Kill the child we started and drop its lock. + const cleanupOnSignal=()=>{ + try{browser?.process?.()?.kill?.('SIGKILL');}catch{} + try{fs.rmSync(path.join(profile,'SingletonLock'),{force:true});}catch{} + process.exit(130); + }; + process.once('SIGINT',cleanupOnSignal); + process.once('SIGTERM',cleanupOnSignal); let result; - try {result=await restoreSites(browser,sites,opts.timeout);} - finally {await browser.close();} + try { + // Never start with a personal profile unless explicitly specified by the operator. + // Keep Chrome sandbox enabled; do not pass --no-sandbox. + browser=await puppeteer.launch({executablePath:path.resolve(opts.browser),userDataDir:profile, + headless:true,defaultViewport:{width:600,height:400},...chromiumLaunchProfileOptions(profile), + args:['--profile-directory='+opts.profileDirectory,'--no-first-run','--no-default-browser-check', + '--disable-background-networking','--disable-sync','--disable-extensions','--disable-features=MediaRouter']}); + result=await restoreSites(browser,sites,opts.timeout); + } finally { + process.removeListener('SIGINT',cleanupOnSignal); + process.removeListener('SIGTERM',cleanupOnSignal); + try{if(browser)await browser.close();}catch{} + } console.log(`Imported ${result.imported}/${sites.length} origins and ${result.keys} keys; skipped ${result.skipped}.`); if(result.errors.length)console.log('Skipped (index and reason; no credentials):',JSON.stringify(result.errors)); if(result.skipped)process.exitCode=2; diff --git a/tools/firefox_localstorage.py b/tools/firefox_localstorage.py index 06dc6ee..bad7b87 100644 --- a/tools/firefox_localstorage.py +++ b/tools/firefox_localstorage.py @@ -12,6 +12,7 @@ from contextlib import closing import json import os from pathlib import Path +import re import sqlite3 import subprocess import sys @@ -129,15 +130,45 @@ def valid_origin(origin: str) -> bool: return normalize_origin(origin) is not None +def firefox_lock_path(profile: Path): + for name in ('.parentlock', 'lock'): + candidate = profile / name + try: + os.lstat(candidate) + except OSError: + continue + return candidate + return None + + def firefox_profile_in_use(profile: Path) -> bool: """Detect a Firefox process holding this profile's lock file open. Existence of .parentlock is not enough because a crash can leave a stale lock behind; /proc exposes the open descriptors of the running Firefox. + Old macOS/BSD Firefox uses a `lock` symlink such as "host:1234", so fall + back to checking that PID if the link has no resolvable target. """ - lock = profile / '.parentlock' - if not lock.exists(): + lock = firefox_lock_path(profile) + if lock is None: return False + if not os.path.exists(lock): + # Dangling legacy `lock` symlink ("host:pid"). Path.resolve() does not + # raise for it, so inspect the link target directly and check the PID. + try: + raw = os.readlink(lock) + except OSError: + return False + match = re.search(r':(\d+)$', raw) + if not match: + return False + try: + os.kill(int(match.group(1)), 0) + except ProcessLookupError: + return False + except PermissionError: + return True + return True try: target = str(lock.resolve()) except OSError: diff --git a/tools/indexeddb_codec.js b/tools/indexeddb_codec.js index 85a5565..ed3294d 100644 --- a/tools/indexeddb_codec.js +++ b/tools/indexeddb_codec.js @@ -1,6 +1,10 @@ /* Portable, lossless subset of IndexedDB structured-clone values. Unsupported types and cyclic/shared references are refused, never silently discarded. */ 'use strict'; +const MAX_BINARY_BYTES = 8 * 1024 * 1024; +function assertBinaryLimit(bytes, label) { + if (bytes > MAX_BINARY_BYTES) throw new Error(label + ' larger than 8 MiB migration limit'); +} async function encode(value, seen = new WeakSet()) { if (value === null) return {t:'null'}; const typ = typeof value; @@ -13,13 +17,17 @@ async function encode(value, seen = new WeakSet()) { seen.add(value); if(value instanceof Date) return {t:'date',v:Number.isNaN(value.getTime())?'NaN':value.getTime()}; if(value instanceof RegExp) return {t:'regexp',s:value.source,f:value.flags}; - if(value instanceof ArrayBuffer) return {t:'buffer',v:Array.from(new Uint8Array(value))}; + if(value instanceof ArrayBuffer){ + assertBinaryLimit(value.byteLength,'ArrayBuffer'); + return {t:'buffer',v:Array.from(new Uint8Array(value))}; + } if(ArrayBuffer.isView(value)) { + assertBinaryLimit(value.byteLength,value.constructor.name); if (value instanceof DataView) return {t:'dataview',v:Array.from(new Uint8Array(value.buffer,value.byteOffset,value.byteLength))}; return {t:'typedarray',type:value.constructor.name,v:Array.from(new Uint8Array(value.buffer,value.byteOffset,value.byteLength))}; } if(typeof Blob !== 'undefined' && value instanceof Blob){ - if(value.size>8*1024*1024)throw new Error('Blob larger than 8 MiB migration limit'); + assertBinaryLimit(value.size, value instanceof File ? 'File' : 'Blob'); const v=Array.from(new Uint8Array(await value.arrayBuffer())); if(typeof File !== 'undefined' && value instanceof File)return {t:'file',v,name:value.name,mime:value.type,lastModified:value.lastModified}; return {t:'blob',v,mime:value.type}; diff --git a/tools/indexeddb_migrate.cjs b/tools/indexeddb_migrate.cjs index edea363..61b4570 100644 --- a/tools/indexeddb_migrate.cjs +++ b/tools/indexeddb_migrate.cjs @@ -10,7 +10,7 @@ const path = require('node:path'); const os = require('node:os'); const cp = require('node:child_process'); const {validOrigin} = require('./chromium_localstorage_import.cjs'); -const {assertSafeTargetProfile, assertChromiumClosed, assertFirefoxClosed, chromiumLaunchProfileOptions} = require('./profile_safety.cjs'); +const {assertSafeTargetProfile, assertDisjointProfiles, cloneFirefoxProfile, assertChromiumClosed, assertFirefoxClosed, chromiumLaunchProfileOptions} = require('./profile_safety.cjs'); function options(argv) { const o={apply:false,timeout:20000}; @@ -72,6 +72,7 @@ async function snapshotOrigin(page) { r.onblocked=()=>reject(Error('IndexedDB open blocked')); }); const dump={name:db.name,version:db.version,stores:[]}; + let encodedChars=0; for (const storeName of Array.from(db.objectStoreNames)) { const tx=db.transaction(storeName,'readonly'); const store=tx.objectStore(storeName); @@ -79,7 +80,9 @@ async function snapshotOrigin(page) { indexes:Array.from(store.indexNames,n=>{ const ix=store.index(n);return {name:ix.name,keyPath:ix.keyPath,unique:ix.unique,multiEntry:ix.multiEntry}; }),records:[]}; - // Cap retrieval at 50,001 entries; never materialize unbounded stores. + // Cap retrieval at 50,001 entries. Individual binary values are + // capped in the codec before they are expanded into number arrays, + // and the encoded budget below stops oversized databases early. const values=await new Promise((resolve,reject)=>{ const req=store.getAll(undefined,50001);req.onsuccess=()=>resolve(req.result);req.onerror=()=>reject(req.error); }); @@ -90,7 +93,13 @@ async function snapshotOrigin(page) { }); if(keys.length!==values.length)throw Error('Key/value length mismatch'); if(values.length>50000)throw Error('Store has over 50000 records (migration safety limit)'); - for(let j=0;j32*1024*1024)throw Error('Database over 32 MiB encoded transport limit'); + schema.records.push([encodedKey,encodedValue]); + } dump.stores.push(schema); } if(JSON.stringify(dump).length>32*1024*1024)throw Error('Database over 32 MiB transport limit'); @@ -198,10 +207,9 @@ async function migrate(opts) { // Resolve symlinks: cp -a would otherwise copy a symlink of the source // profile and Firefox would be launched against the original profile. const fx=realDirectory(opts.firefoxProfile, 'Firefox source profile'); - const targetCandidate=path.resolve(opts.chromiumProfile); - const target=fs.existsSync(targetCandidate)?fs.realpathSync(targetCandidate):targetCandidate; + const target=assertSafeTargetProfile(opts.chromiumProfile, 'Chromium user-data-dir'); if(target===fx)throw Error('Source and destination profiles must differ'); - assertSafeTargetProfile(target, 'Chromium user-data-dir'); + assertDisjointProfiles(fx, target); assertFirefoxClosed(fx); const origins=originsForFirefox(fx); console.log(`Firefox IndexedDB inventory: ${origins.length} first-party origin(s); container/partitioned origins intentionally excluded.`); @@ -217,7 +225,7 @@ async function migrate(opts) { // Do NOT launch Firefox against the original profile, which would modify it. let fb,cb;const stats={origins:origins.length,restored:0,skipped:0,sourceSkipped:0,errors:[]}; try { - cp.execFileSync('cp',['-a','--reflink=auto',fx,clone],{timeout:120000}); + cloneFirefoxProfile(fx,clone); const pp=require('puppeteer-core'); fb=await pp.launch({browser:'firefox',protocol:'webDriverBiDi',executablePath:opts.firefox, userDataDir:clone,headless:true,timeout:20000, diff --git a/tools/list_firefox_idb_origins.py b/tools/list_firefox_idb_origins.py index 0d2a868..238c07f 100644 --- a/tools/list_firefox_idb_origins.py +++ b/tools/list_firefox_idb_origins.py @@ -5,7 +5,8 @@ import sqlite3 import sys from contextlib import closing from pathlib import Path -from urllib.parse import urlsplit + +from firefox_localstorage import normalize_origin def list_origins(profile): @@ -15,14 +16,13 @@ def list_origins(profile): result = [] with closing(sqlite3.connect(db.as_uri() + '?mode=ro', uri=True, timeout=5)) as connection: for origin, usage in connection.execute('SELECT origin, client_usages FROM origin'): - if not origin or '^' in origin or not isinstance(usage, str) or 'I' not in usage: + if not origin or not isinstance(usage, str) or 'I' not in usage: continue # no privileged schemes or origin-attribute partition flattening - try: - u = urlsplit(origin) - if u.scheme in ('http','https') and u.hostname and u.path in ('','/') and not u.username and not u.password: - result.append(origin.rstrip('/')) - except ValueError: - pass + # Share the LocalStorage exporter's canonicalisation so a stray + # uppercase/default-port origin cannot fail the whole run later. + normalized = normalize_origin(origin) + if normalized: + result.append(normalized) return sorted(set(result)) diff --git a/tools/profile_safety.cjs b/tools/profile_safety.cjs index caecd81..f5a6df9 100644 --- a/tools/profile_safety.cjs +++ b/tools/profile_safety.cjs @@ -9,8 +9,21 @@ const cp = require('node:child_process'); const FIREFOX_MARKERS = ['prefs.js', 'places.sqlite', 'cookies.sqlite', 'storage.sqlite']; -function assertSafeTargetProfile(directory, label = 'Chromium profile') { +// Resolve a target path as far as it exists. Existing symlinks are followed so +// that a link to `/` or the home directory cannot bypass the guard below; for a +// not-yet-created directory, the parent symlinks are resolved instead. +function resolveForSafety(directory) { const resolved = path.resolve(directory); + try { + if (fs.existsSync(resolved)) return fs.realpathSync(resolved); + const parent = path.dirname(resolved); + if (fs.existsSync(parent)) return path.join(fs.realpathSync(parent), path.basename(resolved)); + } catch { /* fall through to the lexical path */ } + return resolved; +} + +function assertSafeTargetProfile(directory, label = 'Chromium profile') { + const resolved = resolveForSafety(directory); if (resolved === '/' || resolved === os.homedir()) { throw new Error(`Refusing to use root or home as ${label}: ${resolved}`); } @@ -22,6 +35,50 @@ function assertSafeTargetProfile(directory, label = 'Chromium profile') { return resolved; } +function findSymlinks(directory, root = directory, found = []) { + for (const entry of fs.readdirSync(directory, {withFileTypes: true})) { + const full = path.join(directory, entry.name); + if (entry.isSymbolicLink()) found.push(path.relative(root, full)); + else if (entry.isDirectory()) findSymlinks(full, root, found); + } + return found; +} + +// Copying a profile that contains symlinks is dangerous: `cp -a` preserves +// them, so the clone can point back at the original profile or outside the +// scratch directory. Reflink-copy first (fast), drop Firefox's stale lock +// markers, then refuse any remaining symlink so Firefox can only write inside +// the disposable clone. Users with symlinked storage can copy the profile to a +// regular directory first. +function cloneFirefoxProfile(source, destination) { + cp.execFileSync('cp', + ['-a', '--reflink=auto', source, destination], + {timeout: 120000}); + for (const name of ['.parentlock', 'lock']) { + try { fs.rmSync(path.join(destination, name), {force: true}); } catch {} + } + const symlinks = findSymlinks(destination); + if (symlinks.length) { + throw new Error(`Firefox profile contains symlinks (${symlinks.slice(0, 5).join(', ')}); ` + + 'copy the profile to a regular directory before IndexedDB migration so the source cannot be modified'); + } +} + +// Two profiles must not contain each other, otherwise Chromium can write into +// the Firefox source (or vice versa) despite both paths being individually safe. +function assertDisjointProfiles(source, target, label = 'Chromium user-data-dir') { + const inside = (parent, child) => { + const relative = path.relative(parent, child); + return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative)); + }; + if (inside(source, target)) { + throw new Error(`Refusing overlapping profiles: ${label} is inside the Firefox source profile: ${target}`); + } + if (inside(target, source)) { + throw new Error(`Refusing overlapping profiles: Firefox source profile is inside ${label}: ${source}`); + } +} + const CHROMIUM_KEYRING_DEFAULT_ARGS = ['--password-store=basic', '--use-mock-keychain']; // Puppeteer forces --password-store=basic, which encrypts cookies with the @@ -60,7 +117,19 @@ function firefoxLockPath(profile) { // existence alone is not enough because a crash can leave a stale lock behind. function isLockHeld(lockPath) { let target; - try { target = fs.realpathSync(lockPath); } catch { return false; } + try { + target = fs.realpathSync(lockPath); + } catch { + // macOS/BSD Firefox uses `lock`, a symlink such as "host:1234", rather + // than an open file descriptor. Fall back to checking that PID. + try { + const match = /:([0-9]+)$/.exec(fs.readlinkSync(lockPath)); + if (match) { + try { process.kill(Number(match[1]), 0); return true; } catch { return false; } + } + } catch { /* not a symlink */ } + return false; + } if (fs.existsSync('/proc')) { for (const pid of fs.readdirSync('/proc')) { if (!/^\d+$/.test(pid)) continue; @@ -92,4 +161,4 @@ function assertFirefoxClosed(profile) { return lockPath; } -module.exports = {assertSafeTargetProfile, chromiumLaunchProfileOptions, chromiumLockPath, assertChromiumClosed, firefoxLockPath, isLockHeld, assertFirefoxClosed}; +module.exports = {assertSafeTargetProfile, assertDisjointProfiles, cloneFirefoxProfile, chromiumLaunchProfileOptions, chromiumLockPath, assertChromiumClosed, firefoxLockPath, isLockHeld, assertFirefoxClosed}; From 487282b5bd6b1ea30940720c7232025cf18c47ff Mon Sep 17 00:00:00 2001 From: souta <109493063+souta-lab@users.noreply.github.com> Date: Fri, 23 Oct 2026 21:15:53 +0900 Subject: [PATCH 11/12] audit: make IndexedDB restore atomic and widen supported clone values - Write schema and records in one versionchange transaction so an interrupted restore cannot leave a schema-only database that later runs skip forever. Existing-database skips no longer make a clean rerun exit non-zero. - Encode binary payloads as base64 (much smaller and faster than number arrays), keep the 8 MiB per-value cap reachable inside the 32 MiB encoded budget, and check the encoded budget incrementally while snapshotting. - Add Float16Array, Error subclasses (name/message/stack/cause), Number/String/Boolean wrappers and ImageData. Typed arrays carry a byte-order marker so a cross-endian migration cannot silently swap numeric values. - Add 120 s per-origin snapshot/restore timeouts and document the 64 MiB origin cap, atomic restore, and the current limits. - Extend the Firefox/Chrome IndexedDB E2E with these values, an aborted-restore atomicity check and the rerun semantics. --- tests/e2e_indexeddb.cjs | 28 ++++++++- tests/test_indexeddb_codec.cjs | 34 ++++++++++- tools/README.md | 37 +++++++----- tools/indexeddb_codec.js | 102 ++++++++++++++++++++++++++++----- tools/indexeddb_migrate.cjs | 48 ++++++++++------ 5 files changed, 199 insertions(+), 50 deletions(-) diff --git a/tests/e2e_indexeddb.cjs b/tests/e2e_indexeddb.cjs index 296d63e..70a00c1 100644 --- a/tests/e2e_indexeddb.cjs +++ b/tests/e2e_indexeddb.cjs @@ -35,11 +35,14 @@ async function main(){ const db=r.result; await new Promise((resolve,reject)=>{ const tx=db.transaction(['keyed','auto'],'readwrite'); + const error=new TypeError('boom');error.cause={code:'E_TEST'}; const obj={id:number+1,name:'site-'+number,when:new Date('2020-02-03T04:05:06Z'), bytes:new Uint8Array([1,2,3,255]),big:12345678901234567890n, blob:new Blob(['file-contents'],{type:'text/plain'}), map:new Map([['hello','猫']]),set:new Set(['a','b']), - maybe:undefined,negativeZero:-0}; + maybe:undefined,negativeZero:-0, + f16:new Float16Array([1.5,-2]),error,numObject:Object(7), + image:new ImageData(new Uint8ClampedArray([1,2,3,255]),1,1)}; tx.objectStore('keyed').put(obj); tx.objectStore('auto').put({tag:['alpha','beta'],value:'origin-'+number}); tx.oncomplete=resolve;tx.onerror=()=>reject(tx.error); @@ -71,13 +74,20 @@ async function main(){ name:obj.name,id:obj.id,when:obj.when.toISOString(),bytes:Array.from(obj.bytes), big:String(obj.big),blob:await obj.blob.text(),map:obj.map.get('hello'),set:Array.from(obj.set), undefinedValue:obj.maybe===undefined,negativeZero:Object.is(obj.negativeZero,-0), + f16:Array.from(obj.f16),error:obj.error instanceof TypeError?obj.error.message:'wrong type', + errorCause:obj.error.cause?.code, + numberObject:obj.numObject instanceof Number?obj.numObject.valueOf():'wrong type', + image:[obj.image.width,obj.image.height,Array.from(obj.image.data)], byName:byName.name,byTag:byTag.value,autoValue:au.value}; db.close();return results; }); assert.deepEqual(result,{version:7,storeCount:2,name:'site-'+n,id:n+1, when:'2020-02-03T04:05:06.000Z',bytes:[1,2,3,255], big:'12345678901234567890',blob:'file-contents',map:'猫',set:['a','b'], - undefinedValue:true,negativeZero:true,byName:'site-'+n,byTag:'origin-'+n,autoValue:'origin-'+n}); + undefinedValue:true,negativeZero:true, + f16:[1.5,-2],error:'boom',errorCause:'E_TEST',numberObject:7, + image:[1,1,[1,2,3,255]], + byName:'site-'+n,byTag:'origin-'+n,autoValue:'origin-'+n}); // Invalid structured clone payload must not create a partially valid DB. const rejected=await restoreOrigin(verify,{databases:[{ name:'portage-unsupported-test',version:1,stores:[{ @@ -89,12 +99,26 @@ async function main(){ assert.equal(rejected.skipped,1); const after=await verify.evaluate(()=>indexedDB.databases()); assert(!after.some(x=>x.name==='portage-unsupported-test'), 'Rejected DB should not exist'); + // A record that throws while writing inside the upgrade transaction must + // abort the whole database, not leave a schema-only DB for later runs. + const invalidRecord=await restoreOrigin(verify,{databases:[{ + name:'portage-invalid-record-test',version:1,stores:[{ + name:'keyed',keyPath:'id',autoIncrement:false,indexes:[], + records:[[{t:'number',v:1},{t:'object',plain:true,v:[]}]] + }] + }]}); + assert.equal(invalidRecord.restored,0,JSON.stringify(invalidRecord)); + assert.equal(invalidRecord.skipped,1); + const afterInvalid=await verify.evaluate(()=>indexedDB.databases()); + assert(!afterInvalid.some(x=>x.name==='portage-invalid-record-test'), + 'Aborted restore must not leave a schema-only database'); } await verify.close();await browser.close();browser=null; assert.deepEqual(hits,before,'No real site traffic including verification'); // Re-running must never overwrite existing destination IndexedDB databases. const repeated=await migrate({firefoxProfile:fx,chromiumProfile:chrome,firefox:FIREFOX,chromium:CHROMIUM,apply:true,timeout:20000}); assert.equal(repeated.restored,0);assert.equal(repeated.skipped,2); + assert.deepEqual(repeated.errors,[],'existing-DB skips are not failures'); process.exitCode=undefined; console.log('PASS: Firefox 159 -> Chrome 156 indexedDB: 2 origins, schema, indexes, rich values, no target-site traffic'); }finally{ diff --git a/tests/test_indexeddb_codec.cjs b/tests/test_indexeddb_codec.cjs index 4856d51..6499d28 100644 --- a/tests/test_indexeddb_codec.cjs +++ b/tests/test_indexeddb_codec.cjs @@ -21,13 +21,45 @@ const {encode,decode}=require('../tools/indexeddb_codec.js'); else if(entry instanceof Map||entry instanceof Set)assert.deepEqual([...restored],[...entry]); else assert.deepEqual(JSON.parse(JSON.stringify(restored)),JSON.parse(JSON.stringify(entry))); } + // Structured-cloneable built-ins that are not plain objects. + const error=new TypeError('boom');error.cause={code:'E_TEST'}; + const errorRestored=decode(JSON.parse(JSON.stringify(await encode(error)))); + assert(errorRestored instanceof TypeError); + assert.equal(errorRestored.message,'boom'); + assert.equal(errorRestored.name,'TypeError'); + assert.deepEqual(errorRestored.cause,{code:'E_TEST'}); + assert(decode(JSON.parse(JSON.stringify(await encode(Object(42))))) instanceof Number); + assert.equal(decode(JSON.parse(JSON.stringify(await encode(Object('x'))))).valueOf(),'x'); + assert.equal(decode(JSON.parse(JSON.stringify(await encode(Object(false))))).valueOf(),false); + + // Typed arrays carry the source byte order; decoding the same big-endian + // payload on a little-endian host must still produce the original values. + const bigEndianTypedArray={t:'typedarray',type:'Uint16Array',le:false, + v:Buffer.from([0,1,1,2]).toString('base64')}; + assert.deepEqual(Array.from(decode(bigEndianTypedArray)),[1,258]); + + if(typeof Float16Array!=='undefined'){ + const floats=new Float16Array([1.5,-2]); + const restored=decode(JSON.parse(JSON.stringify(await encode(floats)))); + assert(restored instanceof Float16Array); + assert.deepEqual(Array.from(restored),Array.from(floats)); + } + const cycle={};cycle.self=cycle; await assert.rejects(()=>encode(cycle),/cyclic/); const shared={shared:true}; await assert.rejects(()=>encode([shared,shared]),/Shared\/cyclic/); - // Binary values are rejected before Array.from() expands them. + // Binary values are rejected before expansion; an 8 MiB value is allowed + // and base64 keeps its encoded form inside the 32 MiB database budget. await assert.rejects(()=>encode(new ArrayBuffer(9*1024*1024)),/8 MiB/); await assert.rejects(()=>encode(new Uint8Array(9*1024*1024)),/8 MiB/); + const eightMiB=new Uint8Array(8*1024*1024);eightMiB[0]=255;eightMiB[eightMiB.length-1]=7; + const eightEncoded=await encode(eightMiB); + assert(JSON.stringify(eightEncoded).length<32*1024*1024); + const eightRestored=decode(JSON.parse(JSON.stringify(eightEncoded))); + assert.equal(eightRestored.byteLength,8*1024*1024); + assert.equal(eightRestored[0],255); + assert.equal(eightRestored[eightRestored.length-1],7); const special=Object.create(null);Object.defineProperty(special,'__proto__',{value:{safe:1},enumerable:true}); const recovered=decode(JSON.parse(JSON.stringify(await encode(special)))); assert.equal(Object.getPrototypeOf(recovered),null); diff --git a/tools/README.md b/tools/README.md index 1b1793a..c17d1d4 100644 --- a/tools/README.md +++ b/tools/README.md @@ -93,11 +93,15 @@ markers are dropped, and a profile containing other symlinks is refused (copy it to a regular directory first). Source/destination paths that contain each other are also refused. Chromium's destination profile **will be changed** with `--apply`. Existing IndexedDB databases are **never overwritten**: the -whole database is skipped if its name already exists at that origin. The -destination Chromium lock file and the Firefox source profile's open lock are -checked before migration; the Chromium profile named `Default` is used unless -`--chromium-profile-directory` is passed. Do not use this on a profile that -another browser process is accessing. +whole database is skipped if its name already exists at that origin. Schema and +records are written in the same version-change transaction, so an interrupted +restore cannot leave a schema-only database that a later run would skip; an +aborted database is reported and can be retried after fixing the cause. A +clean rerun reports intentional existing-database skips but exits successfully. +The destination Chromium lock file and the Firefox source profile's open lock +are checked before migration; the Chromium profile named `Default` is used +unless `--chromium-profile-directory` is passed. Do not use this on a profile +that another browser process is accessing. ```bash # First, preview first-party IndexedDB origin count, WITHOUT modifying a profile: @@ -125,16 +129,21 @@ copies the whole Firefox profile, so treat it as sensitive. **Migrated**: IndexedDB database names and versions, object stores, key paths, auto-increment flags, indexes (including multi-entry/unique), primary keys, and -supported stored values (ordinary objects/arrays, strings/numbers/booleans, -BigInt, Date, RegExp, Map/Set, binary buffers and typed arrays, Blob/File). +supported stored values: ordinary objects/arrays, strings/numbers/booleans, +BigInt, Date, RegExp, Map/Set, binary buffers, typed arrays (including +`Float16Array` where the browsers support it; multi-byte elements carry a byte +order marker so cross-endian migrations do not byte-swap values), Blob/File, +`Error` subclasses (name/message/stack/cause), `Number`/`String`/`Boolean` +wrapper objects, and `ImageData`. -**Still unsupported**: cyclic or shared object references, CryptoKey, -non-standard browser objects, IndexedDB databases larger than 32 MiB in the -encoded wire representation, stores with over 50,000 records, arrays with over -50,000 elements, and individual Blob/File/ArrayBuffer/typed-array values larger -than 8 MiB (checked before they are expanded). The bridge -**skips entire databases** when it finds unsupported data, and reports -aggregate counts without printing record values. +**Still unsupported**: cyclic or shared object references, CryptoKey, other +platform/browser objects, databases larger than 32 MiB in the encoded wire +representation, an origin whose encoded payload exceeds 64 MiB, stores with +over 50,000 records, arrays with over 50,000 elements, individual +Blob/File/ArrayBuffer/typed-array/ImageData values larger than 8 MiB (checked +before they are expanded), and a per-origin snapshot/restore that takes longer +than 120 seconds. The bridge **skips entire databases** when it finds +unsupported data, and reports aggregate counts without printing record values. The IndexedDB API does not expose an object store's current auto-increment counter, so after restoring records that were deleted at the source a new record can reuse a deleted key number; verify apps that require monotonically diff --git a/tools/indexeddb_codec.js b/tools/indexeddb_codec.js index ed3294d..4021c9e 100644 --- a/tools/indexeddb_codec.js +++ b/tools/indexeddb_codec.js @@ -1,17 +1,54 @@ /* Portable, lossless subset of IndexedDB structured-clone values. - Unsupported types and cyclic/shared references are refused, never silently discarded. */ + Unsupported types and shared/cyclic references are refused, never silently discarded. */ 'use strict'; const MAX_BINARY_BYTES = 8 * 1024 * 1024; +const LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; + function assertBinaryLimit(bytes, label) { if (bytes > MAX_BINARY_BYTES) throw new Error(label + ' larger than 8 MiB migration limit'); } + +function bytesToBase64(bytes) { + let binary = ''; + const chunk = 0x8000; + for (let i = 0; i < bytes.length; i += chunk) { + binary += String.fromCharCode.apply(null, bytes.subarray(i, i + chunk)); + } + return btoa(binary); +} + +function base64ToBytes(text) { + if (typeof text !== 'string') throw new Error('Invalid base64 binary payload'); + const binary = atob(text); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); + return bytes; +} + +// Typed arrays are stored as raw bytes plus the source host's byte order. If +// the destination host uses the opposite order, swap each element so a +// big-endian migration cannot silently byte-swap numeric values. +function swapBytes(bytes, bytesPerElement) { + for (let i = 0; i < bytes.length; i += bytesPerElement) { + for (let j = 0; j < bytesPerElement / 2; j++) { + const a = i + j, b = i + bytesPerElement - 1 - j; + const tmp = bytes[a]; bytes[a] = bytes[b]; bytes[b] = tmp; + } + } + return bytes; +} + +function encodeNumber(value) { + return {t: 'number', v: Object.is(value, -0) ? '-0' : Number.isFinite(value) ? value : String(value)}; +} + async function encode(value, seen = new WeakSet()) { if (value === null) return {t:'null'}; const typ = typeof value; if (typ === 'undefined') return {t:'undefined'}; if (typ === 'string' || typ === 'boolean') return {t:typ,v:value}; if (typ === 'bigint') return {t:'bigint',v:value.toString()}; - if (typ === 'number') return {t:'number',v:Object.is(value,-0)?'-0':Number.isFinite(value)?value:String(value)}; + if (typ === 'number') return encodeNumber(value); if (typ !== 'object') throw new Error('Unsupported IndexedDB value type: '+typ); if(seen.has(value)) throw new Error('Shared/cyclic references cannot yet be migrated losslessly'); seen.add(value); @@ -19,18 +56,21 @@ async function encode(value, seen = new WeakSet()) { if(value instanceof RegExp) return {t:'regexp',s:value.source,f:value.flags}; if(value instanceof ArrayBuffer){ assertBinaryLimit(value.byteLength,'ArrayBuffer'); - return {t:'buffer',v:Array.from(new Uint8Array(value))}; + return {t:'buffer',v:bytesToBase64(new Uint8Array(value))}; } if(ArrayBuffer.isView(value)) { assertBinaryLimit(value.byteLength,value.constructor.name); - if (value instanceof DataView) return {t:'dataview',v:Array.from(new Uint8Array(value.buffer,value.byteOffset,value.byteLength))}; - return {t:'typedarray',type:value.constructor.name,v:Array.from(new Uint8Array(value.buffer,value.byteOffset,value.byteLength))}; + const bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength); + if (value instanceof DataView) return {t:'dataview',v:bytesToBase64(bytes)}; + return {t:'typedarray',type:value.constructor.name,v:bytesToBase64(bytes),le:LITTLE_ENDIAN}; } if(typeof Blob !== 'undefined' && value instanceof Blob){ assertBinaryLimit(value.size, value instanceof File ? 'File' : 'Blob'); - const v=Array.from(new Uint8Array(await value.arrayBuffer())); - if(typeof File !== 'undefined' && value instanceof File)return {t:'file',v,name:value.name,mime:value.type,lastModified:value.lastModified}; - return {t:'blob',v,mime:value.type}; + const bytes = new Uint8Array(await value.arrayBuffer()); + if(typeof File !== 'undefined' && value instanceof File){ + return {t:'file',v:bytesToBase64(bytes),name:value.name,mime:value.type,lastModified:value.lastModified}; + } + return {t:'blob',v:bytesToBase64(bytes),mime:value.type}; } if(Array.isArray(value)) { if(value.length>50000)throw new Error('Array exceeds migration length limit'); @@ -51,12 +91,28 @@ async function encode(value, seen = new WeakSet()) { if(value instanceof Set) { const arr=[];for(const v of value)arr.push(await encode(v,seen));return {t:'set',v:arr}; } + // Structured-cloneable built-ins that are not plain objects. + if(value instanceof Error){ + const encoded={t:'error',name:value.name,message:value.message,stack:value.stack}; + if(Object.prototype.hasOwnProperty.call(value,'cause')) encoded.cause=await encode(value.cause,seen); + return encoded; + } + const tag=Object.prototype.toString.call(value); + if(tag==='[object Number]')return {t:'numberobject',v:encodeNumber(value.valueOf())}; + if(tag==='[object String]')return {t:'stringobject',v:value.valueOf()}; + if(tag==='[object Boolean]')return {t:'booleanobject',v:value.valueOf()}; + if(typeof ImageData!=='undefined' && value instanceof ImageData){ + assertBinaryLimit(value.data.byteLength,'ImageData'); + return {t:'imagedata',w:value.width,h:value.height, + data:bytesToBase64(new Uint8Array(value.data.buffer,value.data.byteOffset,value.data.byteLength))}; + } if(Object.getPrototypeOf(value)!==Object.prototype && Object.getPrototypeOf(value)!==null) throw new Error('Unsupported IndexedDB object prototype'); const pairs=[]; for (const k of Object.keys(value)) pairs.push([k,await encode(value[k],seen)]); return {t:'object',plain:Object.getPrototypeOf(value)===Object.prototype,v:pairs}; } + function decode(o){ if(!o || typeof o.t!=='string')throw new Error('Invalid encoded value'); switch(o.t){ @@ -67,16 +123,34 @@ function decode(o){ case 'bigint':return BigInt(o.v); case 'date':return new Date(o.v); case 'regexp':return new RegExp(o.s,o.f); - case 'buffer':return Uint8Array.from(o.v).buffer; - case 'dataview':return new DataView(Uint8Array.from(o.v).buffer); + case 'buffer':return base64ToBytes(o.v).buffer; + case 'dataview':return new DataView(base64ToBytes(o.v).buffer); case 'typedarray': { const types={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array}; + if(typeof Float16Array!=='undefined')types.Float16Array=Float16Array; const ctor=types[o.type]; if(!ctor)throw new Error('Unknown typed array type'); - const a=Uint8Array.from(o.v); if(a.byteLength%ctor.BYTES_PER_ELEMENT)throw new Error('Invalid typed array data'); + const a=base64ToBytes(o.v); if(a.byteLength%ctor.BYTES_PER_ELEMENT)throw new Error('Invalid typed array data'); + if(o.le!==undefined && o.le!==LITTLE_ENDIAN && ctor.BYTES_PER_ELEMENT>1)swapBytes(a,ctor.BYTES_PER_ELEMENT); return new ctor(a.buffer); } - case 'blob':return new Blob([Uint8Array.from(o.v)],{type:o.mime}); - case 'file':return new File([Uint8Array.from(o.v)],o.name,{type:o.mime,lastModified:o.lastModified}); + case 'blob':return new Blob([base64ToBytes(o.v)],{type:o.mime}); + case 'file':return new File([base64ToBytes(o.v)],o.name,{type:o.mime,lastModified:o.lastModified}); + case 'error': { + const types={Error,TypeError,RangeError,SyntaxError,ReferenceError,EvalError,URIError}; + const Ctor=types[o.name]||Error; + const error=new Ctor(o.message||''); + if(o.name)error.name=o.name; + if(o.stack)error.stack=o.stack; + if('cause' in o)error.cause=decode(o.cause); + return error; + } + case 'numberobject':return new Number(decode(o.v)); + case 'stringobject':return new String(o.v); + case 'booleanobject':return new Boolean(o.v); + case 'imagedata': { + if(typeof ImageData==='undefined')throw new Error('ImageData is not supported in this browser'); + return new ImageData(new Uint8ClampedArray(base64ToBytes(o.data)),o.w,o.h); + } case 'array': { const arr=new Array(o.v.length); for(let i=0;i{ + timer=setTimeout(()=>reject(Error(label+' timed out after '+Math.round(timeoutMs/1000)+'s')),timeoutMs); + }), + ]).finally(()=>clearTimeout(timer)); +} + async function snapshotOrigin(page) { return page.evaluate(async () => { const {encode}=globalThis.PortageIDBCodec; @@ -118,9 +128,10 @@ async function restoreOrigin(page,source) { const results={restored:0,skipped:0,errors:[]}; const existing=new Set((await indexedDB.databases()).map(x=>x.name)); for(const spec of source.databases) { - if(existing.has(spec.name)) {results.skipped++;results.errors.push('Existing destination database preserved');continue;} + if(existing.has(spec.name)) {results.skipped++;continue;} let db; let created=false; + let failure=null; try { // Decode EVERYTHING before creating the DB; unsupported values must not // leave a partially initialized destination schema. @@ -137,25 +148,22 @@ async function restoreOrigin(page,source) { if(s.keyPath!==null)opts.keyPath=s.keyPath; const store=d.createObjectStore(s.name,opts); for(const ix of s.indexes)store.createIndex(ix.name,ix.keyPath,{unique:ix.unique,multiEntry:ix.multiEntry}); + // Write schema and records in the same versionchange + // transaction so an interrupted restore cannot leave a + // schema-only database that later runs skip forever. + for(const [key,value] of s.records){ + if(s.keyPath===null)store.put(value,key);else store.put(value); + } } - }catch(e){request.transaction.abort();} + }catch(e){ + failure=e; + try{request.transaction.abort();}catch{} + } }; request.onsuccess=()=>resolve(request.result); - request.onerror=()=>reject(request.error||Error('Open error')); + request.onerror=()=>reject(failure||request.error||Error('Open error')); request.onblocked=()=>reject(Error('IndexedDB upgrade blocked')); }); - for(const s of decoded){ - if(!s.records.length)continue; - await new Promise((resolve,reject)=>{ - const tx=db.transaction(s.name,'readwrite'); - tx.oncomplete=()=>resolve();tx.onerror=()=>reject(tx.error||Error('Write failed')); - tx.onabort=()=>reject(tx.error||Error('Transaction aborted')); - const store=tx.objectStore(s.name); - try{for(const [key,value] of s.records) { - if(s.keyPath===null)store.put(value,key);else store.put(value); - }}catch(e){tx.abort();reject(e);} - }); - } results.restored++; }catch(e){ results.skipped++; @@ -245,14 +253,14 @@ async function migrate(opts) { for(const [i,origin]of origins.entries()){ try { await navigateOffline(sourcePage,origin,opts.timeout); - const exported=await snapshotOrigin(sourcePage); + const exported=await withTimeout(snapshotOrigin(sourcePage),120000,'IndexedDB snapshot'); if(exported.errors.length){stats.sourceSkipped+=exported.errors.length;stats.errors.push({originIndex:i+1,reason:'Unsupported source database/record type'});} if(!exported.databases.length)continue; await navigateOffline(destPage,origin,opts.timeout); - const result=await restoreOrigin(destPage,exported); + const result=await withTimeout(restoreOrigin(destPage,exported),120000,'IndexedDB restore'); stats.restored+=result.restored;stats.skipped+=result.skipped; if(result.errors.length)stats.errors.push({originIndex:i+1,reason:'Target database skipped or unsupported'}); - }catch(e){stats.skipped++;stats.errors.push({originIndex:i+1,reason:String(e.message||e).slice(0,150)});} + }catch(e){stats.skipped++;stats.errors.push({originIndex:i+1,reason:String(e.message||e).slice(0,150)});if(String(e.message||'').includes('timed out'))throw e;} } await sourcePage.close();await destPage.close(); }finally { @@ -267,7 +275,9 @@ async function migrate(opts) { } console.log(`IndexedDB migration: ${stats.restored} database(s) restored; ${stats.skipped} target skips; ${stats.sourceSkipped} source skips.`); if(stats.errors.length)console.log('Failures (origin indices only, no contents):',JSON.stringify(stats.errors)); - if(stats.skipped||stats.sourceSkipped)process.exitCode=2; + // Existing destination databases are intentionally skipped, so only real + // source/restore errors make the command exit non-zero. + if(stats.sourceSkipped||stats.errors.length)process.exitCode=2; return stats; } if(require.main===module){ From 4f630de25fe1b9689935c7791b2485df86375cb1 Mon Sep 17 00:00:00 2001 From: souta <109493063+souta-lab@users.noreply.github.com> Date: Fri, 23 Oct 2026 21:24:55 +0900 Subject: [PATCH 12/12] audit: recover interrupted IndexedDB restores and harden codec edge cases - Treat an existing destination database with no object stores (when the source has stores) as an interrupted upgrade: delete and retry instead of skipping it forever. Verified by killing Chrome mid-restore; the next run restored all 49,990 synthetic records. - Keep snapshot error indices aligned with the actual database index. - Look up Error constructors through a Map: a site-controlled Error.name of "constructor"/"__proto__"/"toString" could corrupt the value or abort the DB. - Brand-check Number/String/Boolean wrappers instead of toString sniffing so Symbol.toStringTag cannot change a plain object's type; accept ordinary class instances as plain objects (prototype dropped, matching structured clone) while still rejecting platform-object tags. - Preserve AggregateError.errors and ImageData.colorSpace. - Document the empty-container retry, the 120 s per-origin timeout and the additional clone types. --- tests/e2e_indexeddb.cjs | 21 +++++++++++++ tests/test_indexeddb_codec.cjs | 21 +++++++++++++ tools/README.md | 19 +++++++----- tools/indexeddb_codec.js | 41 ++++++++++++++++++------ tools/indexeddb_migrate.cjs | 57 +++++++++++++++++++++++++++------- 5 files changed, 130 insertions(+), 29 deletions(-) diff --git a/tests/e2e_indexeddb.cjs b/tests/e2e_indexeddb.cjs index 70a00c1..d879188 100644 --- a/tests/e2e_indexeddb.cjs +++ b/tests/e2e_indexeddb.cjs @@ -112,6 +112,27 @@ async function main(){ const afterInvalid=await verify.evaluate(()=>indexedDB.databases()); assert(!afterInvalid.some(x=>x.name==='portage-invalid-record-test'), 'Aborted restore must not leave a schema-only database'); + // An interrupted upgrade can leave an empty version-1 database. The next + // run must detect that (no object stores) and retry it instead of + // reporting a permanent skip. + await verify.evaluate(()=>new Promise((ok,no)=>{ + const r=indexedDB.open('portage-interrupted-test',1); + r.onsuccess=()=>{r.result.close();ok();};r.onerror=()=>no(r.error); + })); + const recovered=await restoreOrigin(verify,{databases:[{ + name:'portage-interrupted-test',version:1,stores:[{ + name:'data',keyPath:null,autoIncrement:false,indexes:[], + records:[[{t:'string',v:'k'},{t:'string',v:'v'}]] + }] + }]}); + assert.equal(recovered.restored,1,JSON.stringify(recovered)); + assert.equal(recovered.retried,1); + const recoveredValue=await verify.evaluate(async()=>{ + const db=await new Promise((ok,no)=>{const r=indexedDB.open('portage-interrupted-test');r.onsuccess=()=>ok(r.result);r.onerror=()=>no(r.error)}); + const value=await new Promise((ok,no)=>{const q=db.transaction('data','readonly').objectStore('data').get('k');q.onsuccess=()=>ok(q.result);q.onerror=()=>no(q.error)}); + db.close();return value; + }); + assert.equal(recoveredValue,'v'); } await verify.close();await browser.close();browser=null; assert.deepEqual(hits,before,'No real site traffic including verification'); diff --git a/tests/test_indexeddb_codec.cjs b/tests/test_indexeddb_codec.cjs index 6499d28..e865037 100644 --- a/tests/test_indexeddb_codec.cjs +++ b/tests/test_indexeddb_codec.cjs @@ -31,6 +31,27 @@ const {encode,decode}=require('../tools/indexeddb_codec.js'); assert(decode(JSON.parse(JSON.stringify(await encode(Object(42))))) instanceof Number); assert.equal(decode(JSON.parse(JSON.stringify(await encode(Object('x'))))).valueOf(),'x'); assert.equal(decode(JSON.parse(JSON.stringify(await encode(Object(false))))).valueOf(),false); + // Site-controlled Error.name must not be used as a plain-object key. + for(const name of ['constructor','__proto__','toString']){ + const named=new Error('named');named.name=name; + const restored=decode(JSON.parse(JSON.stringify(await encode(named)))); + assert(restored instanceof Error,name); + assert.equal(restored.message,'named'); + } + if(typeof AggregateError!=='undefined'){ + const aggregate=new AggregateError([new TypeError('first'),new Error('second')],'many'); + const restored=decode(JSON.parse(JSON.stringify(await encode(aggregate)))); + assert(restored instanceof AggregateError); + assert.equal(restored.message,'many'); + assert.deepEqual(restored.errors.map((error)=>error.message),['first','second']); + } + // Symbol.toStringTag spoofing must not turn a plain object into a wrapper. + class Spoofed{constructor(){this.x=1;}get [Symbol.toStringTag](){return 'Number';}valueOf(){return 7;}} + await assert.rejects(()=>encode(new Spoofed()),/Unsupported IndexedDB object prototype/); + class Plainish{constructor(){this.x=1;}} + const plainish=decode(JSON.parse(JSON.stringify(await encode(new Plainish())))); + assert.equal(plainish.x,1); + assert.equal(Object.getPrototypeOf(plainish),Object.prototype); // Typed arrays carry the source byte order; decoding the same big-endian // payload on a little-endian host must still produce the original values. diff --git a/tools/README.md b/tools/README.md index c17d1d4..b6f487c 100644 --- a/tools/README.md +++ b/tools/README.md @@ -94,10 +94,12 @@ it to a regular directory first). Source/destination paths that contain each other are also refused. Chromium's destination profile **will be changed** with `--apply`. Existing IndexedDB databases are **never overwritten**: the whole database is skipped if its name already exists at that origin. Schema and -records are written in the same version-change transaction, so an interrupted -restore cannot leave a schema-only database that a later run would skip; an -aborted database is reported and can be retried after fixing the cause. A -clean rerun reports intentional existing-database skips but exits successfully. +records are written in the same version-change transaction. An interrupted +restore can still leave an **empty version-1 database container** (no object +stores); the next run detects that when the source database has stores, removes +the empty container, and retries instead of skipping it forever. Databases that +already contain object stores are preserved. A clean rerun reports intentional +existing-database skips but exits successfully. The destination Chromium lock file and the Firefox source profile's open lock are checked before migration; the Chromium profile named `Default` is used unless `--chromium-profile-directory` is passed. Do not use this on a profile @@ -129,12 +131,14 @@ copies the whole Firefox profile, so treat it as sensitive. **Migrated**: IndexedDB database names and versions, object stores, key paths, auto-increment flags, indexes (including multi-entry/unique), primary keys, and -supported stored values: ordinary objects/arrays, strings/numbers/booleans, +supported stored values: ordinary objects/arrays (class-instance prototypes are +dropped, as in structured clone), strings/numbers/booleans, BigInt, Date, RegExp, Map/Set, binary buffers, typed arrays (including `Float16Array` where the browsers support it; multi-byte elements carry a byte order marker so cross-endian migrations do not byte-swap values), Blob/File, `Error` subclasses (name/message/stack/cause), `Number`/`String`/`Boolean` -wrapper objects, and `ImageData`. +wrapper objects, `AggregateError` (including `.errors`), and `ImageData` +(including `colorSpace`). **Still unsupported**: cyclic or shared object references, CryptoKey, other platform/browser objects, databases larger than 32 MiB in the encoded wire @@ -142,7 +146,8 @@ representation, an origin whose encoded payload exceeds 64 MiB, stores with over 50,000 records, arrays with over 50,000 elements, individual Blob/File/ArrayBuffer/typed-array/ImageData values larger than 8 MiB (checked before they are expanded), and a per-origin snapshot/restore that takes longer -than 120 seconds. The bridge **skips entire databases** when it finds +than 120 seconds (a timed-out run aborts and the next run retries a left-over +empty database container). The bridge **skips entire databases** when it finds unsupported data, and reports aggregate counts without printing record values. The IndexedDB API does not expose an object store's current auto-increment counter, so after restoring records that were deleted at the source a new diff --git a/tools/indexeddb_codec.js b/tools/indexeddb_codec.js index 4021c9e..3905a16 100644 --- a/tools/indexeddb_codec.js +++ b/tools/indexeddb_codec.js @@ -92,25 +92,36 @@ async function encode(value, seen = new WeakSet()) { const arr=[];for(const v of value)arr.push(await encode(v,seen));return {t:'set',v:arr}; } // Structured-cloneable built-ins that are not plain objects. + if(typeof AggregateError!=='undefined' && value instanceof AggregateError){ + const encoded={t:'aggregateerror',message:value.message,stack:value.stack,errors:[]}; + for(const nested of value.errors) encoded.errors.push(await encode(nested,seen)); + if(Object.prototype.hasOwnProperty.call(value,'cause')) encoded.cause=await encode(value.cause,seen); + return encoded; + } if(value instanceof Error){ const encoded={t:'error',name:value.name,message:value.message,stack:value.stack}; if(Object.prototype.hasOwnProperty.call(value,'cause')) encoded.cause=await encode(value.cause,seen); return encoded; } - const tag=Object.prototype.toString.call(value); - if(tag==='[object Number]')return {t:'numberobject',v:encodeNumber(value.valueOf())}; - if(tag==='[object String]')return {t:'stringobject',v:value.valueOf()}; - if(tag==='[object Boolean]')return {t:'booleanobject',v:value.valueOf()}; + // Brand checks, not Object.prototype.toString sniffing: a site-controlled + // Symbol.toStringTag must not turn an ordinary object into a wrapper. + try{return {t:'numberobject',v:encodeNumber(Number.prototype.valueOf.call(value))};}catch{} + try{return {t:'stringobject',v:String.prototype.valueOf.call(value)};}catch{} + try{return {t:'booleanobject',v:Boolean.prototype.valueOf.call(value)};}catch{} if(typeof ImageData!=='undefined' && value instanceof ImageData){ assertBinaryLimit(value.data.byteLength,'ImageData'); - return {t:'imagedata',w:value.width,h:value.height, + return {t:'imagedata',w:value.width,h:value.height,cs:value.colorSpace, data:bytesToBase64(new Uint8Array(value.data.buffer,value.data.byteOffset,value.data.byteLength))}; } - if(Object.getPrototypeOf(value)!==Object.prototype && Object.getPrototypeOf(value)!==null) + const prototype=Object.getPrototypeOf(value); + if(prototype!==Object.prototype && prototype!==null && + Object.prototype.toString.call(value)!=='[object Object]') throw new Error('Unsupported IndexedDB object prototype'); + // Ordinary class instances are structured-cloneable; the clone drops the + // prototype, so encode own enumerable properties as a plain object. const pairs=[]; for (const k of Object.keys(value)) pairs.push([k,await encode(value[k],seen)]); - return {t:'object',plain:Object.getPrototypeOf(value)===Object.prototype,v:pairs}; + return {t:'object',plain:prototype!==null,v:pairs}; } function decode(o){ @@ -136,20 +147,30 @@ function decode(o){ case 'blob':return new Blob([base64ToBytes(o.v)],{type:o.mime}); case 'file':return new File([base64ToBytes(o.v)],o.name,{type:o.mime,lastModified:o.lastModified}); case 'error': { - const types={Error,TypeError,RangeError,SyntaxError,ReferenceError,EvalError,URIError}; - const Ctor=types[o.name]||Error; + const types=new Map([['Error',Error],['TypeError',TypeError],['RangeError',RangeError], + ['SyntaxError',SyntaxError],['ReferenceError',ReferenceError],['EvalError',EvalError],['URIError',URIError]]); + const Ctor=types.get(o.name)||Error; const error=new Ctor(o.message||''); if(o.name)error.name=o.name; if(o.stack)error.stack=o.stack; if('cause' in o)error.cause=decode(o.cause); return error; } + case 'aggregateerror': { + if(typeof AggregateError==='undefined')throw new Error('AggregateError is not supported in this browser'); + const error=new AggregateError(o.errors.map(decode),o.message||''); + if(o.stack)error.stack=o.stack; + if('cause' in o)error.cause=decode(o.cause); + return error; + } case 'numberobject':return new Number(decode(o.v)); case 'stringobject':return new String(o.v); case 'booleanobject':return new Boolean(o.v); case 'imagedata': { if(typeof ImageData==='undefined')throw new Error('ImageData is not supported in this browser'); - return new ImageData(new Uint8ClampedArray(base64ToBytes(o.data)),o.w,o.h); + const data=new Uint8ClampedArray(base64ToBytes(o.data)); + if(o.cs){try{return new ImageData(data,o.w,o.h,{colorSpace:o.cs});}catch{}} + return new ImageData(data,o.w,o.h); } case 'array': { const arr=new Array(o.v.length); diff --git a/tools/indexeddb_migrate.cjs b/tools/indexeddb_migrate.cjs index 8298ae9..cfb3a09 100644 --- a/tools/indexeddb_migrate.cjs +++ b/tools/indexeddb_migrate.cjs @@ -71,7 +71,7 @@ async function snapshotOrigin(page) { const {encode}=globalThis.PortageIDBCodec; const output={databases:[],errors:[]}; const metas=await indexedDB.databases(); - for(const meta of metas) { + for(const [dbIndex, meta] of metas.entries()) { if(typeof meta.name!=='string')continue; let db; try { @@ -115,7 +115,7 @@ async function snapshotOrigin(page) { if(JSON.stringify(dump).length>32*1024*1024)throw Error('Database over 32 MiB transport limit'); if(JSON.stringify(output).length+JSON.stringify(dump).length>64*1024*1024)throw Error('Origin over 64 MiB transport limit'); output.databases.push(dump); - }catch(e){output.errors.push('Database '+output.databases.length+' skipped: '+String(e.message||e).slice(0,160));} + }catch(e){output.errors.push('Database '+dbIndex+' skipped: '+String(e.message||e).slice(0,160));} finally {db?.close();} } return output; @@ -125,10 +125,46 @@ async function snapshotOrigin(page) { async function restoreOrigin(page,source) { return page.evaluate(async ({source})=>{ const {decode}=globalThis.PortageIDBCodec; - const results={restored:0,skipped:0,errors:[]}; + const results={restored:0,skipped:0,retried:0,errors:[]}; const existing=new Set((await indexedDB.databases()).map(x=>x.name)); + const deleteDatabase=name=>new Promise((resolve,reject)=>{ + const request=indexedDB.deleteDatabase(name); + request.onsuccess=()=>resolve(); + request.onerror=()=>reject(request.error||Error('DB deletion failed')); + request.onblocked=()=>reject(Error('DB deletion blocked')); + }); + const openExisting=name=>new Promise((resolve,reject)=>{ + const request=indexedDB.open(name); + request.onsuccess=()=>resolve(request.result); + request.onerror=()=>reject(request.error||Error('DB open failed')); + request.onblocked=()=>reject(Error('DB open blocked')); + }); for(const spec of source.databases) { - if(existing.has(spec.name)) {results.skipped++;continue;} + let needsRestore=true; + if(existing.has(spec.name)) { + let previous=null; + try { + previous=await openExisting(spec.name); + const storeCount=previous.objectStoreNames.length; + previous.close();previous=null; + if(storeCount===0 && spec.stores.length>0) { + // An interrupted upgrade can leave an empty version-1 container + // with no object stores. Treat it as an incomplete attempt, remove + // it, and retry instead of skipping the origin forever. + await deleteDatabase(spec.name); + results.retried++; + } else { + results.skipped++; + needsRestore=false; + } + }catch(e){ + if(previous)previous.close(); + results.skipped++; + results.errors.push(String(e.message||e).slice(0,160)); + needsRestore=false; + } + } + if(!needsRestore)continue; let db; let created=false; let failure=null; @@ -172,11 +208,8 @@ async function restoreOrigin(page,source) { // delete a target database when validation failed before creation. if(db){db.close();db=null;} if(created){ - try{await new Promise((resolve,reject)=>{ - const q=indexedDB.deleteDatabase(spec.name); - q.onsuccess=()=>resolve();q.onerror=()=>reject(q.error); - q.onblocked=()=>reject(Error('DB deletion blocked')); - });}catch{results.errors.push('Partial database cleanup failed; inspect target profile');} + try{await deleteDatabase(spec.name);} + catch{results.errors.push('Partial database cleanup failed; inspect target profile');} } }finally {db?.close();} } @@ -231,7 +264,7 @@ async function migrate(opts) { const clone=path.join(scratch,'firefox-clone'); // Reflinks avoid copying large databases when the filesystem supports CoW. // Do NOT launch Firefox against the original profile, which would modify it. - let fb,cb;const stats={origins:origins.length,restored:0,skipped:0,sourceSkipped:0,errors:[]}; + let fb,cb;const stats={origins:origins.length,restored:0,skipped:0,retried:0,sourceSkipped:0,errors:[]}; try { cloneFirefoxProfile(fx,clone); const pp=require('puppeteer-core'); @@ -258,7 +291,7 @@ async function migrate(opts) { if(!exported.databases.length)continue; await navigateOffline(destPage,origin,opts.timeout); const result=await withTimeout(restoreOrigin(destPage,exported),120000,'IndexedDB restore'); - stats.restored+=result.restored;stats.skipped+=result.skipped; + stats.restored+=result.restored;stats.skipped+=result.skipped;stats.retried+=result.retried||0; if(result.errors.length)stats.errors.push({originIndex:i+1,reason:'Target database skipped or unsupported'}); }catch(e){stats.skipped++;stats.errors.push({originIndex:i+1,reason:String(e.message||e).slice(0,150)});if(String(e.message||'').includes('timed out'))throw e;} } @@ -273,7 +306,7 @@ async function migrate(opts) { cleanupState.paths = cleanupState.paths.filter(entry => entry !== scratch); removeSignalHandlers(); } - console.log(`IndexedDB migration: ${stats.restored} database(s) restored; ${stats.skipped} target skips; ${stats.sourceSkipped} source skips.`); + console.log(`IndexedDB migration: ${stats.restored} database(s) restored; ${stats.retried} interrupted database(s) retried; ${stats.skipped} target skips; ${stats.sourceSkipped} source skips.`); if(stats.errors.length)console.log('Failures (origin indices only, no contents):',JSON.stringify(stats.errors)); // Existing destination databases are intentionally skipped, so only real // source/restore errors make the command exit non-zero.