mirror of
https://github.com/pvrzz/Portage.git
synced 2026-11-29 05:22:26 +00:00
feat: migrate Firefox IndexedDB through offline browser-native bridge
This commit is contained in:
@@ -18,11 +18,18 @@ jobs:
|
||||
run: python3 -m unittest discover -s tests -p 'test_*.py'
|
||||
- name: Browser API mock tests
|
||||
run: node tests/test_storage_browser.cjs
|
||||
- name: IndexedDB codec tests
|
||||
run: node tests/test_indexeddb_codec.cjs
|
||||
- name: Python syntax
|
||||
run: python3 -m py_compile tools/list_firefox_idb_origins.py tools/firefox_localstorage.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
|
||||
- name: CLI help
|
||||
run: node tools/chromium_localstorage_import.cjs --help
|
||||
|
||||
@@ -67,3 +67,7 @@ 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.
|
||||
|
||||
### 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.
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
'use strict';
|
||||
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');
|
||||
const {migrate,originsForFirefox,inertPage,navigateOffline}=require('../tools/indexeddb_migrate.cjs');
|
||||
async function main(){
|
||||
const scratch=fs.mkdtempSync(path.join(os.tmpdir(),'portage-idb-test-'));
|
||||
const fx=path.join(scratch,'firefox'),chrome=path.join(scratch,'chrome');
|
||||
const hits=[0,0];
|
||||
const servers=[0,1].map(i=>http.createServer((req,res)=>{hits[i]++;res.writeHead(200,{'content-type':'text/html; charset=utf-8','cache-control':'no-store'});res.end('<!doctype html><title>fixture</title>');}));
|
||||
await Promise.all(servers.map(s=>new Promise(resolve=>s.listen(0,'127.0.0.1',resolve))));
|
||||
const origins=servers.map(s=>`http://127.0.0.1:${s.address().port}`);
|
||||
let browser;
|
||||
try {
|
||||
browser=await pp.launch({browser:'firefox',protocol:'webDriverBiDi',executablePath:'/usr/local/bin/firefox',userDataDir:fx,headless:true});
|
||||
const page=await browser.newPage();
|
||||
for(const [n,origin] of origins.entries()) {
|
||||
await page.goto(origin);
|
||||
await page.evaluate(async number=>{
|
||||
const r=indexedDB.open('portage-indexeddb-test',7);
|
||||
await new Promise((resolve,reject)=>{
|
||||
r.onupgradeneeded=()=>{
|
||||
const db=r.result;
|
||||
db.createObjectStore('keyed',{keyPath:'id'}).createIndex('by-name','name',{unique:true});
|
||||
db.createObjectStore('auto',{autoIncrement:true}).createIndex('by-tag','tag',{multiEntry:true});
|
||||
};
|
||||
r.onsuccess=()=>resolve();r.onerror=()=>reject(r.error);
|
||||
});
|
||||
const db=r.result;
|
||||
await new Promise((resolve,reject)=>{
|
||||
const tx=db.transaction(['keyed','auto'],'readwrite');
|
||||
const obj={id:number+1,name:'site-'+number,when:new Date('2020-02-03T04:05:06Z'),
|
||||
bytes:new Uint8Array([1,2,3,255]),big:12345678901234567890n,
|
||||
blob:new Blob(['file-contents'],{type:'text/plain'}),
|
||||
map:new Map([['hello','猫']]),set:new Set(['a','b']),
|
||||
maybe:undefined,negativeZero:-0};
|
||||
tx.objectStore('keyed').put(obj);
|
||||
tx.objectStore('auto').put({tag:['alpha','beta'],value:'origin-'+number});
|
||||
tx.oncomplete=resolve;tx.onerror=()=>reject(tx.error);
|
||||
});
|
||||
db.close();
|
||||
},n);
|
||||
}
|
||||
await browser.close();browser=null;
|
||||
assert.deepEqual(originsForFirefox(fx),[...origins].sort());
|
||||
const before=hits.slice();
|
||||
const stats=await migrate({firefoxProfile:fx,chromiumProfile:chrome,firefox:'/usr/local/bin/firefox',chromium:'/usr/bin/google-chrome',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:'/usr/bin/google-chrome',userDataDir:chrome,headless:true,args:['--disable-background-networking']});
|
||||
const verify=await inertPage(browser,'chromium');
|
||||
for(const [n,origin] of origins.entries()){
|
||||
await navigateOffline(verify,origin,20000);
|
||||
const result=await verify.evaluate(async()=>{
|
||||
const names=await indexedDB.databases();
|
||||
const r=indexedDB.open('portage-indexeddb-test');
|
||||
const db=await new Promise((ok,no)=>{r.onsuccess=()=>ok(r.result);r.onerror=()=>no(r.error)});
|
||||
const t=db.transaction(['keyed','auto'],'readonly');
|
||||
const s=t.objectStore('keyed');const a=t.objectStore('auto');
|
||||
const obj=await new Promise((ok,no)=>{let q=s.getAll();q.onsuccess=()=>ok(q.result[0]);q.onerror=()=>no(q.error)});
|
||||
const au=await new Promise((ok,no)=>{let q=a.getAll();q.onsuccess=()=>ok(q.result[0]);q.onerror=()=>no(q.error)});
|
||||
const byName=await new Promise((ok,no)=>{let q=s.index('by-name').get(obj.name);q.onsuccess=()=>ok(q.result);q.onerror=()=>no(q.error)});
|
||||
const byTag=await new Promise((ok,no)=>{let q=a.index('by-tag').get('alpha');q.onsuccess=()=>ok(q.result);q.onerror=()=>no(q.error)});
|
||||
const results={version:db.version,storeCount:db.objectStoreNames.length,
|
||||
name:obj.name,id:obj.id,when:obj.when.toISOString(),bytes:Array.from(obj.bytes),
|
||||
big:String(obj.big),blob:await obj.blob.text(),map:obj.map.get('hello'),set:Array.from(obj.set),
|
||||
undefinedValue:obj.maybe===undefined,negativeZero:Object.is(obj.negativeZero,-0),
|
||||
byName:byName.name,byTag:byTag.value,autoValue:au.value};
|
||||
db.close();return results;
|
||||
});
|
||||
assert.deepEqual(result,{version:7,storeCount:2,name:'site-'+n,id:n+1,
|
||||
when:'2020-02-03T04:05:06.000Z',bytes:[1,2,3,255],
|
||||
big:'12345678901234567890',blob:'file-contents',map:'猫',set:['a','b'],
|
||||
undefinedValue:true,negativeZero:true,byName:'site-'+n,byTag:'origin-'+n,autoValue:'origin-'+n});
|
||||
}
|
||||
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:'/usr/bin/google-chrome',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');
|
||||
}finally{
|
||||
if(browser)await browser.close();
|
||||
await Promise.all(servers.map(s=>new Promise(ok=>s.close(ok))));
|
||||
fs.rmSync(scratch,{recursive:true,force:true});
|
||||
}
|
||||
}
|
||||
main().catch(e=>{console.error(e.stack);process.exitCode=1});
|
||||
@@ -0,0 +1,31 @@
|
||||
'use strict';
|
||||
const assert=require('node:assert/strict');
|
||||
const {encode,decode}=require('../tools/indexeddb_codec.js');
|
||||
(async()=>{
|
||||
const entries=[undefined,null,true,false,'hello 猫',0,-0,1.25,NaN,Infinity,-Infinity,123n,
|
||||
new Date('2021-02-03T04:05:06Z'), new Date(NaN),/abc/gi,
|
||||
new Uint8Array([0,200,255]),new Int32Array([-2,1,900]),new DataView(new Uint8Array([7,8,9]).buffer),
|
||||
new Blob(['hello'],{type:'text/plain'}),new Map([['a',12]]),new Set(['a','b']),
|
||||
[1,undefined,'x'],{a:'__proto__',nested:{b:'yes'}}];
|
||||
for(const entry of entries){
|
||||
const encoded=JSON.parse(JSON.stringify(await encode(entry)));
|
||||
const restored=decode(encoded);
|
||||
if(entry===undefined) assert.equal(restored,undefined);
|
||||
else if(typeof entry==='number')assert(Object.is(restored,entry));
|
||||
else if(typeof entry==='bigint')assert.equal(restored,entry);
|
||||
else if(entry instanceof Blob)assert.equal(await restored.text(),await entry.text());
|
||||
else if(entry instanceof Date)assert.equal(Number.isNaN(entry.valueOf())?Number.isNaN(restored.valueOf()):restored.valueOf(),Number.isNaN(entry.valueOf())?true:entry.valueOf());
|
||||
else if(entry instanceof RegExp)assert.equal(restored.toString(),entry.toString());
|
||||
else if(entry instanceof DataView)assert.deepEqual(Array.from(new Uint8Array(restored.buffer)),Array.from(new Uint8Array(entry.buffer)));
|
||||
else if(ArrayBuffer.isView(entry))assert.deepEqual(Array.from(restored),Array.from(entry));
|
||||
else if(entry instanceof Map||entry instanceof Set)assert.deepEqual([...restored],[...entry]);
|
||||
else assert.deepEqual(JSON.parse(JSON.stringify(restored)),JSON.parse(JSON.stringify(entry)));
|
||||
}
|
||||
const cycle={};cycle.self=cycle;
|
||||
await assert.rejects(()=>encode(cycle),/cyclic/);
|
||||
const special=Object.create(null);Object.defineProperty(special,'__proto__',{value:{safe:1},enumerable:true});
|
||||
const recovered=decode(JSON.parse(JSON.stringify(await encode(special))));
|
||||
assert.equal(Object.getPrototypeOf(recovered),null);
|
||||
assert.deepEqual(recovered['__proto__'].safe,1);
|
||||
console.log('PASS: IndexedDB codec rich types, -0, invalid dates, cyclic rejection and prototype safety');
|
||||
})().catch(e=>{console.error(e.stack);process.exitCode=1});
|
||||
@@ -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
|
||||
```
|
||||
|
||||
@@ -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};
|
||||
@@ -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};
|
||||
@@ -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])))
|
||||
Reference in New Issue
Block a user