// Reusable real Development sessions. Test executable/browser tooling only; never deployed. 'use strict'; const fs=require('node:fs'),path=require('node:path'),os=require('node:os'),crypto=require('node:crypto'); const {chromium}=require('playwright'); const BASE='https://dev.plotdirector.com'; const STATIC_SCRIPTS=new Set(['https://cdn.jsdelivr.net/npm/chart.js@4.4.9/dist/chart.umd.min.js','https://cdn.jsdelivr.net/npm/@microsoft/signalr@8.0.7/dist/browser/signalr.min.js']); function requestAllowed(url,method='GET',type='document'){try{return new URL(url).origin===BASE||(method==='GET'&&type==='script'&&STATIC_SCRIPTS.has(url));}catch{return false;}} const IDENTITY=path.join(os.homedir(),'.config/cyj/credentials/application-browser.json'); function check(condition,message){if(!condition)throw new Error(message);} function target(route){check(typeof route==='string'&&route.startsWith('/')&&!route.startsWith('//'),'Only Development-relative routes are supported');const url=new URL(route,BASE);check(url.origin===BASE,'Only Development is permitted');return url.href;} function workspaceAllowed(cards,projects){return cards.every(card=>projects.some(record=>(record.id===card.id||record.id===null)&&record.name===card.name));} function loadIdentity(file=IDENTITY){ const parent=fs.lstatSync(path.dirname(file));check(parent.isDirectory()&&!parent.isSymbolicLink()&&parent.uid===process.getuid()&&(parent.mode&0o777)===0o700,'Private credential directory required'); const fd=fs.openSync(file,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW); try{const st=fs.fstatSync(fd);check(st.isFile()&&st.uid===process.getuid()&&(st.mode&0o777)===0o600&&st.nlink===1&&st.size<16384,'Private credential file required'); let i;try{i=JSON.parse(fs.readFileSync(fd,'utf8'));}catch{throw new Error('Private credential record is invalid; no contents logged');} check(i.Database==='PlotDirector_Development'&&i.Origin===BASE&&i.Worker==='application'&&i.Purpose==='CYJ Development browser acceptance','Dedicated Development identity required'); check(Number.isSafeInteger(i.UserID)&&i.UserID>0&&/^pwa-browser-[a-f0-9]{32}@example\.invalid$/.test(i.Email)&&typeof i.Password==='string'&&i.Password.length>=40,'Invalid dedicated identity');return i; }finally{fs.closeSync(fd);} } function runState(){ const id=process.env.PD_DEV_BROWSER_RUN_ID,fd=Number(process.env.PD_DEV_BROWSER_LOCK_FD),file=process.env.PD_DEV_BROWSER_STATE; check(/^[a-f0-9]{32}$/.test(id||'')&&Number.isInteger(fd)&&fd>=3,'Use Tools/BrowserAcceptance/run.py'); const text=Buffer.alloc(32);check(fs.readSync(fd,text,0,32,0)===32&&text.toString()===id,'Acceptance lock mismatch'); check(file===path.join(os.homedir(),'.local/state/cyj/browser/application',id+'.json'),'Invalid run state path'); let state={runId:id,projects:[]};if(fs.existsSync(file)){check(!fs.lstatSync(file).isSymbolicLink(),'Linked state refused');state=JSON.parse(fs.readFileSync(file));check(state.runId===id&&Array.isArray(state.projects),'Invalid run state');} return {id,state,save(){const temporary=file+'.'+crypto.randomUUID();fs.writeFileSync(temporary,JSON.stringify(state),{mode:0o600,flag:'wx'});fs.renameSync(temporary,file);}}; } async function login(page,identity){ try{check((await page.goto(target('/Account/Login'))).status()===200,'Login unavailable'); await page.locator('#Email').fill(identity.Email);await page.locator('#Password').fill(identity.Password); await Promise.all([page.waitForURL(BASE+'/Projects'),page.locator('form button[type=submit]').click()]); }catch{throw new Error('Normal Development login failed; check fixture account, MFA and private provisioning. No input values retained.');} } async function open(){ let browser; try{const scope=runState(),identity=loadIdentity();browser=await chromium.launch({headless:true,executablePath:process.env.CHROMIUM_PATH||undefined});const context=await browser.newContext({viewport:{width:1440,height:1000},serviceWorkers:'block'}); // Intercept every browser request, including form submissions and redirects. // Only the two pinned scripts already used by the application may load externally. // Production and other external requests, including form submissions, are blocked. let blockedExternal=0; await context.route('**/*',route=>{if(requestAllowed(route.request().url(),route.request().method(),route.request().resourceType()))return route.continue();blockedExternal++;return route.abort('blockedbyclient');}); const page=await context.newPage();await login(page,identity); const visible=await page.locator('.project-card').evaluateAll(cards=>cards.map(card=>({id:Number(card.dataset.pdContextId),name:card.dataset.pdContextLabel}))); check(workspaceAllowed(visible,scope.state.projects),'Unexpected project membership; operator review required'); async function goto(route){const response=await page.goto(target(route));check(new URL(page.url()).origin===BASE,'Unexpected destination');return response;} async function post(route,fields){ // Browser fetch is subject to the same origin gate, unlike context.request. const result=await page.evaluate(async ({url,fields})=>{const token=document.querySelector('input[name=__RequestVerificationToken]')?.value;if(!token)return {status:0}; const response=await fetch(url,{method:'POST',credentials:'same-origin',body:new URLSearchParams({...fields,__RequestVerificationToken:token})});return {status:response.status}; },{url:target(route),fields});check(result.status>=200&&result.status<400,'Normal application mutation failed');return result; } async function create(area,query,fields,prepare){ let phase='form',invalidFields=[];try { if(area==='Projects')check(scope.state.projects.some(record=>record.id===null&&record.name===fields.ProjectName),'Register the run project before creating it'); else check(scope.state.projects.length===1&&Number.isSafeInteger(scope.state.projects[0].id),'Create the registered disposable project first'); check(['Projects','Books','Chapters','Characters','Locations','StoryAssets','PlotLines','PlotThreads'].includes(area),'Unsupported fixture record'); check((await goto(`/${area}/Create${query||''}`)).status()===200,'Fixture create form unavailable'); phase='fields';for(const [name,value]of Object.entries(fields)){const field=page.locator(`[name="${name}"]`).first();if(await field.evaluate(e=>e.tagName)==='SELECT')await field.selectOption(String(value));else await field.fill(String(value));} if(prepare)await prepare(page); phase='validation';invalidFields=await page.locator('main form.pd-record-form').evaluate(form=>Array.from(form.elements).filter(e=>e.willValidate&&!e.validity.valid).map(e=>e.name));check(invalidFields.length===0,'Fixture requires valid form fields'); phase='submit';await Promise.all([page.waitForNavigation(),page.locator('main form.pd-record-form button[type=submit]').filter({hasText:/Save/}).evaluate(button=>button.form.requestSubmit(button))]); check(!/\/Save$/.test(new URL(page.url()).pathname),'Fixture form validation failed'); phase='identity';let id=Number(new URL(page.url()).pathname.match(/\/(?:Details|Edit)\/(\d+)/)?.[1]); if(!id){const href=await page.locator(`main a[href*="/${area}/Edit/"],main a[href*="/${area}/Details/"]`).first().getAttribute('href');id=Number(href?.match(/\/(?:Edit|Details)\/(\d+)/)?.[1]);} check(Number.isSafeInteger(id)&&id>0,'Fixture record ID unavailable');return id; }catch(error){throw new Error('fixture-create:'+JSON.stringify({area,phase,path:new URL(page.url()).pathname,type:error.name,invalidFields}));} } async function project(){ check(scope.state.projects.length===0,'One disposable project per run; reuse its books and records'); const name='CYJ acceptance '+scope.id; // Persist intent before submitting, so interrupted creates can be recovered by exact name. const record={id:null,name};scope.state.projects.push(record);scope.save(); record.id=await create('Projects','',{ProjectName:name,Description:'Disposable automated Development acceptance fixture.'});scope.save();return record.id; } async function cleanup(){ for(const record of [...scope.state.projects]){ check(record.name==='CYJ acceptance '+scope.id,'Cleanup scope mismatch'); if(!record.id){await goto('/Projects');const matches=page.locator('a[href^="/Projects/Details/"]').filter({hasText:record.name});check(await matches.count()<=1,'Ambiguous recovery');if(await matches.count())record.id=Number((await matches.getAttribute('href')).split('/').pop());else{scope.state.projects.splice(scope.state.projects.indexOf(record),1);scope.save();continue;}scope.save();} let response=await goto('/Projects/Edit/'+record.id); if(response.status()===404){ // A previous cleanup may have archived the project before it was interrupted. await goto('/Projects'); }else{check(response.status()===200&&await page.locator('[name=ProjectName]').inputValue()===record.name,'Cleanup owner/name verification failed');await post('/Projects/Archive/'+record.id,{});await goto('/Projects');} // Server requires archived owner plus the exact confirmation name. Never delete accounts here. await post('/Projects/HardDeleteArchivedProject',{projectId:String(record.id),confirmationName:record.name}); await goto('/Projects');check(await page.locator(`.project-card[data-pd-context-id="${record.id}"]`).count()===0,'Archived fixture still exists after cleanup'); check((await goto('/Projects/Details/'+record.id)).status()===404,'Fixture cleanup not confirmed'); scope.state.projects.splice(scope.state.projects.indexOf(record),1);scope.save(); } } return {page,goto,post,create,project,cleanup,runId:scope.id,blockedExternal:()=>blockedExternal,async close(){await context.close();await browser.close();}}; }catch{if(browser)await browser.close().catch(()=>{});throw new Error('Development acceptance session unavailable; check the launcher, fixture credentials/MFA and unexpected project membership. No input values logged.');} } module.exports={BASE,IDENTITY,target,requestAllowed,workspaceAllowed,loadIdentity,login,open};