54 lines
13 KiB
JavaScript
54 lines
13 KiB
JavaScript
// Opt-in real Development protocol and recovery test. Synthetic account/scope only; no Word automation.
|
|
const {chromium}=require('playwright'),fs=require('fs'),crypto=require('crypto'),assert=require('assert/strict');
|
|
const identityPath=process.argv[2],scopePath=process.argv[3];
|
|
(async()=>{assert.ok(identityPath?.startsWith('/tmp/pd-dev-browser-')&&scopePath?.startsWith('/tmp/pd-context-'));assert.equal(fs.statSync(identityPath).mode&0o077,0);const identity=JSON.parse(fs.readFileSync(identityPath)),scope=JSON.parse(fs.readFileSync(scopePath)),evidence=JSON.parse(fs.readFileSync(scopePath+'.evidence.json'));assert.equal(identity.Database,'PlotDirector_Development');assert.match(identity.Email,/^pwa-browser-[a-f0-9]+@example.invalid$/);assert.equal(identity.UserID,scope.User);assert.equal(evidence.Book,scope.Book);
|
|
const base='https://dev.plotdirector.com',browser=await chromium.launch();try{const page=await browser.newPage();await page.goto(base+'/Account/Login');await page.locator('[name=Email]').fill(identity.Email);await page.locator('[name=Password]').fill(identity.Password);await Promise.all([page.waitForURL(u=>u.pathname!='/Account/Login'),page.locator('form:has(input[name=Password]) button[type=submit]').click()]);
|
|
const verifier=crypto.randomBytes(32).toString('base64url'),challenge=crypto.createHash('sha256').update(verifier).digest('hex').toUpperCase();let r=await page.request.post(base+'/api/native-companion/pair',{data:{challenge}});assert.equal(r.status(),200);const {code}=await r.json();await page.goto(base+'/native-companion/authorize?code='+code);const csrf=await page.locator('[name=__RequestVerificationToken]').inputValue();r=await page.request.post(base+'/native-companion/authorize',{form:{code,__RequestVerificationToken:csrf}});assert.equal(r.status(),200);r=await page.request.post(base+'/api/native-companion/token',{data:{code,verifier}});assert.equal(r.status(),200);const {accessToken}=await r.json(),headers={Authorization:'Bearer '+accessToken};
|
|
const session=crypto.randomUUID(),instance=crypto.randomUUID(),endpoint=base+'/api/native-companion/books/'+scope.Book+'/chapter-sync',presence=base+`/api/native-companion/instances/${instance}/documents/${session}/presence`;let sequence=0,wordRevision=0;
|
|
async function observe(cursor){const res=await page.request.post(presence,{headers,data:{bookId:scope.Book,manuscriptId:scope.Manuscript,revision:wordRevision,sequence:++sequence,documentTitle:'Synthetic chapter qualification.docx',wordAvailable:true,wordRunning:true,wordSaved:true,active:true,canCapture:true,canParagraphSync:true,canChapterSync:true,cursorStart:cursor}});assert.equal(res.status(),200);return res.json();}
|
|
async function manifest(){const res=await page.request.get(endpoint+`?session=${session}&wordRevision=${wordRevision}`,{headers});assert.equal(res.status(),200,await res.text());return res.json();}
|
|
async function validate(proof,status=200){const res=await page.request.post(endpoint+'/validate',{headers,data:proof});assert.equal(res.status(),status,await res.text());return res.json();}
|
|
let reply=await observe(1000);assert.equal(reply.navigation,null,'automatic reopening must not request a full extraction or navigation');assert.equal(reply.sceneId,null);let current=await manifest();assert.equal(current.chapters.length,2);assert.equal(current.chapters.filter(c=>c.state==='Synchronised').length,0);
|
|
const proofs=evidence.Proofs.map(p=>({...p,InstanceId:instance,SessionId:session,WordRevision:wordRevision,OperationId:'00000000-0000-0000-0000-000000000000',RequestId:crypto.randomUUID(),Reconcile:false}));
|
|
for(const proof of proofs){const accepted=await validate(proof);assert.equal(accepted.accepted,true);await validate(proof);const cursor=proof.Start+proof.Paragraphs[0].Length;reply=await observe(cursor);assert.equal(reply.chapterId,proof.ChapterId);assert.equal(reply.sceneId,scope.Scenes[proofs.indexOf(proof)]);assert.equal(reply.navigation,null);}
|
|
r=await page.request.post(endpoint+'/finish',{headers,data:{instanceId:instance,sessionId:session,wordRevision}});assert.equal(r.status(),200);assert.equal((await r.json()).state,'Synchronised');console.log('PASS deployed authenticated cross-session chapter adoption, current positions across chapters, idempotent retry, no automatic full capture/navigation and server-confirmed progress');
|
|
// Same live revision cannot acquire contradictory ranges.
|
|
await validate({...proofs[0],RequestId:crypto.randomUUID(),Start:proofs[0].Start+1,End:proofs[0].End+1},409);
|
|
await validate({...proofs[0],RequestId:crypto.randomUUID(),BaseRevision:0},409);
|
|
wordRevision=1;await observe(1000);let changed={...proofs[0],RequestId:crypto.randomUUID(),WordRevision:wordRevision};
|
|
const rows=evidence.Paragraphs.filter(p=>p.ChapterId===changed.ChapterId).map(p=>({NativeId:p.Occurrence.NativeId,Text:p.Occurrence.Text,Length:p.Occurrence.Text.length,Outline:p.Occurrence.Outline}));rows[1].Text='Edited exact synthetic paragraph.\r';rows[1].Length=rows[1].Text.length;
|
|
const i32=n=>{const b=Buffer.alloc(4);b.writeInt32LE(n);return b;},text=s=>Buffer.concat([i32(s.length),Buffer.from(s,'utf16le')]),version='sha256-utf16le-paragraphs-v1';
|
|
changed.ContentHash=crypto.createHash('sha256').update(Buffer.concat([text(version),i32(rows.length),...rows.map(p=>text(p.Text))])).digest('hex').toUpperCase();changed.IdentityHash=crypto.createHash('sha256').update(Buffer.concat([text(version+'/identity'),i32(rows.length),...rows.flatMap(p=>[text(p.NativeId),i32(p.Length),i32(p.Outline)])])).digest('hex').toUpperCase();changed.End=changed.Start+rows.reduce((n,p)=>n+p.Length,0);changed.Paragraphs=rows.map(({Text,...p})=>p);
|
|
let refused=await validate(changed);assert.equal(refused.state,'Changed');assert.equal(refused.allowText,false,'manual mode must not upload changed prose automatically');
|
|
r=await page.request.post(endpoint+'/repair',{headers,data:{instanceId:instance,sessionId:session,wordRevision}});assert.equal(r.status(),200,await r.text());changed.OperationId=(await r.json()).operationId;reply=await observe(1000);assert.equal(reply.navigation.kind,'chapter-repair');assert.equal(reply.navigation.id,changed.OperationId);assert.equal((await observe(1000)).navigation,null,'repair command is consumed once');
|
|
assert.equal((await validate(changed)).allowText,true);changed.Paragraphs=rows;changed.Reconcile=true;const reconciled=await validate(changed);assert.equal(reconciled.accepted,true);assert.equal(reconciled.revision,evidence.Revision+1);
|
|
const second={...proofs[1],RequestId:crypto.randomUUID(),WordRevision:wordRevision,BaseRevision:reconciled.revision,Start:proofs[1].Start+(changed.End-proofs[0].End),End:proofs[1].End+(changed.End-proofs[0].End)};assert.equal((await validate(second)).accepted,true);reply=await observe(second.Start+second.Paragraphs[0].Length);assert.equal(reply.sceneId,scope.Scenes[1]);assert.equal(reply.navigation,null);await validate({...changed,BaseRevision:evidence.Revision,RequestId:crypto.randomUUID()},409);
|
|
r=await page.request.post(endpoint+'/finish',{headers,data:{instanceId:instance,sessionId:session,wordRevision,operationId:changed.OperationId}});assert.equal(r.status(),200);const progress=await r.json();assert.equal(progress.state,'Synchronised');assert.equal(progress.repaired,1);
|
|
console.log('PASS manual-mode upload refusal, explicit existing repair command, changed-chapter-only reconciliation, stale CAS rejection and shifted later-chapter cursor mapping');
|
|
// Optional native Word geometry regression: values model an observed zero-text floating picture anchor.
|
|
// This exercises the deployed protocol, not real Word/COM.
|
|
if(process.argv.includes('--structural')){
|
|
assert.equal((await manifest()).nativePositionsSupported,true,'server explicitly advertises native geometry support');
|
|
wordRevision=2;await observe(1000);
|
|
const nativeRows=rows.map(({Text,...p})=>({...p,WordLength:p.Length,Anchors:[]}));
|
|
nativeRows[1].WordLength++;nativeRows[1].Anchors=[{Offset:0,ShapeId:37,ShapeType:13}];
|
|
const nativeString=s=>{const bytes=Buffer.from(s,'utf8');assert.ok(bytes.length<128);return Buffer.concat([Buffer.from([bytes.length]),bytes]);};
|
|
const positionHash=crypto.createHash('sha256').update(Buffer.concat([nativeString('native-picture-positions-v1'),i32(nativeRows.length),...nativeRows.flatMap(p=>[nativeString(p.NativeId),i32(p.Length),i32(p.Outline),i32(p.WordLength),i32(p.Anchors.length),...p.Anchors.flatMap(a=>[i32(a.Offset),i32(a.ShapeId),i32(a.ShapeType)])])])).digest('hex').toUpperCase();
|
|
const nativeProof={...changed,RequestId:crypto.randomUUID(),WordRevision:wordRevision,BaseRevision:reconciled.revision,End:changed.End+1,OperationId:'00000000-0000-0000-0000-000000000000',Reconcile:false,Paragraphs:nativeRows,PositionHash:positionHash};
|
|
assert.equal((await validate(nativeProof)).accepted,true,'native spans and exact text lengths are distinct and both validated');
|
|
const afterAnchor=nativeProof.Start+nativeRows[0].WordLength+nativeRows[1].WordLength;
|
|
reply=await observe(afterAnchor);assert.equal(reply.sceneId,scope.Scenes[0],'Context after the zero-text anchor has no one-position drift');
|
|
await validate({...nativeProof,RequestId:crypto.randomUUID(),PositionHash:'0'.repeat(64)},409);
|
|
const secondNative={...second,RequestId:crypto.randomUUID(),WordRevision:wordRevision,Start:second.Start+1,End:second.End+1};
|
|
assert.equal((await validate(secondNative)).accepted,true);reply=await observe(secondNative.Start+secondNative.Paragraphs[0].Length);assert.equal(reply.sceneId,scope.Scenes[1]);
|
|
r=await page.request.post(endpoint+'/finish',{headers,data:{instanceId:instance,sessionId:session,wordRevision}});assert.equal(r.status(),200);assert.equal((await r.json()).state,'Synchronised');
|
|
assert.equal((await manifest()).chapters.filter(c=>c.state==='Synchronised').length,2,'rejected geometry leaves accepted chapters intact');
|
|
console.log('PASS deployed native picture geometry, unchanged text/identity evidence, post-anchor Context, shifted following chapter, bad-digest rejection and complete acceptance');
|
|
}
|
|
// Download and restore through the established author-facing recovery workflow.
|
|
await page.goto(base+'/BookRecovery/Backup?projectId='+scope.Project);let token=await page.locator('form[action="/BookRecovery/ReviewBackup"] input[name=__RequestVerificationToken]').inputValue();r=await page.request.post(base+'/BookRecovery/Download',{form:{projectId:String(scope.Project),books:String(scope.Book),__RequestVerificationToken:token}});assert.equal(r.status(),200);assert.match(r.headers()['content-disposition'],/\.plotdirector/);const buffer=await r.body(),backup=JSON.parse(buffer);const source=backup.Snapshot.Recovery.ParagraphManuscripts[0];assert.equal(source.ChapterCheckpoints.length,2);assert.equal(source.Paragraphs[1].Occurrence.Text,rows[1].Text);assert.deepEqual(source.Paragraphs.map(p=>p.Occurrence.Id),evidence.Paragraphs.map(p=>p.Occurrence.Id));
|
|
await page.goto(base+'/BookRecovery/Restore');await page.locator('input[type=file]').setInputFiles({name:'chapter-checkpoint.plotdirector',mimeType:'application/json',buffer});await page.getByRole('button',{name:'Validate backup',exact:true}).click();await page.locator('[name=name]').fill('Chapter sync restored synthetic fixture');await page.getByRole('button',{name:'Preview restore',exact:true}).click();await page.locator('#confirm').check();await page.getByRole('button',{name:'Restore books',exact:true}).click();assert.match(await page.locator('main').innerText(),/restor/i);assert.ok(!(await page.locator('main').innerText()).includes('could not be confirmed'));const link=page.locator('a[href*="/Projects/Details/"]').first();const restoredProject=Number((await link.getAttribute('href')).match(/\d+$/)[0]);assert.ok(restoredProject&&restoredProject!==scope.Project);
|
|
await page.goto(base+'/BookRecovery/Backup?projectId='+restoredProject);token=await page.locator('form[action="/BookRecovery/ReviewBackup"] input[name=__RequestVerificationToken]').inputValue();const restoredBook=Number(await page.locator('[name=books]').first().inputValue());r=await page.request.post(base+'/BookRecovery/Download',{form:{projectId:String(restoredProject),books:String(restoredBook),__RequestVerificationToken:token}});assert.equal(r.status(),200);const restored=(await r.json()).Snapshot.Recovery.ParagraphManuscripts[0];assert.deepEqual(restored.Paragraphs.map(p=>[p.Occurrence.Id,p.Occurrence.NativeId,p.Occurrence.Text,p.SceneId]),source.Paragraphs.map(p=>[p.Occurrence.Id,p.Occurrence.NativeId,p.Occurrence.Text,p.SceneId]));assert.deepEqual(restored.ChapterCheckpoints.map(p=>p.ContentHash),source.ChapterCheckpoints.map(p=>p.ContentHash));assert.ok(restored.ChapterCheckpoints.every(p=>p.Status==='Not yet checked'));assert.equal(restored.SessionId,'00000000-0000-0000-0000-000000000000');console.log('PASS real backup/download/upload/preview/transactional restore and re-export: checkpoint hashes, paragraph/native IDs, exact prose and scene GUIDs survive; live session trust detached');
|
|
await page.request.delete(presence,{headers});
|
|
}finally{await browser.close();}})().catch(e=>{console.error('Synthetic chapter Development qualification: '+e.message);process.exit(1)});
|