64 lines
11 KiB
JavaScript
64 lines
11 KiB
JavaScript
// C110 only: normal synthetic MFA in isolated QA on an untrusted HTTP hostname.
|
|
const fs = require('node:fs'),path=require('node:path'),assert=require('node:assert/strict'),crypto=require('node:crypto'),cp=require('node:child_process');
|
|
const { chromium } = require('C:/Users/macbook/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright');
|
|
const ROOT=path.resolve(__dirname,'..'),DIR=path.join(ROOT,'storage/app/private/investmoz-v2/portal-audit');
|
|
const source=JSON.parse(fs.readFileSync(path.join(DIR,'country-c110-source-latest.json'))).source;
|
|
const target=JSON.parse(fs.readFileSync(path.join(source,'storage/app/private/investmoz-v2/portal-audit/country-production-browser-target.json')));
|
|
const actor=JSON.parse(fs.readFileSync(target.credentials_path)),stage=JSON.parse(fs.readFileSync(path.join(DIR,'country-c110-production-stage-latest.json')));
|
|
const BASE='http://country02-qa.test:18103',ID=target.target.database+':55441',INSTALL='/management/opportunity-resources-install/organization-country';
|
|
assert.equal(target.base,BASE);assert.match(target.target.database,/^country_candidate_\d{8}_\d{6}_test$/);
|
|
const proof={at:new Date().toISOString(),origin:BASE,target:target.target,code_hash:target.code_hash,build_sha256:stage.build_manifest_sha256,session_driver:target.session_driver,checks:{},navigation:[],assets:{},javascript_errors:[],separate_private_consumer_failure:null,active_writes:0};
|
|
const receipt=path.join(DIR,'country-c110-chromium-20261011.json');
|
|
if(fs.existsSync(receipt))fs.copyFileSync(receipt,receipt.replace('.json','-attempt-'+Date.now()+'.json'));
|
|
const save=()=>fs.writeFileSync(receipt,JSON.stringify(proof,null,2));
|
|
function otp(){const alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',bytes=[];let bits=0,value=0;for(const c of actor.totp_secret){value=(value<<5)|alphabet.indexOf(c);bits+=5;if(bits>=8){bytes.push((value>>>(bits-8))&255);bits-=8;}}const counter=Buffer.alloc(8);counter.writeBigUInt64BE(BigInt(Math.floor(Date.now()/30000)));const d=crypto.createHmac('sha1',Buffer.from(bytes)).update(counter).digest(),o=d[19]&15;return String((d.readUInt32BE(o)&0x7fffffff)%1000000).padStart(6,'0');}
|
|
(async()=>{
|
|
const browser=await chromium.launch({headless:true,executablePath:'C:/Users/macbook/AppData/Local/ms-playwright/chromium-1243/chrome-win64/chrome.exe',args:['--host-resolver-rules=MAP country02-qa.test 127.0.0.1','--no-proxy-server']});
|
|
const context=await browser.newContext({viewport:{width:390,height:900},locale:'pt-MZ'}),page=await context.newPage();page.setDefaultTimeout(30000);
|
|
const pending=[],bodies=[];
|
|
await context.route('**/*',r=>new URL(r.request().url()).origin===BASE?r.continue():r.abort());
|
|
page.on('pageerror',e=>{const message=e.message.replaceAll(actor.password,'[REDACTED]').replaceAll(actor.totp_secret,'[REDACTED]');const route=new URL(page.url()).pathname;if(message==='Unable to encrypt history'&&route.startsWith('/investidor/')){proof.separate_private_consumer_failure={case:'C111',route,message,history_encryption_preserved:true};}else{proof.javascript_errors.push({route,message});}});
|
|
page.on('request',r=>{if(new URL(r.url()).pathname===INSTALL&&r.method()==='POST')bodies.push(JSON.parse(r.postData()));});
|
|
page.on('response',r=>{const u=new URL(r.url());if(u.origin!==BASE)return;proof.navigation.push({path:u.pathname,method:r.request().method(),status:r.status()});if(u.pathname.startsWith('/build/'))pending.push((async()=>{const b=await r.body();proof.assets[u.pathname]={status:r.status(),sha256:crypto.createHash('sha256').update(b).digest('hex')};})().catch(()=>{}));});
|
|
async function open(route){const r=await page.goto(BASE+route,{waitUntil:'networkidle'});assert.equal(r.headers()['x-investmoz-qa-target'],ID);assert.equal(r.headers()['x-investmoz-candidate-code'],target.code_hash);return r;}
|
|
async function plan(){return await page.evaluate(async endpoint=>{const response=await fetch(endpoint,{headers:{Accept:'application/json'}});if(!response.ok)throw new Error('Authenticated QA preview unavailable');return response.json();},INSTALL);}
|
|
const readyFile=path.join(target.runtime,'app/private/investmoz-v2/organization-country-installation/readiness.json');let readinessBackup;
|
|
try{
|
|
await open(INSTALL);assert.equal(new URL(page.url()).pathname,'/login');
|
|
await page.locator('#email').fill(actor.email);await page.locator('#password').fill(actor.password);await page.locator('[data-test="login-button"]').click();await page.waitForURL(BASE+'/two-factor-challenge');
|
|
await page.locator('input[name="code"]').fill(otp());await page.getByRole('button',{name:'Continue',exact:true}).click();await page.waitForURL(u=>!['/login','/two-factor-challenge'].includes(u.pathname));
|
|
proof.checks.synthetic_manager_normal_mfa=true;
|
|
await open(INSTALL);await page.getByRole('heading',{name:'Instalação do país de constituição'}).waitFor();
|
|
proof.runtime=await page.evaluate(()=>({secureContext:isSecureContext,randomUUID:typeof crypto.randomUUID,getRandomValues:typeof crypto.getRandomValues,subtle:typeof crypto.subtle}));
|
|
assert.equal(proof.runtime.secureContext,false);assert.equal(proof.runtime.randomUUID,'undefined');
|
|
const first=await plan();assert.equal(first.installed,false);assert.equal(first.consistent,true);assert.equal(first.ready,true);assert.equal(first.target.database,target.target.database);assert.equal(first.target.port,55441);assert.equal(first.code_hash,target.code_hash);
|
|
assert.match(first.operationKey,/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i);
|
|
proof.operation_key=first.operationKey;proof.pre_install_plan={hash:first.hash,migration:first.migration,ready:first.ready,consistent:first.consistent,installed:first.installed};
|
|
const apply=page.getByRole('button',{name:'Aplicar extensão do país',exact:true});assert(await apply.isDisabled());proof.checks.confirmation_required=true;
|
|
await page.reload({waitUntil:'networkidle'});const refreshed=await plan();assert.equal(refreshed.operationKey,first.operationKey);assert.equal(refreshed.hash,first.hash);proof.checks.server_key_survives_reload=true;
|
|
const reason='Synthetic C110 QA HTTP hostname rehearsal: country only, no active operation';
|
|
await page.getByLabel('Confirmo a aplicação deste plano').check();await page.getByLabel('Fundamentação da instalação').fill(reason);assert(!(await apply.isDisabled()));
|
|
// Expire only this QA evidence between preview and POST to exercise actual server409 recovery.
|
|
readinessBackup=fs.readFileSync(readyFile);const stale=JSON.parse(readinessBackup);stale.verified_at='2000-01-01T00:00:00+00:00';fs.writeFileSync(readyFile,JSON.stringify(stale));
|
|
const failedResponse=page.waitForResponse(r=>new URL(r.url()).pathname===INSTALL&&r.request().method()==='POST');await apply.click();assert.equal((await failedResponse).status(),409);proof.checks.stale_preview_rejected_before_writes=true;
|
|
fs.writeFileSync(readyFile,readinessBackup);readinessBackup=null;
|
|
await open(INSTALL);await page.getByRole('heading',{name:'Instalação do país de constituição'}).waitFor();const recovered=await plan();assert.equal(recovered.operationKey,first.operationKey);assert.equal(recovered.installed,false);assert.equal(recovered.ready,true);proof.checks.error_recovery_keeps_operation_key=true;
|
|
await page.getByLabel('Confirmo a aplicação deste plano').check();await page.getByLabel('Fundamentação da instalação').fill(reason);
|
|
const installedResponse=page.waitForResponse(r=>new URL(r.url()).pathname===INSTALL&&r.request().method()==='POST');await apply.click();assert.equal((await installedResponse).status(),302);await page.getByText(/Base:.*Instalado/).waitFor();assert(await apply.isDisabled());proof.checks.cold_install_visible=true;
|
|
assert.equal(bodies.length,2);assert.equal(bodies[0].idempotency_key,first.operationKey);assert.equal(bodies[1].idempotency_key,first.operationKey);assert.deepEqual(bodies[0],bodies[1]);
|
|
const original=bodies[1];
|
|
const replay=await page.evaluate(async({endpoint,body})=>{const cookie=document.cookie.split('; ').find(x=>x.startsWith('XSRF-TOKEN='));const token=decodeURIComponent(cookie.slice(11));const req=b=>fetch(endpoint,{method:'POST',headers:{Accept:'application/json','Content-Type':'application/json','X-XSRF-TOKEN':token},body:JSON.stringify(b)});const a=await req(body),one=await a.json(),b=await req(body),two=await b.json(),c=await req({...body,reason:'Changed payload under same completed operation key must be denied'});return{status:[a.status,b.status],one,two,conflict:c.status};},{endpoint:INSTALL,body:original});
|
|
assert.deepEqual(replay.status,[200,200]);assert.deepEqual(replay.one,replay.two);assert.equal(replay.one.changed,true);assert.equal(replay.one.new_columns,2);assert.equal(replay.one.new_tables,0);assert.equal(replay.one.flags_changed,false);assert.equal(replay.conflict,409);proof.checks.same_body_replay_returns_original_receipt=replay;proof.checks.changed_body_same_key_denied=true;
|
|
await open(INSTALL);assert.equal((await plan()).operationKey,first.operationKey);await page.getByText(/Base:.*Instalado/).waitFor();proof.checks.receipt_recovered_after_reload=true;
|
|
const screenshot=path.join(DIR,'country-c110-install-http-390.png');await page.screenshot({path:screenshot,fullPage:true});proof.screenshot=screenshot;
|
|
for(const route of ['/management/opportunity-management-install','/management/opportunity-resources-install']){await open(route);await page.getByRole('heading',{name:'Ativação da Gestão de Oportunidades',exact:true}).waitFor();}proof.checks.other_shared_installers_render_get_only=true;
|
|
cp.execFileSync('C:/Users/macbook/.config/investmoz/php-8.5.11/php.exe',[path.join(source,'tools/portal-country-c110-qa.php'),'enable-country'],{stdio:'pipe'});
|
|
await open('/investidor/profile');await page.getByText('Sem representação organizacional registada para esta conta.').waitFor();proof.checks.country_consumer_empty_master_controlled=true;
|
|
proof.checks.width_390_no_overflow=await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth);assert(proof.checks.width_390_no_overflow);
|
|
await Promise.allSettled(pending);assert.equal(proof.javascript_errors.length,0);
|
|
for(const [url,asset]of Object.entries(proof.assets)){assert.equal(asset.status,200);assert.equal(asset.sha256,stage.assets[url.slice('/build/'.length)]);}proof.checks.loaded_production_assets_identical=true;
|
|
proof.result='passed';proof.scope='C110 installer complete; C111 private HTTP history remains a separate activation stop condition';save();console.log(JSON.stringify({result:proof.result,origin:BASE,runtime:proof.runtime,checks:Object.keys(proof.checks),assets:Object.keys(proof.assets).length,separate_private_consumer_failure:proof.separate_private_consumer_failure,active_writes:0}));
|
|
}catch(e){proof.result='failed';proof.failure=String(e.message).replaceAll(actor.password,'[REDACTED]').replaceAll(actor.totp_secret,'[REDACTED]').replace(/\b\d{6}\b/g,'[OTP OMITTED]').slice(0,1000);save();console.log(JSON.stringify({result:'failed',failure:proof.failure}));process.exitCode=1;}
|
|
finally{if(readinessBackup)fs.writeFileSync(readyFile,readinessBackup);await context.close();await browser.close();}
|
|
})().catch(()=>{console.error('C110 QA browser initialization failed; no active writes.');process.exitCode=1;});
|