Report verified project archive export progress

This commit is contained in:
Sander Grootendorst
2026-11-30 22:33:32 +01:00
parent 4822a697bf
commit 257ebd2775
6 changed files with 163 additions and 28 deletions
+15 -8
View File
@@ -1,8 +1,7 @@
const encoder = new TextEncoder();
export function validateEntries(entries) {
export function validateEntries(entries, keys = new Set()) {
if(!Array.isArray(entries))throw new Error('Invalid KV snapshot entries');
const keys=new Set();
for(const entry of entries) {
if(!entry||typeof entry.key!=='string'||!entry.key||entry.key.includes('\0')||keys.has(entry.key)||entry.status!=='found'||!['value','list'].includes(entry.kind)||!Object.hasOwn(entry,'value'))throw new Error('Invalid or duplicate KV snapshot key');
keys.add(entry.key);
@@ -13,23 +12,31 @@ export function validateEntries(entries) {
} else if(Array.isArray(entry.value))throw new Error('Array KV values require list identities');
}
}
export async function readKvSnapshot(bridge,scope,path,assertCurrent,maxBytes) {
export async function readKvSnapshot(bridge,scope,path,assertCurrent,maxBytes,onPage) {
if(typeof bridge.snapshotKv!=='function')throw new Error('Host consistent KV snapshots unavailable');
const entries=[],cursors=new Set();let cursor,anchor,fence;
const entries=[],cursors=new Set();let cursor,anchor,fence,snapshotId;
const keys = new Set();
let encodedSize = 2; // The surrounding JSON array brackets.
do {
assertCurrent();
const page=await bridge.snapshotKv({...scope,path,limit:100,cursor});
const page=await bridge.snapshotKv({...scope,path,limit:100,cursor,...(cursor ? {snapshotId,revision:fence.revision} : {})});
assertCurrent();
const local=page?.local===true&&page.snapshotComplete===true&&page.nextCursor==null&&!cursor&&Number.isSafeInteger(page.localRevision);
if(!Number.isSafeInteger(page?.revision)||!Array.isArray(page.entries)||page.incomplete||page.stale||(!local&&(typeof page.snapshotId!=='string'||!page.snapshotId)))throw new Error('Invalid host KV snapshot');
const generation=JSON.stringify([page.snapshotId??'local-complete',page.revision,page.localRevision??null,page.storeId??null,page.incarnation??null]);
if(anchor&&anchor!==generation)throw new Error('KV snapshot generation changed');
anchor=generation;fence={revision:page.revision,localRevision:page.localRevision??null,storeId:page.storeId??null,incarnation:page.incarnation??null,local:page.local===true};entries.push(...page.entries);
if(maxBytes !== undefined && encoder.encode(JSON.stringify(entries)).length>maxBytes)throw new Error('KV snapshot exceeds transfer limit');
snapshotId=page.snapshotId;
anchor=generation;fence={revision:page.revision,localRevision:page.localRevision??null,storeId:page.storeId??null,incarnation:page.incarnation??null,local:page.local===true};
cursor=page.nextCursor;
if(cursor!=null&&(typeof cursor!=='string'||!cursor||cursors.has(cursor)))throw new Error('Invalid or repeated KV snapshot cursor');
if(cursor)cursors.add(cursor);
validateEntries(page.entries, keys);
if (maxBytes !== undefined) {
if (page.entries.length) encodedSize += encoder.encode(JSON.stringify(page.entries)).length - 2 + (entries.length ? 1 : 0);
if (encodedSize > maxBytes) throw new Error('KV snapshot exceeds transfer limit');
}
for (const entry of page.entries) entries.push(entry);
onPage?.(page.entries);
}while(cursor);
validateEntries(entries);
return {entries:entries.map(entry=>({key:entry.key,status:'found',kind:entry.kind,value:entry.value,...(entry.kind==='list'?{itemIds:entry.itemIds}:{})})),fence};
}
+13
View File
@@ -1,8 +1,18 @@
export const TRANSFER_MANIFEST: '.isa-transfer.json';
export const TRANSFER_VERSION: 1;
export type ProjectExportProgress =
| { type: 'listing' | 'verifying' }
| { type: 'inventory'; files: number; stores: number }
| { type: 'reading' | 'store'; path: string }
| { type: 'records'; path: string; entries: ReadonlyArray<{key: string; value: unknown}> }
| { type: 'file'; path: string; size: number; projectName?: string }
| { type: 'fileBytes'; path: string; loaded: number; total: number }
| { type: 'packing'; loaded: number; total: number | null };
export interface ProjectTransferOptions {
bridge: ProjectBridge;
scope?: ProjectScope;
signal?: AbortSignal;
onProgress?: (progress: ProjectExportProgress) => void;
beforeExport?: (session: ProjectSession) => void | Promise<void>;
name?: string;
fileName?: string;
@@ -16,3 +26,6 @@ export function importProject(client: ProjectClient, bytes: Uint8Array | ArrayBu
export function exportProjectToDialog(session: ProjectSession, options: ProjectTransferOptions): Promise<unknown>;
export function importProjectFromDialog(client: ProjectClient, options: ProjectTransferOptions): Promise<ProjectSession | null>;
import type { ProjectBridge, ProjectClient, ProjectSession, ProjectScope } from './index.js';
export function inspectArchive(bytes: Uint8Array | ArrayBuffer, options?: Partial<ProjectTransferOptions>): {files: Map<string, Uint8Array>, manifest: {name: string}, types: Map<string,string>, directories: string[], stores: {path:string, entries:{key:string,value:unknown}[]}[]};
export function saveProjectArchiveToDialog(session: ProjectSession, bytes: Uint8Array, options: ProjectTransferOptions): Promise<unknown>;
+50 -12
View File
@@ -1,5 +1,6 @@
import {readKvSnapshot,validateEntries} from './kv-snapshot.js';
import { readExportFile } from './transfer/files.js';
import { manifestFromSnapshot } from './project-filesystem.js';
import { confirmedWrite } from './proofs.js';
import { parseProjectManifest, validateArchivePath } from './format.js';
import { packZip, unpackZip, limits, validatePaths } from './transfer/zip.js';
@@ -51,48 +52,82 @@ function inventorySignature(rows) {
function assertLive(session) {session.assertCurrent();if(session.signal?.aborted)throw new DOMException('Project transfer cancelled','AbortError');}
export async function exportProject(session, options={}) {
const bridge=bridgeFor(options),scope=scoped(session,options),bound=limits(options);
function checkCurrent() {
assertLive(session);
if(options.beforeExport) {await options.beforeExport(session);assertLive(session);}
if (options.signal?.aborted) throw new DOMException('Project export cancelled', 'AbortError');
}
checkCurrent();
if(options.beforeExport) {await options.beforeExport(session);checkCurrent();}
if(session.dirty)throw new Error('Save project changes before exporting');
const rows=await session.listFiles('',true);assertLive(session);
const report = options.onProgress;
report?.({ type: 'listing' });
const rows=await session.listFiles('',true);checkCurrent();
if(!Array.isArray(rows)||rows.length>bound.maxEntries)throw new Error('Invalid or oversized project inventory');
const inventory=rows.filter(row=>row.path!==session.project.path);
const signature=inventorySignature(inventory);
validatePaths(inventory.map(row=>({path:relative(session,row.path),directory:row.kind==='folder'})));
if (report) {
const resources = inventory.filter(row => row.kind === 'file');
const storeCount = resources.filter(row => row.contentType === KV_TYPE).length;
report({ type: 'inventory', files: resources.length - storeCount, stores: storeCount });
}
const files=new Map(),metadata=[],stores=[],directories=[];
for(const row of inventory) {
assertLive(session);
checkCurrent();
if(row.kind==='folder'){directories.push(relative(session,row.path));continue;}
if(row.kind!=='file')throw new Error('Unsupported project resource kind');
const path=relative(session,row.path);
if(path===TRANSFER_MANIFEST)throw new Error('Project uses reserved transfer manifest path');
report?.({ type: 'reading', path });
if(row.contentType===KV_TYPE) {
const captured=await readKvSnapshot(bridge,scope,row.path,() => assertLive(session),bound.maxFileBytes);
const captured=await readKvSnapshot(bridge,scope,row.path,checkCurrent,bound.maxFileBytes,
report && (entries => report({ type: 'records', path, entries })));
checkCurrent();
stores.push({path,revision:captured.fence.revision,entries:captured.entries,fence:captured.fence});
report?.({ type: 'store', path });
continue;
}
const expected=identity(row);
const bytes=await readExportFile(session,bridge,scope,row,expected,bound.maxFileBytes);
const bytes=await readExportFile(session,bridge,scope,row,expected,bound.maxFileBytes,
report && ((loaded, total) => report({ type: 'fileBytes', path, loaded, total })), options.signal);
checkCurrent();
let projectName;
if(path==='project.json') {
const manifest=portableManifest(json(bytes));
if(manifest.id!==session.project.projectIdentity)throw new Error('Project manifest identity changed');
projectName = manifest.name;
files.set(path,jsonBytes(manifest));
} else files.set(path,bytes);
metadata.push({path,contentType:typeof row.contentType==='string'?row.contentType:'application/octet-stream'});
const contentType = typeof row.contentType === 'string' ? row.contentType : 'application/octet-stream';
if (contentType.length > 256) throw new Error('Invalid project file metadata');
metadata.push({path, contentType});
report?.({ type: 'file', path, size: files.get(path).byteLength, projectName });
}
if(!files.has('project.json'))throw new Error('Project manifest missing from export inventory');
report?.({ type: 'verifying' });
for(const store of stores) {
const current=await bridge.snapshotKv({...scope,path:session.path(store.path),limit:1});assertLive(session);
checkCurrent();
const current=await bridge.snapshotKv({...scope,path:session.path(store.path),limit:1});checkCurrent();
const fence={revision:current.revision,localRevision:current.localRevision??null,storeId:current.storeId??null,incarnation:current.incarnation??null,local:current.local===true};
if(JSON.stringify(fence)!==JSON.stringify(store.fence))throw new Error('KV changed during project export');
}
const current=await session.listFiles('',true);assertLive(session);
const current=await session.listFiles('',true);checkCurrent();
if(inventorySignature(current.filter(row=>row.path!==session.project.path))!==signature)throw new Error('Project inventory changed during export');
if (report) {
report({ type: 'packing', loaded: 0, total: null });
await new Promise(resolve => setTimeout(resolve, 0));
checkCurrent();
}
files.set(TRANSFER_MANIFEST,jsonBytes({formatVersion:TRANSFER_VERSION,files:metadata,directories,kvStores:stores.map(({fence,...store})=>store),auditAuthority:'historical-only'}));
const bytes=packZip(files,bound,directories);assertLive(session);return bytes;
const bytes = await packZip(files, bound, directories, report && ((loaded, total) => {
checkCurrent();
report({ type: 'packing', loaded, total });
}));
checkCurrent();
return bytes;
}
function inspectArchive(bytes,options) {
export function inspectArchive(bytes,options = {}) {
const files=unpackZip(bytes,options),raw=files.get('project.json');
if(!raw)throw new Error('Project archive requires project.json');
const manifest=portableManifest(json(raw));
@@ -187,7 +222,7 @@ export async function importProject(client,bytes,options={}) {
}
const base=await session.readFile('project.json');assertLive(session);
if(base.status!=='found')throw new Error('New project manifest unavailable');
const host=parseProjectManifest(JSON.parse(base.text));
const host=manifestFromSnapshot(base);
const imported={...archive.manifest,archived:false,id:host.id,name:host.name,createdAt:host.createdAt,updatedAt:new Date().toISOString(),importedFrom:{id:archive.manifest.id,importedAt:new Date().toISOString()},auditAuthority:'historical-only'};
await session.writeJson('project.json',imported,base);assertLive(session);
return await client.adopt(session);
@@ -195,7 +230,10 @@ export async function importProject(client,bytes,options={}) {
}
export async function exportProjectToDialog(session,options={}) {
const bytes=await exportProject(session,options);assertLive(session);
return saveProjectArchiveToDialog(session,await exportProject(session,options),options);
}
export async function saveProjectArchiveToDialog(session,bytes,options={}) {
assertLive(session);
const result=await bridgeFor(options).invoke('save_file_dialog',{fileName:options.fileName??`${session.project.name||'project'}.isap.zip`,bytesBase64:base64(bytes),filterName:'ISA Project',extensions:['zip']});
assertLive(session);return result;
}
+6 -2
View File
@@ -8,7 +8,7 @@ function decode(value) {
if(typeof value!=='string'||value.length%4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value))throw new Error('Invalid host file encoding');
return Uint8Array.from(atob(value),character=>character.charCodeAt(0));
}
export async function readExportFile(session,bridge,scope,row,expected,maxBytes) {
export async function readExportFile(session,bridge,scope,row,expected,maxBytes,onBytes,signal) {
session.assertCurrent();
if(expected.size!==null&&(!Number.isSafeInteger(expected.size)||expected.size<0||expected.size>maxBytes))throw new Error('Project file exceeds transfer limit');
const request={...scope,path:row.path,cachePolicy:'dashboard-required',expectedSyncRevision:expected.revision,...(expected.hash?{expectedContentHash:expected.hash}:{})};
@@ -18,15 +18,19 @@ export async function readExportFile(session,bridge,scope,row,expected,maxBytes)
if(!Number.isSafeInteger(link.fileSize)||link.fileSize!==expected.size||link.fileSize>maxBytes||typeof link.contentHash!=='string'||!/^[a-f0-9]{64}$/i.test(link.contentHash))throw new Error('Large project file lacks a bounded verified snapshot');
const url=new URL(link.downloadUrl,globalThis.location?.href);
if(!['http:','https:'].includes(url.protocol))throw new Error('Unsupported project download URL');
const response=await fetch(url,{signal:session.signal,credentials:'omit',redirect:'error'});session.assertCurrent();
const downloadSignal = signal && session.signal && typeof AbortSignal.any === 'function'
? AbortSignal.any([signal, session.signal]) : session.signal ?? signal;
const response=await fetch(url,{signal:downloadSignal,credentials:'omit',redirect:'error'});session.assertCurrent();
if(!response.ok||!response.body)throw new Error('Project media download failed');
const reader=response.body.getReader();const chunks=[];let length=0;
try {
while(true) {
if (signal?.aborted) throw new DOMException('Project export cancelled', 'AbortError');
const next=await reader.read();session.assertCurrent();if(next.done)break;
length+=next.value.byteLength;
if(length>link.fileSize||length>maxBytes)throw new Error('Project media exceeds its declared size');
chunks.push(next.value);
onBytes?.(length, link.fileSize);
}
} finally {await reader.cancel().catch(()=>{});reader.releaseLock();}
if(length!==link.fileSize)throw new Error('Project media download was incomplete');
+26 -4
View File
@@ -119,7 +119,7 @@ export function unpackZip(input, options) {
return files;
}
export function packZip(files, options, directories=[]) {
export async function packZip(files, options, directories=[], onProgress) {
const bound=limits(options), records=[...files.keys()].map(path=>({path,directory:false})).concat(directories.map(path=>({path,directory:true})));
validatePaths(records);
if(records.length>bound.maxEntries)throw new Error('Too many project files');
@@ -130,12 +130,34 @@ export function packZip(files, options, directories=[]) {
if(archiveBytes>bound.maxArchiveBytes)throw new Error('Project ZIP exceeds archive limit');
chunks.push(chunk);
});
for(const [path,bytes] of files) {
if(bytes.length>bound.maxFileBytes||(total+=bytes.length)>bound.maxTotalBytes)throw new Error('Project transfer limits exceeded');
const file=new ZipDeflate(path,{level:6});archive.add(file);file.push(bytes,true);
for (const bytes of files.values()) {
total += bytes.length;
if (bytes.length > bound.maxFileBytes || total > bound.maxTotalBytes) throw new Error('Project transfer limits exceeded');
}
let loaded = 0;
let lastYield = performance.now();
for (const [path, bytes] of files) {
const file = new ZipDeflate(path, {level:6});
archive.add(file);
if (!onProgress || bytes.length === 0) {
file.push(bytes, true);
continue;
}
const chunkSize = 128 * 1024;
for (let offset = 0; offset < bytes.length; offset += chunkSize) {
const chunk = bytes.subarray(offset, offset + chunkSize);
file.push(chunk, offset + chunk.length === bytes.length);
loaded += chunk.length;
if (performance.now() - lastYield >= 40) {
onProgress(loaded, total);
await new Promise(resolve => setTimeout(resolve, 0));
lastYield = performance.now();
}
}
}
for(const path of directories){const directory=new ZipPassThrough(`${path}/`);archive.add(directory);directory.push(new Uint8Array(),true);}
archive.end();
onProgress?.(loaded, total);
const result=new Uint8Array(archiveBytes);let offset=0;
for(const chunk of chunks){result.set(chunk,offset);offset+=chunk.length;}
return result;
+52 -1
View File
@@ -109,6 +109,34 @@ test('whole project ZIP roundtrip preserves unknown files, media, live KV list I
function zipped(extra={}) {return zipSync({'project.json':strToU8(JSON.stringify(manifest('old'))),...extra});}
function central(bytes){const view=new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength);for(let index=0;index<bytes.length-4;index++)if(view.getUint32(index,true)===0x02014b50)return index;throw new Error('Missing central');}
test('export progress tracks inventory and KV pages and stops when the preview is abandoned', async () => {
const f = fixture();
const session = await f.client.activate(f.original);
const controller = new AbortController();
const events = [];
await assert.rejects(exportProject(session, {
bridge: f.bridge, signal: controller.signal,
onProgress(event) {
events.push(event);
if (event.type === 'records') controller.abort();
}
}), {name: 'AbortError'});
assert.equal(events.at(-1).type, 'records');
assert.equal(events.at(-1).entries.length, 2);
events.length = 0;
const bytes = await exportProject(session, {bridge: f.bridge, onProgress: event => events.push(event)});
const inventory = events.find(event => event.type === 'inventory');
assert.equal(inventory.files, events.filter(event => event.type === 'file').length);
assert.equal(inventory.stores, events.filter(event => event.type === 'store').length);
assert.deepEqual(events.filter(event => event.type === 'records').map(event => event.entries.length), [2, 1]);
const packing = events.at(-1);
assert.equal(packing.type, 'packing');
assert.equal(packing.loaded, packing.total);
const decoded = unpackZip(bytes);
assert.equal(packing.total, [...decoded.values()].reduce((sum, file) => sum + file.length, 0));
});
test('unsafe ZIP paths, collisions, links, corruption and decompression bounds fail before host creation',async()=>{
const duplicate=zipped({a:strToU8('a'),b:strToU8('b')});
for(let i=0;i<duplicate.length-4;i++) {
@@ -151,6 +179,29 @@ test('host save/select dialogs transfer real ZIP bytes with cancellation and val
assert.ok(await importProjectFromDialog(f.client,{bridge:f.bridge}));
});
test('project transfer continues pinned KV pages and imports base64-only manifests', async () => {
const f = fixture();
const snapshot = f.bridge.snapshotKv.bind(f.bridge);
let first;
f.bridge.snapshotKv = async args => {
if (args.cursor) {
assert.equal(args.snapshotId, first.snapshotId);
assert.equal(args.revision, first.revision);
}
const page = await snapshot(args);
if (!args.cursor) first = page;
return page;
};
const bytes = await exportProject(await f.client.activate(f.original), {bridge:f.bridge});
const invoke = f.bridge.invoke.bind(f.bridge);
f.bridge.invoke = async (command, args) => {
const reply = await invoke(command, args);
if (command === 'filesystem_get_files') for (const item of reply.items) delete item.text;
return reply;
};
assert.ok(await importProject(f.client, bytes, {bridge:f.bridge}));
});
test('complete local KV snapshots retain unsent values and reject a changed local revision',async()=>{
const f=fixture(),session=await f.client.activate(f.original);
let localRevision=20;
@@ -168,7 +219,7 @@ test('malformed logical KV snapshots and unsupported transfer versions fail befo
for(const change of [sidecar=>{sidecar.formatVersion=2;},sidecar=>{sidecar.kvStores[0].entries[0].itemIds=['duplicate','duplicate'];},sidecar=>{sidecar.kvStores[0].path='../escape.kv';},sidecar=>{sidecar.kvStores.push(structuredClone(sidecar.kvStores[0]));}]) {
const f=fixture(),session=await f.client.activate(f.original),files=unpackZip(await exportProject(session,{bridge:f.bridge}));
const sidecar=JSON.parse(strFromU8(files.get(TRANSFER_MANIFEST)));change(sidecar);files.set(TRANSFER_MANIFEST,strToU8(JSON.stringify(sidecar)));
await assert.rejects(importProject(f.client,packZip(files,{},files.directories),{bridge:f.bridge}));assert.equal(f.creates,0);
await assert.rejects(importProject(f.client,await packZip(files,{},files.directories),{bridge:f.bridge}));assert.equal(f.creates,0);
}
});