diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..552d5a0 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,40 @@ +name: Unit tests +on: + push: + pull_request: +permissions: + contents: read +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 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/*.py tests/*.py + - name: JavaScript syntax + run: | + 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 + node tools/indexeddb_migrate.cjs --help diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c59dc93 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +__pycache__/ +*.py[cod] +*.portage.json +tools/node_modules/ diff --git a/README.md b/README.md index 0f222d2..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. @@ -63,3 +63,11 @@ 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: 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). 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 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 385bd3d..1fcc6c9 100644 --- a/chrome/dashboard.js +++ b/chrome/dashboard.js @@ -142,8 +142,27 @@ 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 })); + // 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, 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, + 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 +224,52 @@ 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 (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) 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 !== 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 }; + // 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; + 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++; } if (i % 100 === 0) { onProg(i, total); await tick(); } } onProg(total, total); return { imported, skipped }; } + async function importTabs(items, onProg) { const total = items.length; let imported = 0, skipped = 0; for (let i = 0; i < total; i++) { diff --git a/firefox/dashboard.js b/firefox/dashboard.js index 8da23d2..f4f6786 100644 --- a/firefox/dashboard.js +++ b/firefox/dashboard.js @@ -145,8 +145,27 @@ 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 })); + // 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, 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, + 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 +227,52 @@ 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 (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) 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 !== 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 }; + // 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; + 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++; } if (i % 100 === 0) { onProg(i, total); await tick(); } } onProg(total, total); return { imported, skipped }; } + async function importTabs(items, onProg) { const total = items.length; let imported = 0, skipped = 0; for (let i = 0; i < total; i++) { diff --git a/tests/e2e_chrome.cjs b/tests/e2e_chrome.cjs new file mode 100644 index 0000000..dbc4e2a --- /dev/null +++ b/tests/e2e_chrome.cjs @@ -0,0 +1,79 @@ +#!/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 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'); +const fs = require('node:fs'); +const path = require('node:path'); +let puppeteer; try { puppeteer = require('../tools/node_modules/puppeteer-core'); } catch { 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 dir = fs.mkdtempSync(path.join(os.tmpdir(), 'portage-e2e-')); + const extDir = path.resolve('chrome'); + let browser; + try { + 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'); + 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 page=await browser.newPage(); + await page.goto(origin); + 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'); + // 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)); + fs.rmSync(dir,{recursive:true,force:true}); + } +} +main().catch(e=>{console.error('E2E failed:',e.stack);process.exitCode=1}); diff --git a/tests/e2e_cookie_cli.cjs b/tests/e2e_cookie_cli.cjs new file mode 100644 index 0000000..19244b6 --- /dev/null +++ b/tests/e2e_cookie_cli.cjs @@ -0,0 +1,69 @@ +'use strict'; +// 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 new file mode 100644 index 0000000..bb157bb --- /dev/null +++ b/tests/e2e_cross_browser.cjs @@ -0,0 +1,62 @@ +#!/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 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(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; + 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',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: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})); + 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_indexeddb.cjs b/tests/e2e_indexeddb.cjs new file mode 100644 index 0000000..d879188 --- /dev/null +++ b/tests/e2e_indexeddb.cjs @@ -0,0 +1,151 @@ +'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'); +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]; + 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: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 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, + 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); + }); + 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: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']}); + 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), + 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, + 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:[{ + 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'); + // 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'); + // 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'); + // 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{ + 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/e2e_offline_import.cjs b/tests/e2e_offline_import.cjs new file mode 100644 index 0000000..5b3d9b3 --- /dev/null +++ b/tests/e2e_offline_import.cjs @@ -0,0 +1,43 @@ +#!/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'); +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}`; + // 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,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']}); + 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')),'猫'); + 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 { + 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_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 new file mode 100644 index 0000000..9b4549b --- /dev/null +++ b/tests/test_firefox_localstorage.py @@ -0,0 +1,212 @@ +import base64 +import hashlib +import json +import os +import sqlite3 +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, 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): + 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('日本語', 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_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) + 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' + 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)) + # 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: + 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__': + unittest.main() diff --git a/tests/test_indexeddb_codec.cjs b/tests/test_indexeddb_codec.cjs new file mode 100644 index 0000000..e865037 --- /dev/null +++ b/tests/test_indexeddb_codec.cjs @@ -0,0 +1,95 @@ +'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))); + } + // 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); + // 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. + 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 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); + 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/tests/test_indexeddb_paths.cjs b/tests/test_indexeddb_paths.cjs new file mode 100644 index 0000000..26ae615 --- /dev/null +++ b/tests/test_indexeddb_paths.cjs @@ -0,0 +1,80 @@ +'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 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({ + 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_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 new file mode 100644 index 0000000..b997180 --- /dev/null +++ b/tests/test_profile_safety.cjs @@ -0,0 +1,127 @@ +'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 {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) { + 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')); + + // 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), {}); + 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); + + // 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}); + } +} + +main().catch((error) => { console.error(error.stack); process.exitCode = 1; }); diff --git a/tests/test_storage_browser.cjs b/tests/test_storage_browser.cjs new file mode 100644 index 0000000..986c95c --- /dev/null +++ b/tests/test_storage_browser.cjs @@ -0,0 +1,113 @@ +'use strict'; +// 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); + } + return context; +} + +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 new file mode 100644 index 0000000..b6f487c --- /dev/null +++ b/tools/README.md @@ -0,0 +1,201 @@ +# 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** fetch live website content during import. + +**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`, 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 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. 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. + +## 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 "$HOME/.mozilla/firefox/your-profile" \ + --output "$HOME/firefox-storage.portage.json" + ``` + + 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. + +2. Install the *optional* importer dependency, once: + + ```bash + cd tools && npm ci && cd .. + ``` + +3. Close Brave. Check data counts in **dry-run** mode (the default): + + ```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 +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. + +## 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. 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 +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 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: 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. Schema and +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 +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, 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 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 +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, `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 +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 (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 +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 +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 +``` + +## 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. 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 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. 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 +the browser is not at `/usr/bin/brave-browser`. diff --git a/tools/chromium_cookie_import.cjs b/tools/chromium_cookie_import.cjs new file mode 100644 index 0000000..a02fe8e --- /dev/null +++ b/tools/chromium_cookie_import.cjs @@ -0,0 +1,59 @@ +#!/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'); +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; +} +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(source===target)throw Error('Source and destination profiles must differ'); + assertDisjointProfiles(source, target); + 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'); + const parsed=JSON.parse(p.stdout);p.stdout=''; + 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), + 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{ + let {success}=await session.send('Network.setCookie',cookie); + if(success)result.accepted++;else result.failed++; + }catch(e){result.failed++;} + } + }finally{ + process.removeListener('SIGINT',cleanupOnSignal); + process.removeListener('SIGTERM',cleanupOnSignal); + try{if(browser)await browser.close();}catch{} + } + return result; +} +if(require.main===module){ + const args=process.argv.slice(2); + 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,assertProfileDirectory}; diff --git a/tools/chromium_localstorage_import.cjs b/tools/chromium_localstorage_import.cjs new file mode 100644 index 0000000..db58738 --- /dev/null +++ b/tools/chromium_localstorage_import.cjs @@ -0,0 +1,209 @@ +#!/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'); +const {assertSafeTargetProfile, assertChromiumClosed, chromiumLaunchProfileOptions} = require('./profile_safety.cjs'); + +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=[]; 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; +} + +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=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) { + 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)');}} + 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 { + // 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; +} + +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_cookie_stream.py b/tools/firefox_cookie_stream.py new file mode 100644 index 0000000..db69e2d --- /dev/null +++ b/tools/firefox_cookie_stream.py @@ -0,0 +1,56 @@ +#!/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 contextlib import closing +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,'session':0,'invalid':0,'insecure_none':0} + now=time.time() + 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' + ): + 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 + # moz_cookies.expiry is milliseconds since the UNIX epoch, while + # Chrome's Network.setCookie expects seconds. Convert both the + # expiry comparison and the value sent over CDP to seconds. + expiry_seconds=expiry/1000.0 if expiry else 0 + if not expiry_seconds: + # Session cookies would end with the temporary Chromium session + # that the importer closes, so importing them would only inflate + # the accepted count without keeping the login. + reason['session']+=1 + continue + if expiry_seconds 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: + # 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) + 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 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 None # no silent loss of Firefox origin attributes / partitions + try: + u = urlsplit(origin) + 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_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 = 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: + 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): + root = profile / 'storage' / 'default' + 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() + 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 + 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 + 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') + items[key] = decode_value(value, conversion, compression) + sites.append({'origin': origin, 'items': items}) + except (sqlite3.Error, ValueError, TypeError, UnicodeError, OSError) as exc: + warnings.append(f'Skipped unreadable/unsupported origin (details omitted): {type(exc).__name__}') + 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)') + 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() + # 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. + 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)}, + '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, 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=(',', ':')) + except BaseException: + output.unlink(missing_ok=True) + raise + 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: + print(f'Skipped {len(warnings)} origin(s); check warning lines.', file=sys.stderr) + + +if __name__ == '__main__': + main() diff --git a/tools/indexeddb_codec.js b/tools/indexeddb_codec.js new file mode 100644 index 0000000..3905a16 --- /dev/null +++ b/tools/indexeddb_codec.js @@ -0,0 +1,193 @@ +/* Portable, lossless subset of IndexedDB structured-clone values. + 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 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); + 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){ + assertBinaryLimit(value.byteLength,'ArrayBuffer'); + return {t:'buffer',v:bytesToBase64(new Uint8Array(value))}; + } + if(ArrayBuffer.isView(value)) { + assertBinaryLimit(value.byteLength,value.constructor.name); + 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 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'); + const items=[]; + for(let i=0;i1)swapBytes(a,ctor.BYTES_PER_ELEMENT); + return new ctor(a.buffer); + } + 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=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'); + 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); + for(let i=0;i[decode(k),decode(v)])); + case 'set':return new Set(o.v.map(decode)); + case 'object': { + 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); + } +} +// CommonJS for unit tests; browser global for the inert migration document. +if(typeof module !== 'undefined' && module.exports)module.exports={encode,decode,MAX_BINARY_BYTES}; +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 new file mode 100644 index 0000000..cfb3a09 --- /dev/null +++ b/tools/indexeddb_migrate.cjs @@ -0,0 +1,322 @@ +#!/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 {validOrigin} = require('./chromium_localstorage_import.cjs'); +const {assertSafeTargetProfile, assertDisjointProfiles, cloneFirefoxProfile, assertChromiumClosed, assertFirefoxClosed, chromiumLaunchProfileOptions} = require('./profile_safety.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(); + // 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 => { + 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'); + // Load trusted codec from the local repository, no eval or remote scripts. + await page.addScriptTag({path:path.join(__dirname,'indexeddb_codec.js')}); +} + +function withTimeout(promise, timeoutMs, label) { + let timer; + return Promise.race([ + promise, + new Promise((_,reject)=>{ + 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; + const output={databases:[],errors:[]}; + const metas=await indexedDB.databases(); + for(const [dbIndex, meta] of metas.entries()) { + 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:[]}; + let encodedChars=0; + 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:[]}; + // 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); + }); + // 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(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)'); + 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'); + 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 '+dbIndex+' skipped: '+String(e.message||e).slice(0,160));} + finally {db?.close();} + } + return output; + }); +} + +async function restoreOrigin(page,source) { + return page.evaluate(async ({source})=>{ + const {decode}=globalThis.PortageIDBCodec; + 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) { + 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; + 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=()=>{ + created=true; + 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}); + // 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){ + failure=e; + try{request.transaction.abort();}catch{} + } + }; + request.onsuccess=()=>resolve(request.result); + request.onerror=()=>reject(failure||request.error||Error('Open error')); + request.onblocked=()=>reject(Error('IndexedDB upgrade blocked')); + }); + results.restored++; + }catch(e){ + results.skipped++; + results.errors.push(String(e.message||e).slice(0,160)); + // 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;} + if(created){ + try{await deleteDatabase(spec.name);} + catch{results.errors.push('Partial database cleanup failed; inspect target profile');} + } + }finally {db?.close();} + } + return results; + },{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) { + // 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 target=assertSafeTargetProfile(opts.chromiumProfile, 'Chromium user-data-dir'); + if(target===fx)throw Error('Source and destination profiles must differ'); + 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.`); + if(!opts.apply){console.log('DRY RUN: No browser started. Add --apply to migrate to a backed-up target profile.');return {origins:origins.length};} + 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. + 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'); + fb=await pp.launch({browser:'firefox',protocol:'webDriverBiDi',executablePath:opts.firefox, + 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, + }}); + cleanupState.browsers.push(fb); + cb=await pp.launch({browser:'chrome',executablePath:opts.chromium, + 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 { + await navigateOffline(sourcePage,origin,opts.timeout); + 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 withTimeout(restoreOrigin(destPage,exported),120000,'IndexedDB restore'); + 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;} + } + await sourcePage.close();await destPage.close(); + }finally { + // 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);} + 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.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. + if(stats.sourceSkipped||stats.errors.length)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. [--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;} +} +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..238c07f --- /dev/null +++ b/tools/list_firefox_idb_origins.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +"""List Firefox first-party HTTP(S) IndexedDB origins using QuotaManager metadata.""" +import json +import sqlite3 +import sys +from contextlib import closing +from pathlib import Path + +from firefox_localstorage import normalize_origin + + +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 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 not isinstance(usage, str) or 'I' not in usage: + continue # no privileged schemes or origin-attribute partition flattening + # 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)) + + +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]))) diff --git a/tools/package-lock.json b/tools/package-lock.json new file mode 100644 index 0000000..6448720 --- /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": ">=22.12.0" + } + }, + "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..4855b7a --- /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": ">=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..f5a6df9 --- /dev/null +++ b/tools/profile_safety.cjs @@ -0,0 +1,164 @@ +'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']; + +// 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}`); + } + 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; +} + +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 +// 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 { + // 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; + 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, assertDisjointProfiles, cloneFirefoxProfile, chromiumLaunchProfileOptions, chromiumLockPath, assertChromiumClosed, firefoxLockPath, isLockHeld, assertFirefoxClosed};