From 7fb8ef750975d2c8cdef318ff23c0967265c2b1e Mon Sep 17 00:00:00 2001 From: souta <109493063+souta-lab@users.noreply.github.com> Date: Fri, 23 Oct 2026 20:54:18 +0900 Subject: [PATCH] audit: fix cookie expiry/partition fidelity and profile-safety gaps - Cookie stream: moz_cookies.expiry is milliseconds, but CDP expects seconds. The old code imported 52 already-expired cookies in the real profile and gave every remaining cookie a ~55,000-year expiry; convert units before comparing/sending, and skip session cookies that cannot survive the temporary Chromium session. - Dashboard cookies: request partitionKey:{} for Chrome as well as Firefox (Chrome also omits CHIPS cookies otherwise), keep hasCrossSiteAncestor, omit the "unspecified" SameSite attribute for older targets, and never fall back to an arbitrary cookie store when importing. - Profile safety: resolve symlinks before cp -a (a symlinked --firefox-profile was copied as a symlink and Firefox then opened the original profile), detect Chromium's dangling SingletonLock symlink with lstat, check Firefox's .parentlock/open descriptors via /proc instead of an optional fuser, refuse Firefox-looking Chromium targets and root/home, keep the OS password store for existing Chromium profiles, and clean the sensitive profile clone on SIGINT/SIGTERM. - Exporter: never write through a dangling output symlink (O_EXCL|O_NOFOLLOW), refuse to export while Firefox holds the profile lock, and canonicalise origins so one odd origin cannot make the importer reject the whole bundle. - Revert formatting-only manifest changes; align tools/README with the code (IndexedDB is supported, Node.js 22.12+, lock/symlink/password-store and key-generator limitations) and add regression tests for all of the above. --- .github/workflows/tests.yml | 28 ++-- README.md | 6 +- chrome/dashboard.js | 47 ++++-- chrome/manifest.json | 4 +- firefox/dashboard.js | 47 ++++-- firefox/manifest.json | 14 +- tests/e2e_chrome.cjs | 29 +++- tests/e2e_cookie_cli.cjs | 89 +++++++++--- tests/e2e_cross_browser.cjs | 4 +- tests/e2e_indexeddb.cjs | 10 +- tests/e2e_offline_import.cjs | 8 +- tests/test_firefox_cookie_stream.py | 73 ++++++++++ tests/test_firefox_localstorage.py | 190 +++++++++++++++++++++---- tests/test_indexeddb_paths.cjs | 72 ++++++++++ tests/test_profile_safety.cjs | 79 ++++++++++ tests/test_storage_browser.cjs | 140 ++++++++++++++---- tools/README.md | 66 ++++++--- tools/chromium_cookie_import.cjs | 26 ++-- tools/chromium_localstorage_import.cjs | 9 +- tools/firefox_cookie_stream.py | 21 ++- tools/firefox_localstorage.py | 101 +++++++++++-- tools/indexeddb_migrate.cjs | 66 ++++++--- tools/list_firefox_idb_origins.py | 3 +- tools/package-lock.json | 2 +- tools/package.json | 2 +- tools/profile_safety.cjs | 95 +++++++++++++ 26 files changed, 1021 insertions(+), 210 deletions(-) create mode 100644 tests/test_firefox_cookie_stream.py create mode 100644 tests/test_indexeddb_paths.cjs create mode 100644 tests/test_profile_safety.cjs create mode 100644 tools/profile_safety.cjs diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 36ad0d7..6cb2a07 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,8 +1,10 @@ name: Unit tests on: push: - branches: [main, feat/profile-storage-migration] + branches: [main] pull_request: +permissions: + contents: read jobs: test: runs-on: ubuntu-latest @@ -14,24 +16,26 @@ jobs: - uses: actions/setup-node@v4 with: node-version: '22' + - name: Python dependencies + run: python3 -m pip install cryptography - name: Python tests run: python3 -m unittest discover -s tests -p 'test_*.py' - name: Browser API mock tests run: node tests/test_storage_browser.cjs + - name: Profile safety tests + run: node tests/test_profile_safety.cjs - name: IndexedDB codec tests run: node tests/test_indexeddb_codec.cjs + - name: IndexedDB path tests + run: node tests/test_indexeddb_paths.cjs - name: Python syntax - run: python3 -m py_compile tools/list_firefox_idb_origins.py tools/firefox_localstorage.py tools/firefox_cookie_stream.py + run: python3 -m py_compile tools/*.py tests/*.py - name: JavaScript syntax run: | - node --check chrome/dashboard.js - node --check firefox/dashboard.js - node --check tools/chromium_localstorage_import.cjs - node --check tests/e2e_cross_browser.cjs - node --check tools/indexeddb_migrate.cjs - node --check tools/indexeddb_codec.js - node --check tests/e2e_indexeddb.cjs - node --check tools/chromium_cookie_import.cjs - node --check tests/e2e_cookie_cli.cjs + for file in tools/*.cjs tools/*.js tests/*.cjs chrome/dashboard.js firefox/dashboard.js; do + node --check "$file" + done - name: CLI help - run: node tools/chromium_localstorage_import.cjs --help + run: | + node tools/chromium_localstorage_import.cjs --help + node tools/indexeddb_migrate.cjs --help diff --git a/README.md b/README.md index 1cf1528..e955206 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ Passwords and autofill data are completely walled off from extension APIs. You w ## Privacy & Security Model -* **Zero telemetry:** Everything runs entirely on your local machine. No network requests are ever made. +* **Zero telemetry:** Everything runs entirely on your local machine. The extension makes no network requests. The experimental profile helpers in `tools/` also run locally, but they launch a browser and cannot guarantee zero browser background traffic (see the caveat in [tools/README.md](tools/README.md)). * **Memory only:** Portage holds your data in the active page's memory and wipes it completely as soon as you export, import, or close the tab. * **Handle with care:** Your export bundle contains live session cookies. Treat this file exactly like an exported password vault. Keep it local, import it, and delete it immediately. * **No deduplication:** Importing the exact same file twice will duplicate your history and cookies. Just run it once and verify. @@ -66,8 +66,8 @@ Check the releases tab of the repo, or go to the website for Portage at: https:/ ## Experimental: whole-profile Firefox LocalStorage transfer (Linux) -Optional Python + Node helpers can migrate **all compatible first-party origins**, not just open tabs, to a closed Chrome/Brave profile. Export is encrypted by default; import uses intercepted inert responses rather than contacting websites. See the [step-by-step CLI and privacy limitations](tools/README.md). This does **not** include IndexedDB or guarantee login-session preservation. +Optional Python + Node helpers can migrate **all compatible first-party origins**, not just open tabs, to a closed Chrome/Brave profile. Export is encrypted by default; import uses intercepted inert responses rather than contacting websites. See the [step-by-step CLI and privacy limitations](tools/README.md). Login-session preservation is **not guaranteed**: partitioned/container data is skipped and some sites re-authenticate for unrelated reasons. The offline cookie companion skips session and already-expired cookies. ### Experimental IndexedDB migration -The Linux companion now also supports **first-party IndexedDB** for Firefox → Chromium. It recreates database schemas, indexes, keys and supported Structured Clone data using Firefox/Chromium browser APIs, without loading live sites. Existing target IndexedDB databases are skipped to prevent accidental overwrites. **Back up both profiles before using `--apply`.** See [tools/README.md](tools/README.md#indexeddb-migration-experimental-firefox--chromebrave) for instructions, compatibility limits and tests. +The Linux companion also supports **first-party IndexedDB** for Firefox → Chromium. It recreates database schemas, indexes, keys and supported Structured Clone data using Firefox/Chromium browser APIs, without loading live sites. Existing target IndexedDB databases are skipped to prevent accidental overwrites. **Back up both profiles before using `--apply`.** See [tools/README.md](tools/README.md#indexeddb-migration-experimental-firefox--chromebrave) for instructions, compatibility limits and tests. diff --git a/chrome/dashboard.js b/chrome/dashboard.js index 3023acb..1fcc6c9 100644 --- a/chrome/dashboard.js +++ b/chrome/dashboard.js @@ -142,15 +142,19 @@ async function collectHistory() { return { data, count: data.length }; } async function collectCookies() { - // Firefox's default getAll({}) omits Total Cookie Protection partitions. - // Firefox accepts partitionKey:{} to return both partitioned and normal cookies. - // First-Party Isolation requires firstPartyDomain:null to include all domains. + // Both Chrome and Firefox omit partitioned (CHIPS / Total Cookie Protection) + // cookies unless a partitionKey filter is requested. An empty filter matches + // partitioned and unpartitioned cookies, so ask for both. + // Firefox additionally needs firstPartyDomain:null to include First-Party + // Isolation cookies. Each cookie store is queried separately because store + // IDs are browser-specific and isolated stores must not be merged. const stores = await api.cookies.getAllCookieStores(); const all = []; for (const store of stores) { - const query = { storeId: store.id }; - if (IS_FIREFOX) { query.partitionKey = {}; query.firstPartyDomain = null; } - all.push(...await api.cookies.getAll(query)); + const query = { storeId: store.id, partitionKey: {} }; + if (IS_FIREFOX) query.firstPartyDomain = null; + try { all.push(...await api.cookies.getAll(query)); } + catch { /* A store this context cannot read must not abort the whole scan. */ } } const data = all.map((c) => ({ name: c.name, value: c.value, domain: c.domain, path: c.path, @@ -227,24 +231,37 @@ function mapSameSite(s) { async function importCookies(items, onProg) { const total = items.length; let imported = 0, skipped = 0; // Store IDs are browser-specific. Only copy into the selected browser's - // default cookie store; isolated Firefox Containers are not safely mergeable. - const stores = await api.cookies.getAllCookieStores(); - const targetStore = stores.find((s) => s.id === (IS_FIREFOX ? "firefox-default" : "0")) || stores[0]; + // default cookie store; isolated Firefox Containers (and private/incognito + // stores) are not safely mergeable. Never fall back to an arbitrary store. + const defaultStoreId = IS_FIREFOX ? "firefox-default" : "0"; for (let i = 0; i < total; i++) { const c = items[i]; try { const host = (c.domain || "").replace(/^\./, ""); if (!host || (c.firstPartyDomain && !IS_FIREFOX)) { skipped++; continue; } // Do not silently collapse isolated container stores into one login. - if (c.storeId && c.storeId !== "firefox-default" && c.storeId !== "0" && c.storeId !== targetStore?.id) { skipped++; continue; } + if (c.storeId && c.storeId !== "firefox-default" && c.storeId !== "0" && c.storeId !== defaultStoreId) { skipped++; continue; } const url = (c.secure ? "https" : "http") + "://" + host + (c.path || "/"); - const d = { url, name: c.name, value: c.value, path: c.path || "/", secure: !!c.secure, httpOnly: !!c.httpOnly, sameSite: mapSameSite(c.sameSite) }; + const d = { url, name: c.name, value: c.value, path: c.path || "/", secure: !!c.secure, httpOnly: !!c.httpOnly }; + // Omitting sameSite has the same meaning as "unspecified" and avoids + // depending on that enum value being supported by older browsers. + const sameSite = mapSameSite(c.sameSite); + if (sameSite !== "unspecified") d.sameSite = sameSite; if (!c.hostOnly) d.domain = c.domain; if (!c.session && Number.isFinite(c.expirationDate)) d.expirationDate = c.expirationDate; - if (targetStore?.id) d.storeId = targetStore.id; - if (c.partitionKey?.topLevelSite) d.partitionKey = { topLevelSite: c.partitionKey.topLevelSite }; - // Firefox requires firstPartyDomain even for the default (empty) domain - // when First-Party Isolation is enabled. + d.storeId = defaultStoreId; + if (c.partitionKey?.topLevelSite) { + d.partitionKey = { topLevelSite: c.partitionKey.topLevelSite }; + // The ancestor bit changes which embedding contexts can read it; + // dropping it would move third-party cookies between partitions. + if (typeof c.partitionKey.hasCrossSiteAncestor === "boolean") { + d.partitionKey.hasCrossSiteAncestor = c.partitionKey.hasCrossSiteAncestor; + } + } + // Firefox's cookies.set rejects calls without firstPartyDomain when + // First-Party Isolation is enabled; pass the source value (or the default + // empty domain) so non-FPI imports keep working. FPI cookies arriving + // from Chrome are skipped above because their first-party context is lost. if (IS_FIREFOX) d.firstPartyDomain = c.firstPartyDomain || ""; if (await api.cookies.set(d)) imported++; else skipped++; } catch { skipped++; } diff --git a/chrome/manifest.json b/chrome/manifest.json index 2c6add4..7636bb9 100644 --- a/chrome/manifest.json +++ b/chrome/manifest.json @@ -13,9 +13,7 @@ "management", "readingList" ], - "host_permissions": [ - "" - ], + "host_permissions": [""], "action": { "default_popup": "popup.html", "default_title": "Portage", diff --git a/firefox/dashboard.js b/firefox/dashboard.js index 363ce84..f4f6786 100644 --- a/firefox/dashboard.js +++ b/firefox/dashboard.js @@ -145,15 +145,19 @@ async function collectHistory() { return { data, count: data.length }; } async function collectCookies() { - // Firefox's default getAll({}) omits Total Cookie Protection partitions. - // Firefox accepts partitionKey:{} to return both partitioned and normal cookies. - // First-Party Isolation requires firstPartyDomain:null to include all domains. + // Both Chrome and Firefox omit partitioned (CHIPS / Total Cookie Protection) + // cookies unless a partitionKey filter is requested. An empty filter matches + // partitioned and unpartitioned cookies, so ask for both. + // Firefox additionally needs firstPartyDomain:null to include First-Party + // Isolation cookies. Each cookie store is queried separately because store + // IDs are browser-specific and isolated stores must not be merged. const stores = await api.cookies.getAllCookieStores(); const all = []; for (const store of stores) { - const query = { storeId: store.id }; - if (IS_FIREFOX) { query.partitionKey = {}; query.firstPartyDomain = null; } - all.push(...await api.cookies.getAll(query)); + const query = { storeId: store.id, partitionKey: {} }; + if (IS_FIREFOX) query.firstPartyDomain = null; + try { all.push(...await api.cookies.getAll(query)); } + catch { /* A store this context cannot read must not abort the whole scan. */ } } const data = all.map((c) => ({ name: c.name, value: c.value, domain: c.domain, path: c.path, @@ -230,24 +234,37 @@ function mapSameSite(s) { async function importCookies(items, onProg) { const total = items.length; let imported = 0, skipped = 0; // Store IDs are browser-specific. Only copy into the selected browser's - // default cookie store; isolated Firefox Containers are not safely mergeable. - const stores = await api.cookies.getAllCookieStores(); - const targetStore = stores.find((s) => s.id === (IS_FIREFOX ? "firefox-default" : "0")) || stores[0]; + // default cookie store; isolated Firefox Containers (and private/incognito + // stores) are not safely mergeable. Never fall back to an arbitrary store. + const defaultStoreId = IS_FIREFOX ? "firefox-default" : "0"; for (let i = 0; i < total; i++) { const c = items[i]; try { const host = (c.domain || "").replace(/^\./, ""); if (!host || (c.firstPartyDomain && !IS_FIREFOX)) { skipped++; continue; } // Do not silently collapse isolated container stores into one login. - if (c.storeId && c.storeId !== "firefox-default" && c.storeId !== "0" && c.storeId !== targetStore?.id) { skipped++; continue; } + if (c.storeId && c.storeId !== "firefox-default" && c.storeId !== "0" && c.storeId !== defaultStoreId) { skipped++; continue; } const url = (c.secure ? "https" : "http") + "://" + host + (c.path || "/"); - const d = { url, name: c.name, value: c.value, path: c.path || "/", secure: !!c.secure, httpOnly: !!c.httpOnly, sameSite: mapSameSite(c.sameSite) }; + const d = { url, name: c.name, value: c.value, path: c.path || "/", secure: !!c.secure, httpOnly: !!c.httpOnly }; + // Omitting sameSite has the same meaning as "unspecified" and avoids + // depending on that enum value being supported by older browsers. + const sameSite = mapSameSite(c.sameSite); + if (sameSite !== "unspecified") d.sameSite = sameSite; if (!c.hostOnly) d.domain = c.domain; if (!c.session && Number.isFinite(c.expirationDate)) d.expirationDate = c.expirationDate; - if (targetStore?.id) d.storeId = targetStore.id; - if (c.partitionKey?.topLevelSite) d.partitionKey = { topLevelSite: c.partitionKey.topLevelSite }; - // Firefox requires firstPartyDomain even for the default (empty) domain - // when First-Party Isolation is enabled. + d.storeId = defaultStoreId; + if (c.partitionKey?.topLevelSite) { + d.partitionKey = { topLevelSite: c.partitionKey.topLevelSite }; + // The ancestor bit changes which embedding contexts can read it; + // dropping it would move third-party cookies between partitions. + if (typeof c.partitionKey.hasCrossSiteAncestor === "boolean") { + d.partitionKey.hasCrossSiteAncestor = c.partitionKey.hasCrossSiteAncestor; + } + } + // Firefox's cookies.set rejects calls without firstPartyDomain when + // First-Party Isolation is enabled; pass the source value (or the default + // empty domain) so non-FPI imports keep working. FPI cookies arriving + // from Chrome are skipped above because their first-party context is lost. if (IS_FIREFOX) d.firstPartyDomain = c.firstPartyDomain || ""; if (await api.cookies.set(d)) imported++; else skipped++; } catch { skipped++; } diff --git a/firefox/manifest.json b/firefox/manifest.json index 7fe066a..35b78c3 100644 --- a/firefox/manifest.json +++ b/firefox/manifest.json @@ -2,16 +2,14 @@ "manifest_version": 3, "name": "Portage", "version": "2.0.1", - "description": "Universal browser data swap. Export bookmarks, history, cookies, tabs and sessions to a portable JSON bundle, then import into any browser running Portage \u2014 Firefox to Chrome, or the same browser on a new machine. Also exports your add-on list as a reinstall checklist.", + "description": "Universal browser data swap. Export bookmarks, history, cookies, tabs and sessions to a portable JSON bundle, then import into any browser running Portage — Firefox to Chrome, or the same browser on a new machine. Also exports your add-on list as a reinstall checklist.", "homepage_url": "https://github.com/pvrzz/Portage/", "browser_specific_settings": { "gecko": { "id": "portage@local", "strict_min_version": "115.0", "data_collection_permissions": { - "required": [ - "none" - ] + "required": ["none"] } } }, @@ -23,9 +21,7 @@ "sessions", "management" ], - "host_permissions": [ - "" - ], + "host_permissions": [""], "action": { "default_popup": "popup.html", "default_title": "Portage", @@ -43,8 +39,6 @@ "128": "icons/icon128.png" }, "background": { - "scripts": [ - "background.js" - ] + "scripts": ["background.js"] } } diff --git a/tests/e2e_chrome.cjs b/tests/e2e_chrome.cjs index 9b326a3..dbc4e2a 100644 --- a/tests/e2e_chrome.cjs +++ b/tests/e2e_chrome.cjs @@ -42,7 +42,34 @@ async function main() { ],()=>{}), '127.0.0.1'); assert.equal(cookie.imported,1,JSON.stringify(cookie)); assert.equal((await page.cookies()).find(c=>c.name==='portage-test')?.value,'synthetic'); - console.log(`PASS actual Chrome ${await browser.version()}: synthetic cookie imported`); + // The dashboard must also *collect* partitioned (CHIPS) cookies; Chrome's + // getAllCookieStores()/getAll() omit them unless partitionKey is requested. + const collected = await ext.evaluate(async () => { + await chrome.cookies.set({url:'https://example.com/',name:'portage-partitioned',value:'p', + secure:true,sameSite:'no_restriction',partitionKey:{topLevelSite:'https://example.com'}}); + const result = await collectCookies(); + const partitioned = result.data.find((entry) => entry.name === 'portage-partitioned'); + return {count: result.count, partitionKey: partitioned?.partitionKey || null}; + }); + assert.equal(collected.partitionKey?.topLevelSite, 'https://example.com', + 'collectCookies() must include partitioned cookies'); + assert(collected.count >= 2); + // Importing a partitioned cookie must preserve the top-level site and the + // third-party ancestor bit; dropping either moves it between partitions. + const importedPartition = await ext.evaluate(async () => { + const result = await importCookies([{ + name:'portage-import-partitioned', value:'v', domain:'example.com', path:'/', hostOnly:true, + secure:true, sameSite:'no_restriction', + partitionKey:{topLevelSite:'https://example.com', hasCrossSiteAncestor:true}, + }], () => {}); + const cookies = await chrome.cookies.getAll({partitionKey:{}}); + const found = cookies.find((entry) => entry.name === 'portage-import-partitioned'); + return {result, partitionKey: found?.partitionKey || null}; + }); + assert.equal(importedPartition.result.imported, 1); + assert.equal(importedPartition.partitionKey?.topLevelSite, 'https://example.com'); + assert.equal(importedPartition.partitionKey?.hasCrossSiteAncestor, true); + console.log(`PASS actual Chrome ${await browser.version()}: cookie import/collect, partitioning and ancestor bit`); } finally { if(browser) await browser.close(); await new Promise(resolve=>server.close(resolve)); diff --git a/tests/e2e_cookie_cli.cjs b/tests/e2e_cookie_cli.cjs index d798f41..19244b6 100644 --- a/tests/e2e_cookie_cli.cjs +++ b/tests/e2e_cookie_cli.cjs @@ -1,22 +1,69 @@ 'use strict'; -const cp=require('node:child_process'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),assert=require('node:assert/strict'); -const {transfer}=require('../tools/chromium_cookie_import.cjs'); -const pp=require('../tools/node_modules/puppeteer-core'); -(async()=>{const root=fs.mkdtempSync(path.join(os.tmpdir(),'portage-cookie-cli-')); - const src=path.join(root,'firefox'),dst=path.join(root,'brave');fs.mkdirSync(src); - try{ - const code=`import sqlite3,sys; c=sqlite3.connect(sys.argv[1]);c.execute('CREATE TABLE moz_cookies (name TEXT,value TEXT,host TEXT,path TEXT,expiry INTEGER,isSecure INTEGER,isHttpOnly INTEGER,sameSite INTEGER,originAttributes TEXT)');c.executemany('INSERT INTO moz_cookies VALUES(?,?,?,?,?,?,?,?,?)',[ - ('hello','test-value','example.com','/',1999999999,1,1,1,''), - ('divided','test-value','example.org','/',1999999999,1,1,2,'^userContextId=1'), - ('invalid','test-value','example.org','/',1999999999,0,0,0,''), - ]);c.commit()`; - const p=cp.spawnSync('python3',['-c',code,path.join(src,'cookies.sqlite')],{encoding:'utf8'});assert.equal(p.status,0,p.stderr); - const result=await transfer({sourceProfile:src,targetProfile:dst,browserPath:'/usr/bin/brave-browser'}); - assert.equal(result.candidate,1);assert.equal(result.accepted,1);assert.equal(result.failed,0); - assert.equal(result.skipped.partitioned_or_containers,1);assert.equal(result.skipped.insecure_none,1); - const browser=await pp.launch({executablePath:'/usr/bin/brave-browser',userDataDir:dst,headless:true,args:['--disable-background-networking']}); - try{const page=await browser.newPage(),session=await page.createCDPSession();let r=await session.send('Storage.getCookies');assert(r.cookies.some(c=>c.name==='hello'&&c.httpOnly&&c.secure));} - finally{await browser.close()} - console.log('PASS native Brave cookie CLI: 1 persisted; unsafe/partitioned skipped'); - }finally{fs.rmSync(root,{recursive:true,force:true})} -})().catch(e=>{console.error(e.stack);process.exitCode=1}); +// Synthetic Firefox cookie DB -> CDP cookie import -> disposable Brave/Chrome +// profile. No real browser profile or cookie value is read or written. +const cp = require('node:child_process'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const assert = require('node:assert/strict'); +const {transfer} = require('../tools/chromium_cookie_import.cjs'); +let puppeteer; +try { puppeteer = require('../tools/node_modules/puppeteer-core'); } catch { puppeteer = require('puppeteer'); } + +const BROWSER = process.env.PORTAGE_TEST_BRAVE + || process.env.PORTAGE_TEST_COOKIE_BROWSER + || '/usr/bin/brave-browser'; + +(async () => { + if (!fs.existsSync(BROWSER)) { + console.log(`SKIP: browser not found at ${BROWSER}; set PORTAGE_TEST_BRAVE`); + return; + } + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'portage-cookie-cli-')); + const src = path.join(root, 'firefox'), dst = path.join(root, 'chromium'); + fs.mkdirSync(src); + const futureMs = Date.now() + 3600 * 1000; + const pastMs = Date.now() - 3600 * 1000; + try { + // moz_cookies.expiry is milliseconds since the epoch. The expired row and + // a seconds-based value would both have been imported by the old code. + const code = `import sqlite3,sys +c=sqlite3.connect(sys.argv[1]) +c.execute('CREATE TABLE moz_cookies (name TEXT,value TEXT,host TEXT,path TEXT,expiry INTEGER,isSecure INTEGER,isHttpOnly INTEGER,sameSite INTEGER,originAttributes TEXT)') +c.executemany('INSERT INTO moz_cookies VALUES(?,?,?,?,?,?,?,?,?)',[ + ('hello','test-value','example.com','/',${futureMs},1,1,1,''), + ('expired','test-value','example.com','/',${pastMs},1,0,1,''), + ('divided','test-value','example.org','/',${futureMs},1,1,2,'^userContextId=1'), + ('invalid','test-value','example.org','/',${futureMs},0,0,0,''), +]) +c.commit()`; + const created = cp.spawnSync('python3', ['-c', code, path.join(src, 'cookies.sqlite')], {encoding: 'utf8'}); + assert.equal(created.status, 0, created.stderr); + + const result = await transfer({sourceProfile: src, targetProfile: dst, browserPath: BROWSER}); + assert.equal(result.candidate, 1); + assert.equal(result.accepted, 1); + assert.equal(result.failed, 0); + assert.equal(result.skipped.partitioned_or_containers, 1); + assert.equal(result.skipped.expired, 1, 'expired milliseconds cookies must be excluded'); + assert.equal(result.skipped.insecure_none, 1); + + const browser = await puppeteer.launch({ + executablePath: BROWSER, userDataDir: dst, headless: true, args: ['--disable-background-networking'], + }); + try { + const page = await browser.newPage(); + const session = await page.createCDPSession(); + const stored = (await session.send('Storage.getCookies')).cookies; + const hello = stored.find((cookie) => cookie.name === 'hello'); + assert(hello && hello.httpOnly && hello.secure); + assert(Math.abs(hello.expires - futureMs / 1000) < 5, 'expiry must be stored in seconds'); + assert(!stored.some((cookie) => cookie.name === 'expired'), 'expired cookie must not be resurrected'); + } finally { + await browser.close(); + } + console.log('PASS native Chromium cookie CLI: expiry unit/expiry filtering, unsafe/partitioned skipped'); + } finally { + fs.rmSync(root, {recursive: true, force: true}); + } +})().catch((error) => { console.error(error.stack); process.exitCode = 1; }); diff --git a/tests/e2e_cross_browser.cjs b/tests/e2e_cross_browser.cjs index 4e74268..bb157bb 100644 --- a/tests/e2e_cross_browser.cjs +++ b/tests/e2e_cross_browser.cjs @@ -3,19 +3,21 @@ // Creates only disposable profiles and uses synthetic site values. 'use strict'; const CHROMIUM = process.env.PORTAGE_TEST_CHROMIUM || '/usr/bin/google-chrome'; +const FIREFOX = process.env.PORTAGE_TEST_FIREFOX || '/usr/local/bin/firefox'; const fs=require('node:fs'),os=require('node:os'),path=require('node:path'),http=require('node:http'); const assert=require('node:assert/strict'); const {spawn,spawnSync}=require('node:child_process'); let pp; try { pp = require('../tools/node_modules/puppeteer-core'); } catch { pp = require('puppeteer'); } const {decryptWrapper,validateBundle,restoreSites}=require('../tools/chromium_localstorage_import.cjs'); function fire(args) {return new Promise((resolve,reject)=>{ - let stderr='';const p=spawn('/usr/local/bin/firefox',args,{stdio:['ignore','ignore','pipe']}); + let stderr='';const p=spawn(FIREFOX,args,{stdio:['ignore','ignore','pipe']}); p.stderr.on('data',b=>{stderr+=b.toString()}); const kill=setTimeout(()=>{p.kill();reject(new Error('Firefox timeout'))},20000); p.on('error',e=>{clearTimeout(kill);reject(e)}); p.on('exit',code=>{clearTimeout(kill);if(code!==0)reject(new Error(`Firefox exited ${code}: ${stderr.slice(-500)}`));else resolve()}); });} async function main(){ + if(!fs.existsSync(FIREFOX)||!fs.existsSync(CHROMIUM)){console.log(`SKIP: Firefox/Chromium not found (PORTAGE_TEST_FIREFOX=${FIREFOX}, PORTAGE_TEST_CHROMIUM=${CHROMIUM})`);return;} const dir=fs.mkdtempSync(path.join(os.tmpdir(),'portage-cross-browser-')); const fx=path.join(dir,'firefox-profile'), chrome=path.join(dir,'chrome-profile'); fs.mkdirSync(fx);let requests=0; diff --git a/tests/e2e_indexeddb.cjs b/tests/e2e_indexeddb.cjs index 90f9745..296d63e 100644 --- a/tests/e2e_indexeddb.cjs +++ b/tests/e2e_indexeddb.cjs @@ -1,13 +1,15 @@ 'use strict'; const CHROMIUM = process.env.PORTAGE_TEST_CHROMIUM || '/usr/bin/google-chrome'; +const FIREFOX = process.env.PORTAGE_TEST_FIREFOX || '/usr/local/bin/firefox'; const assert=require('node:assert/strict'); const fs=require('node:fs'); const os=require('node:os'); const path=require('node:path'); const http=require('node:http'); -const pp=require('../tools/node_modules/puppeteer-core'); +let pp; try { pp = require('../tools/node_modules/puppeteer-core'); } catch { pp = require('puppeteer'); } const {migrate,originsForFirefox,inertPage,navigateOffline,restoreOrigin}=require('../tools/indexeddb_migrate.cjs'); async function main(){ + if(!fs.existsSync(FIREFOX)||!fs.existsSync(CHROMIUM)){console.log(`SKIP: Firefox/Chromium not found (PORTAGE_TEST_FIREFOX=${FIREFOX}, PORTAGE_TEST_CHROMIUM=${CHROMIUM})`);return;} const scratch=fs.mkdtempSync(path.join(os.tmpdir(),'portage-idb-test-')); const fx=path.join(scratch,'firefox'),chrome=path.join(scratch,'chrome'); const hits=[0,0]; @@ -16,7 +18,7 @@ async function main(){ const origins=servers.map(s=>`http://127.0.0.1:${s.address().port}`); let browser; try { - browser=await pp.launch({browser:'firefox',protocol:'webDriverBiDi',executablePath:'/usr/local/bin/firefox',userDataDir:fx,headless:true}); + browser=await pp.launch({browser:'firefox',protocol:'webDriverBiDi',executablePath:FIREFOX,userDataDir:fx,headless:true}); const page=await browser.newPage(); for(const [n,origin] of origins.entries()) { await page.goto(origin); @@ -48,7 +50,7 @@ async function main(){ await browser.close();browser=null; assert.deepEqual(originsForFirefox(fx),[...origins].sort()); const before=hits.slice(); - const stats=await migrate({firefoxProfile:fx,chromiumProfile:chrome,firefox:'/usr/local/bin/firefox',chromium:CHROMIUM,apply:true,timeout:20000}); + const stats=await migrate({firefoxProfile:fx,chromiumProfile:chrome,firefox:FIREFOX,chromium:CHROMIUM,apply:true,timeout:20000}); assert.equal(stats.restored,2,JSON.stringify(stats)); assert.deepEqual(hits,before,'IndexedDB migration must not access real origin'); browser=await pp.launch({executablePath:CHROMIUM,userDataDir:chrome,headless:true,args:['--disable-background-networking']}); @@ -91,7 +93,7 @@ async function main(){ await verify.close();await browser.close();browser=null; assert.deepEqual(hits,before,'No real site traffic including verification'); // Re-running must never overwrite existing destination IndexedDB databases. - const repeated=await migrate({firefoxProfile:fx,chromiumProfile:chrome,firefox:'/usr/local/bin/firefox',chromium:CHROMIUM,apply:true,timeout:20000}); + const repeated=await migrate({firefoxProfile:fx,chromiumProfile:chrome,firefox:FIREFOX,chromium:CHROMIUM,apply:true,timeout:20000}); assert.equal(repeated.restored,0);assert.equal(repeated.skipped,2); process.exitCode=undefined; console.log('PASS: Firefox 159 -> Chrome 156 indexedDB: 2 origins, schema, indexes, rich values, no target-site traffic'); diff --git a/tests/e2e_offline_import.cjs b/tests/e2e_offline_import.cjs index 4117819..5b3d9b3 100644 --- a/tests/e2e_offline_import.cjs +++ b/tests/e2e_offline_import.cjs @@ -16,11 +16,14 @@ async function main() { const dir=fs.mkdtempSync(path.join(os.tmpdir(),'portage-offline-e2e-')); const profile=path.join(dir,'profile'); const origin=`http://127.0.0.1:${server.address().port}`; - const bundle={portage:{format:'portage-bundle',version:1,source:'firefox'},data:{localStorage:[{origin,items:{token:'synthetic-value',a:'猫'}}]}}; + // A __proto__ key must survive as ordinary localStorage data, not mutate the + // bundle object. JSON.parse (unlike an object literal) creates an own property. + const items=JSON.parse('{"token":"synthetic-value","a":"猫","__proto__":"proto-value"}'); + const bundle={portage:{format:'portage-bundle',version:1,source:'firefox'},data:{localStorage:[{origin,items}]}}; const file=path.join(dir,'synthetic.portage.json'); fs.writeFileSync(file,JSON.stringify(bundle),{mode:0o600}); try { - assert.equal(validateBundle(bundle).totalKeys,2); + assert.equal(validateBundle(bundle).totalKeys,3); await run({bundle:file, userDataDir:profile, browser:CHROMIUM, profileDirectory:'Default', timeout:12000, apply:true}); assert.equal(hits,0,'Importer must NOT send a single request to the origin'); const browser=await puppeteer.launch({executablePath:CHROMIUM,headless:true,userDataDir:profile,args:['--no-sandbox','--disable-background-networking']}); @@ -29,6 +32,7 @@ async function main() { await page.goto(origin); assert.equal(await page.evaluate(()=>localStorage.getItem('token')),'synthetic-value'); assert.equal(await page.evaluate(()=>localStorage.getItem('a')),'猫'); + assert.equal(await page.evaluate(()=>localStorage.getItem('__proto__')),'proto-value'); } finally {await browser.close();} console.log('PASS Chrome offline LocalStorage restore: zero origin requests during import; persistent after restart'); } finally { diff --git a/tests/test_firefox_cookie_stream.py b/tests/test_firefox_cookie_stream.py new file mode 100644 index 0000000..250bf1d --- /dev/null +++ b/tests/test_firefox_cookie_stream.py @@ -0,0 +1,73 @@ +import sqlite3 +import sys +import tempfile +import time +import unittest +from contextlib import closing +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools')) +from firefox_cookie_stream import collect + + +class FirefoxCookieStreamTest(unittest.TestCase): + def _profile(self, root, rows): + profile = Path(root) / 'profile' + profile.mkdir() + with closing(sqlite3.connect(profile / 'cookies.sqlite')) as connection, connection: + connection.execute( + 'CREATE TABLE moz_cookies (name TEXT, value TEXT, host TEXT, path TEXT, ' + 'expiry INTEGER, isSecure INTEGER, isHttpOnly INTEGER, sameSite INTEGER, ' + 'originAttributes TEXT)' + ) + connection.executemany('INSERT INTO moz_cookies VALUES (?,?,?,?,?,?,?,?,?)', rows) + return profile + + def test_expiry_is_converted_from_milliseconds_and_unsafe_cookies_are_skipped(self): + now = time.time() + future_ms = int((now + 3600) * 1000) + past_ms = int((now - 3600) * 1000) + rows = [ + # Persistent, unspecified SameSite: included, expiry seconds. + ('future', 'v', 'example.com', '/', future_ms, 1, 1, 256, ''), + # Already expired: the old milliseconds-vs-seconds mix-up imported these. + ('expired', 'v', 'example.com', '/', past_ms, 1, 0, 256, ''), + # Session cookies cannot survive the importer closing Chromium. + ('session', 'v', 'example.com', '/', 0, 1, 0, 1, ''), + # SameSite=None (requires Secure) and Strict map to CDP names. + ('none_secure', 'v', 'example.com', '/', future_ms, 1, 0, 0, ''), + ('strict', 'v', 'example.com', '/', future_ms, 1, 0, 2, ''), + # Insecure SameSite=None is invalid and must be skipped. + ('insecure_none', 'v', 'example.com', '/', future_ms, 0, 0, 0, ''), + # Firefox containers/partitions carry non-empty originAttributes. + ('partitioned', 'v', 'example.com', '/', future_ms, 1, 0, 1, '^userContextId=1'), + # Malformed rows are skipped rather than forwarded to Chrome. + ('bad_host', 'v', '', '/', future_ms, 1, 0, 1, ''), + ('bad_path', 'v', 'example.com', 'not-a-path', future_ms, 1, 0, 1, ''), + ] + with tempfile.TemporaryDirectory() as root: + profile = self._profile(root, rows) + result = collect(profile) + + cookies = {cookie['name']: cookie for cookie in result['cookies']} + self.assertEqual(set(cookies), {'future', 'none_secure', 'strict'}) + self.assertAlmostEqual(cookies['future']['expires'], now + 3600, delta=2) + self.assertNotIn('sameSite', cookies['future']) + self.assertEqual(cookies['none_secure']['sameSite'], 'None') + self.assertEqual(cookies['strict']['sameSite'], 'Strict') + self.assertEqual(result['skipped'], { + 'partitioned_or_containers': 1, + 'expired': 1, + 'session': 1, + 'invalid': 2, + 'insecure_none': 1, + }) + + def test_missing_database_is_an_error(self): + with tempfile.TemporaryDirectory() as root: + with self.assertRaises(FileNotFoundError): + collect(Path(root) / 'missing-profile') + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_firefox_localstorage.py b/tests/test_firefox_localstorage.py index fd087f0..dcd50e8 100644 --- a/tests/test_firefox_localstorage.py +++ b/tests/test_firefox_localstorage.py @@ -1,14 +1,48 @@ +import base64 +import hashlib import json import os import sqlite3 -from pathlib import Path import subprocess import sys import tempfile +import time import unittest +from contextlib import closing +from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools')) -from firefox_localstorage import decode_value, export_profile, snappy_decode, valid_origin +from firefox_localstorage import ( + decode_value, export_profile, firefox_profile_in_use, normalize_origin, snappy_decode, valid_origin, +) + +try: + import cryptography # noqa: F401 (only needed for the encryption test) + HAVE_CRYPTOGRAPHY = True +except ImportError: + HAVE_CRYPTOGRAPHY = False + +SCRIPT = Path(__file__).resolve().parents[1] / 'tools' / 'firefox_localstorage.py' + + +def write_ls_origin(profile, directory_name, origin, items): + ls = Path(profile) / 'storage' / 'default' / directory_name / 'ls' + ls.mkdir(parents=True) + with closing(sqlite3.connect(ls / 'data.sqlite')) as con, con: + con.execute('CREATE TABLE "database" (origin TEXT)') + con.execute('INSERT INTO "database" VALUES (?)', (origin,)) + con.execute( + 'CREATE TABLE data (key TEXT, utf16_length INTEGER, conversion_type INTEGER, ' + 'compression_type INTEGER, last_access_time INTEGER, value BLOB)' + ) + for key, value in items.items(): + con.execute('INSERT INTO data VALUES (?,?,?,?,?,?)', (key, len(value), 1, 0, 0, value.encode())) + + +def make_profile(root): + profile = Path(root) / 'profile' + write_ls_origin(profile, 'https+++first.test', 'https://first.test', {'login': 'token-A'}) + return profile class FirefoxLocalStorageTest(unittest.TestCase): @@ -33,34 +67,136 @@ class FirefoxLocalStorageTest(unittest.TestCase): self.assertFalse(valid_origin('https://example.org/some/path')) self.assertFalse(valid_origin('javascript:alert(1)')) + def test_origin_normalization_matches_chromium_url_parser(self): + self.assertEqual(normalize_origin('HTTPS://Example.ORG:443/'), 'https://example.org') + self.assertEqual(normalize_origin('http://Example.org:80'), 'http://example.org') + self.assertEqual(normalize_origin('https://example.org:8443'), 'https://example.org:8443') + self.assertEqual(normalize_origin('https://[::1]:443'), 'https://[::1]') + self.assertIsNone(normalize_origin('https://例え.jp')) # Firefox stores punycode + self.assertIsNone(normalize_origin('https://example.org^userContextId=1')) + self.assertIsNone(normalize_origin('https://[::1')) + self.assertIsNone(normalize_origin('https://example.org:not-a-port')) + def test_export_all_offline_origins_and_permissions(self): with tempfile.TemporaryDirectory() as t: - p=Path(t) - for name, origin, value in [('https+++first.test','https://first.test','token-A'), ('https+++second.test','https://second.test','こんにちは')]: - d=p/'storage'/'default'/name/'ls' - d.mkdir(parents=True) - with sqlite3.connect(d/'data.sqlite') as con: - con.execute('CREATE TABLE "database" (origin TEXT)') - con.execute('INSERT INTO "database" VALUES (?)',(origin,)) - con.execute('CREATE TABLE data (key TEXT, utf16_length INTEGER, conversion_type INTEGER, compression_type INTEGER, last_access_time INTEGER, value BLOB)') - con.execute('INSERT INTO data VALUES (?,?,?,?,?,?)',('login',len(value),1,0,0,value.encode())) - con.close() - (p/'storage'/'default'/'idb-site'/'idb').mkdir(parents=True) - (p/'storage'/'default'/'idb-site'/'idb'/'1.sqlite').touch() - sites,warnings=export_profile(p) - self.assertEqual(len(sites),2) + p = Path(t) + write_ls_origin(p, 'https+++first.test', 'https://first.test', {'login': 'token-A'}) + write_ls_origin(p, 'https+++second.test', 'https://second.test', {'login': 'こんにちは'}) + (p / 'storage' / 'default' / 'idb-site' / 'idb').mkdir(parents=True) + (p / 'storage' / 'default' / 'idb-site' / 'idb' / '1.sqlite').touch() + sites, warnings = export_profile(p) + self.assertEqual(len(sites), 2) self.assertFalse(warnings) - self.assertEqual([s['origin'] for s in sites],['https://first.test','https://second.test']) - output=p/'export.portage.json' - script=Path(__file__).resolve().parents[1]/'tools'/'firefox_localstorage.py' - r=subprocess.run([sys.executable,str(script),'--profile',str(p),'--output',str(output),'--plaintext'],capture_output=True,text=True) - self.assertEqual(r.returncode,0,r.stderr) - self.assertEqual(os.stat(output).st_mode & 0o777,0o600) - parsed=json.loads(output.read_text()) - self.assertEqual(parsed['meta']['counts']['localStorage'],2) - self.assertEqual(parsed['meta']['unsupported']['indexedDBOrigins'],1) - self.assertEqual(len(parsed['data']['localStorage']),2) - self.assertNotEqual(subprocess.run([sys.executable,str(script),'--profile',str(p),'--output',str(output)],capture_output=True).returncode,0) + self.assertEqual([s['origin'] for s in sites], ['https://first.test', 'https://second.test']) + output = p / 'export.portage.json' + result = subprocess.run( + [sys.executable, str(SCRIPT), '--profile', str(p), '--output', str(output), '--plaintext'], + capture_output=True, text=True, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(os.stat(output).st_mode & 0o777, 0o600) + parsed = json.loads(output.read_text()) + self.assertEqual(parsed['meta']['counts']['localStorage'], 2) + self.assertEqual(parsed['meta']['unsupported']['indexedDBOrigins'], 1) + self.assertEqual(len(parsed['data']['localStorage']), 2) + # Existing output is never overwritten, even by the encrypted path. + self.assertNotEqual(subprocess.run( + [sys.executable, str(SCRIPT), '--profile', str(p), '--output', str(output)], + capture_output=True, + ).returncode, 0) + + def test_export_normalizes_duplicate_and_invalid_origins(self): + with tempfile.TemporaryDirectory() as t: + p = Path(t) + write_ls_origin(p, 'https+++upper.test', 'HTTPS://Upper.TEST:443/', {'k': 'v'}) + write_ls_origin(p, 'https+++canonical.test', 'https://upper.test', {'k': 'v'}) + write_ls_origin(p, 'https+++container.test', 'https://container.test^userContextId=1', {'k': 'v'}) + sites, warnings = export_profile(p) + self.assertEqual([s['origin'] for s in sites], ['https://upper.test']) + self.assertEqual(len(warnings), 2) + + def test_output_symlink_is_not_followed(self): + with tempfile.TemporaryDirectory() as t: + p = Path(t) + profile = make_profile(p) + victim = p / 'victim' + victim.mkdir() + output = p / 'export.portage.json' + os.symlink(victim / 'created.json', output) + result = subprocess.run( + [sys.executable, str(SCRIPT), '--profile', str(profile), '--output', str(output), '--plaintext'], + capture_output=True, text=True, + ) + self.assertNotEqual(result.returncode, 0) + self.assertFalse((victim / 'created.json').exists()) + self.assertTrue(output.is_symlink()) + + def test_firefox_lock_detection(self): + with tempfile.TemporaryDirectory() as t: + profile = make_profile(Path(t)) + self.assertFalse(firefox_profile_in_use(profile)) + lock = profile / '.parentlock' + lock.write_bytes(b'') + # A stale lock file alone does not count as a running profile. + self.assertFalse(firefox_profile_in_use(profile)) + descriptor = os.open(lock, os.O_RDONLY) + try: + self.assertTrue(firefox_profile_in_use(profile)) + finally: + os.close(descriptor) + self.assertFalse(firefox_profile_in_use(profile)) + + def test_cli_refuses_a_running_profile(self): + with tempfile.TemporaryDirectory() as t: + profile = make_profile(Path(t)) + output = Path(t) / 'export.portage.json' + lock = profile / '.parentlock' + lock.write_bytes(b'') + descriptor = os.open(lock, os.O_RDONLY) + try: + result = subprocess.run( + [sys.executable, str(SCRIPT), '--profile', str(profile), '--output', str(output), + '--plaintext'], + capture_output=True, text=True, + ) + finally: + os.close(descriptor) + self.assertNotEqual(result.returncode, 0) + self.assertIn('close Firefox', result.stderr) + self.assertFalse(output.exists()) + + @unittest.skipUnless(HAVE_CRYPTOGRAPHY, 'cryptography package is not installed') + def test_encrypted_export_roundtrip(self): + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + + passphrase = 'synthetic-passphrase-for-test-123' + with tempfile.TemporaryDirectory() as t: + p = Path(t) + profile = make_profile(p) + write_ls_origin(profile, 'https+++second.test', 'https://second.test', {'secret': 'secret-value-猫'}) + output = p / 'encrypted.portage.json' + result = subprocess.run( + [sys.executable, str(SCRIPT), '--profile', str(profile), '--output', str(output), + '--passphrase-stdin'], + input=passphrase + '\n', capture_output=True, text=True, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(os.stat(output).st_mode & 0o777, 0o600) + raw = output.read_text() + self.assertNotIn('secret-value', raw) + wrapper = json.loads(raw) + meta = wrapper['portage'] + self.assertEqual(meta['format'], 'portage-bundle-encrypted') + self.assertEqual(meta['iterations'], 250000) + key = hashlib.pbkdf2_hmac( + 'sha256', passphrase.encode(), base64.b64decode(meta['salt']), meta['iterations'], dklen=32, + ) + plaintext = AESGCM(key).decrypt( + base64.b64decode(meta['iv']), base64.b64decode(wrapper['ciphertext']), None, + ) + inner = json.loads(plaintext) + self.assertEqual(inner['meta']['counts']['localStorage'], 2) + self.assertEqual(inner['data']['localStorage'][1]['items']['secret'], 'secret-value-猫') if __name__ == '__main__': diff --git a/tests/test_indexeddb_paths.cjs b/tests/test_indexeddb_paths.cjs new file mode 100644 index 0000000..54ed329 --- /dev/null +++ b/tests/test_indexeddb_paths.cjs @@ -0,0 +1,72 @@ +'use strict'; +// Path/symlink handling for the IndexedDB tool. Runs in dry-run mode only, so +// no Firefox or Chromium executable is needed and no browser profile is touched. +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const {migrate, options} = require('../tools/indexeddb_migrate.cjs'); + +function createQuotaDatabase(profile) { + // Use the Python toolchain when node:sqlite is unavailable. + const script = `import sqlite3,sys\ncon=sqlite3.connect(sys.argv[1])\ncon.execute('CREATE TABLE origin (origin TEXT, client_usages TEXT)')\ncon.execute('INSERT INTO origin VALUES (?,?)', ('https://example.test','I1234'))\ncon.commit()\ncon.close()`; + const result = require('node:child_process').spawnSync('python3', ['-c', script, path.join(profile, 'storage.sqlite')], {encoding: 'utf8'}); + assert.equal(result.status, 0, result.stderr); +} + +async function main() { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'portage-idb-paths-')); + try { + const source = path.join(root, 'firefox-profile'); + const target = path.join(root, 'chromium-profile'); + fs.mkdirSync(source); + fs.mkdirSync(target); + createQuotaDatabase(source); + + // A symlinked --firefox-profile must be resolved before cp/browser launch; + // otherwise `cp -a` copies the symlink and Firefox opens the source profile. + const sourceLink = path.join(root, 'firefox-link'); + fs.symlinkSync(source, sourceLink); + const dry = await migrate({ + firefoxProfile: sourceLink, chromiumProfile: target, + firefox: path.join(root, 'missing-firefox'), chromium: path.join(root, 'missing-chromium'), + apply: false, + }); + assert.equal(dry.origins, 1); + + // A target that is a symlink to the source must be rejected, not silently + // used as the destination profile. + const targetLink = path.join(root, 'chromium-link'); + fs.symlinkSync(source, targetLink); + await assert.rejects(() => migrate({ + firefoxProfile: sourceLink, chromiumProfile: targetLink, + firefox: path.join(root, 'missing-firefox'), chromium: path.join(root, 'missing-chromium'), + apply: false, + }), /must differ|looks like a Firefox profile/); + + // A Firefox-looking Chromium target is refused before anything is written. + fs.writeFileSync(path.join(target, 'prefs.js'), ''); + await assert.rejects(() => migrate({ + firefoxProfile: source, chromiumProfile: target, + firefox: path.join(root, 'missing-firefox'), chromium: path.join(root, 'missing-chromium'), + apply: false, + }), /looks like a Firefox profile/); + + const parsed = options([ + '--firefox-profile', source, '--chromium-profile', target, + '--firefox', '/usr/bin/firefox', '--chromium', '/usr/bin/chromium', + '--chromium-profile-directory', 'Profile 1', + ]); + assert.equal(parsed.chromiumProfileDirectory, 'Profile 1'); + assert.throws(() => options([ + '--firefox-profile', source, '--chromium-profile', target, + '--firefox', '/usr/bin/firefox', '--chromium', '/usr/bin/chromium', + '--chromium-profile-directory', '../escape', + ]), /Invalid Chromium profile directory/); + console.log('PASS: IndexedDB path resolution, symlink and profile guards'); + } finally { + fs.rmSync(root, {recursive: true, force: true}); + } +} + +main().catch((error) => { console.error(error.stack); process.exitCode = 1; }); diff --git a/tests/test_profile_safety.cjs b/tests/test_profile_safety.cjs new file mode 100644 index 0000000..13876d6 --- /dev/null +++ b/tests/test_profile_safety.cjs @@ -0,0 +1,79 @@ +'use strict'; +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const cp = require('node:child_process'); +const {assertSafeTargetProfile, chromiumLaunchProfileOptions, chromiumLockPath, assertChromiumClosed, firefoxLockPath, isLockHeld, assertFirefoxClosed} = + require('../tools/profile_safety.cjs'); + +function waitFor(predicate, timeoutMs = 3000) { + const start = Date.now(); + return new Promise((resolve, reject) => { + const poll = () => { + if (predicate()) return resolve(); + if (Date.now() - start > timeoutMs) return reject(new Error('timed out waiting for lock state')); + setTimeout(poll, 25); + }; + poll(); + }); +} + +async function main() { + assert.throws(() => assertSafeTargetProfile('/'), /root or home/); + assert.throws(() => assertSafeTargetProfile(os.homedir()), /root or home/); + + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'portage-safety-')); + const firefoxProfile = path.join(root, 'firefox-profile'); + const chromiumProfile = path.join(root, 'chromium-profile'); + fs.mkdirSync(firefoxProfile); + fs.mkdirSync(chromiumProfile); + fs.writeFileSync(path.join(firefoxProfile, 'prefs.js'), ''); + try { + assert.throws(() => assertSafeTargetProfile(firefoxProfile), /looks like a Firefox profile/); + assert.equal(assertSafeTargetProfile(chromiumProfile), chromiumProfile); + assert.equal(assertSafeTargetProfile(path.join(root, 'not-created-yet')), + path.join(root, 'not-created-yet')); + // Fresh disposable profiles keep Puppeteer's --password-store=basic, while + // existing profiles must not be switched to the fallback cookie key store. + assert.deepEqual(chromiumLaunchProfileOptions(chromiumProfile), {}); + fs.mkdirSync(path.join(chromiumProfile, 'Default')); + assert.deepEqual(chromiumLaunchProfileOptions(chromiumProfile).ignoreDefaultArgs, + ['--password-store=basic', '--use-mock-keychain']); + + // Chrome's lock is a dangling symlink while the browser is running; + // existsSync() would miss it, so the helper must use lstat(). + assert.equal(chromiumLockPath(chromiumProfile), null); + assertChromiumClosed(chromiumProfile); + fs.symlinkSync('somehost-4242', path.join(chromiumProfile, 'SingletonLock')); + assert.equal(chromiumLockPath(chromiumProfile), path.join(chromiumProfile, 'SingletonLock')); + assert.throws(() => assertChromiumClosed(chromiumProfile), /SingletonLock present/); + fs.unlinkSync(path.join(chromiumProfile, 'SingletonLock')); + + // Stale lock file: exists but is not held open => the profile is closed. + const lock = firefoxLockPath(firefoxProfile); + // prefs.js is a marker, not a lock; add one. + fs.writeFileSync(path.join(firefoxProfile, '.parentlock'), ''); + assert.equal(firefoxLockPath(firefoxProfile), path.join(firefoxProfile, '.parentlock')); + assert.equal(isLockHeld(path.join(firefoxProfile, '.parentlock')), false); + assertFirefoxClosed(firefoxProfile); + + // A live process holding the lock file open must be detected. + const child = cp.spawn(process.execPath, ['-e', + "require('node:fs').openSync(process.argv[1], 'r'); setTimeout(() => {}, 15000);", + path.join(firefoxProfile, '.parentlock')], {stdio: 'ignore'}); + try { + await waitFor(() => isLockHeld(path.join(firefoxProfile, '.parentlock'))); + assert.throws(() => assertFirefoxClosed(firefoxProfile), /appears to be in use/); + } finally { + child.kill('SIGKILL'); + } + await waitFor(() => !isLockHeld(path.join(firefoxProfile, '.parentlock'))); + assertFirefoxClosed(firefoxProfile); + console.log('PASS: profile target and Firefox lock safety checks'); + } finally { + fs.rmSync(root, {recursive: true, force: true}); + } +} + +main().catch((error) => { console.error(error.stack); process.exitCode = 1; }); diff --git a/tests/test_storage_browser.cjs b/tests/test_storage_browser.cjs index 9500c3c..986c95c 100644 --- a/tests/test_storage_browser.cjs +++ b/tests/test_storage_browser.cjs @@ -1,33 +1,113 @@ 'use strict'; -const assert=require('node:assert/strict'),fs=require('node:fs'),vm=require('node:vm'); -const {validOrigin, validateBundle}=require('../tools/chromium_localstorage_import.cjs'); -for (const browser of ['chrome','firefox']) { - const src=fs.readFileSync(`${browser}/dashboard.js`,'utf8'); - const start=src.indexOf('function mapSameSite('); - const end=src.indexOf('async function importTabs(',start); - assert(start>0 && end>start); - const ctx=vm.createContext({URL,Number,Array,IS_FIREFOX:browser==='firefox',tick:async()=>{}}); - vm.runInContext(src.slice(start,end),ctx); - for(const s of ['strict','lax','no_restriction','unspecified']) { - assert.equal(ctx.mapSameSite(s),s); +// Exercises the dashboard's cookie collection/import code in a VM with mocked +// WebExtension APIs; no real browser profile is read or written. +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const vm = require('node:vm'); +const {validOrigin, validateBundle} = require('../tools/chromium_localstorage_import.cjs'); + +function browserContext(browser) { + const source = fs.readFileSync(`${browser}/dashboard.js`, 'utf8'); + const context = vm.createContext({ + URL, Number, Array, String, Object, IS_FIREFOX: browser === 'firefox', tick: async () => {}, + }); + for (const [startMarker, endMarker] of [ + ['async function collectCookies()', 'async function collectTabs()'], + ['function mapSameSite(s)', 'async function importTabs('], + ]) { + const start = source.indexOf(startMarker); + const end = source.indexOf(endMarker, start); + assert(start > 0 && end > start, `${browser}: missing ${startMarker}`); + vm.runInContext(source.slice(start, end), context); } - assert.equal(ctx.mapSameSite('unknown'),'unspecified'); - (async()=>{ - const written=[]; - ctx.api={cookies:{getAllCookieStores:async()=>[{id:browser==='firefox'?'firefox-default':'0'}],set:async d=>{written.push(d);return d;}}}; - const r=await ctx.importCookies([ - {name:'test',value:'value',domain:'example.com',path:'/',hostOnly:true,sameSite:'unspecified'}, - {name:'partition',value:'v',domain:'example.com',path:'/',hostOnly:true,sameSite:'lax',partitionKey:{topLevelSite:'https://site.test'}}, - {name:'container',domain:'example.org',storeId:'firefox-container-1',hostOnly:true}, - ],()=>{}); - assert.equal(r.imported,2);assert.equal(r.skipped,1); - assert.equal(written[0].sameSite,'unspecified'); - assert.equal(written[1].partitionKey.topLevelSite,'https://site.test'); - if(browser==='firefox')assert.equal(written[0].firstPartyDomain,''); - console.log(browser+': cookie import metadata and SameSite passed'); - })().catch(e=>{console.error(e);process.exitCode=1}); + return context; } -assert(validOrigin('https://example.org')); -assert(!validOrigin('javascript:foo')); -assert.throws(()=>validateBundle({portage:{format:'portage-bundle',version:1},data:{localStorage:[{origin:'https://example.org/path',items:{x:'y'}}]}})); -assert.throws(()=>validateBundle({portage:{format:'portage-bundle',version:1},data:{localStorage:[{origin:'https://example.org',items:{x:123}}]}})); + +async function main() { + for (const browser of ['chrome', 'firefox']) { + const firefox = browser === 'firefox'; + const context = browserContext(browser); + const defaultStoreId = firefox ? 'firefox-default' : '0'; + + for (const sameSite of ['strict', 'lax', 'no_restriction', 'unspecified']) { + assert.equal(context.mapSameSite(sameSite), sameSite); + } + assert.equal(context.mapSameSite(undefined), 'unspecified'); + assert.equal(context.mapSameSite('unknown'), 'unspecified'); + + // collectCookies: partitioned cookies must be requested explicitly for + // both browsers; a store that cannot be read must not abort the scan. + const queries = []; + context.api = { + cookies: { + getAllCookieStores: async () => [ + {id: defaultStoreId}, {id: firefox ? 'firefox-container-1' : '1'}, {id: 'unreadable-store'}, + ], + getAll: async (query) => { + queries.push({...query}); + if (query.storeId === 'unreadable-store') throw new Error('store is not accessible'); + return [{ + name: 'cookie-' + query.storeId, value: 'v', domain: 'example.com', path: '/', + secure: true, httpOnly: true, sameSite: 'lax', session: true, hostOnly: true, + storeId: query.storeId, partitionKey: {topLevelSite: 'https://top.test', hasCrossSiteAncestor: false}, + firstPartyDomain: firefox ? '' : undefined, + }]; + }, + }, + }; + const collected = await context.collectCookies(); + assert.equal(queries.length, 3); + for (const query of queries) { + assert.equal(Object.keys(query.partitionKey).length, 0, `${browser}: partitionKey filter missing`); + assert.equal(typeof query.storeId, 'string'); + if (firefox) assert.equal(query.firstPartyDomain, null); + else assert.equal('firstPartyDomain' in query, false, 'Chrome rejects unknown firstPartyDomain'); + } + assert.equal(collected.count, 2, `${browser}: unreadable store aborted collection`); + assert.equal(collected.data[0].partitionKey.topLevelSite, 'https://top.test'); + + // importCookies: only the browser default store is a valid target, and + // partitioned/FPI metadata must survive the conversion. + const written = []; + context.api = {cookies: {set: async (details) => { written.push(details); return details; }}}; + const result = await context.importCookies([ + {name: 'plain', value: 'v', domain: 'example.com', path: '/', hostOnly: true, sameSite: undefined}, + {name: 'partitioned', value: 'v', domain: 'example.com', path: '/', hostOnly: true, sameSite: 'lax', + partitionKey: {topLevelSite: 'https://top.test', hasCrossSiteAncestor: true}}, + {name: 'container', value: 'v', domain: 'example.com', path: '/', storeId: 'firefox-container-1'}, + {name: 'incognito', value: 'v', domain: 'example.com', path: '/', storeId: '1'}, + {name: 'fpi', value: 'v', domain: 'example.com', path: '/', firstPartyDomain: 'example.com'}, + ], () => {}); + const names = written.map((details) => details.name); + assert.equal(result.imported, firefox ? 3 : 2, `${browser}: unexpected import count`); + assert.equal(result.skipped, firefox ? 2 : 3, `${browser}: unexpected skip count`); + assert.deepEqual(names, firefox ? ['plain', 'partitioned', 'fpi'] : ['plain', 'partitioned']); + for (const details of written) assert.equal(details.storeId, defaultStoreId); + assert.equal('sameSite' in written[0], false, 'unspecified must omit the attribute'); + assert.equal(written.find((details) => details.name === 'partitioned').partitionKey.hasCrossSiteAncestor, true); + if (firefox) { + assert.equal(written[0].firstPartyDomain, ''); + assert.equal(written.find((details) => details.name === 'fpi').firstPartyDomain, 'example.com'); + } + console.log(`${browser}: cookie collect/import metadata, partitioning, SameSite passed`); + } + + assert(validOrigin('https://example.org')); + assert(!validOrigin('javascript:foo')); + assert.throws(() => validateBundle({portage: {format: 'portage-bundle', version: 1}, + data: {localStorage: [{origin: 'https://example.org/path', items: {x: 'y'}}]}})); + assert.throws(() => validateBundle({portage: {format: 'portage-bundle', version: 1}, + data: {localStorage: [{origin: 'https://example.org', items: {x: 123}}]}})); + + // A __proto__ storage key is data, not a prototype mutation; JSON.parse + // defines it as an own property, and validateBundle must accept it. + const protoBundle = JSON.parse('{"portage":{"format":"portage-bundle","version":1},' + + '"data":{"localStorage":[{"origin":"https://example.org","items":{"__proto__":"value"}}]}}'); + const protoItems = validateBundle(protoBundle).sites[0].items; + assert.equal(Object.getPrototypeOf(protoItems), Object.prototype); + assert.equal(Object.prototype.hasOwnProperty.call(protoItems, '__proto__'), true); + assert.equal(protoItems['__proto__'], 'value'); + console.log('PASS: dashboard cookies and bundle validation'); +} + +main().catch((error) => { console.error(error.stack); process.exitCode = 1; }); diff --git a/tools/README.md b/tools/README.md index 98b1856..e4b385b 100644 --- a/tools/README.md +++ b/tools/README.md @@ -1,18 +1,19 @@ # Experimental whole-profile Firefox → Chromium LocalStorage migration -The Portage extension cannot enumerate every origin's LocalStorage via WebExtension APIs. This optional Linux companion migrates **every compatible first-party Firefox LocalStorage origin** by reading the offline Firefox profile and writing via a separate, headless Chrome/Brave session. It does **not** depend on currently open tabs, and does **not** visit the real websites during import. +The Portage extension cannot enumerate every origin's LocalStorage via WebExtension APIs. This optional Linux companion migrates **every compatible first-party Firefox LocalStorage origin** by reading the offline Firefox profile and writing via a separate, headless Chrome/Brave session. It does **not** depend on currently open tabs, and does **not** fetch live website content during import. -**This is not complete browser-profile migration.** It does *not* migrate IndexedDB, sessionStorage, Service Workers, Firefox Containers, partitioned localStorage, WebAuthn/passkeys, or device-bound session credentials. Login persistence cannot be guaranteed. Cookies and bookmarks can be migrated separately using the standard Portage extension. +**This is not complete browser-profile migration.** The LocalStorage helper does *not* migrate sessionStorage, Service Workers, Firefox Containers, partitioned LocalStorage, WebAuthn/passkeys, or device-bound session credentials. IndexedDB has a separate experimental section below with its own limitations. Login persistence cannot be guaranteed. The standard Portage extension can migrate bookmarks and cookies; this folder also adds an offline cookie companion. ## Safety / prerequisites - Backup the Firefox and Chromium/Brave profiles first. -- Close Firefox before exporting; close Brave/Chrome before applying to its profile. The importer refuses an existing Chromium `SingletonLock`. +- Close Firefox before exporting; close Brave/Chrome before applying to its profile. The importer refuses an existing Chromium `SingletonLock`, and the tools refuse a Firefox-looking profile as the Chromium target, as well as `/` or the home directory. - LocalStorage can contain live session tokens. **Encrypted AES-256-GCM export is the default**; use a long unique passphrase. `--plaintext` is an explicitly unsafe opt-out. Output is mode 0600. Never attach exported bundles to an issue, share them, or commit them. -- Require **Python 3** and `cryptography` for encryption (`sudo apt install python3-cryptography` on Debian), and **Node.js 20+**, plus Puppeteer Core (`cd tools && npm install`). Puppeteer Core uses the existing installed Chrome/Brave and downloads no browsers. -- The exporter reports a **count of IndexedDB origins omitted** (without opening their records), so you can estimate missing coverage. +- Require **Python 3** and `cryptography` for encryption (`sudo apt install python3-cryptography` on Debian), and **Node.js 22.12+**, plus Puppeteer Core (`cd tools && npm ci`). Puppeteer Core uses the existing installed Chrome/Brave and downloads no browsers. +- The exporter reports a **count of IndexedDB origins omitted** (without opening their records); use the IndexedDB section below if you need them. - Import is **merge/upsert**: values with matching LocalStorage keys in the target are overwritten. Use a fresh Chromium profile where possible. Failed sites are reported and attempted writes are rolled back within the page when possible; this does not provide cross-origin atomic transactions. - Import launches the browser **headless**, intercepts all page network requests to return inert local HTML, disables service workers for the temporary page, and validates the loaded origin. This avoids visiting live websites but does not formally guarantee that the browser itself makes no background connections. Standard Chrome sandboxing remains enabled. +- Existing Chromium/Brave profiles keep their normal OS password-store settings: Puppeteer's forced `--password-store=basic` default is dropped for non-empty profiles so imported cookies stay readable after a normal launch. Fresh disposable profiles keep the automation default. ## Usage on Linux @@ -50,11 +51,17 @@ The Portage extension cannot enumerate every origin's LocalStorage via WebExtens ```bash python3 -m unittest discover -s tests -p 'test_*.py' node tests/test_storage_browser.cjs -# Optional desktop E2E: local Firefox 159 and Chrome 156 were verified; -# needs installed Firefox and Google Chrome plus Puppeteer -node tests/e2e_cross_browser.cjs +node tests/test_profile_safety.cjs +node tests/test_indexeddb_codec.cjs +node tests/test_indexeddb_paths.cjs +# Optional desktop E2E (synthetic disposable profiles only). Set +# PORTAGE_TEST_FIREFOX / PORTAGE_TEST_CHROMIUM / PORTAGE_TEST_BRAVE when the +# browsers are not at the default paths; a missing browser skips that test. node tests/e2e_offline_import.cjs +node tests/e2e_cookie_cli.cjs node tests/e2e_chrome.cjs +node tests/e2e_cross_browser.cjs +node tests/e2e_indexeddb.cjs ``` Chromium E2E tests verify that **requests to the synthetic target origin equal zero during import**, and the stored values remain readable after browser restart. The cross-browser test verifies Firefox LSNG decoding, AES encryption compatibility and Chromium restoration. Neither test guarantees the preservation of real-world login sessions. @@ -74,14 +81,18 @@ requests during transfer. This is *not* a guarantee of zero browser background network activity. The transfer stays in memory; it does **not** export tokens into an unencrypted intermediate JSON file. A temporary Firefox profile copy containing sensitive data is created under a mode-0700 temporary directory and -removed when the tool exits normally. A crash or power failure can leave it -behind, so inspect `portage-idb-*` in your temporary directory if interrupted. +removed when the tool exits normally or is interrupted with Ctrl-C / SIGTERM. +A hard kill or power failure can still leave it behind, so inspect +`portage-idb-*` in your temporary directory if a run is interrupted. **Close both browsers and back up both profiles before beginning.** Firefox's source is not modified, but Chromium's destination profile **will be changed** with `--apply`. Existing IndexedDB databases are **never overwritten**: the -whole database is skipped if its name already exists at that origin. The destination Chromium lock file and the Firefox source profile's live lock are checked before migration. Do not use this on a profile -that another browser process is accessing. +whole database is skipped if its name already exists at that origin. The +destination Chromium lock file and the Firefox source profile's open lock are +checked before migration; the Chromium profile named `Default` is used unless +`--chromium-profile-directory` is passed. Do not use this on a profile that +another browser process is accessing. ```bash # First, preview first-party IndexedDB origin count, WITHOUT modifying a profile: @@ -113,9 +124,14 @@ BigInt, Date, RegExp, Map/Set, binary buffers and typed arrays, Blob/File). **Still unsupported**: cyclic or shared object references, CryptoKey, non-standard browser objects, IndexedDB databases larger than 32 MiB in the -wire representation, stores with over 50,000 records, and individual Blob/File -values larger than 8 MiB. The bridge **skips entire databases** when it finds -unsupported data, and reports aggregate counts without printing record values. +wire representation, stores with over 50,000 records, arrays with over 50,000 +elements, and individual Blob/File values larger than 8 MiB. The bridge +**skips entire databases** when it finds unsupported data, and reports +aggregate counts without printing record values. +The IndexedDB API does not expose an object store's current auto-increment +counter, so after restoring records that were deleted at the source a new +record can reuse a deleted key number; verify apps that require monotonically +increasing keys after a migration. There is no guarantee that every session will remain logged in; site-specific security mechanisms and passkeys can require reauthentication. Importing an IDB database into another browser also does not make Firefox extension storage or @@ -132,22 +148,30 @@ node tests/e2e_indexeddb.cjs The `chromium_cookie_import.cjs` companion can transfer Firefox cookies into a closed Chromium/Brave profile without creating a plaintext cookie bundle on -disk. Python reads the backed-up Firefox `cookies.sqlite` and passes the -records through a **local subprocess pipe** to Chrome's native cookie API. -Only aggregate counts are printed. The entire profile should be backed up. +disk. Close Firefox first; the source profile's open lock is checked. Python +reads the backed-up Firefox `cookies.sqlite` and passes the records through a +**local subprocess pipe** to Chrome's native cookie API. Only aggregate counts +are printed. The entire profile should be backed up. ```bash node tools/chromium_cookie_import.cjs \ "$HOME/.mozilla/firefox/dev-edition-default" \ "$HOME/.config/BraveSoftware/Brave-Browser" \ /usr/bin/brave-browser + # optional 4th argument: the Chromium profile directory (default: Default) ``` -Firefox containers, origin-attribute partitions and expired cookies are -conservatively excluded, rather than incorrectly combining isolated sessions. +Firefox stores cookie expiry in milliseconds; the bridge converts it to the +seconds expected by Chromium's cookie API and never resurrects expired cookies. +Firefox containers, origin-attribute partitions, expired cookies and session +cookies are conservatively excluded, rather than incorrectly combining +isolated sessions or counting ephemeral cookies as migrated. Session cookies +are skipped because the importer closes its temporary Chromium session +immediately, so they could not survive the import anyway. Some cookies or logins remain tied to browser/device-bound secrets; a successful CDP `Network.setCookie` result does **not** guarantee continued authentication. Never collect or paste exported cookie values into bug reports. `node tests/e2e_cookie_cli.cjs` verifies this transfer with synthetic cookie -values and disposable Brave profiles only. +values and disposable Brave/Chrome profiles only; set `PORTAGE_TEST_BRAVE` if +the browser is not at `/usr/bin/brave-browser`. diff --git a/tools/chromium_cookie_import.cjs b/tools/chromium_cookie_import.cjs index c0db759..f59d0ed 100644 --- a/tools/chromium_cookie_import.cjs +++ b/tools/chromium_cookie_import.cjs @@ -1,11 +1,20 @@ #!/usr/bin/env node 'use strict'; /** Private-process Firefox -> Chromium cookie transfer. Do not print cookie values. */ -const cp=require('node:child_process'),path=require('node:path'),fs=require('node:fs'),os=require('node:os'); -async function transfer({sourceProfile,targetProfile,browserPath}) { - const source=path.resolve(sourceProfile),target=path.resolve(targetProfile); +const cp=require('node:child_process'),path=require('node:path'),fs=require('node:fs'); +const {assertSafeTargetProfile, assertChromiumClosed, assertFirefoxClosed, chromiumLaunchProfileOptions}=require('./profile_safety.cjs'); +function assertProfileDirectory(value) { + if(typeof value!=='string'||!/^[\w. -]+$/.test(value)||value==='.'||value==='..')throw Error('Invalid Chromium profile directory name'); + return value; +} +async function transfer({sourceProfile,targetProfile,browserPath,profileDirectory='Default'}) { + const source=path.resolve(sourceProfile); + const target=assertSafeTargetProfile(targetProfile, 'Chromium user-data-dir'); if(!fs.existsSync(source)||!fs.existsSync(browserPath))throw Error('Source or browser missing'); - if(fs.existsSync(path.join(target,'SingletonLock')))throw Error('Target browser lock present'); + if(source===target)throw Error('Source and destination profiles must differ'); + assertProfileDirectory(profileDirectory); + assertFirefoxClosed(source); + assertChromiumClosed(target); const p=cp.spawnSync('python3',[path.join(__dirname,'firefox_cookie_stream.py'),source],{ encoding:'utf8',maxBuffer:32*1024*1024,timeout:20000,stdio:['ignore','pipe','pipe']}); if(p.status!==0)throw Error('Cookie decoding failed; no destination modifications'); @@ -14,7 +23,8 @@ async function transfer({sourceProfile,targetProfile,browserPath}) { const result={candidate:parsed.cookies.length,skipped:parsed.skipped,accepted:0,failed:0}; try{ browser=await puppeteer.launch({executablePath:browserPath,userDataDir:target,headless:true, - args:['--disable-background-networking','--disable-sync','--disable-extensions','--no-first-run']}); + ...chromiumLaunchProfileOptions(target), + args:['--profile-directory='+profileDirectory,'--disable-background-networking','--disable-sync','--disable-extensions','--no-first-run']}); const page=await browser.newPage(),session=await page.createCDPSession(); for(const cookie of parsed.cookies){ try{ @@ -27,9 +37,9 @@ async function transfer({sourceProfile,targetProfile,browserPath}) { } if(require.main===module){ const args=process.argv.slice(2); - if(args.length!==3){console.error('Usage: node chromium_cookie_import.cjs FIREFOX_CLOSED_PROFILE CHROMIUM_CLOSED_PROFILE CHROME_EXECUTABLE');process.exit(2)} - transfer({sourceProfile:args[0],targetProfile:args[1],browserPath:args[2]}).then(r=>{ + if(args.length!==3&&args.length!==4){console.error('Usage: node chromium_cookie_import.cjs FIREFOX_CLOSED_PROFILE CHROMIUM_CLOSED_PROFILE CHROME_EXECUTABLE [CHROMIUM_PROFILE_DIRECTORY]');process.exit(2)} + transfer({sourceProfile:args[0],targetProfile:args[1],browserPath:args[2],profileDirectory:args[3]||'Default'}).then(r=>{ console.log('Cookies (counts only):',JSON.stringify(r));if(r.failed)process.exitCode=2; }).catch(e=>{console.error('Cookie import failed:',e.message);process.exitCode=1}); } -module.exports={transfer}; +module.exports={transfer,assertProfileDirectory}; diff --git a/tools/chromium_localstorage_import.cjs b/tools/chromium_localstorage_import.cjs index 692dbe8..13392e1 100644 --- a/tools/chromium_localstorage_import.cjs +++ b/tools/chromium_localstorage_import.cjs @@ -11,6 +11,7 @@ const fs = require('node:fs'); const path = require('node:path'); const crypto = require('node:crypto'); const readline = require('node:readline'); +const {assertSafeTargetProfile, assertChromiumClosed, chromiumLaunchProfileOptions} = require('./profile_safety.cjs'); function parseArgs(argv) { const opts = {apply: false, profileDirectory: 'Default', timeout: 12000}; @@ -154,10 +155,8 @@ async function restoreSites(browser, sites, timeout=12000) { async function run(opts) { const bundle=await loadBundle(path.resolve(opts.bundle),opts.passphraseStdin); const {sites,totalKeys}=validateBundle(bundle); - const profile=path.resolve(opts.userDataDir); - if(profile==='/' || profile===require('node:os').homedir()) throw Error('Refusing to use root or home as Chrome user-data-dir'); - const lock=path.join(profile,'SingletonLock'); - if (fs.existsSync(lock) || fs.lstatSync(lock, {throwIfNoEntry:false})) throw Error('Browser profile appears to be in use (SingletonLock present); close browser and retry'); + const profile=assertSafeTargetProfile(opts.userDataDir, 'Chromium user-data-dir'); + assertChromiumClosed(profile); console.log(`Validated ${sites.length} origins / ${totalKeys} LocalStorage keys.`); const unsupportedIdb = bundle?.meta?.unsupported?.indexedDBOrigins; if (Number.isInteger(unsupportedIdb) && unsupportedIdb > 0) { @@ -170,7 +169,7 @@ async function run(opts) { // Never start with a personal profile unless explicitly specified by the operator. // Keep Chrome sandbox enabled; do not pass --no-sandbox. const browser=await puppeteer.launch({executablePath:path.resolve(opts.browser),userDataDir:profile, - headless:true,defaultViewport:{width:600,height:400}, + headless:true,defaultViewport:{width:600,height:400},...chromiumLaunchProfileOptions(profile), args:['--profile-directory='+opts.profileDirectory,'--no-first-run','--no-default-browser-check', '--disable-background-networking','--disable-sync','--disable-extensions','--disable-features=MediaRouter']}); let result; diff --git a/tools/firefox_cookie_stream.py b/tools/firefox_cookie_stream.py index 550fd0a..db69e2d 100644 --- a/tools/firefox_cookie_stream.py +++ b/tools/firefox_cookie_stream.py @@ -3,6 +3,7 @@ Never redirect stdout to a file or issue tracker: it contains session credentials. """ import json, sqlite3, sys, time +from contextlib import closing from pathlib import Path @@ -12,9 +13,9 @@ def collect(profile): raise FileNotFoundError('Firefox cookies.sqlite not found') uri=file.resolve().as_uri()+'?mode=ro' included=[] - reason={'partitioned_or_containers':0,'expired':0,'invalid':0,'insecure_none':0} + reason={'partitioned_or_containers':0,'expired':0,'session':0,'invalid':0,'insecure_none':0} now=time.time() - with sqlite3.connect(uri, uri=True, timeout=10) as conn: + with closing(sqlite3.connect(uri, uri=True, timeout=10)) as conn: for name,value,host,path,expiry,secure,http_only,same_site,attrs in conn.execute( 'SELECT name,value,host,path,expiry,isSecure,isHttpOnly,sameSite,originAttributes FROM moz_cookies' ): @@ -24,7 +25,17 @@ def collect(profile): if not host or not isinstance(name,str) or not isinstance(value,str) or not host.strip('.') or not path.startswith('/'): reason['invalid']+=1 continue - if expiry and expiry str: raise ValueError(f'Unknown conversion type: {conversion_type}') -def valid_origin(origin: str) -> bool: +def normalize_origin(origin: str): + """Return the canonical origin Chromium's URL parser will accept. + + Firefox stores origins in canonical form, but synthetic/corrupted profiles + may use uppercase hosts or an explicit default port. Emitting those would + make the JavaScript importer reject the whole bundle, so normalise here and + skip origins that cannot be represented safely. + """ if not isinstance(origin, str) or '^' in origin or '#' in origin or '?' in origin: - return False # no silent loss of Firefox origin attributes / partitions + return None # no silent loss of Firefox origin attributes / partitions try: u = urlsplit(origin) - return u.scheme in ('https', 'http') and bool(u.hostname) and not u.username and not u.password and u.path in ('', '/') + port = u.port + host = u.hostname except ValueError: + return None + scheme = u.scheme.lower() + if scheme not in ('http', 'https') or not host or u.username or u.password or u.path not in ('', '/'): + return None + if any(ord(ch) > 127 for ch in host): + return None # Firefox stores punycode; do not risk a WHATWG IDNA mismatch + if ':' in host: + host = f'[{host}]' + default_port = 443 if scheme == 'https' else 80 + netloc = host if port is None or port == default_port else f'{host}:{port}' + return f'{scheme}://{netloc}' + + +def valid_origin(origin: str) -> bool: + return normalize_origin(origin) is not None + + +def firefox_profile_in_use(profile: Path) -> bool: + """Detect a Firefox process holding this profile's lock file open. + + Existence of .parentlock is not enough because a crash can leave a stale + lock behind; /proc exposes the open descriptors of the running Firefox. + """ + lock = profile / '.parentlock' + if not lock.exists(): return False + try: + target = str(lock.resolve()) + except OSError: + return False + proc = Path('/proc') + if proc.is_dir(): + for pid in os.listdir(proc): + if not pid.isdigit(): + continue + fd_dir = proc / pid / 'fd' + try: + descriptors = os.listdir(fd_dir) + except OSError: + continue + for descriptor in descriptors: + try: + linked = os.readlink(fd_dir / descriptor) + except OSError: + continue + if linked == target or linked == target + ' (deleted)': + return True + return False + try: + probe = subprocess.run(['fuser', '-s', str(lock)], capture_output=True, timeout=3) + except (OSError, subprocess.SubprocessError) as exc: + raise RuntimeError('Cannot verify that Firefox is closed (no /proc and no fuser)') from exc + if probe.returncode not in (0, 1): + raise RuntimeError('Cannot verify that Firefox is closed (fuser failed)') + return probe.returncode == 0 def export_profile(profile: Path): @@ -111,15 +174,20 @@ def export_profile(profile: Path): if not root.is_dir(): raise ValueError('Expected Firefox profile with storage/default directory') sites, warnings = [], [] + seen_origins = set() for db in sorted(root.glob('*/ls/data.sqlite')): try: # SQLite read-only URI avoids creating journal files or modifying profile. with closing(sqlite3.connect(db.as_uri() + '?mode=ro', uri=True, timeout=3)) as conn: row = conn.execute('SELECT origin FROM "database" LIMIT 1').fetchone() - if not row or not valid_origin(row[0]): + origin = normalize_origin(row[0]) if row else None + if origin is None: warnings.append('Skipped partitioned or invalid origin (name omitted for privacy)') continue - origin = row[0].rstrip('/') + if origin in seen_origins: + warnings.append('Skipped duplicate origin (name omitted for privacy)') + continue + seen_origins.add(origin) entries = conn.execute('SELECT key, value, conversion_type, compression_type FROM data').fetchall() if not entries: continue @@ -142,11 +210,18 @@ def main(argv=None): parser.add_argument('--passphrase-stdin', action='store_true', help='Read encryption passphrase from stdin instead of prompting') args = parser.parse_args(argv) profile = args.profile.expanduser().resolve() - output = args.output.expanduser().resolve() - if output.exists(): + # Do not resolve the output path: resolving a dangling symlink would write + # through it and defeat the no-clobber guarantee below. + output = args.output.expanduser() + if os.path.lexists(output): parser.error('Output already exists: will not overwrite sensitive data') if not profile.is_dir(): parser.error('Profile directory does not exist') + try: + if firefox_profile_in_use(profile): + parser.error('Firefox appears to be running with this profile; close Firefox before exporting') + except RuntimeError as exc: + parser.error(str(exc)) sites, warnings = export_profile(profile) # Inventory unsupported IndexedDB without opening or reading any IDB records. # Counts, not credential-bearing names/values, go into the bundle metadata. @@ -192,8 +267,16 @@ def main(argv=None): }, 'ciphertext':base64.b64encode(ciphertext).decode(), } - # Create mode 0600: no permissive intermediate file, no clobber. - fd = os.open(output, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + # Create mode 0600: no permissive intermediate file, no clobber, and never + # follow a symlink (a dangling link would otherwise redirect the write). + try: + fd = os.open(output, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_NOFOLLOW', 0), 0o600) + except FileExistsError: + parser.error('Output already exists: will not overwrite sensitive data') + except FileNotFoundError: + parser.error(f'Output directory does not exist: {output.parent}') + except OSError as exc: + parser.error(f'Cannot create output file: {exc.strerror or exc}') try: with os.fdopen(fd, 'w', encoding='utf-8') as out: json.dump(bundle, out, ensure_ascii=False, separators=(',', ':')) diff --git a/tools/indexeddb_migrate.cjs b/tools/indexeddb_migrate.cjs index e8af471..edea363 100644 --- a/tools/indexeddb_migrate.cjs +++ b/tools/indexeddb_migrate.cjs @@ -10,6 +10,7 @@ const path = require('node:path'); const os = require('node:os'); const cp = require('node:child_process'); const {validOrigin} = require('./chromium_localstorage_import.cjs'); +const {assertSafeTargetProfile, assertChromiumClosed, assertFirefoxClosed, chromiumLaunchProfileOptions} = require('./profile_safety.cjs'); function options(argv) { const o={apply:false,timeout:20000}; @@ -17,11 +18,12 @@ function options(argv) { const a=argv[i]; if(a==='--apply')o.apply=true; else if(a==='--help')o.help=true; - else if(['--firefox-profile','--chromium-profile','--firefox','--chromium'].includes(a)) { - o[{'--firefox-profile':'firefoxProfile','--chromium-profile':'chromiumProfile','--firefox':'firefox','--chromium':'chromium'}[a]]=argv[++i]; + else if(['--firefox-profile','--chromium-profile','--firefox','--chromium','--chromium-profile-directory'].includes(a)) { + o[{'--firefox-profile':'firefoxProfile','--chromium-profile':'chromiumProfile','--firefox':'firefox','--chromium':'chromium','--chromium-profile-directory':'chromiumProfileDirectory'}[a]]=argv[++i]; }else throw Error('Unknown option: '+a); } if(!o.help && (!o.firefoxProfile||!o.chromiumProfile||!o.firefox||!o.chromium))throw Error('Required: --firefox-profile --chromium-profile --firefox --chromium'); + if(o.chromiumProfileDirectory&&(!/^[\w. -]+$/.test(o.chromiumProfileDirectory)||o.chromiumProfileDirectory==='.'||o.chromiumProfileDirectory==='..'))throw Error('Invalid Chromium profile directory name'); return o; } @@ -165,24 +167,51 @@ async function restoreOrigin(page,source) { },{source}); } +const cleanupState = {paths: [], browsers: []}; +function cleanupSensitiveState() { + for (const browser of cleanupState.browsers) { + try { browser.process?.()?.kill?.('SIGKILL'); } catch {} + } + for (const target of cleanupState.paths) { + try { fs.rmSync(target, {recursive: true, force: true}); } catch {} + } + cleanupState.paths.length = 0; + cleanupState.browsers.length = 0; +} +function installCleanupHandlers() { + // Ctrl-C or SIGTERM must not leave the temporary Firefox profile clone (which + // contains cookies and storage data) behind in /tmp. + const handler = (signal) => { cleanupSensitiveState(); process.exit(signal === 'SIGINT' ? 130 : 143); }; + process.once('SIGINT', handler); + process.once('SIGTERM', handler); + return () => { process.removeListener('SIGINT', handler); process.removeListener('SIGTERM', handler); }; +} + +function realDirectory(directory, label) { + if(!fs.existsSync(directory))throw Error(`${label} does not exist: ${directory}`); + const resolved=fs.realpathSync(directory); + if(!fs.statSync(resolved).isDirectory())throw Error(`${label} is not a directory: ${resolved}`); + return resolved; +} + async function migrate(opts) { - const fx=path.resolve(opts.firefoxProfile),target=path.resolve(opts.chromiumProfile); - if(!fs.statSync(fx).isDirectory())throw Error('Firefox source profile is not a directory'); - if(target===fx || fx==='/' || target==='/' || target===os.homedir())throw Error('Unsafe profile directory'); + // Resolve symlinks: cp -a would otherwise copy a symlink of the source + // profile and Firefox would be launched against the original profile. + const fx=realDirectory(opts.firefoxProfile, 'Firefox source profile'); + const targetCandidate=path.resolve(opts.chromiumProfile); + const target=fs.existsSync(targetCandidate)?fs.realpathSync(targetCandidate):targetCandidate; + if(target===fx)throw Error('Source and destination profiles must differ'); + assertSafeTargetProfile(target, 'Chromium user-data-dir'); + assertFirefoxClosed(fx); const origins=originsForFirefox(fx); console.log(`Firefox IndexedDB inventory: ${origins.length} first-party origin(s); container/partitioned origins intentionally excluded.`); if(!opts.apply){console.log('DRY RUN: No browser started. Add --apply to migrate to a backed-up target profile.');return {origins:origins.length};} - if(fs.existsSync(path.join(target,'SingletonLock')))throw Error('Target Chromium profile appears to be open'); - // On Linux the .parentlock file may exist after Firefox exits, so test - // whether any process actually has the file open rather than its existence. - const sourceLock=path.join(fx,'.parentlock'); - if(fs.existsSync(sourceLock)) { - const locked=cp.spawnSync('fuser',['-s',sourceLock],{timeout:3000,stdio:'ignore'}); - if(locked.status===0)throw Error('Firefox source profile is running; close Firefox before migration'); - } + assertChromiumClosed(target); for(const exe of [opts.firefox,opts.chromium])if(!fs.existsSync(exe))throw Error('Executable not found: '+exe); const scratch=fs.mkdtempSync(path.join(os.tmpdir(),'portage-idb-')); fs.chmodSync(scratch,0o700); + cleanupState.paths.push(scratch); + const removeSignalHandlers = installCleanupHandlers(); const clone=path.join(scratch,'firefox-clone'); // Reflinks avoid copying large databases when the filesystem supports CoW. // Do NOT launch Firefox against the original profile, which would modify it. @@ -199,9 +228,11 @@ async function migrate(opts) { 'dom.serviceWorkers.enabled':false, 'extensions.enabledScopes':0, }}); + cleanupState.browsers.push(fb); cb=await pp.launch({browser:'chrome',executablePath:opts.chromium, - userDataDir:target,headless:true,timeout:20000, - args:['--no-first-run','--no-default-browser-check','--disable-background-networking','--disable-sync','--disable-extensions']}); + userDataDir:target,headless:true,timeout:20000,...chromiumLaunchProfileOptions(target), + args:['--profile-directory='+(opts.chromiumProfileDirectory||'Default'),'--no-first-run','--no-default-browser-check','--disable-background-networking','--disable-sync','--disable-extensions']}); + cleanupState.browsers.push(cb); const sourcePage=await inertPage(fb,'firefox'),destPage=await inertPage(cb,'chromium'); for(const [i,origin]of origins.entries()){ try { @@ -221,7 +252,10 @@ async function migrate(opts) { // even if either browser fails to shut down cleanly. try {if(fb)await fb.close();} catch(e) {console.warn('Firefox close failed:',e.message);} try {if(cb)await cb.close();} catch(e) {console.warn('Chromium close failed:',e.message);} + cleanupState.browsers = cleanupState.browsers.filter(browser => browser !== fb && browser !== cb); fs.rmSync(scratch,{recursive:true,force:true}); + cleanupState.paths = cleanupState.paths.filter(entry => entry !== scratch); + removeSignalHandlers(); } console.log(`IndexedDB migration: ${stats.restored} database(s) restored; ${stats.skipped} target skips; ${stats.sourceSkipped} source skips.`); if(stats.errors.length)console.log('Failures (origin indices only, no contents):',JSON.stringify(stats.errors)); @@ -230,7 +264,7 @@ async function migrate(opts) { } if(require.main===module){ try{const o=options(process.argv.slice(2)); - if(o.help)console.log('Usage: node tools/indexeddb_migrate.cjs --firefox-profile PATH --chromium-profile PATH --firefox /usr/local/bin/firefox --chromium /usr/bin/google-chrome [--apply]\nDry-run by default. Use closed profiles; back up both before --apply. Existing target IndexedDB databases will be skipped.'); + if(o.help)console.log('Usage: node tools/indexeddb_migrate.cjs --firefox-profile PATH --chromium-profile PATH --firefox /usr/local/bin/firefox --chromium /usr/bin/google-chrome [--apply]\nDry-run by default. Use closed profiles; back up both before --apply. Existing target IndexedDB databases will be skipped. [--chromium-profile-directory Default]'); else migrate(o).catch(e=>{console.error('IndexedDB transfer failed:',e.message);process.exitCode=1}); }catch(e){console.error(e.message);process.exitCode=1;} } diff --git a/tools/list_firefox_idb_origins.py b/tools/list_firefox_idb_origins.py index 6eda5dc..0d2a868 100644 --- a/tools/list_firefox_idb_origins.py +++ b/tools/list_firefox_idb_origins.py @@ -3,6 +3,7 @@ import json import sqlite3 import sys +from contextlib import closing from pathlib import Path from urllib.parse import urlsplit @@ -12,7 +13,7 @@ def list_origins(profile): if not db.is_file(): raise FileNotFoundError(f'Missing Firefox QuotaManager storage.sqlite: {db}') result = [] - with sqlite3.connect(db.as_uri() + '?mode=ro', uri=True, timeout=5) as connection: + with closing(sqlite3.connect(db.as_uri() + '?mode=ro', uri=True, timeout=5)) as connection: for origin, usage in connection.execute('SELECT origin, client_usages FROM origin'): if not origin or '^' in origin or not isinstance(usage, str) or 'I' not in usage: continue # no privileged schemes or origin-attribute partition flattening diff --git a/tools/package-lock.json b/tools/package-lock.json index 994d100..6448720 100644 --- a/tools/package-lock.json +++ b/tools/package-lock.json @@ -11,7 +11,7 @@ "puppeteer-core": "^25.14.0" }, "engines": { - "node": ">=20" + "node": ">=22.12.0" } }, "node_modules/@puppeteer/browsers": { diff --git a/tools/package.json b/tools/package.json index fcf06d6..4855b7a 100644 --- a/tools/package.json +++ b/tools/package.json @@ -3,6 +3,6 @@ "version": "0.1.0", "private": true, "description": "Optional offline profile migration helpers for Portage", - "engines": { "node": ">=20" }, + "engines": { "node": ">=22.12.0" }, "dependencies": { "puppeteer-core": "^25.14.0" } } diff --git a/tools/profile_safety.cjs b/tools/profile_safety.cjs new file mode 100644 index 0000000..caecd81 --- /dev/null +++ b/tools/profile_safety.cjs @@ -0,0 +1,95 @@ +'use strict'; +// Shared safety checks for the optional profile migration CLI tools. +// These helpers refuse obviously wrong target directories and detect a +// Firefox profile that is still open before its SQLite files are read/copied. +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const cp = require('node:child_process'); + +const FIREFOX_MARKERS = ['prefs.js', 'places.sqlite', 'cookies.sqlite', 'storage.sqlite']; + +function assertSafeTargetProfile(directory, label = 'Chromium profile') { + const resolved = path.resolve(directory); + if (resolved === '/' || resolved === os.homedir()) { + throw new Error(`Refusing to use root or home as ${label}: ${resolved}`); + } + for (const marker of FIREFOX_MARKERS) { + if (fs.existsSync(path.join(resolved, marker))) { + throw new Error(`${label} looks like a Firefox profile (${marker}); refusing to write Chromium data into ${resolved}`); + } + } + return resolved; +} + +const CHROMIUM_KEYRING_DEFAULT_ARGS = ['--password-store=basic', '--use-mock-keychain']; + +// Puppeteer forces --password-store=basic, which encrypts cookies with the +// fallback key. That is fine for disposable profiles but can make cookies +// unreadable in an existing profile whose normal launch uses the OS keyring. +// For existing profiles, drop that default so Chromium uses its normal store. +function chromiumLaunchProfileOptions(profile) { + const existing = fs.existsSync(path.join(profile, 'Local State')) + || fs.existsSync(path.join(profile, 'Default')); + return existing ? {ignoreDefaultArgs: CHROMIUM_KEYRING_DEFAULT_ARGS.slice()} : {}; +} + +function chromiumLockPath(profile) { + // Chrome's SingletonLock is a dangling symlink while the browser is running. + // existsSync() follows links and returns false for it, so use lstat(). + const candidate = path.join(profile, 'SingletonLock'); + return fs.lstatSync(candidate, {throwIfNoEntry: false}) ? candidate : null; +} + +function assertChromiumClosed(profile) { + if (chromiumLockPath(profile)) { + throw new Error(`Chromium profile appears to be open (SingletonLock present); close the browser and retry. If no browser is running, remove the stale SingletonLock after confirming: ${profile}`); + } +} + +function firefoxLockPath(profile) { + for (const name of ['.parentlock', 'lock']) { + const candidate = path.join(profile, name); + if (fs.lstatSync(candidate, {throwIfNoEntry: false})) return candidate; + } + return null; +} + +// Returns true when some process holds the lock file open. Firefox keeps an +// open descriptor on its profile lock for as long as the profile is in use; +// existence alone is not enough because a crash can leave a stale lock behind. +function isLockHeld(lockPath) { + let target; + try { target = fs.realpathSync(lockPath); } catch { return false; } + if (fs.existsSync('/proc')) { + for (const pid of fs.readdirSync('/proc')) { + if (!/^\d+$/.test(pid)) continue; + let descriptors; + try { descriptors = fs.readdirSync(`/proc/${pid}/fd`); } catch { continue; } + for (const descriptor of descriptors) { + let linked; + try { linked = fs.readlinkSync(`/proc/${pid}/fd/${descriptor}`); } catch { continue; } + if (linked === target || linked === target + ' (deleted)') return true; + } + } + return false; + } + // Non-Linux fallback: fuser is part of psmisc and reports whether a file is + // open. If neither /proc nor fuser is available, fail closed instead of + // silently copying a profile that might still be in use. + const probe = cp.spawnSync('fuser', ['-s', lockPath], {timeout: 3000, stdio: 'ignore'}); + if (probe.error || probe.status === null) { + throw new Error('Cannot verify that the Firefox profile is closed (no /proc and no fuser); close Firefox and retry'); + } + return probe.status === 0; +} + +function assertFirefoxClosed(profile) { + const lockPath = firefoxLockPath(profile); + if (lockPath && isLockHeld(lockPath)) { + throw new Error(`Firefox profile appears to be in use (${path.basename(lockPath)} is open); close Firefox and retry`); + } + return lockPath; +} + +module.exports = {assertSafeTargetProfile, chromiumLaunchProfileOptions, chromiumLockPath, assertChromiumClosed, firefoxLockPath, isLockHeld, assertFirefoxClosed};