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.
This commit is contained in:
souta
2026-10-23 20:54:18 +09:00
parent 1b617cef84
commit 7fb8ef7509
26 changed files with 1021 additions and 210 deletions
+45 -21
View File
@@ -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`.
+18 -8
View File
@@ -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};
+4 -5
View File
@@ -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;
+17 -4
View File
@@ -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<now:
# moz_cookies.expiry is milliseconds since the UNIX epoch, while
# Chrome's Network.setCookie expects seconds. Convert both the
# expiry comparison and the value sent over CDP to seconds.
expiry_seconds=expiry/1000.0 if expiry else 0
if not expiry_seconds:
# Session cookies would end with the temporary Chromium session
# that the importer closes, so importing them would only inflate
# the accepted count without keeping the login.
reason['session']+=1
continue
if expiry_seconds<now:
reason['expired']+=1
continue
if same_site==0 and not secure:
@@ -32,7 +43,9 @@ def collect(profile):
continue
cookie={'name':name,'value':value,'domain':host,'path':path,
'secure':bool(secure),'httpOnly':bool(http_only),
'expires':float(expiry) if expiry else -1}
'expires':expiry_seconds}
# 0=None, 1=Lax, 2=Strict; 256 means no SameSite attribute, so the
# property is omitted and Chrome keeps its "unspecified" default.
if same_site in (0,1,2):cookie['sameSite']={0:'None',1:'Lax',2:'Strict'}[same_site]
included.append(cookie)
return {'cookies':included,'skipped':reason}
+92 -9
View File
@@ -13,6 +13,7 @@ import json
import os
from pathlib import Path
import sqlite3
import subprocess
import sys
from datetime import datetime, timezone
from urllib.parse import urlsplit
@@ -96,14 +97,76 @@ def decode_value(value, conversion_type, compression_type) -> 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=(',', ':'))
+50 -16
View File
@@ -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;}
}
+2 -1
View File
@@ -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
+1 -1
View File
@@ -11,7 +11,7 @@
"puppeteer-core": "^25.14.0"
},
"engines": {
"node": ">=20"
"node": ">=22.12.0"
}
},
"node_modules/@puppeteer/browsers": {
+1 -1
View File
@@ -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" }
}
+95
View File
@@ -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};