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()