mirror of
https://github.com/pvrzz/Portage.git
synced 2026-11-29 05:22:26 +00:00
audit: recover interrupted IndexedDB restores and harden codec edge cases
- Treat an existing destination database with no object stores (when the source has stores) as an interrupted upgrade: delete and retry instead of skipping it forever. Verified by killing Chrome mid-restore; the next run restored all 49,990 synthetic records. - Keep snapshot error indices aligned with the actual database index. - Look up Error constructors through a Map: a site-controlled Error.name of "constructor"/"__proto__"/"toString" could corrupt the value or abort the DB. - Brand-check Number/String/Boolean wrappers instead of toString sniffing so Symbol.toStringTag cannot change a plain object's type; accept ordinary class instances as plain objects (prototype dropped, matching structured clone) while still rejecting platform-object tags. - Preserve AggregateError.errors and ImageData.colorSpace. - Document the empty-container retry, the 120 s per-origin timeout and the additional clone types.
This commit is contained in:
+12
-7
@@ -94,10 +94,12 @@ it to a regular directory first). Source/destination paths that contain each
|
||||
other are also refused. 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. Schema and
|
||||
records are written in the same version-change transaction, so an interrupted
|
||||
restore cannot leave a schema-only database that a later run would skip; an
|
||||
aborted database is reported and can be retried after fixing the cause. A
|
||||
clean rerun reports intentional existing-database skips but exits successfully.
|
||||
records are written in the same version-change transaction. An interrupted
|
||||
restore can still leave an **empty version-1 database container** (no object
|
||||
stores); the next run detects that when the source database has stores, removes
|
||||
the empty container, and retries instead of skipping it forever. Databases that
|
||||
already contain object stores are preserved. A clean rerun reports intentional
|
||||
existing-database skips but exits successfully.
|
||||
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
|
||||
@@ -129,12 +131,14 @@ copies the whole Firefox profile, so treat it as sensitive.
|
||||
|
||||
**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,
|
||||
supported stored values: ordinary objects/arrays (class-instance prototypes are
|
||||
dropped, as in structured clone), strings/numbers/booleans,
|
||||
BigInt, Date, RegExp, Map/Set, binary buffers, typed arrays (including
|
||||
`Float16Array` where the browsers support it; multi-byte elements carry a byte
|
||||
order marker so cross-endian migrations do not byte-swap values), Blob/File,
|
||||
`Error` subclasses (name/message/stack/cause), `Number`/`String`/`Boolean`
|
||||
wrapper objects, and `ImageData`.
|
||||
wrapper objects, `AggregateError` (including `.errors`), and `ImageData`
|
||||
(including `colorSpace`).
|
||||
|
||||
**Still unsupported**: cyclic or shared object references, CryptoKey, other
|
||||
platform/browser objects, databases larger than 32 MiB in the encoded wire
|
||||
@@ -142,7 +146,8 @@ representation, an origin whose encoded payload exceeds 64 MiB, stores with
|
||||
over 50,000 records, arrays with over 50,000 elements, individual
|
||||
Blob/File/ArrayBuffer/typed-array/ImageData values larger than 8 MiB (checked
|
||||
before they are expanded), and a per-origin snapshot/restore that takes longer
|
||||
than 120 seconds. The bridge **skips entire databases** when it finds
|
||||
than 120 seconds (a timed-out run aborts and the next run retries a left-over
|
||||
empty database container). 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
|
||||
|
||||
+31
-10
@@ -92,25 +92,36 @@ async function encode(value, seen = new WeakSet()) {
|
||||
const arr=[];for(const v of value)arr.push(await encode(v,seen));return {t:'set',v:arr};
|
||||
}
|
||||
// Structured-cloneable built-ins that are not plain objects.
|
||||
if(typeof AggregateError!=='undefined' && value instanceof AggregateError){
|
||||
const encoded={t:'aggregateerror',message:value.message,stack:value.stack,errors:[]};
|
||||
for(const nested of value.errors) encoded.errors.push(await encode(nested,seen));
|
||||
if(Object.prototype.hasOwnProperty.call(value,'cause')) encoded.cause=await encode(value.cause,seen);
|
||||
return encoded;
|
||||
}
|
||||
if(value instanceof Error){
|
||||
const encoded={t:'error',name:value.name,message:value.message,stack:value.stack};
|
||||
if(Object.prototype.hasOwnProperty.call(value,'cause')) encoded.cause=await encode(value.cause,seen);
|
||||
return encoded;
|
||||
}
|
||||
const tag=Object.prototype.toString.call(value);
|
||||
if(tag==='[object Number]')return {t:'numberobject',v:encodeNumber(value.valueOf())};
|
||||
if(tag==='[object String]')return {t:'stringobject',v:value.valueOf()};
|
||||
if(tag==='[object Boolean]')return {t:'booleanobject',v:value.valueOf()};
|
||||
// Brand checks, not Object.prototype.toString sniffing: a site-controlled
|
||||
// Symbol.toStringTag must not turn an ordinary object into a wrapper.
|
||||
try{return {t:'numberobject',v:encodeNumber(Number.prototype.valueOf.call(value))};}catch{}
|
||||
try{return {t:'stringobject',v:String.prototype.valueOf.call(value)};}catch{}
|
||||
try{return {t:'booleanobject',v:Boolean.prototype.valueOf.call(value)};}catch{}
|
||||
if(typeof ImageData!=='undefined' && value instanceof ImageData){
|
||||
assertBinaryLimit(value.data.byteLength,'ImageData');
|
||||
return {t:'imagedata',w:value.width,h:value.height,
|
||||
return {t:'imagedata',w:value.width,h:value.height,cs:value.colorSpace,
|
||||
data:bytesToBase64(new Uint8Array(value.data.buffer,value.data.byteOffset,value.data.byteLength))};
|
||||
}
|
||||
if(Object.getPrototypeOf(value)!==Object.prototype && Object.getPrototypeOf(value)!==null)
|
||||
const prototype=Object.getPrototypeOf(value);
|
||||
if(prototype!==Object.prototype && prototype!==null &&
|
||||
Object.prototype.toString.call(value)!=='[object Object]')
|
||||
throw new Error('Unsupported IndexedDB object prototype');
|
||||
// Ordinary class instances are structured-cloneable; the clone drops the
|
||||
// prototype, so encode own enumerable properties as a plain object.
|
||||
const pairs=[];
|
||||
for (const k of Object.keys(value)) pairs.push([k,await encode(value[k],seen)]);
|
||||
return {t:'object',plain:Object.getPrototypeOf(value)===Object.prototype,v:pairs};
|
||||
return {t:'object',plain:prototype!==null,v:pairs};
|
||||
}
|
||||
|
||||
function decode(o){
|
||||
@@ -136,20 +147,30 @@ function decode(o){
|
||||
case 'blob':return new Blob([base64ToBytes(o.v)],{type:o.mime});
|
||||
case 'file':return new File([base64ToBytes(o.v)],o.name,{type:o.mime,lastModified:o.lastModified});
|
||||
case 'error': {
|
||||
const types={Error,TypeError,RangeError,SyntaxError,ReferenceError,EvalError,URIError};
|
||||
const Ctor=types[o.name]||Error;
|
||||
const types=new Map([['Error',Error],['TypeError',TypeError],['RangeError',RangeError],
|
||||
['SyntaxError',SyntaxError],['ReferenceError',ReferenceError],['EvalError',EvalError],['URIError',URIError]]);
|
||||
const Ctor=types.get(o.name)||Error;
|
||||
const error=new Ctor(o.message||'');
|
||||
if(o.name)error.name=o.name;
|
||||
if(o.stack)error.stack=o.stack;
|
||||
if('cause' in o)error.cause=decode(o.cause);
|
||||
return error;
|
||||
}
|
||||
case 'aggregateerror': {
|
||||
if(typeof AggregateError==='undefined')throw new Error('AggregateError is not supported in this browser');
|
||||
const error=new AggregateError(o.errors.map(decode),o.message||'');
|
||||
if(o.stack)error.stack=o.stack;
|
||||
if('cause' in o)error.cause=decode(o.cause);
|
||||
return error;
|
||||
}
|
||||
case 'numberobject':return new Number(decode(o.v));
|
||||
case 'stringobject':return new String(o.v);
|
||||
case 'booleanobject':return new Boolean(o.v);
|
||||
case 'imagedata': {
|
||||
if(typeof ImageData==='undefined')throw new Error('ImageData is not supported in this browser');
|
||||
return new ImageData(new Uint8ClampedArray(base64ToBytes(o.data)),o.w,o.h);
|
||||
const data=new Uint8ClampedArray(base64ToBytes(o.data));
|
||||
if(o.cs){try{return new ImageData(data,o.w,o.h,{colorSpace:o.cs});}catch{}}
|
||||
return new ImageData(data,o.w,o.h);
|
||||
}
|
||||
case 'array': {
|
||||
const arr=new Array(o.v.length);
|
||||
|
||||
+45
-12
@@ -71,7 +71,7 @@ async function snapshotOrigin(page) {
|
||||
const {encode}=globalThis.PortageIDBCodec;
|
||||
const output={databases:[],errors:[]};
|
||||
const metas=await indexedDB.databases();
|
||||
for(const meta of metas) {
|
||||
for(const [dbIndex, meta] of metas.entries()) {
|
||||
if(typeof meta.name!=='string')continue;
|
||||
let db;
|
||||
try {
|
||||
@@ -115,7 +115,7 @@ async function snapshotOrigin(page) {
|
||||
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));}
|
||||
}catch(e){output.errors.push('Database '+dbIndex+' skipped: '+String(e.message||e).slice(0,160));}
|
||||
finally {db?.close();}
|
||||
}
|
||||
return output;
|
||||
@@ -125,10 +125,46 @@ async function snapshotOrigin(page) {
|
||||
async function restoreOrigin(page,source) {
|
||||
return page.evaluate(async ({source})=>{
|
||||
const {decode}=globalThis.PortageIDBCodec;
|
||||
const results={restored:0,skipped:0,errors:[]};
|
||||
const results={restored:0,skipped:0,retried:0,errors:[]};
|
||||
const existing=new Set((await indexedDB.databases()).map(x=>x.name));
|
||||
const deleteDatabase=name=>new Promise((resolve,reject)=>{
|
||||
const request=indexedDB.deleteDatabase(name);
|
||||
request.onsuccess=()=>resolve();
|
||||
request.onerror=()=>reject(request.error||Error('DB deletion failed'));
|
||||
request.onblocked=()=>reject(Error('DB deletion blocked'));
|
||||
});
|
||||
const openExisting=name=>new Promise((resolve,reject)=>{
|
||||
const request=indexedDB.open(name);
|
||||
request.onsuccess=()=>resolve(request.result);
|
||||
request.onerror=()=>reject(request.error||Error('DB open failed'));
|
||||
request.onblocked=()=>reject(Error('DB open blocked'));
|
||||
});
|
||||
for(const spec of source.databases) {
|
||||
if(existing.has(spec.name)) {results.skipped++;continue;}
|
||||
let needsRestore=true;
|
||||
if(existing.has(spec.name)) {
|
||||
let previous=null;
|
||||
try {
|
||||
previous=await openExisting(spec.name);
|
||||
const storeCount=previous.objectStoreNames.length;
|
||||
previous.close();previous=null;
|
||||
if(storeCount===0 && spec.stores.length>0) {
|
||||
// An interrupted upgrade can leave an empty version-1 container
|
||||
// with no object stores. Treat it as an incomplete attempt, remove
|
||||
// it, and retry instead of skipping the origin forever.
|
||||
await deleteDatabase(spec.name);
|
||||
results.retried++;
|
||||
} else {
|
||||
results.skipped++;
|
||||
needsRestore=false;
|
||||
}
|
||||
}catch(e){
|
||||
if(previous)previous.close();
|
||||
results.skipped++;
|
||||
results.errors.push(String(e.message||e).slice(0,160));
|
||||
needsRestore=false;
|
||||
}
|
||||
}
|
||||
if(!needsRestore)continue;
|
||||
let db;
|
||||
let created=false;
|
||||
let failure=null;
|
||||
@@ -172,11 +208,8 @@ async function restoreOrigin(page,source) {
|
||||
// delete a target database when validation failed before creation.
|
||||
if(db){db.close();db=null;}
|
||||
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');}
|
||||
try{await deleteDatabase(spec.name);}
|
||||
catch{results.errors.push('Partial database cleanup failed; inspect target profile');}
|
||||
}
|
||||
}finally {db?.close();}
|
||||
}
|
||||
@@ -231,7 +264,7 @@ async function migrate(opts) {
|
||||
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:[]};
|
||||
let fb,cb;const stats={origins:origins.length,restored:0,skipped:0,retried:0,sourceSkipped:0,errors:[]};
|
||||
try {
|
||||
cloneFirefoxProfile(fx,clone);
|
||||
const pp=require('puppeteer-core');
|
||||
@@ -258,7 +291,7 @@ async function migrate(opts) {
|
||||
if(!exported.databases.length)continue;
|
||||
await navigateOffline(destPage,origin,opts.timeout);
|
||||
const result=await withTimeout(restoreOrigin(destPage,exported),120000,'IndexedDB restore');
|
||||
stats.restored+=result.restored;stats.skipped+=result.skipped;
|
||||
stats.restored+=result.restored;stats.skipped+=result.skipped;stats.retried+=result.retried||0;
|
||||
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)});if(String(e.message||'').includes('timed out'))throw e;}
|
||||
}
|
||||
@@ -273,7 +306,7 @@ async function migrate(opts) {
|
||||
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.`);
|
||||
console.log(`IndexedDB migration: ${stats.restored} database(s) restored; ${stats.retried} interrupted database(s) retried; ${stats.skipped} target skips; ${stats.sourceSkipped} source skips.`);
|
||||
if(stats.errors.length)console.log('Failures (origin indices only, no contents):',JSON.stringify(stats.errors));
|
||||
// Existing destination databases are intentionally skipped, so only real
|
||||
// source/restore errors make the command exit non-zero.
|
||||
|
||||
Reference in New Issue
Block a user