feat: migrate Firefox IndexedDB through offline browser-native bridge

This commit is contained in:
souta
2026-10-23 17:15:33 +09:00
parent 1e5ba9c91c
commit 3e59605794
8 changed files with 523 additions and 0 deletions
+70
View File
@@ -58,3 +58,73 @@ node tests/e2e_chrome.cjs
```
Chromium E2E tests verify that **requests to the synthetic target origin equal zero during import**, and the stored values remain readable after browser restart. The cross-browser test verifies Firefox LSNG decoding, AES encryption compatibility and Chromium restoration. Neither test guarantees the preservation of real-world login sessions.
## IndexedDB migration (experimental, Firefox → Chrome/Brave)
Unlike localStorage, IndexedDB stores browser-specific Structured Clone values
and may keep binary data in separate `.files` directories. **Do not copy its
SQLite files directly to Chromium.** This optional bridge launches a temporary
**copy** of your closed Firefox profile in Firefox 159+ using WebDriver BiDi,
reads each first-party origin's IndexedDB through Firefox's real IndexedDB API,
then restores databases through Chromium's native IndexedDB API.
During migration both browsers receive only **inert, locally intercepted HTML**
for each site. In the automated tests the source sites received zero HTTP
requests during transfer. This is *not* a guarantee of zero browser background
network activity. The transfer stays in memory; it does **not** export tokens
into an unencrypted intermediate JSON file. A temporary Firefox profile copy
containing sensitive data is created under a mode-0700 temporary directory and
removed when the tool exits normally. A crash or power failure can leave it
behind, so inspect `portage-idb-*` in your temporary directory if 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. Normal
browser lock files are checked on the destination. Do not use this on a profile
that another browser process is accessing.
```bash
# First, preview first-party IndexedDB origin count, WITHOUT modifying a profile:
node tools/indexeddb_migrate.cjs \
--firefox-profile "$HOME/.mozilla/firefox/your-profile" \
--chromium-profile "$HOME/.config/BraveSoftware/Brave-Browser" \
--firefox /usr/local/bin/firefox \
--chromium /usr/bin/brave-browser
# After backing up both profiles, repeat with --apply:
node tools/indexeddb_migrate.cjs \
--firefox-profile "$HOME/.mozilla/firefox/your-profile" \
--chromium-profile "$HOME/.config/BraveSoftware/Brave-Browser" \
--firefox /usr/local/bin/firefox \
--chromium /usr/bin/brave-browser --apply
```
This companion uses the same `tools/node_modules/puppeteer-core` dependency as
the other CLI; run `npm ci --prefix tools` first. Firefox must support WebDriver
BiDi; validated with Firefox 159.0b5 and Google Chrome 156.0.8078.47, not yet
with Brave Stable. Origin enumeration reads the QuotaManager `storage.sqlite`
metadata; only HTTP(S) origins without Firefox container/partition attributes
are considered. It does not inspect Chrome or Firefox passwords/cookies.
**Migrated**: IndexedDB database names and versions, object stores, key paths,
auto-increment flags, indexes (including multi-entry/unique), primary keys, and
supported stored values (ordinary objects/arrays, strings/numbers/booleans,
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.
There is no guarantee that every session will remain logged in; site-specific
security mechanisms and passkeys can require reauthentication. Importing an IDB
database into another browser also does not make Firefox extension storage or
browser-specific JavaScript APIs compatible.
For an actual two-origin cross-browser IndexedDB test with disposable profiles:
```bash
node tests/test_indexeddb_codec.cjs
node tests/e2e_indexeddb.cjs
```
+80
View File
@@ -0,0 +1,80 @@
/* Portable, lossless subset of IndexedDB structured-clone values.
Unsupported types and cyclic/shared references are refused, never silently discarded. */
'use strict';
async function encode(value, seen = new WeakSet()) {
if (value === null) return {t:'null'};
const typ = typeof value;
if (typ === 'undefined') return {t:'undefined'};
if (typ === 'string' || typ === 'boolean') return {t:typ,v:value};
if (typ === 'bigint') return {t:'bigint',v:value.toString()};
if (typ === 'number') return {t:'number',v:Object.is(value,-0)?'-0':Number.isFinite(value)?value:String(value)};
if (typ !== 'object') throw new Error('Unsupported IndexedDB value type: '+typ);
if(seen.has(value)) throw new Error('Shared/cyclic references cannot yet be migrated losslessly');
seen.add(value);
if(value instanceof Date) return {t:'date',v:Number.isNaN(value.getTime())?'NaN':value.getTime()};
if(value instanceof RegExp) return {t:'regexp',s:value.source,f:value.flags};
if(value instanceof ArrayBuffer) return {t:'buffer',v:Array.from(new Uint8Array(value))};
if(ArrayBuffer.isView(value)) {
if (value instanceof DataView) return {t:'dataview',v:Array.from(new Uint8Array(value.buffer,value.byteOffset,value.byteLength))};
return {t:'typedarray',type:value.constructor.name,v:Array.from(new Uint8Array(value.buffer,value.byteOffset,value.byteLength))};
}
if(typeof Blob !== 'undefined' && value instanceof Blob){
if(value.size>8*1024*1024)throw new Error('Blob larger than 8 MiB migration limit');
const v=Array.from(new Uint8Array(await value.arrayBuffer()));
if(typeof File !== 'undefined' && value instanceof File)return {t:'file',v,name:value.name,mime:value.type,lastModified:value.lastModified};
return {t:'blob',v,mime:value.type};
}
if(Array.isArray(value)) {
const items=[];
for(let i=0;i<value.length;i++) items.push(Object.prototype.hasOwnProperty.call(value,i)?await encode(value[i],seen):{t:'hole'});
return {t:'array',v:items};
}
if(value instanceof Map) {
const pairs=[];for(const [k,v] of value) pairs.push([await encode(k,seen),await encode(v,seen)]);
return {t:'map',v:pairs};
}
if(value instanceof Set) {
const arr=[];for(const v of value)arr.push(await encode(v,seen));return {t:'set',v:arr};
}
if(Object.getPrototypeOf(value)!==Object.prototype && Object.getPrototypeOf(value)!==null)
throw new Error('Unsupported IndexedDB object prototype');
const pairs=[];
for (const k of Object.keys(value)) pairs.push([k,await encode(value[k],seen)]);
return {t:'object',v:pairs};
}
function decode(o){
if(!o || typeof o.t!=='string')throw new Error('Invalid encoded value');
switch(o.t){
case 'null':return null;
case 'undefined':return undefined;
case 'string':case 'boolean':return o.v;
case 'number':return typeof o.v==='number'?o.v:Number(o.v);
case 'bigint':return BigInt(o.v);
case 'date':return new Date(o.v);
case 'regexp':return new RegExp(o.s,o.f);
case 'buffer':return Uint8Array.from(o.v).buffer;
case 'dataview':return new DataView(Uint8Array.from(o.v).buffer);
case 'typedarray': {
const types={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array};
const ctor=types[o.type]; if(!ctor)throw new Error('Unknown typed array type');
const a=Uint8Array.from(o.v); if(a.byteLength%ctor.BYTES_PER_ELEMENT)throw new Error('Invalid typed array data');
return new ctor(a.buffer);
}
case 'blob':return new Blob([Uint8Array.from(o.v)],{type:o.mime});
case 'file':return new File([Uint8Array.from(o.v)],o.name,{type:o.mime,lastModified:o.lastModified});
case 'array': {
const arr=new Array(o.v.length);
for(let i=0;i<o.v.length;i++)if(o.v[i].t!=='hole')arr[i]=decode(o.v[i]);
return arr;
}
case 'map':return new Map(o.v.map(([k,v])=>[decode(k),decode(v)]));
case 'set':return new Set(o.v.map(decode));
case 'object': {
const obj=Object.create(null);
for(const [k,v]of o.v)Object.defineProperty(obj,k,{value:decode(v),enumerable:true,writable:true,configurable:true});
return obj;
}
default:throw new Error('Unknown structured clone value: '+o.t);
}
}
module.exports={encode,decode};
+207
View File
@@ -0,0 +1,207 @@
#!/usr/bin/env node
/** Offline IndexedDB bridge: Firefox 159+ -> Chromium 156+, all supported origins.
* Does not parse Firefox's opaque structured-clone SQLite blobs. A cloned
* Firefox profile reads the data with native IDB, and Chromium reconstructs
* the database via native IDB, using inert intercepted documents for origins.
*/
'use strict';
const fs = require('node:fs');
const path = require('node:path');
const os = require('node:os');
const cp = require('node:child_process');
const {encode,decode} = require('./indexeddb_codec.js');
const {validOrigin} = require('./chromium_localstorage_import.cjs');
function options(argv) {
const o={apply:false,timeout:20000};
for (let i=0;i<argv.length;i++) {
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 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');
return o;
}
function originsForFirefox(profile) {
const script=path.join(__dirname,'list_firefox_idb_origins.py');
const proc=cp.spawnSync('python3',[script,profile],{encoding:'utf8',timeout:10000,maxBuffer:1024*1024});
if(proc.status!==0)throw Error('Firefox origin inventory failed: '+(proc.stderr||'no output').slice(0,300));
const origins=JSON.parse(proc.stdout);
if(!Array.isArray(origins)||origins.length>100000||!origins.every(validOrigin))throw Error('Invalid IndexedDB origin inventory');
return origins;
}
async function inertPage(browser, kind) {
const page=await browser.newPage();
if(kind==='chromium') {await page.setBypassServiceWorker(true);await page.setCacheEnabled(false);}
await page.setRequestInterception(true);
page.on('request',request => {
if(request.isNavigationRequest() && request.frame()===page.mainFrame()) {
request.respond({status:200,contentType:'text/html; charset=utf-8',headers:{'cache-control':'no-store'},body:'<!doctype html><title>Portage offline storage transfer</title>'}).catch(()=>{});
}else request.respond({status:204,body:''}).catch(()=>{});
});
return page;
}
async function navigateOffline(page,origin,timeout) {
await page.goto(origin+'/',{waitUntil:'domcontentloaded',timeout});
if(new URL(page.url()).origin!==origin)throw Error('Navigation crossed origin');
}
async function snapshotOrigin(page) {
return page.evaluate(async (source) => {
const encode=(0,eval)('('+source+')'); // trusted, embedded function source; never user input
const output={databases:[],errors:[]};
const metas=await indexedDB.databases();
for(const meta of metas) {
if(typeof meta.name!=='string')continue;
let db;
try {
db=await new Promise((resolve,reject)=>{
const r=indexedDB.open(meta.name);
r.onsuccess=()=>resolve(r.result);
r.onerror=()=>reject(r.error);
r.onblocked=()=>reject(Error('IndexedDB open blocked'));
});
const dump={name:db.name,version:db.version,stores:[]};
for (const storeName of Array.from(db.objectStoreNames)) {
const tx=db.transaction(storeName,'readonly');
const store=tx.objectStore(storeName);
const schema={name:storeName,keyPath:store.keyPath,autoIncrement:store.autoIncrement,
indexes:Array.from(store.indexNames,n=>{
const ix=store.index(n);return {name:ix.name,keyPath:ix.keyPath,unique:ix.unique,multiEntry:ix.multiEntry};
}),records:[]};
const values=await new Promise((resolve,reject)=>{
const req=store.getAll();req.onsuccess=()=>resolve(req.result);req.onerror=()=>reject(req.error);
});
// Key retrieval is a second transaction to avoid inactive transactions after await.
const tx2=db.transaction(storeName,'readonly');
const keys=await new Promise((resolve,reject)=>{
const req=tx2.objectStore(storeName).getAllKeys();req.onsuccess=()=>resolve(req.result);req.onerror=()=>reject(req.error);
});
if(keys.length!==values.length)throw Error('Key/value length mismatch');
if(values.length>50000)throw Error('Store has over 50000 records (migration safety limit)');
for(let j=0;j<values.length;j++)schema.records.push([await encode(keys[j]),await encode(values[j])]);
dump.stores.push(schema);
}
if(JSON.stringify(dump).length>32*1024*1024)throw Error('Database over 32 MiB transport limit');
if(JSON.stringify(output).length+JSON.stringify(dump).length>64*1024*1024)throw Error('Origin over 64 MiB transport limit');
output.databases.push(dump);
}catch(e){output.errors.push('Database '+output.databases.length+' skipped: '+String(e.message||e).slice(0,160));}
finally {db?.close();}
}
return output;
},encode.toString());
}
async function restoreOrigin(page,source) {
return page.evaluate(async ({source,codec})=>{
const decode=(0,eval)('('+codec+')');
const results={restored:0,skipped:0,errors:[]};
const existing=new Set((await indexedDB.databases()).map(x=>x.name));
for(const spec of source.databases) {
if(existing.has(spec.name)) {results.skipped++;results.errors.push('Existing destination database preserved');continue;}
let db;
try {
// Decode EVERYTHING before creating the DB; unsupported values must not
// leave a partially initialized destination schema.
const decoded=spec.stores.map(s=>({name:s.name,keyPath:s.keyPath,autoIncrement:s.autoIncrement,indexes:s.indexes,
records:s.records.map(([k,v])=>[decode(k),decode(v)])}));
db=await new Promise((resolve,reject)=>{
const request=indexedDB.open(spec.name,spec.version);
request.onupgradeneeded=()=>{
try{
const d=request.result;
for(const s of decoded){
const opts={autoIncrement:s.autoIncrement};
if(s.keyPath!==null)opts.keyPath=s.keyPath;
const store=d.createObjectStore(s.name,opts);
for(const ix of s.indexes)store.createIndex(ix.name,ix.keyPath,{unique:ix.unique,multiEntry:ix.multiEntry});
}
}catch(e){request.transaction.abort();}
};
request.onsuccess=()=>resolve(request.result);
request.onerror=()=>reject(request.error||Error('Open error'));
request.onblocked=()=>reject(Error('IndexedDB upgrade blocked'));
});
for(const s of decoded){
if(!s.records.length)continue;
await new Promise((resolve,reject)=>{
const tx=db.transaction(s.name,'readwrite');
tx.oncomplete=()=>resolve();tx.onerror=()=>reject(tx.error||Error('Write failed'));
tx.onabort=()=>reject(tx.error||Error('Transaction aborted'));
const store=tx.objectStore(s.name);
try{for(const [key,value] of s.records) {
if(s.keyPath===null)store.put(value,key);else store.put(value);
}}catch(e){tx.abort();reject(e);}
});
}
results.restored++;
}catch(e){
results.skipped++;
results.errors.push(String(e.message||e).slice(0,160));
// Newly created DB may now contain a partial subset of stores; remove it.
if(db){db.close();db=null;}
try{await new Promise((resolve,reject)=>{const q=indexedDB.deleteDatabase(spec.name);q.onsuccess=()=>resolve();q.onerror=()=>reject(q.error);q.onblocked=()=>reject(Error('DB deletion blocked'));});}catch{}
}finally {db?.close();}
}
return results;
},{source,codec:decode.toString()});
}
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');
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');
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);
const clone=path.join(scratch,'firefox-clone');
// Reflinks avoid copying large databases when the filesystem supports CoW.
// Do NOT launch Firefox against the original profile, which would modify it.
let fb,cb;const stats={origins:origins.length,restored:0,skipped:0,sourceSkipped:0,errors:[]};
try {
cp.execFileSync('cp',['-a','--reflink=auto',fx,clone],{timeout:120000});
const pp=require('puppeteer-core');
fb=await pp.launch({browser:'firefox',protocol:'webDriverBiDi',executablePath:opts.firefox,
userDataDir:clone,headless:true,timeout:20000});
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']});
const sourcePage=await inertPage(fb,'firefox'),destPage=await inertPage(cb,'chromium');
for(const [i,origin]of origins.entries()){
try {
await navigateOffline(sourcePage,origin,opts.timeout);
const exported=await snapshotOrigin(sourcePage);
if(exported.errors.length){stats.sourceSkipped+=exported.errors.length;stats.errors.push({originIndex:i+1,reason:'Unsupported source database/record type'});}
if(!exported.databases.length)continue;
await navigateOffline(destPage,origin,opts.timeout);
const result=await restoreOrigin(destPage,exported);
stats.restored+=result.restored;stats.skipped+=result.skipped;
if(result.errors.length)stats.errors.push({originIndex:i+1,reason:'Target database skipped or unsupported'});
}catch(e){stats.skipped++;stats.errors.push({originIndex:i+1,reason:String(e.message||e).slice(0,150)});}
}
await sourcePage.close();await destPage.close();
}finally {
if(fb)await fb.close();if(cb)await cb.close();
fs.rmSync(scratch,{recursive:true,force:true});
}
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));
if(stats.skipped||stats.sourceSkipped)process.exitCode=2;
return stats;
}
if(require.main===module){
try{const o=options(process.argv.slice(2));
if(o.help)console.log('Usage: node tools/indexeddb_migrate.cjs --firefox-profile PATH --chromium-profile PATH --firefox /usr/local/bin/firefox --chromium /usr/bin/google-chrome [--apply]\nDry-run by default. Use closed profiles; back up both before --apply. Existing target IndexedDB databases will be skipped.');
else migrate(o).catch(e=>{console.error('IndexedDB transfer failed:',e.message);process.exitCode=1});
}catch(e){console.error(e.message);process.exitCode=1;}
}
module.exports={options,originsForFirefox,inertPage,navigateOffline,snapshotOrigin,restoreOrigin,migrate};
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env python3
"""List Firefox first-party HTTP(S) IndexedDB origins using QuotaManager metadata."""
import json
import sqlite3
import sys
from pathlib import Path
from urllib.parse import urlsplit
def list_origins(profile):
db = Path(profile) / 'storage.sqlite'
if not db.is_file():
raise FileNotFoundError(f'Missing Firefox QuotaManager storage.sqlite: {db}')
result = []
with 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
try:
u = urlsplit(origin)
if u.scheme in ('http','https') and u.hostname and u.path in ('','/') and not u.username and not u.password:
result.append(origin.rstrip('/'))
except ValueError:
pass
return sorted(set(result))
if __name__ == '__main__':
if len(sys.argv) != 2:
print('Usage: list_firefox_idb_origins.py PROFILE', file=sys.stderr)
sys.exit(2)
print(json.dumps(list_origins(sys.argv[1])))