mirror of
https://github.com/pvrzz/Portage.git
synced 2026-11-29 05:22:26 +00:00
test: harden IndexedDB migration and verify Brave Stable compatibility
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
// Real Chromium/Brave WebExtensions smoke test, using only temporary browser
|
||||
// profiles and a local HTTP fixture; no personal browser profiles or secrets.
|
||||
'use strict';
|
||||
const CHROMIUM = process.env.PORTAGE_TEST_CHROMIUM || '/usr/bin/google-chrome';
|
||||
const assert = require('node:assert/strict');
|
||||
const http = require('node:http');
|
||||
const os = require('node:os');
|
||||
@@ -27,7 +28,7 @@ async function main() {
|
||||
const extDir = path.resolve('chrome');
|
||||
let browser;
|
||||
try {
|
||||
browser = await puppeteer.launch({executablePath: '/usr/bin/google-chrome',headless:true,userDataDir:dir,timeout:25000,pipe:true,enableExtensions:true,args:['--no-sandbox','--disable-gpu','--no-first-run','--no-default-browser-check']});
|
||||
browser = await puppeteer.launch({executablePath: CHROMIUM,headless:true,userDataDir:dir,timeout:25000,pipe:true,enableExtensions:true,args:['--no-sandbox','--disable-gpu','--no-first-run','--no-default-browser-check']});
|
||||
const id=await browser.installExtension(extDir);
|
||||
console.log('installed id:',id);
|
||||
if (!id) throw new Error('Portage extension failed to load');
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// Firefox 159 -> AES encrypted Portage file -> offline Chrome 156 import.
|
||||
// Creates only disposable profiles and uses synthetic site values.
|
||||
'use strict';
|
||||
const CHROMIUM = process.env.PORTAGE_TEST_CHROMIUM || '/usr/bin/google-chrome';
|
||||
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');
|
||||
@@ -42,13 +43,13 @@ async function main(){
|
||||
// Exercise the actual command-line importer, including encrypted input.
|
||||
const imported=spawnSync(process.execPath,[
|
||||
'tools/chromium_localstorage_import.cjs',
|
||||
'--bundle',file,'--user-data-dir',chrome,'--browser','/usr/bin/google-chrome',
|
||||
'--bundle',file,'--user-data-dir',chrome,'--browser',CHROMIUM,
|
||||
'--passphrase-stdin','--apply'
|
||||
],{input:passphrase+'\n',encoding:'utf8',env:process.env,timeout:30000});
|
||||
assert.equal(imported.status,0,imported.stderr+'\n'+imported.stdout);
|
||||
assert(imported.stdout.includes('Imported 1/1 origins'), imported.stdout);
|
||||
assert.equal(requests,before,'Offline import must not access website');
|
||||
browser=await pp.launch({executablePath:'/usr/bin/google-chrome',headless:true,userDataDir:chrome,args:['--disable-background-networking','--no-first-run']});
|
||||
browser=await pp.launch({executablePath:CHROMIUM,headless:true,userDataDir:chrome,args:['--disable-background-networking','--no-first-run']});
|
||||
const page=await browser.newPage();
|
||||
await page.goto(origin);
|
||||
const v=await page.evaluate(()=>({first:localStorage.getItem('migration_probe'),len:localStorage.getItem('large_probe').length}));
|
||||
|
||||
+16
-4
@@ -1,11 +1,12 @@
|
||||
'use strict';
|
||||
const CHROMIUM = process.env.PORTAGE_TEST_CHROMIUM || '/usr/bin/google-chrome';
|
||||
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');
|
||||
const {migrate,originsForFirefox,inertPage,navigateOffline,restoreOrigin}=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');
|
||||
@@ -47,10 +48,10 @@ 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:'/usr/bin/google-chrome',apply:true,timeout:20000});
|
||||
const stats=await migrate({firefoxProfile:fx,chromiumProfile:chrome,firefox:'/usr/local/bin/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:'/usr/bin/google-chrome',userDataDir:chrome,headless:true,args:['--disable-background-networking']});
|
||||
browser=await pp.launch({executablePath:CHROMIUM,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);
|
||||
@@ -75,11 +76,22 @@ async function main(){
|
||||
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});
|
||||
// Invalid structured clone payload must not create a partially valid DB.
|
||||
const rejected=await restoreOrigin(verify,{databases:[{
|
||||
name:'portage-unsupported-test',version:1,stores:[{
|
||||
name:'bad',keyPath:null,autoIncrement:false,indexes:[],
|
||||
records:[[{t:'number',v:1},{t:'unsupported-cryptokey'}]]
|
||||
}]
|
||||
}]});
|
||||
assert.equal(rejected.restored,0);
|
||||
assert.equal(rejected.skipped,1);
|
||||
const after=await verify.evaluate(()=>indexedDB.databases());
|
||||
assert(!after.some(x=>x.name==='portage-unsupported-test'), 'Rejected DB should not exist');
|
||||
}
|
||||
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});
|
||||
const repeated=await migrate({firefoxProfile:fx,chromiumProfile:chrome,firefox:'/usr/local/bin/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');
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#!/usr/bin/env node
|
||||
'use strict';
|
||||
const CHROMIUM = process.env.PORTAGE_TEST_CHROMIUM || '/usr/bin/google-chrome';
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
@@ -20,9 +21,9 @@ async function main() {
|
||||
fs.writeFileSync(file,JSON.stringify(bundle),{mode:0o600});
|
||||
try {
|
||||
assert.equal(validateBundle(bundle).totalKeys,2);
|
||||
await run({bundle:file, userDataDir:profile, browser:'/usr/bin/google-chrome', profileDirectory:'Default', timeout:12000, apply:true});
|
||||
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:'/usr/bin/google-chrome',headless:true,userDataDir:profile,args:['--no-sandbox','--disable-background-networking']});
|
||||
const browser=await puppeteer.launch({executablePath:CHROMIUM,headless:true,userDataDir:profile,args:['--no-sandbox','--disable-background-networking']});
|
||||
try {
|
||||
const page=await browser.newPage();
|
||||
await page.goto(origin);
|
||||
|
||||
@@ -27,5 +27,11 @@ const {encode,decode}=require('../tools/indexeddb_codec.js');
|
||||
const recovered=decode(JSON.parse(JSON.stringify(await encode(special))));
|
||||
assert.equal(Object.getPrototypeOf(recovered),null);
|
||||
assert.deepEqual(recovered['__proto__'].safe,1);
|
||||
const normal={alpha:1};
|
||||
const normalRestored=decode(JSON.parse(JSON.stringify(await encode(normal))));
|
||||
assert.equal(Object.getPrototypeOf(normalRestored),Object.prototype);
|
||||
const arr=[1,,3];arr.label='tag';
|
||||
const arrRestored=decode(JSON.parse(JSON.stringify(await encode(arr))));
|
||||
assert.equal(arrRestored.label,'tag');assert.equal(1 in arrRestored,false);
|
||||
console.log('PASS: IndexedDB codec rich types, -0, invalid dates, cyclic rejection and prototype safety');
|
||||
})().catch(e=>{console.error(e.stack);process.exitCode=1});
|
||||
|
||||
+4
-5
@@ -29,7 +29,7 @@ The Portage extension cannot enumerate every origin's LocalStorage via WebExtens
|
||||
2. Install the *optional* importer dependency, once:
|
||||
|
||||
```bash
|
||||
cd tools && npm install && cd ..
|
||||
cd tools && npm ci && cd ..
|
||||
```
|
||||
|
||||
3. Close Brave. Check data counts in **dry-run** mode (the default):
|
||||
@@ -80,8 +80,7 @@ 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
|
||||
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.
|
||||
|
||||
```bash
|
||||
@@ -102,8 +101,8 @@ node tools/indexeddb_migrate.cjs \
|
||||
|
||||
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`
|
||||
BiDi; validated with Firefox 159.0b5, Google Chrome 156.0.8078.47, and
|
||||
**Brave Stable 1.98.60** in disposable test profiles. Origin enumeration reads the QuotaManager `storage.sqlite`
|
||||
metadata; only HTTP(S) origins without Firefox container/partition attributes
|
||||
are considered. It does not inspect Chrome or Firefox passwords/cookies.
|
||||
|
||||
|
||||
@@ -25,9 +25,16 @@ async function encode(value, seen = new WeakSet()) {
|
||||
return {t:'blob',v,mime:value.type};
|
||||
}
|
||||
if(Array.isArray(value)) {
|
||||
if(value.length>50000)throw new Error('Array exceeds migration length limit');
|
||||
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};
|
||||
// Preserve custom enumerable properties, not only numeric array elements.
|
||||
const extras=[];
|
||||
for(const k of Object.keys(value)) {
|
||||
if(/^(0|[1-9][0-9]*)$/.test(k) && Number(k)<value.length)continue;
|
||||
extras.push([k,await encode(value[k],seen)]);
|
||||
}
|
||||
return {t:'array',v:items,extras};
|
||||
}
|
||||
if(value instanceof Map) {
|
||||
const pairs=[];for(const [k,v] of value) pairs.push([await encode(k,seen),await encode(v,seen)]);
|
||||
@@ -40,7 +47,7 @@ async function encode(value, seen = new WeakSet()) {
|
||||
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};
|
||||
return {t:'object',plain:Object.getPrototypeOf(value)===Object.prototype,v:pairs};
|
||||
}
|
||||
function decode(o){
|
||||
if(!o || typeof o.t!=='string')throw new Error('Invalid encoded value');
|
||||
@@ -65,16 +72,19 @@ function decode(o){
|
||||
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]);
|
||||
for(const [k,v]of (o.extras||[]))Object.defineProperty(arr,k,{value:decode(v),enumerable:true,writable:true,configurable:true});
|
||||
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);
|
||||
const obj=o.plain===false?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};
|
||||
// CommonJS for unit tests; browser global for the inert migration document.
|
||||
if(typeof module !== 'undefined' && module.exports)module.exports={encode,decode};
|
||||
else Object.defineProperty(globalThis,'PortageIDBCodec',{value:Object.freeze({encode,decode}),writable:false,configurable:false});
|
||||
|
||||
+43
-13
@@ -9,7 +9,6 @@ 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) {
|
||||
@@ -37,6 +36,8 @@ function originsForFirefox(profile) {
|
||||
|
||||
async function inertPage(browser, kind) {
|
||||
const page=await browser.newPage();
|
||||
// Do not let a source page escape into another origin or create popups.
|
||||
page.on('popup', popup => popup.close().catch(() => {}));
|
||||
if(kind==='chromium') {await page.setBypassServiceWorker(true);await page.setCacheEnabled(false);}
|
||||
await page.setRequestInterception(true);
|
||||
page.on('request',request => {
|
||||
@@ -49,11 +50,13 @@ async function inertPage(browser, kind) {
|
||||
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');
|
||||
// Load trusted codec from the local repository, no eval or remote scripts.
|
||||
await page.addScriptTag({path:path.join(__dirname,'indexeddb_codec.js')});
|
||||
}
|
||||
|
||||
async function snapshotOrigin(page) {
|
||||
return page.evaluate(async (source) => {
|
||||
const encode=(0,eval)('('+source+')'); // trusted, embedded function source; never user input
|
||||
return page.evaluate(async () => {
|
||||
const {encode}=globalThis.PortageIDBCodec;
|
||||
const output={databases:[],errors:[]};
|
||||
const metas=await indexedDB.databases();
|
||||
for(const meta of metas) {
|
||||
@@ -74,13 +77,14 @@ async function snapshotOrigin(page) {
|
||||
indexes:Array.from(store.indexNames,n=>{
|
||||
const ix=store.index(n);return {name:ix.name,keyPath:ix.keyPath,unique:ix.unique,multiEntry:ix.multiEntry};
|
||||
}),records:[]};
|
||||
// Cap retrieval at 50,001 entries; never materialize unbounded stores.
|
||||
const values=await new Promise((resolve,reject)=>{
|
||||
const req=store.getAll();req.onsuccess=()=>resolve(req.result);req.onerror=()=>reject(req.error);
|
||||
const req=store.getAll(undefined,50001);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);
|
||||
const req=tx2.objectStore(storeName).getAllKeys(undefined,50001);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)');
|
||||
@@ -94,17 +98,18 @@ async function snapshotOrigin(page) {
|
||||
finally {db?.close();}
|
||||
}
|
||||
return output;
|
||||
},encode.toString());
|
||||
});
|
||||
}
|
||||
|
||||
async function restoreOrigin(page,source) {
|
||||
return page.evaluate(async ({source,codec})=>{
|
||||
const decode=(0,eval)('('+codec+')');
|
||||
return page.evaluate(async ({source})=>{
|
||||
const {decode}=globalThis.PortageIDBCodec;
|
||||
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;
|
||||
let created=false;
|
||||
try {
|
||||
// Decode EVERYTHING before creating the DB; unsupported values must not
|
||||
// leave a partially initialized destination schema.
|
||||
@@ -113,6 +118,7 @@ async function restoreOrigin(page,source) {
|
||||
db=await new Promise((resolve,reject)=>{
|
||||
const request=indexedDB.open(spec.name,spec.version);
|
||||
request.onupgradeneeded=()=>{
|
||||
created=true;
|
||||
try{
|
||||
const d=request.result;
|
||||
for(const s of decoded){
|
||||
@@ -143,13 +149,20 @@ async function restoreOrigin(page,source) {
|
||||
}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.
|
||||
// Only remove a database created by THIS migration attempt. Never
|
||||
// delete a target database when validation failed before creation.
|
||||
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{}
|
||||
if(created){
|
||||
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{results.errors.push('Partial database cleanup failed; inspect target profile');}
|
||||
}
|
||||
}finally {db?.close();}
|
||||
}
|
||||
return results;
|
||||
},{source,codec:decode.toString()});
|
||||
},{source});
|
||||
}
|
||||
|
||||
async function migrate(opts) {
|
||||
@@ -160,6 +173,13 @@ async function migrate(opts) {
|
||||
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');
|
||||
}
|
||||
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);
|
||||
@@ -171,7 +191,14 @@ async function migrate(opts) {
|
||||
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});
|
||||
userDataDir:clone,headless:true,timeout:20000,
|
||||
extraPrefsFirefox:{
|
||||
'browser.startup.page':0,
|
||||
'browser.startup.homepage':'about:blank',
|
||||
'browser.sessionstore.resume_from_crash':false,
|
||||
'dom.serviceWorkers.enabled':false,
|
||||
'extensions.enabledScopes':0,
|
||||
}});
|
||||
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']});
|
||||
@@ -190,7 +217,10 @@ async function migrate(opts) {
|
||||
}
|
||||
await sourcePage.close();await destPage.close();
|
||||
}finally {
|
||||
if(fb)await fb.close();if(cb)await cb.close();
|
||||
// Finally must always attempt to dispose of the sensitive source clone,
|
||||
// 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);}
|
||||
fs.rmSync(scratch,{recursive:true,force:true});
|
||||
}
|
||||
console.log(`IndexedDB migration: ${stats.restored} database(s) restored; ${stats.skipped} target skips; ${stats.sourceSkipped} source skips.`);
|
||||
|
||||
Reference in New Issue
Block a user