Files
isa-project-format/test/transfer.test.js
T

229 lines
18 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import {zipSync,unzipSync,strToU8,strFromU8} from 'fflate';
import {createProjectClient} from '../src/client.js';
import {exportProject,importProject,exportProjectToDialog,importProjectFromDialog,TRANSFER_MANIFEST} from '../src/transfer.js';
import {packZip,unpackZip} from '../src/transfer/zip.js';
const scope={workspaceId:'workspace',groupId:'group'};
const KV_TYPE='application/vnd.isa.kv-store';
const manifest=id=>({formatVersion:1,id,name:'Example',createdAt:'2026-11-03T12:00:00Z',updatedAt:'2026-11-03T12:00:00Z',unknown:{keep:true}});
const project=id=>({id,folderId:id,name:'Example',path:`/projects/${id}.isap`,projectIdentity:id});
function fixture() {
const files=new Map(),stores=new Map(),snapshots=new Map(),calls=[];
let creates=0,snapshotSequence=0;
function add(path,bytes,type='application/octet-stream') {files.set(path,{bytes:bytes instanceof Uint8Array?bytes:strToU8(bytes),contentType:type,revision:1,id:path});}
function folder(path){files.set(path,{kind:'folder',bytes:new Uint8Array(),revision:0,id:path});}
function putProject(id,name='Example') {const value={...project(id),name};folder(value.path);folder(`${value.path}/extensions`);folder(`${value.path}/assets`);add(`${value.path}/project.json`,JSON.stringify({...manifest(id),name}),'application/json');return value;}
folder('/projects');
const original=putProject('original');
const media=new Uint8Array([0,255,17,48,0,99]);
add(`${original.path}/assets/audio.bin`,media,'audio/wav');
add(`${original.path}/extensions/unknown/future.json`,'{"future":true}','application/json');
add(`${original.path}/extensions/unknown/opaque.kv`,'ordinary unknown bytes','application/octet-stream');
add(`${original.path}/__proto__`,'unknown root file','application/octet-stream');
folder(`${original.path}/extensions/unknown`);folder(`${original.path}/extensions/unknown/empty`);folder(`${original.path}/extensions/unknown/empty/deep`);folder(`${original.path}/extensions/quote`);
const kvPath=`${original.path}/extensions/quote/state.kv`;
add(kvPath,'STALE CHECKPOINT',KV_TYPE);
stores.set(kvPath,{revision:9,entries:[{key:'empty',status:'found',kind:'list',itemIds:[],value:[]},{key:'rows',status:'found',kind:'list',itemIds:['stable-b','stable-a'],value:[{name:'Latest'},{name:'Second'}]},{key:'value',status:'found',kind:'value',value:{updated:true}}]});
const bridge={
async invoke(command,args) {
calls.push({command,args});
if(command==='localstorage_get')return args.key==='isa-project-format.folders.v1' ? [{path:'/projects',id:'/projects',canWrite:true}] : [];
if(command==='localstorage_put')return {status:'ok'};
if(command==='filesystem_list_dir')return {authoritative:true,files:[...files].filter(([path])=>path===args.path||path.startsWith(`${args.path}/`)).map(([path,row])=>({path,id:row.id,kind:row.kind??'file',contentType:row.contentType,syncRevision:row.revision,fileSize:row.bytes.length}))};
if(command==='filesystem_create_folder') {if(args.path.endsWith('.isap'))creates++;assert.equal(files.get(args.path.slice(0,args.path.lastIndexOf('/')))?.kind,'folder');folder(args.path);return {status:'ok',path:args.path,fileId:files.get(args.path).id};}
if(command==='filesystem_get_files')return {items:args.files.map(request=>{
const row=files.get(request.path);
if(!row)return {status:'absent',path:request.path,source:'dashboard',authoritative:true};
if(request.expectedSyncRevision!==undefined)assert.equal(request.expectedSyncRevision,row.revision);
return {status:'ok',source:'dashboard',authoritative:true,path:request.path,fileId:row.id,syncRevision:row.revision,bytesBase64:Buffer.from(row.bytes).toString('base64'),...(row.contentType==='application/json'?{text:strFromU8(row.bytes)}:{})};
})};
if(command==='filesystem_upload_files') {
for(const item of args.files) {
const previous=files.get(item.path);
assert.equal(item.replaceExisting,Boolean(previous));
if(previous)assert.equal(item.expectedSyncRevision,previous.revision);
add(item.path,item.text??new Uint8Array(Buffer.from(item.bytesBase64,'base64')),item.contentType);
if(previous)files.get(item.path).revision=previous.revision+1;
}
return {items:args.files.map(item=>({status:'ok',isComplete:true,path:item.path,fileId:files.get(item.path).id}))};
}
if(command==='kv_store_open') {add(args.path,'NEW CHECKPOINT',KV_TYPE);stores.set(args.path,{revision:0,entries:[]});return {status:'ok'};}
if(command==='save_file_dialog')return {status:'ok',saved:true};
if(command==='select_files')return bridge.selection??{canceled:true,selections:[]};
throw new Error(`Unexpected ${command}`);
},
async snapshotKv(args) {
calls.push({command:'snapshotKv',args});
let id,index;
if(args.cursor){[id,index]=args.cursor.split(':');index=Number(index);}
else {id=`snapshot-${++snapshotSequence}`;index=0;snapshots.set(id,structuredClone(stores.get(args.path)));}
const store=snapshots.get(id),limit=Math.min(args.limit??1,2),entries=store.entries.slice(index,index+limit);
return {snapshotId:id,revision:store.revision,storeId:args.path,incarnation:'incarnation',entries,nextCursor:index+limit<store.entries.length?`${id}:${index+limit}`:null};
},
async applyKv(args) {
calls.push({command:'applyKv',args});
const store=stores.get(args.path);
for(const operation of args.operations) {
let entry=store.entries.find(entry=>entry.key===operation.key);
if(operation.kind==='set') {
entry={key:operation.key,status:'found',kind:Array.isArray(operation.value)?'list':'value',value:structuredClone(operation.value),...(Array.isArray(operation.value)?{itemIds:[]}:{})};
store.entries=store.entries.filter(other=>other.key!==entry.key);store.entries.push(entry);
}else if(operation.kind==='list_append') {entry.itemIds.push(operation.id);entry.value.push(structuredClone(operation.value));}
else assert.fail(`Unexpected operation ${operation.kind}`);
}
store.revision++;return {status:'ok'};
}
};
const client=createProjectClient({bridge,extensionId:'contracts',scope});
return {bridge,client,files,stores,calls,original,media,kvPath,get creates(){return creates;}};
}
test('whole project ZIP roundtrip preserves unknown files, media, live KV list IDs and a new identity',async()=>{
const f=fixture(),source=await f.client.activate(f.original);
source.permission={grantId:'DO-NOT-EXPORT'};
const originalManifest=manifest('original');originalManifest.credentials={token:'DO-NOT-EXPORT'};
f.files.get(`${f.original.path}/project.json`).bytes=strToU8(JSON.stringify(originalManifest));
const bytes=await exportProject(source,{bridge:f.bridge});
assert.equal(new DataView(bytes.buffer,bytes.byteOffset).getUint32(0,true),0x04034b50);
const decoded=unzipSync(bytes),sidecar=JSON.parse(strFromU8(decoded[TRANSFER_MANIFEST]));
assert.ok(!decoded['extensions/quote/state.kv']);
assert.ok(!JSON.stringify(sidecar).includes('STALE CHECKPOINT'));
assert.ok(!Object.values(decoded).some(value=>strFromU8(value).includes('DO-NOT-EXPORT')));
assert.deepEqual(sidecar.kvStores[0].entries[1].itemIds,['stable-b','stable-a']);
assert.ok(f.calls.some(call=>call.command==='snapshotKv'&&call.args.cursor));
const imported=await importProject(f.client,bytes,{bridge:f.bridge});
assert.notEqual(imported.project.id,source.project.id);
const saved=JSON.parse(strFromU8(f.files.get(imported.path('project.json')).bytes));
assert.equal(saved.id,imported.project.projectIdentity);assert.deepEqual(saved.unknown,{keep:true});
assert.equal(saved.importedFrom.id,'original');assert.equal(saved.auditAuthority,'historical-only');
assert.deepEqual(f.files.get(imported.path('assets/audio.bin')).bytes,f.media);
assert.equal(strFromU8(f.files.get(imported.path('extensions/unknown/future.json')).bytes),'{"future":true}');
assert.equal(strFromU8(f.files.get(imported.path('extensions/unknown/opaque.kv')).bytes),'ordinary unknown bytes');
assert.equal(strFromU8(f.files.get(imported.path('__proto__')).bytes),'unknown root file');
assert.equal(f.files.get(imported.path('extensions/unknown/empty/deep')).kind,'folder');
assert.ok(decoded['extensions/unknown/empty/deep/']);
assert.deepEqual(f.stores.get(imported.path('extensions/quote/state.kv')).entries,sidecar.kvStores[0].entries);
});
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('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++) {
const view=new DataView(duplicate.buffer),signature=view.getUint32(i,true);
const length=signature===0x04034b50?view.getUint16(i+26,true):signature===0x02014b50?view.getUint16(i+28,true):0;
const name=i+(signature===0x04034b50?30:46);
if(length===1&&duplicate[name]===98)duplicate[name]=97;
}
const link=zipped();new DataView(link.buffer).setUint32(central(link)+38,0xa1ff0000,true);
const corrupt=zipped();new DataView(corrupt.buffer).setUint32(central(corrupt)+16,1,true);
const liar=zipped({bomb:strToU8('x'.repeat(20000))});
const liarView=new DataView(liar.buffer);let position=central(liar);
while(strFromU8(liar.subarray(position+46,position+46+liarView.getUint16(position+28,true)))!=='bomb')position+=46+liarView.getUint16(position+28,true)+liarView.getUint16(position+30,true)+liarView.getUint16(position+32,true);
const local=liarView.getUint32(position+42,true);liarView.setUint32(position+24,0,true);liarView.setUint32(local+22,0,true);
for(const bytes of [zipped({'../escape':strToU8('x')}),zipped({'/absolute':strToU8('x')}),zipped({'C:/drive':strToU8('x')}),zipped({' padded/name':strToU8('x')}),zipped({'folder/name\u00a0':strToU8('x')}),zipped({'same/a':strToU8('x'),'Same/b':strToU8('x')}),zipped({parent:strToU8('x'),'parent/child':strToU8('x')}),duplicate,link,corrupt,liar]) {
const f=fixture();await assert.rejects(importProject(f.client,bytes,{bridge:f.bridge}));assert.equal(f.creates,0);
}
const f=fixture();await assert.rejects(importProject(f.client,zipped({large:strToU8('a'.repeat(4096))}),{bridge:f.bridge,maxFileBytes:2048}));assert.equal(f.creates,0);
});
test('inconsistent KV pages, concurrent files and retired sessions cannot produce an export',async()=>{
const f=fixture(),session=await f.client.activate(f.original),normal=f.bridge.snapshotKv.bind(f.bridge);
f.bridge.snapshotKv=async args=>{const value=await normal(args);if(args.cursor)value.snapshotId='different';return value;};
await assert.rejects(exportProject(session,{bridge:f.bridge}),/generation/);
f.bridge.snapshotKv=normal;
const invoke=f.bridge.invoke.bind(f.bridge);
f.bridge.invoke=async(command,args)=>{const value=await invoke(command,args);if(command==='filesystem_get_files')f.files.get(`${f.original.path}/assets/audio.bin`).revision++;return value;};
await assert.rejects(exportProject(session,{bridge:f.bridge}),/changed|equal/);
await session.close();await assert.rejects(exportProject(session,{bridge:f.bridge}),{name:'AbortError'});
});
test('host save/select dialogs transfer real ZIP bytes with cancellation and validation',async()=>{
const f=fixture(),session=await f.client.activate(f.original);
await exportProjectToDialog(session,{bridge:f.bridge});
const saved=f.calls.find(call=>call.command==='save_file_dialog');
assert.ok(saved.args.fileName.endsWith('.isap.zip'));
assert.equal(await importProjectFromDialog(f.client,{bridge:f.bridge}),null);
assert.deepEqual(f.calls.find(call=>call.command==='select_files').args,{multiple:false,accessPolicy:'read-only',filters:['.zip']});
f.bridge.selection={selections:[{filename:'project.zip',bytesBase64:saved.args.bytesBase64}]};
assert.ok(await importProjectFromDialog(f.client,{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;
f.bridge.snapshotKv=async()=>({local:true,snapshotComplete:true,revision:9,localRevision,storeId:'old-store',incarnation:'old-incarnation',pending:true,entries:structuredClone(f.stores.get(f.kvPath).entries),nextCursor:null});
const bytes=await exportProject(session,{bridge:f.bridge});
const sidecar=JSON.parse(strFromU8(unzipSync(bytes)[TRANSFER_MANIFEST]));
assert.equal(sidecar.kvStores[0].entries[1].value[0].name,'Latest');
assert.ok(!JSON.stringify(sidecar).includes('old-store'));
let calls=0;const snapshot=f.bridge.snapshotKv;
f.bridge.snapshotKv=async args=>{if(++calls>1)localRevision++;return snapshot(args);};
await assert.rejects(exportProject(session,{bridge:f.bridge}),/KV changed/);
});
test('malformed logical KV snapshots and unsupported transfer versions fail before creation',async()=>{
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);
}
});
test('large lists replay in bounded ordered batches and switching stops subsequent mutations',async()=>{
const f=fixture(),session=await f.client.activate(f.original);
const entry={key:'large',status:'found',kind:'list',itemIds:Array.from({length:350},(_,i)=>`id-${350-i}`),value:Array.from({length:350},(_,i)=>({position:i}))};
f.stores.get(f.kvPath).entries=[entry];
const bytes=await exportProject(session,{bridge:f.bridge});
const imported=await importProject(f.client,bytes,{bridge:f.bridge});
const mutations=f.calls.filter(call=>call.command==='applyKv');
assert.equal(mutations.length,3);assert.ok(mutations.every(call=>call.args.operations.length<=128));
assert.deepEqual(f.stores.get(imported.path('extensions/quote/state.kv')).entries,[entry]);
const normal=f.bridge.applyKv.bind(f.bridge);let applied=0;
f.bridge.applyKv=async args=>{const result=await normal(args);if(++applied===1)await f.client.close();return result;};
await assert.rejects(importProject(f.client,bytes,{bridge:f.bridge}),{name:'AbortError'});
assert.equal(applied,1);
});
test('import activates only complete staged projects and picks unique UTF-16-safe names',async()=>{
const f=fixture(),source=await f.client.activate(f.original),bytes=await exportProject(source,{bridge:f.bridge});
let release,started;
const blocked=new Promise(resolve=>{started=resolve;}),normal=f.bridge.invoke.bind(f.bridge);
f.bridge.invoke=async(command,args)=>{if(command==='filesystem_upload_files'&&!release){await new Promise(resolve=>{release=resolve;started();});}return normal(command,args);};
const events=[];f.client.subscribe(({active})=>{if(active&&active!==source)events.push(JSON.parse(strFromU8(f.files.get(active.path('project.json')).bytes)));});
const pending=importProject(f.client,bytes,{bridge:f.bridge});await blocked;
assert.equal(f.client.active,source);assert.deepEqual(events,[]);release();
const imported=await pending;assert.equal(f.client.active,imported);assert.ok(events.length&&events.every(value=>value.importedFrom?.id==='original'));
assert.equal(imported.project.name,'Example (import)');
const second=await importProject(f.client,bytes,{bridge:f.bridge});assert.equal(second.project.name,'Example (import 2)');
const long={...manifest('old'),name:'😀'.repeat(80)};
const third=await importProject(f.client,zipSync({'project.json':strToU8(JSON.stringify(long))}),{bridge:f.bridge});
assert.ok(third.project.name.length<=160);assert.ok(!/[\ud800-\udbff]$/.test(third.project.name.slice(0,-' (import)'.length)));
});
test('failed import retires its staged session while preserving the previously active project',async()=>{
const f=fixture(),source=await f.client.activate(f.original),bytes=await exportProject(source,{bridge:f.bridge});
const normal=f.bridge.invoke.bind(f.bridge);f.bridge.invoke=(command,args)=>command==='filesystem_create_folder'&&args.path.endsWith('/extensions/unknown')?Promise.reject(new Error('Folder write failed')):normal(command,args);
let staged;const stage=f.client.stageCreate.bind(f.client);f.client.stageCreate=async(...args)=>(staged=await stage(...args));
await assert.rejects(importProject(f.client,bytes,{bridge:f.bridge}),error=>error.message==='Folder write failed'&&Boolean(error.project));
assert.equal(f.client.active,source);assert.equal(staged.signal.aborted,true);
});
test('export preparation flushes the captured session before snapshot and fences a closed session',async()=>{
const f=fixture(),session=await f.client.activate(f.original);
session.markDirty();
const bytes=await exportProject(session,{bridge:f.bridge,beforeExport:async captured=>{
assert.equal(captured,session);
f.stores.get(f.kvPath).entries[2].value={flushed:true};
f.stores.get(f.kvPath).revision++;
captured.markDirty(false);
}});
const sidecar=JSON.parse(strFromU8(unpackZip(bytes).get(TRANSFER_MANIFEST)));
assert.deepEqual(sidecar.kvStores[0].entries[2].value,{flushed:true});
const before=f.calls.filter(call=>call.command==='filesystem_list_dir').length;
await assert.rejects(exportProject(session,{bridge:f.bridge,beforeExport:()=>session.close()}),{name:'AbortError'});
assert.equal(f.calls.filter(call=>call.command==='filesystem_list_dir').length,before);
});