diff --git a/tests/test_firefox_localstorage.py b/tests/test_firefox_localstorage.py index dcd50e8..9b4549b 100644 --- a/tests/test_firefox_localstorage.py +++ b/tests/test_firefox_localstorage.py @@ -145,6 +145,15 @@ class FirefoxLocalStorageTest(unittest.TestCase): finally: os.close(descriptor) self.assertFalse(firefox_profile_in_use(profile)) + # Legacy `lock` symlinks encode the owner PID instead of holding + # an open descriptor; a live PID must still be detected. + lock.unlink() + legacy = profile / 'lock' + os.symlink(f'somehost:{os.getpid()}', legacy) + self.assertTrue(firefox_profile_in_use(profile)) + legacy.unlink() + os.symlink('somehost:99999999', legacy) + self.assertFalse(firefox_profile_in_use(profile)) def test_cli_refuses_a_running_profile(self): with tempfile.TemporaryDirectory() as t: diff --git a/tests/test_indexeddb_codec.cjs b/tests/test_indexeddb_codec.cjs index 043c87b..4856d51 100644 --- a/tests/test_indexeddb_codec.cjs +++ b/tests/test_indexeddb_codec.cjs @@ -23,6 +23,11 @@ const {encode,decode}=require('../tools/indexeddb_codec.js'); } const cycle={};cycle.self=cycle; await assert.rejects(()=>encode(cycle),/cyclic/); + const shared={shared:true}; + await assert.rejects(()=>encode([shared,shared]),/Shared\/cyclic/); + // Binary values are rejected before Array.from() expands them. + await assert.rejects(()=>encode(new ArrayBuffer(9*1024*1024)),/8 MiB/); + await assert.rejects(()=>encode(new Uint8Array(9*1024*1024)),/8 MiB/); const special=Object.create(null);Object.defineProperty(special,'__proto__',{value:{safe:1},enumerable:true}); const recovered=decode(JSON.parse(JSON.stringify(await encode(special)))); assert.equal(Object.getPrototypeOf(recovered),null); diff --git a/tests/test_indexeddb_paths.cjs b/tests/test_indexeddb_paths.cjs index 54ed329..26ae615 100644 --- a/tests/test_indexeddb_paths.cjs +++ b/tests/test_indexeddb_paths.cjs @@ -44,6 +44,14 @@ async function main() { apply: false, }), /must differ|looks like a Firefox profile/); + // A destination nested inside the Firefox source is refused (it would let + // Chromium write into the source profile). + await assert.rejects(() => migrate({ + firefoxProfile: source, chromiumProfile: path.join(source, 'Default'), + firefox: path.join(root, 'missing-firefox'), chromium: path.join(root, 'missing-chromium'), + apply: false, + }), /inside the Firefox source/); + // A Firefox-looking Chromium target is refused before anything is written. fs.writeFileSync(path.join(target, 'prefs.js'), ''); await assert.rejects(() => migrate({ diff --git a/tests/test_list_firefox_idb_origins.py b/tests/test_list_firefox_idb_origins.py new file mode 100644 index 0000000..29171ba --- /dev/null +++ b/tests/test_list_firefox_idb_origins.py @@ -0,0 +1,30 @@ +import sqlite3 +import sys +import tempfile +import unittest +from contextlib import closing +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools')) +from list_firefox_idb_origins import list_origins + + +class FirefoxIdbOriginListTest(unittest.TestCase): + def test_origins_are_canonicalised_and_filtered(self): + with tempfile.TemporaryDirectory() as root: + profile = Path(root) + with closing(sqlite3.connect(profile / 'storage.sqlite')) as connection, connection: + connection.execute('CREATE TABLE origin (origin TEXT, client_usages TEXT)') + connection.executemany('INSERT INTO origin VALUES (?,?)', [ + ('HTTPS://Example.test:443/', 'I123'), + ('https://example.test', 'I456'), + ('https://caret.test^userContextId=1', 'I789'), + ('https://no-idb.test', 'L1'), + ('moz-extension://some-uuid', 'I999'), + ('not a url', 'I111'), + ]) + self.assertEqual(list_origins(profile), ['https://example.test']) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_profile_safety.cjs b/tests/test_profile_safety.cjs index 13876d6..b997180 100644 --- a/tests/test_profile_safety.cjs +++ b/tests/test_profile_safety.cjs @@ -4,7 +4,8 @@ const fs = require('node:fs'); const os = require('node:os'); const path = require('node:path'); const cp = require('node:child_process'); -const {assertSafeTargetProfile, chromiumLaunchProfileOptions, chromiumLockPath, assertChromiumClosed, firefoxLockPath, isLockHeld, assertFirefoxClosed} = +const {transfer} = require('../tools/chromium_cookie_import.cjs'); +const {assertSafeTargetProfile, assertDisjointProfiles, cloneFirefoxProfile, chromiumLaunchProfileOptions, chromiumLockPath, assertChromiumClosed, firefoxLockPath, isLockHeld, assertFirefoxClosed} = require('../tools/profile_safety.cjs'); function waitFor(predicate, timeoutMs = 3000) { @@ -34,6 +35,45 @@ async function main() { assert.equal(assertSafeTargetProfile(chromiumProfile), chromiumProfile); assert.equal(assertSafeTargetProfile(path.join(root, 'not-created-yet')), path.join(root, 'not-created-yet')); + + // A symlink to home or root must not bypass the target guard. + const homeLink = path.join(root, 'home-link'); + fs.symlinkSync(os.homedir(), homeLink); + assert.throws(() => assertSafeTargetProfile(homeLink), /root or home/); + const rootLink = path.join(root, 'root-link'); + fs.symlinkSync('/', rootLink); + assert.throws(() => assertSafeTargetProfile(rootLink), /root or home/); + + // Profiles that contain each other are unsafe even when each path is + // individually acceptable. + assert.throws(() => assertDisjointProfiles(firefoxProfile, path.join(firefoxProfile, 'Default')), + /inside the Firefox source/); + assert.throws(() => assertDisjointProfiles(path.join(root, 'parent', 'child'), path.join(root, 'parent')), + /inside Chromium user-data-dir/); + assertDisjointProfiles(firefoxProfile, chromiumProfile); + await assert.rejects(() => transfer({ + sourceProfile: firefoxProfile, + targetProfile: path.join(firefoxProfile, 'Default'), + browserPath: process.execPath, + }), /inside the Firefox source/); + + // A dangling legacy `lock` symlink is a stale marker and is dropped from + // the clone, but a data symlink makes the copy unsafe and is refused so + // Firefox can never write through it into the source or another directory. + fs.symlinkSync('somehost:4242', path.join(firefoxProfile, 'lock')); + const clone = path.join(root, 'firefox-clone'); + cloneFirefoxProfile(firefoxProfile, clone); + assert.equal(fs.existsSync(path.join(clone, 'lock')), false); + fs.unlinkSync(path.join(firefoxProfile, 'lock')); + + const outside = path.join(root, 'outside-storage'); + fs.mkdirSync(outside); + fs.writeFileSync(path.join(outside, 'token.txt'), 'synthetic'); + fs.symlinkSync(outside, path.join(firefoxProfile, 'storage')); + assert.throws(() => cloneFirefoxProfile(firefoxProfile, path.join(root, 'unsafe-clone')), + /contains symlinks/); + assert.equal(fs.readFileSync(path.join(outside, 'token.txt'), 'utf8'), 'synthetic'); + fs.unlinkSync(path.join(firefoxProfile, 'storage')); // Fresh disposable profiles keep Puppeteer's --password-store=basic, while // existing profiles must not be switched to the fallback cookie key store. assert.deepEqual(chromiumLaunchProfileOptions(chromiumProfile), {}); @@ -70,6 +110,14 @@ async function main() { } await waitFor(() => !isLockHeld(path.join(firefoxProfile, '.parentlock'))); assertFirefoxClosed(firefoxProfile); + + // Legacy `lock` symlinks encode the PID; a live PID means the profile is + // in use even though realpath() cannot resolve the symlink target. + fs.unlinkSync(path.join(firefoxProfile, '.parentlock')); + const legacyLock = path.join(firefoxProfile, 'lock'); + fs.symlinkSync(`somehost:${process.pid}`, legacyLock); + assert.equal(isLockHeld(legacyLock), true); + fs.unlinkSync(legacyLock); console.log('PASS: profile target and Firefox lock safety checks'); } finally { fs.rmSync(root, {recursive: true, force: true}); diff --git a/tools/README.md b/tools/README.md index e4b385b..1b1793a 100644 --- a/tools/README.md +++ b/tools/README.md @@ -11,7 +11,7 @@ The Portage extension cannot enumerate every origin's LocalStorage via WebExtens - LocalStorage can contain live session tokens. **Encrypted AES-256-GCM export is the default**; use a long unique passphrase. `--plaintext` is an explicitly unsafe opt-out. Output is mode 0600. Never attach exported bundles to an issue, share them, or commit them. - Require **Python 3** and `cryptography` for encryption (`sudo apt install python3-cryptography` on Debian), and **Node.js 22.12+**, plus Puppeteer Core (`cd tools && npm ci`). Puppeteer Core uses the existing installed Chrome/Brave and downloads no browsers. - The exporter reports a **count of IndexedDB origins omitted** (without opening their records); use the IndexedDB section below if you need them. -- Import is **merge/upsert**: values with matching LocalStorage keys in the target are overwritten. Use a fresh Chromium profile where possible. Failed sites are reported and attempted writes are rolled back within the page when possible; this does not provide cross-origin atomic transactions. +- Import is **merge/upsert**: values with matching LocalStorage keys in the target are overwritten. Use a fresh Chromium profile where possible. Failed sites are reported and attempted writes are rolled back within the page when possible; this does not provide cross-origin atomic transactions. If an import is interrupted, the target can be left partially updated and a stale Chromium `SingletonLock`; close the browser, restore from your backup, or remove the stale lock after confirming no browser is running. - Import launches the browser **headless**, intercepts all page network requests to return inert local HTML, disables service workers for the temporary page, and validates the loaded origin. This avoids visiting live websites but does not formally guarantee that the browser itself makes no background connections. Standard Chrome sandboxing remains enabled. - Existing Chromium/Brave profiles keep their normal OS password-store settings: Puppeteer's forced `--password-store=basic` default is dropped for non-empty profiles so imported cookies stay readable after a normal launch. Fresh disposable profiles keep the automation default. @@ -73,7 +73,9 @@ and may keep binary data in separate `.files` directories. **Do not copy its SQLite files directly to Chromium.** This optional bridge launches a temporary **copy** of your closed Firefox profile in Firefox 159+ using WebDriver BiDi, reads each first-party origin's IndexedDB through Firefox's real IndexedDB API, -then restores databases through Chromium's native IndexedDB API. +then restores databases through Chromium's native IndexedDB API. The cloned +profile still contains cookies, passwords and history even though the bridge +does not read them, so treat `/tmp/portage-idb-*` as sensitive. During migration both browsers receive only **inert, locally intercepted HTML** for each site. In the automated tests the source sites received zero HTTP @@ -86,7 +88,10 @@ A hard kill or power failure can still leave it behind, so inspect `portage-idb-*` in your temporary directory if a run is interrupted. **Close both browsers and back up both profiles before beginning.** Firefox's -source is not modified, but Chromium's destination profile **will be changed** +source is not modified: the profile is copied with reflinks, stale Firefox lock +markers are dropped, and a profile containing other symlinks is refused (copy +it to a regular directory first). Source/destination paths that contain each +other are also refused. Chromium's destination profile **will be changed** with `--apply`. Existing IndexedDB databases are **never overwritten**: the whole database is skipped if its name already exists at that origin. The destination Chromium lock file and the Firefox source profile's open lock are @@ -115,7 +120,8 @@ the other CLI; run `npm ci --prefix tools` first. Firefox must support WebDriver BiDi; validated with Firefox 159.0b5, Google Chrome 156.0.8078.47, and **Brave Stable 1.98.60** in disposable test profiles. Origin enumeration reads the QuotaManager `storage.sqlite` metadata; only HTTP(S) origins without Firefox container/partition attributes -are considered. It does not inspect Chrome or Firefox passwords/cookies. +are considered. It does not read passwords or cookies; the temporary clone +copies the whole Firefox profile, so treat it as sensitive. **Migrated**: IndexedDB database names and versions, object stores, key paths, auto-increment flags, indexes (including multi-entry/unique), primary keys, and @@ -124,8 +130,9 @@ BigInt, Date, RegExp, Map/Set, binary buffers and typed arrays, Blob/File). **Still unsupported**: cyclic or shared object references, CryptoKey, non-standard browser objects, IndexedDB databases larger than 32 MiB in the -wire representation, stores with over 50,000 records, arrays with over 50,000 -elements, and individual Blob/File values larger than 8 MiB. The bridge +encoded wire representation, stores with over 50,000 records, arrays with over +50,000 elements, and individual Blob/File/ArrayBuffer/typed-array values larger +than 8 MiB (checked before they are expanded). The bridge **skips entire databases** when it finds unsupported data, and reports aggregate counts without printing record values. The IndexedDB API does not expose an object store's current auto-increment @@ -170,7 +177,10 @@ are skipped because the importer closes its temporary Chromium session immediately, so they could not survive the import anyway. Some cookies or logins remain tied to browser/device-bound secrets; a successful CDP `Network.setCookie` result does **not** guarantee continued authentication. -Never collect or paste exported cookie values into bug reports. +Never collect or paste exported cookie values into bug reports. If interrupted, +the target profile can be partially written and a stale `SingletonLock` left +behind; restore the backup or remove the stale lock after confirming the +browser is closed. `node tests/e2e_cookie_cli.cjs` verifies this transfer with synthetic cookie values and disposable Brave/Chrome profiles only; set `PORTAGE_TEST_BRAVE` if diff --git a/tools/chromium_cookie_import.cjs b/tools/chromium_cookie_import.cjs index f59d0ed..a02fe8e 100644 --- a/tools/chromium_cookie_import.cjs +++ b/tools/chromium_cookie_import.cjs @@ -2,7 +2,7 @@ 'use strict'; /** Private-process Firefox -> Chromium cookie transfer. Do not print cookie values. */ const cp=require('node:child_process'),path=require('node:path'),fs=require('node:fs'); -const {assertSafeTargetProfile, assertChromiumClosed, assertFirefoxClosed, chromiumLaunchProfileOptions}=require('./profile_safety.cjs'); +const {assertSafeTargetProfile, assertDisjointProfiles, assertChromiumClosed, assertFirefoxClosed, chromiumLaunchProfileOptions}=require('./profile_safety.cjs'); function assertProfileDirectory(value) { if(typeof value!=='string'||!/^[\w. -]+$/.test(value)||value==='.'||value==='..')throw Error('Invalid Chromium profile directory name'); return value; @@ -12,6 +12,7 @@ async function transfer({sourceProfile,targetProfile,browserPath,profileDirector const target=assertSafeTargetProfile(targetProfile, 'Chromium user-data-dir'); if(!fs.existsSync(source)||!fs.existsSync(browserPath))throw Error('Source or browser missing'); if(source===target)throw Error('Source and destination profiles must differ'); + assertDisjointProfiles(source, target); assertProfileDirectory(profileDirectory); assertFirefoxClosed(source); assertChromiumClosed(target); @@ -19,8 +20,17 @@ async function transfer({sourceProfile,targetProfile,browserPath,profileDirector encoding:'utf8',maxBuffer:32*1024*1024,timeout:20000,stdio:['ignore','pipe','pipe']}); if(p.status!==0)throw Error('Cookie decoding failed; no destination modifications'); const parsed=JSON.parse(p.stdout);p.stdout=''; - let puppeteer=require('puppeteer-core'),browser; + let puppeteer=require('puppeteer-core'),browser=null; const result={candidate:parsed.cookies.length,skipped:parsed.skipped,accepted:0,failed:0}; + // Ctrl-C during the import would otherwise leave a stale SingletonLock and a + // partially written cookie store. Kill the child we started and drop its lock. + const cleanupOnSignal=()=>{ + try{browser?.process?.()?.kill?.('SIGKILL');}catch{} + try{fs.rmSync(path.join(target,'SingletonLock'),{force:true});}catch{} + process.exit(130); + }; + process.once('SIGINT',cleanupOnSignal); + process.once('SIGTERM',cleanupOnSignal); try{ browser=await puppeteer.launch({executablePath:browserPath,userDataDir:target,headless:true, ...chromiumLaunchProfileOptions(target), @@ -32,7 +42,11 @@ async function transfer({sourceProfile,targetProfile,browserPath,profileDirector if(success)result.accepted++;else result.failed++; }catch(e){result.failed++;} } - }finally{if(browser)await browser.close();} + }finally{ + process.removeListener('SIGINT',cleanupOnSignal); + process.removeListener('SIGTERM',cleanupOnSignal); + try{if(browser)await browser.close();}catch{} + } return result; } if(require.main===module){ diff --git a/tools/chromium_localstorage_import.cjs b/tools/chromium_localstorage_import.cjs index 13392e1..db58738 100644 --- a/tools/chromium_localstorage_import.cjs +++ b/tools/chromium_localstorage_import.cjs @@ -71,8 +71,12 @@ async function passphrasePrompt() { async function readPassphrase(stdinFlag) { if (!stdinFlag) return passphrasePrompt(); - const chunks=[]; - for await(const c of process.stdin) chunks.push(c); + const chunks=[]; let total=0; + for await(const chunk of process.stdin){ + total+=chunk.length; + if(total>1024*1024) throw Error('Passphrase input too large'); + chunks.push(chunk); + } const value=Buffer.concat(chunks).toString('utf8').replace(/\r?\n$/, ''); if (!value) throw Error('Empty passphrase from standard input'); return value; @@ -166,15 +170,30 @@ async function run(opts) { if(!fs.existsSync(opts.browser))throw Error('Browser executable not found'); let puppeteer; try{puppeteer=require('puppeteer-core');}catch{try{puppeteer=require('puppeteer');}catch{throw Error('Install puppeteer-core locally (npm i --no-save puppeteer-core)');}} - // Never start with a personal profile unless explicitly specified by the operator. - // Keep Chrome sandbox enabled; do not pass --no-sandbox. - const browser=await puppeteer.launch({executablePath:path.resolve(opts.browser),userDataDir:profile, - headless:true,defaultViewport:{width:600,height:400},...chromiumLaunchProfileOptions(profile), - args:['--profile-directory='+opts.profileDirectory,'--no-first-run','--no-default-browser-check', - '--disable-background-networking','--disable-sync','--disable-extensions','--disable-features=MediaRouter']}); + let browser=null; + // Ctrl-C during --apply would otherwise leave a stale SingletonLock (and a + // partially imported profile). Kill the child we started and drop its lock. + const cleanupOnSignal=()=>{ + try{browser?.process?.()?.kill?.('SIGKILL');}catch{} + try{fs.rmSync(path.join(profile,'SingletonLock'),{force:true});}catch{} + process.exit(130); + }; + process.once('SIGINT',cleanupOnSignal); + process.once('SIGTERM',cleanupOnSignal); let result; - try {result=await restoreSites(browser,sites,opts.timeout);} - finally {await browser.close();} + try { + // Never start with a personal profile unless explicitly specified by the operator. + // Keep Chrome sandbox enabled; do not pass --no-sandbox. + browser=await puppeteer.launch({executablePath:path.resolve(opts.browser),userDataDir:profile, + headless:true,defaultViewport:{width:600,height:400},...chromiumLaunchProfileOptions(profile), + args:['--profile-directory='+opts.profileDirectory,'--no-first-run','--no-default-browser-check', + '--disable-background-networking','--disable-sync','--disable-extensions','--disable-features=MediaRouter']}); + result=await restoreSites(browser,sites,opts.timeout); + } finally { + process.removeListener('SIGINT',cleanupOnSignal); + process.removeListener('SIGTERM',cleanupOnSignal); + try{if(browser)await browser.close();}catch{} + } console.log(`Imported ${result.imported}/${sites.length} origins and ${result.keys} keys; skipped ${result.skipped}.`); if(result.errors.length)console.log('Skipped (index and reason; no credentials):',JSON.stringify(result.errors)); if(result.skipped)process.exitCode=2; diff --git a/tools/firefox_localstorage.py b/tools/firefox_localstorage.py index 06dc6ee..bad7b87 100644 --- a/tools/firefox_localstorage.py +++ b/tools/firefox_localstorage.py @@ -12,6 +12,7 @@ from contextlib import closing import json import os from pathlib import Path +import re import sqlite3 import subprocess import sys @@ -129,15 +130,45 @@ def valid_origin(origin: str) -> bool: return normalize_origin(origin) is not None +def firefox_lock_path(profile: Path): + for name in ('.parentlock', 'lock'): + candidate = profile / name + try: + os.lstat(candidate) + except OSError: + continue + return candidate + return None + + def firefox_profile_in_use(profile: Path) -> bool: """Detect a Firefox process holding this profile's lock file open. Existence of .parentlock is not enough because a crash can leave a stale lock behind; /proc exposes the open descriptors of the running Firefox. + Old macOS/BSD Firefox uses a `lock` symlink such as "host:1234", so fall + back to checking that PID if the link has no resolvable target. """ - lock = profile / '.parentlock' - if not lock.exists(): + lock = firefox_lock_path(profile) + if lock is None: return False + if not os.path.exists(lock): + # Dangling legacy `lock` symlink ("host:pid"). Path.resolve() does not + # raise for it, so inspect the link target directly and check the PID. + try: + raw = os.readlink(lock) + except OSError: + return False + match = re.search(r':(\d+)$', raw) + if not match: + return False + try: + os.kill(int(match.group(1)), 0) + except ProcessLookupError: + return False + except PermissionError: + return True + return True try: target = str(lock.resolve()) except OSError: diff --git a/tools/indexeddb_codec.js b/tools/indexeddb_codec.js index 85a5565..ed3294d 100644 --- a/tools/indexeddb_codec.js +++ b/tools/indexeddb_codec.js @@ -1,6 +1,10 @@ /* Portable, lossless subset of IndexedDB structured-clone values. Unsupported types and cyclic/shared references are refused, never silently discarded. */ 'use strict'; +const MAX_BINARY_BYTES = 8 * 1024 * 1024; +function assertBinaryLimit(bytes, label) { + if (bytes > MAX_BINARY_BYTES) throw new Error(label + ' larger than 8 MiB migration limit'); +} async function encode(value, seen = new WeakSet()) { if (value === null) return {t:'null'}; const typ = typeof value; @@ -13,13 +17,17 @@ async function encode(value, seen = new WeakSet()) { seen.add(value); if(value instanceof Date) return {t:'date',v:Number.isNaN(value.getTime())?'NaN':value.getTime()}; if(value instanceof RegExp) return {t:'regexp',s:value.source,f:value.flags}; - if(value instanceof ArrayBuffer) return {t:'buffer',v:Array.from(new Uint8Array(value))}; + if(value instanceof ArrayBuffer){ + assertBinaryLimit(value.byteLength,'ArrayBuffer'); + return {t:'buffer',v:Array.from(new Uint8Array(value))}; + } if(ArrayBuffer.isView(value)) { + assertBinaryLimit(value.byteLength,value.constructor.name); if (value instanceof DataView) return {t:'dataview',v:Array.from(new Uint8Array(value.buffer,value.byteOffset,value.byteLength))}; return {t:'typedarray',type:value.constructor.name,v:Array.from(new Uint8Array(value.buffer,value.byteOffset,value.byteLength))}; } if(typeof Blob !== 'undefined' && value instanceof Blob){ - if(value.size>8*1024*1024)throw new Error('Blob larger than 8 MiB migration limit'); + assertBinaryLimit(value.size, value instanceof File ? 'File' : 'Blob'); const v=Array.from(new Uint8Array(await value.arrayBuffer())); if(typeof File !== 'undefined' && value instanceof File)return {t:'file',v,name:value.name,mime:value.type,lastModified:value.lastModified}; return {t:'blob',v,mime:value.type}; diff --git a/tools/indexeddb_migrate.cjs b/tools/indexeddb_migrate.cjs index edea363..61b4570 100644 --- a/tools/indexeddb_migrate.cjs +++ b/tools/indexeddb_migrate.cjs @@ -10,7 +10,7 @@ const path = require('node:path'); const os = require('node:os'); const cp = require('node:child_process'); const {validOrigin} = require('./chromium_localstorage_import.cjs'); -const {assertSafeTargetProfile, assertChromiumClosed, assertFirefoxClosed, chromiumLaunchProfileOptions} = require('./profile_safety.cjs'); +const {assertSafeTargetProfile, assertDisjointProfiles, cloneFirefoxProfile, assertChromiumClosed, assertFirefoxClosed, chromiumLaunchProfileOptions} = require('./profile_safety.cjs'); function options(argv) { const o={apply:false,timeout:20000}; @@ -72,6 +72,7 @@ async function snapshotOrigin(page) { r.onblocked=()=>reject(Error('IndexedDB open blocked')); }); const dump={name:db.name,version:db.version,stores:[]}; + let encodedChars=0; for (const storeName of Array.from(db.objectStoreNames)) { const tx=db.transaction(storeName,'readonly'); const store=tx.objectStore(storeName); @@ -79,7 +80,9 @@ async function snapshotOrigin(page) { indexes:Array.from(store.indexNames,n=>{ const ix=store.index(n);return {name:ix.name,keyPath:ix.keyPath,unique:ix.unique,multiEntry:ix.multiEntry}; }),records:[]}; - // Cap retrieval at 50,001 entries; never materialize unbounded stores. + // Cap retrieval at 50,001 entries. Individual binary values are + // capped in the codec before they are expanded into number arrays, + // and the encoded budget below stops oversized databases early. const values=await new Promise((resolve,reject)=>{ const req=store.getAll(undefined,50001);req.onsuccess=()=>resolve(req.result);req.onerror=()=>reject(req.error); }); @@ -90,7 +93,13 @@ async function snapshotOrigin(page) { }); if(keys.length!==values.length)throw Error('Key/value length mismatch'); if(values.length>50000)throw Error('Store has over 50000 records (migration safety limit)'); - for(let j=0;j32*1024*1024)throw Error('Database over 32 MiB encoded transport limit'); + schema.records.push([encodedKey,encodedValue]); + } dump.stores.push(schema); } if(JSON.stringify(dump).length>32*1024*1024)throw Error('Database over 32 MiB transport limit'); @@ -198,10 +207,9 @@ async function migrate(opts) { // Resolve symlinks: cp -a would otherwise copy a symlink of the source // profile and Firefox would be launched against the original profile. const fx=realDirectory(opts.firefoxProfile, 'Firefox source profile'); - const targetCandidate=path.resolve(opts.chromiumProfile); - const target=fs.existsSync(targetCandidate)?fs.realpathSync(targetCandidate):targetCandidate; + const target=assertSafeTargetProfile(opts.chromiumProfile, 'Chromium user-data-dir'); if(target===fx)throw Error('Source and destination profiles must differ'); - assertSafeTargetProfile(target, 'Chromium user-data-dir'); + assertDisjointProfiles(fx, target); assertFirefoxClosed(fx); const origins=originsForFirefox(fx); console.log(`Firefox IndexedDB inventory: ${origins.length} first-party origin(s); container/partitioned origins intentionally excluded.`); @@ -217,7 +225,7 @@ async function migrate(opts) { // Do NOT launch Firefox against the original profile, which would modify it. let fb,cb;const stats={origins:origins.length,restored:0,skipped:0,sourceSkipped:0,errors:[]}; try { - cp.execFileSync('cp',['-a','--reflink=auto',fx,clone],{timeout:120000}); + cloneFirefoxProfile(fx,clone); const pp=require('puppeteer-core'); fb=await pp.launch({browser:'firefox',protocol:'webDriverBiDi',executablePath:opts.firefox, userDataDir:clone,headless:true,timeout:20000, diff --git a/tools/list_firefox_idb_origins.py b/tools/list_firefox_idb_origins.py index 0d2a868..238c07f 100644 --- a/tools/list_firefox_idb_origins.py +++ b/tools/list_firefox_idb_origins.py @@ -5,7 +5,8 @@ import sqlite3 import sys from contextlib import closing from pathlib import Path -from urllib.parse import urlsplit + +from firefox_localstorage import normalize_origin def list_origins(profile): @@ -15,14 +16,13 @@ def list_origins(profile): result = [] with closing(sqlite3.connect(db.as_uri() + '?mode=ro', uri=True, timeout=5)) as connection: for origin, usage in connection.execute('SELECT origin, client_usages FROM origin'): - if not origin or '^' in origin or not isinstance(usage, str) or 'I' not in usage: + if not origin or not isinstance(usage, str) or 'I' not in usage: continue # no privileged schemes or origin-attribute partition flattening - try: - u = urlsplit(origin) - if u.scheme in ('http','https') and u.hostname and u.path in ('','/') and not u.username and not u.password: - result.append(origin.rstrip('/')) - except ValueError: - pass + # Share the LocalStorage exporter's canonicalisation so a stray + # uppercase/default-port origin cannot fail the whole run later. + normalized = normalize_origin(origin) + if normalized: + result.append(normalized) return sorted(set(result)) diff --git a/tools/profile_safety.cjs b/tools/profile_safety.cjs index caecd81..f5a6df9 100644 --- a/tools/profile_safety.cjs +++ b/tools/profile_safety.cjs @@ -9,8 +9,21 @@ const cp = require('node:child_process'); const FIREFOX_MARKERS = ['prefs.js', 'places.sqlite', 'cookies.sqlite', 'storage.sqlite']; -function assertSafeTargetProfile(directory, label = 'Chromium profile') { +// Resolve a target path as far as it exists. Existing symlinks are followed so +// that a link to `/` or the home directory cannot bypass the guard below; for a +// not-yet-created directory, the parent symlinks are resolved instead. +function resolveForSafety(directory) { const resolved = path.resolve(directory); + try { + if (fs.existsSync(resolved)) return fs.realpathSync(resolved); + const parent = path.dirname(resolved); + if (fs.existsSync(parent)) return path.join(fs.realpathSync(parent), path.basename(resolved)); + } catch { /* fall through to the lexical path */ } + return resolved; +} + +function assertSafeTargetProfile(directory, label = 'Chromium profile') { + const resolved = resolveForSafety(directory); if (resolved === '/' || resolved === os.homedir()) { throw new Error(`Refusing to use root or home as ${label}: ${resolved}`); } @@ -22,6 +35,50 @@ function assertSafeTargetProfile(directory, label = 'Chromium profile') { return resolved; } +function findSymlinks(directory, root = directory, found = []) { + for (const entry of fs.readdirSync(directory, {withFileTypes: true})) { + const full = path.join(directory, entry.name); + if (entry.isSymbolicLink()) found.push(path.relative(root, full)); + else if (entry.isDirectory()) findSymlinks(full, root, found); + } + return found; +} + +// Copying a profile that contains symlinks is dangerous: `cp -a` preserves +// them, so the clone can point back at the original profile or outside the +// scratch directory. Reflink-copy first (fast), drop Firefox's stale lock +// markers, then refuse any remaining symlink so Firefox can only write inside +// the disposable clone. Users with symlinked storage can copy the profile to a +// regular directory first. +function cloneFirefoxProfile(source, destination) { + cp.execFileSync('cp', + ['-a', '--reflink=auto', source, destination], + {timeout: 120000}); + for (const name of ['.parentlock', 'lock']) { + try { fs.rmSync(path.join(destination, name), {force: true}); } catch {} + } + const symlinks = findSymlinks(destination); + if (symlinks.length) { + throw new Error(`Firefox profile contains symlinks (${symlinks.slice(0, 5).join(', ')}); ` + + 'copy the profile to a regular directory before IndexedDB migration so the source cannot be modified'); + } +} + +// Two profiles must not contain each other, otherwise Chromium can write into +// the Firefox source (or vice versa) despite both paths being individually safe. +function assertDisjointProfiles(source, target, label = 'Chromium user-data-dir') { + const inside = (parent, child) => { + const relative = path.relative(parent, child); + return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative)); + }; + if (inside(source, target)) { + throw new Error(`Refusing overlapping profiles: ${label} is inside the Firefox source profile: ${target}`); + } + if (inside(target, source)) { + throw new Error(`Refusing overlapping profiles: Firefox source profile is inside ${label}: ${source}`); + } +} + const CHROMIUM_KEYRING_DEFAULT_ARGS = ['--password-store=basic', '--use-mock-keychain']; // Puppeteer forces --password-store=basic, which encrypts cookies with the @@ -60,7 +117,19 @@ function firefoxLockPath(profile) { // existence alone is not enough because a crash can leave a stale lock behind. function isLockHeld(lockPath) { let target; - try { target = fs.realpathSync(lockPath); } catch { return false; } + try { + target = fs.realpathSync(lockPath); + } catch { + // macOS/BSD Firefox uses `lock`, a symlink such as "host:1234", rather + // than an open file descriptor. Fall back to checking that PID. + try { + const match = /:([0-9]+)$/.exec(fs.readlinkSync(lockPath)); + if (match) { + try { process.kill(Number(match[1]), 0); return true; } catch { return false; } + } + } catch { /* not a symlink */ } + return false; + } if (fs.existsSync('/proc')) { for (const pid of fs.readdirSync('/proc')) { if (!/^\d+$/.test(pid)) continue; @@ -92,4 +161,4 @@ function assertFirefoxClosed(profile) { return lockPath; } -module.exports = {assertSafeTargetProfile, chromiumLaunchProfileOptions, chromiumLockPath, assertChromiumClosed, firefoxLockPath, isLockHeld, assertFirefoxClosed}; +module.exports = {assertSafeTargetProfile, assertDisjointProfiles, cloneFirefoxProfile, chromiumLaunchProfileOptions, chromiumLockPath, assertChromiumClosed, firefoxLockPath, isLockHeld, assertFirefoxClosed};