audit: make IndexedDB restore atomic and widen supported clone values

- Write schema and records in one versionchange transaction so an interrupted
  restore cannot leave a schema-only database that later runs skip forever.
  Existing-database skips no longer make a clean rerun exit non-zero.
- Encode binary payloads as base64 (much smaller and faster than number
  arrays), keep the 8 MiB per-value cap reachable inside the 32 MiB encoded
  budget, and check the encoded budget incrementally while snapshotting.
- Add Float16Array, Error subclasses (name/message/stack/cause),
  Number/String/Boolean wrappers and ImageData. Typed arrays carry a byte-order
  marker so a cross-endian migration cannot silently swap numeric values.
- Add 120 s per-origin snapshot/restore timeouts and document the 64 MiB origin
  cap, atomic restore, and the current limits.
- Extend the Firefox/Chrome IndexedDB E2E with these values, an aborted-restore
  atomicity check and the rerun semantics.
This commit is contained in:
souta
2026-10-23 21:15:53 +09:00
parent 21b0ca227b
commit 487282b5bd
5 changed files with 199 additions and 50 deletions
+23 -14
View File
@@ -93,11 +93,15 @@ markers are dropped, and a profile containing other symlinks is refused (copy
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. 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.
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.
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:
@@ -125,16 +129,21 @@ 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,
BigInt, Date, RegExp, Map/Set, binary buffers and typed arrays, Blob/File).
supported stored values: ordinary objects/arrays, 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`.
**Still unsupported**: cyclic or shared object references, CryptoKey,
non-standard browser objects, IndexedDB databases larger than 32 MiB in the
encoded wire representation, stores with over 50,000 records, arrays with over
50,000 elements, and individual Blob/File/ArrayBuffer/typed-array values larger
than 8 MiB (checked before they are expanded). The bridge
**skips entire databases** when it finds unsupported data, and reports
aggregate counts without printing record values.
**Still unsupported**: cyclic or shared object references, CryptoKey, other
platform/browser objects, databases larger than 32 MiB in the encoded wire
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
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
+88 -14
View File
@@ -1,17 +1,54 @@
/* Portable, lossless subset of IndexedDB structured-clone values.
Unsupported types and cyclic/shared references are refused, never silently discarded. */
Unsupported types and shared/cyclic references are refused, never silently discarded. */
'use strict';
const MAX_BINARY_BYTES = 8 * 1024 * 1024;
const LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
function assertBinaryLimit(bytes, label) {
if (bytes > MAX_BINARY_BYTES) throw new Error(label + ' larger than 8 MiB migration limit');
}
function bytesToBase64(bytes) {
let binary = '';
const chunk = 0x8000;
for (let i = 0; i < bytes.length; i += chunk) {
binary += String.fromCharCode.apply(null, bytes.subarray(i, i + chunk));
}
return btoa(binary);
}
function base64ToBytes(text) {
if (typeof text !== 'string') throw new Error('Invalid base64 binary payload');
const binary = atob(text);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
return bytes;
}
// Typed arrays are stored as raw bytes plus the source host's byte order. If
// the destination host uses the opposite order, swap each element so a
// big-endian migration cannot silently byte-swap numeric values.
function swapBytes(bytes, bytesPerElement) {
for (let i = 0; i < bytes.length; i += bytesPerElement) {
for (let j = 0; j < bytesPerElement / 2; j++) {
const a = i + j, b = i + bytesPerElement - 1 - j;
const tmp = bytes[a]; bytes[a] = bytes[b]; bytes[b] = tmp;
}
}
return bytes;
}
function encodeNumber(value) {
return {t: 'number', v: Object.is(value, -0) ? '-0' : Number.isFinite(value) ? value : String(value)};
}
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 === 'number') return encodeNumber(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);
@@ -19,18 +56,21 @@ async function encode(value, seen = new WeakSet()) {
if(value instanceof RegExp) return {t:'regexp',s:value.source,f:value.flags};
if(value instanceof ArrayBuffer){
assertBinaryLimit(value.byteLength,'ArrayBuffer');
return {t:'buffer',v:Array.from(new Uint8Array(value))};
return {t:'buffer',v:bytesToBase64(new Uint8Array(value))};
}
if(ArrayBuffer.isView(value)) {
assertBinaryLimit(value.byteLength,value.constructor.name);
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))};
const bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
if (value instanceof DataView) return {t:'dataview',v:bytesToBase64(bytes)};
return {t:'typedarray',type:value.constructor.name,v:bytesToBase64(bytes),le:LITTLE_ENDIAN};
}
if(typeof Blob !== 'undefined' && value instanceof Blob){
assertBinaryLimit(value.size, value instanceof File ? 'File' : 'Blob');
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};
const bytes = new Uint8Array(await value.arrayBuffer());
if(typeof File !== 'undefined' && value instanceof File){
return {t:'file',v:bytesToBase64(bytes),name:value.name,mime:value.type,lastModified:value.lastModified};
}
return {t:'blob',v:bytesToBase64(bytes),mime:value.type};
}
if(Array.isArray(value)) {
if(value.length>50000)throw new Error('Array exceeds migration length limit');
@@ -51,12 +91,28 @@ async function encode(value, seen = new WeakSet()) {
if(value instanceof Set) {
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(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()};
if(typeof ImageData!=='undefined' && value instanceof ImageData){
assertBinaryLimit(value.data.byteLength,'ImageData');
return {t:'imagedata',w:value.width,h:value.height,
data:bytesToBase64(new Uint8Array(value.data.buffer,value.data.byteOffset,value.data.byteLength))};
}
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',plain:Object.getPrototypeOf(value)===Object.prototype,v:pairs};
}
function decode(o){
if(!o || typeof o.t!=='string')throw new Error('Invalid encoded value');
switch(o.t){
@@ -67,16 +123,34 @@ function decode(o){
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 'buffer':return base64ToBytes(o.v).buffer;
case 'dataview':return new DataView(base64ToBytes(o.v).buffer);
case 'typedarray': {
const types={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array};
if(typeof Float16Array!=='undefined')types.Float16Array=Float16Array;
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');
const a=base64ToBytes(o.v); if(a.byteLength%ctor.BYTES_PER_ELEMENT)throw new Error('Invalid typed array data');
if(o.le!==undefined && o.le!==LITTLE_ENDIAN && ctor.BYTES_PER_ELEMENT>1)swapBytes(a,ctor.BYTES_PER_ELEMENT);
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 '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 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 '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);
}
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]);
@@ -94,5 +168,5 @@ function decode(o){
}
}
// CommonJS for unit tests; browser global for the inert migration document.
if(typeof module !== 'undefined' && module.exports)module.exports={encode,decode};
if(typeof module !== 'undefined' && module.exports)module.exports={encode,decode,MAX_BINARY_BYTES};
else Object.defineProperty(globalThis,'PortageIDBCodec',{value:Object.freeze({encode,decode}),writable:false,configurable:false});
+29 -19
View File
@@ -56,6 +56,16 @@ async function navigateOffline(page,origin,timeout) {
await page.addScriptTag({path:path.join(__dirname,'indexeddb_codec.js')});
}
function withTimeout(promise, timeoutMs, label) {
let timer;
return Promise.race([
promise,
new Promise((_,reject)=>{
timer=setTimeout(()=>reject(Error(label+' timed out after '+Math.round(timeoutMs/1000)+'s')),timeoutMs);
}),
]).finally(()=>clearTimeout(timer));
}
async function snapshotOrigin(page) {
return page.evaluate(async () => {
const {encode}=globalThis.PortageIDBCodec;
@@ -118,9 +128,10 @@ async function restoreOrigin(page,source) {
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;}
if(existing.has(spec.name)) {results.skipped++;continue;}
let db;
let created=false;
let failure=null;
try {
// Decode EVERYTHING before creating the DB; unsupported values must not
// leave a partially initialized destination schema.
@@ -137,25 +148,22 @@ async function restoreOrigin(page,source) {
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});
// Write schema and records in the same versionchange
// transaction so an interrupted restore cannot leave a
// schema-only database that later runs skip forever.
for(const [key,value] of s.records){
if(s.keyPath===null)store.put(value,key);else store.put(value);
}
}
}catch(e){request.transaction.abort();}
}catch(e){
failure=e;
try{request.transaction.abort();}catch{}
}
};
request.onsuccess=()=>resolve(request.result);
request.onerror=()=>reject(request.error||Error('Open error'));
request.onerror=()=>reject(failure||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++;
@@ -245,14 +253,14 @@ async function migrate(opts) {
for(const [i,origin]of origins.entries()){
try {
await navigateOffline(sourcePage,origin,opts.timeout);
const exported=await snapshotOrigin(sourcePage);
const exported=await withTimeout(snapshotOrigin(sourcePage),120000,'IndexedDB snapshot');
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);
const result=await withTimeout(restoreOrigin(destPage,exported),120000,'IndexedDB restore');
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)});}
}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;}
}
await sourcePage.close();await destPage.close();
}finally {
@@ -267,7 +275,9 @@ async function migrate(opts) {
}
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;
// Existing destination databases are intentionally skipped, so only real
// source/restore errors make the command exit non-zero.
if(stats.sourceSkipped||stats.errors.length)process.exitCode=2;
return stats;
}
if(require.main===module){