// Complete COUNTRY02 on trusted HTTPS QA; no bypass flags or recorded credentials. 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 meta=JSON.parse(fs.readFileSync(path.join(DIR,'country-https-latest.json'))),source=meta.source; const target=JSON.parse(fs.readFileSync(path.join(source,'storage/app/private/investmoz-v2/portal-audit/country-https-browser-target.json'))); const actor=JSON.parse(fs.readFileSync(target.credentials_path)),stage=JSON.parse(fs.readFileSync(path.join(DIR,'country-https-production-stage-latest.json'))); const BASE=meta.base,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 receipt=path.join(DIR,'country-https-chromium-20261011.json'); const resume=process.argv.includes('--finish'),prior=resume?JSON.parse(fs.readFileSync(receipt)):null; if(resume){assert.equal(prior.code_hash,target.code_hash);assert.deepEqual(prior.target,target.target);assert(prior.checks.new_session_mfa_and_recovery&&prior.javascript_errors.length===0&&prior.mixed_requests.length===0);} const proof={...(prior??{}),at:new Date().toISOString(),origin:BASE,target:target.target,code_hash:target.code_hash,build_sha256:stage.build_manifest_sha256,checks:prior?.checks??{},navigation:[],assets:prior?.assets??{},javascript_errors:[],console_errors:[],mixed_requests:[],cookies:[],tls:[],active_writes:0,...(resume?{previous_run_criteria_preserved:true,previous_validation_failure:prior.failure,previous_navigation:prior.navigation}:{} )}; delete proof.failure; 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 abc='ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',bytes=[];let bits=0,v=0;for(const c of actor.totp_secret){v=(v<<5)|abc.indexOf(c);bits+=5;if(bits>=8){bytes.push((v>>>(bits-8))&255);bits-=8;}}const n=Buffer.alloc(8);n.writeBigUInt64BE(BigInt(Math.floor(Date.now()/30000)));const d=crypto.createHmac('sha1',Buffer.from(bytes)).update(n).digest(),o=d[19]&15;return String((d.readUInt32BE(o)&0x7fffffff)%1000000).padStart(6,'0');} const redact=s=>String(s).split('\nCall log:')[0].replaceAll(actor.password,'[REDACTED]').replaceAll(actor.totp_secret,'[REDACTED]').replace(/\b\d{6}\b/g,'[OTP OMITTED]'); (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']}); let context,page;const pending=[]; async function makeContext(){context=await browser.newContext({viewport:{width:1280,height:900},locale:'pt-MZ',ignoreHTTPSErrors:false});page=await context.newPage();page.setDefaultTimeout(25000); await context.route('**/*',r=>{const u=new URL(r.request().url());if(u.origin!==BASE&&!u.pathname.startsWith('/'))return r.abort();if(u.protocol==='http:'&&!u.port.includes('18105'))proof.mixed_requests.push({path:u.pathname,origin:u.origin});return (u.origin===BASE||u.origin===meta.http_redirect)?r.continue():r.abort();}); page.on('pageerror',e=>proof.javascript_errors.push({path:new URL(page.url()).pathname,message:redact(e.message)})); page.on('console',m=>{if(m.type()==='error')proof.console_errors.push(redact(m.text()).slice(0,300));}); page.on('response',r=>{const u=new URL(r.url());if(![BASE,meta.http_redirect].includes(u.origin))return;const location=r.headers().location;proof.navigation.push({path:u.pathname,scheme:u.protocol,method:r.request().method(),status:r.status(),...(location?{location}:{}),cache:r.headers()['cache-control']??null}); if(u.pathname.startsWith('/build/')||u.pathname==='/favicon.svg')pending.push((async()=>{const b=await r.body();proof.assets[u.pathname]={status:r.status(),sha256:crypto.createHash('sha256').update(b).digest('hex')};})().catch(()=>{})); if(u.protocol==='https:'&&r.request().isNavigationRequest())pending.push((async()=>{const security=await r.securityDetails();if(security)proof.tls.push({path:u.pathname,...security});})()); }); } 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 preview(){return page.evaluate(async endpoint=>(await fetch(endpoint,{headers:{Accept:'application/json'}})).json(),INSTALL);} async function profile(){return page.evaluate(async()=>{const r=await fetch('/api/v1/investment/profile',{headers:{Accept:'application/json'}});if(!r.ok)throw Error('Profile API denied');return r.json();});} async function sessionHash(){return page.evaluate(async()=>{const r=await fetch(location.pathname,{headers:{Accept:'text/html'}});return r.headers.get('X-Investmoz-QA-Session-Hash');});} async function cookieCheck(label){const list=await context.cookies(BASE);const details=list.map(({name,domain,path,secure,httpOnly,sameSite})=>({name,domain,path,secure,httpOnly,sameSite}));const session=list.find(c=>c.name==='country_https_18443_qa');assert(session&&session.secure&&session.httpOnly&&session.sameSite==='Lax'&&session.domain==='country02-qa.test'&&session.path==='/');assert(list.find(c=>c.name==='XSRF-TOKEN')?.secure);proof.cookies.push({step:label,cookies:details});return session.value;} async function 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 cookieCheck('before MFA');const before=await sessionHash();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));await cookieCheck('after MFA');const after=await sessionHash();assert(before&&after&&before!==after);proof.checks.session_regenerated_after_mfa=true;proof.session_transitions??=[];proof.session_transitions.push({step:'MFA',session_id_sha256_before:before,session_id_sha256_after:after});} async function encrypted(label){await page.waitForTimeout(250);const h=await page.evaluate(()=>({hasPage:!!history.state?.page,encrypted:history.state?.page instanceof ArrayBuffer,plainHistory:JSON.stringify(history.state).includes('Synthetic HTTPS QA country'),privateKeysPresent:Object.keys(sessionStorage).some(k=>/inertia/i.test(k))}));assert(h.hasPage&&h.encrypted&&!h.plainHistory);proof.checks[label]=h;} try{ await makeContext();const redirected=await page.goto(meta.http_redirect+INSTALL,{waitUntil:'networkidle'});assert.equal(new URL(page.url()).origin,BASE);assert.equal(new URL(page.url()).pathname,'/login');assert.equal(redirected.status(),200);proof.checks.http_redirect_https_preserves_path=true; proof.runtime=await page.evaluate(()=>({secureContext:isSecureContext,randomUUID:typeof crypto.randomUUID,subtle:typeof crypto.subtle}));assert(proof.runtime.secureContext&&proof.runtime.randomUUID==='function'&&proof.runtime.subtle==='object');proof.checks.certificate_accepted_without_bypass=true; await login();let master; if(!resume){ await open(INSTALL);await page.getByRole('heading',{name:'Instalação do país de constituição'}).waitFor();const first=await preview();assert(!first.installed&&first.ready&&first.consistent);assert.equal(first.code_hash,target.code_hash);assert.equal(first.target.database,target.target.database);assert.equal(first.target.port,55441);proof.operation_key=first.operationKey;proof.preview={hash:first.hash,migration:first.migration,ready:first.ready,installed:false}; const apply=page.getByRole('button',{name:'Aplicar extensão do país',exact:true});assert(await apply.isDisabled());await page.getByLabel('Confirmo a aplicação deste plano').check();await page.getByLabel('Fundamentação da instalação').fill('Synthetic HTTPS QA country installation only; no active changes');const response=page.waitForResponse(r=>new URL(r.url()).pathname===INSTALL&&r.request().method()==='POST');await apply.click();assert.equal((await response).status(),302);await page.getByText(/Base:.*Instalado/).waitFor();assert(await apply.isDisabled());proof.checks.cold_installation_visible=true; const seeded=cp.execFileSync('C:/Users/macbook/.config/investmoz/php-8.5.11/php.exe',[path.join(source,'tools/portal-country-https-qa.php'),'seed'],{encoding:'utf8'});assert.equal(JSON.parse(seeded).active_writes,0); cp.execFileSync('C:/Users/macbook/.config/investmoz/php-8.5.11/php.exe',[path.join(source,'tools/portal-country-https-qa.php'),'enable-country'],{stdio:'pipe'}); const r=await open('/investidor/profile');assert.match(r.headers()['cache-control'],/no-store/);await page.getByRole('heading',{name:'Perfil de investimento e empresas',exact:true}).waitFor();await encrypted('profile_history_encrypted'); master=page.getByRole('region',{name:'Cadastro mestre: Synthetic COUNTRY02 production bundle organization'});await master.waitFor();const initial=await profile();assert(initial.organizationCountryAvailable);assert.equal(initial.organizations.length,1);proof.organization_id=initial.organizations[0].id; async function saveCountry(code,ref){await master.getByRole('combobox',{name:'País de constituição da organização',exact:true}).selectOption(code);await master.getByLabel('Fonte ou referência deste país',{exact:true}).fill(ref);const changed=page.waitForResponse(r=>r.request().method()==='PUT'&&new URL(r.url()).pathname.endsWith('/country'));await master.getByRole('button',{name:'Guardar país no cadastro mestre',exact:true}).click();assert.equal((await changed).status(),303);await page.waitForLoadState('networkidle');assert.equal((await profile()).organizations[0].country,code);} await saveCountry('PT','Synthetic HTTPS QA country declaration one');proof.checks.master_saved_from_ui=true;await page.reload({waitUntil:'networkidle'});assert.equal(await master.getByRole('combobox',{name:'País de constituição da organização',exact:true}).inputValue(),'PT');proof.checks.refresh_recovers_saved_country=true; await saveCountry('MZ','Synthetic HTTPS QA country declaration update');const updated=await profile();proof.master_version=updated.organizations[0].version;assert.equal(updated.organizations[0].provenance.reference,'Synthetic HTTPS QA country declaration update');await encrypted('updated_history_encrypted');proof.checks.master_update_recovered=true; await page.getByRole('link',{name:'Voltar à área do investidor',exact:true}).click();await page.waitForURL(BASE+'/investidor/manifestacoes');await page.goBack({waitUntil:'networkidle'});await master.waitFor();assert.equal(await master.getByRole('combobox',{name:'País de constituição da organização',exact:true}).inputValue(),'MZ');await encrypted('back_history_encrypted');await page.goForward({waitUntil:'networkidle'});assert.equal(new URL(page.url()).pathname,'/investidor/manifestacoes');await page.goBack({waitUntil:'networkidle'});await master.waitFor();proof.checks.back_forward_no_history_error=true; await page.screenshot({path:path.join(DIR,'country-https-profile-20261011.png'),fullPage:true}); }else{await open('/investidor/profile');master=page.getByRole('region',{name:'Cadastro mestre: Synthetic COUNTRY02 production bundle organization'});await master.waitFor();assert.equal(await master.getByRole('combobox',{name:'País de constituição da organização',exact:true}).inputValue(),'MZ');await encrypted('resume_history_encrypted');} await cookieCheck('before logout');const beforeLogout=await sessionHash();const logout=page.getByRole('button',{name:/Terminar sessão|Sair|Log out/i}).first();await logout.click();await page.waitForURL(u=>!u.pathname.startsWith('/investidor/'));await cookieCheck('after logout');const afterLogout=await sessionHash();assert(beforeLogout&&afterLogout&&beforeLogout!==afterLogout);proof.session_transitions.push({step:'logout',session_id_sha256_before:beforeLogout,session_id_sha256_after:afterLogout});const denied=await page.evaluate(async()=>{const r=await fetch('/api/v1/investment/profile',{headers:{Accept:'application/json'}});return r.status;});assert.equal(denied,401);proof.checks.logout_revokes_private_api=true; await page.goBack({waitUntil:'networkidle'});await page.getByRole('heading',{name:'Log in to your account',exact:true}).waitFor();proof.logout_back={path:new URL(page.url()).pathname,private_master_visible:await master.isVisible(),login_form_visible:await page.locator('#email').isVisible(),inertia_key_present:await page.evaluate(()=>Object.keys(sessionStorage).some(k=>/inertia/i.test(k)))};assert(!proof.logout_back.private_master_visible,'Private encrypted profile recovered through Back after logout');assert(proof.logout_back.login_form_visible);proof.checks.logout_back_does_not_reveal_master=true; await context.close();await makeContext();await open('/investidor/profile');assert.equal(new URL(page.url()).pathname,'/login');await login();await open('/investidor/profile');master=page.getByRole('region',{name:'Cadastro mestre: Synthetic COUNTRY02 production bundle organization'});await master.waitFor();assert.equal(await master.getByRole('combobox',{name:'País de constituição da organização',exact:true}).inputValue(),'MZ');assert.equal((await profile()).organizations[0].provenance.reference,'Synthetic HTTPS QA country declaration update');await encrypted('new_session_history_encrypted');proof.checks.new_session_mfa_and_recovery=true; const beforeDisable=(await profile()).organizations; cp.execFileSync('C:/Users/macbook/.config/investmoz/php-8.5.11/php.exe',[path.join(source,'tools/portal-country-https-qa.php'),'disable-country'],{stdio:'pipe'}); await open('/investidor/profile');await page.getByRole('status').filter({hasText:'Extensão do país de constituição ainda não instalada neste ambiente.'}).waitFor();assert.equal((await profile()).organizationCountryAvailable,false);proof.checks.disable_hides_country_consumer=true; cp.execFileSync('C:/Users/macbook/.config/investmoz/php-8.5.11/php.exe',[path.join(source,'tools/portal-country-https-qa.php'),'enable-country'],{stdio:'pipe'}); await open('/investidor/profile');assert.deepEqual((await profile()).organizations,beforeDisable);proof.checks.disable_reenable_preserves_master_version_provenance=true; await Promise.allSettled(pending);assert.equal(proof.javascript_errors.length,0);assert(proof.console_errors.every(s=>s==='Failed to load resource: the server responded with a status of 401 (Unauthorized)'));proof.expected_console_denials=proof.console_errors;proof.console_errors=[];assert.equal(proof.mixed_requests.length,0);for(const [url,a]of Object.entries(proof.assets)){assert.equal(a.status,200);assert.equal(a.sha256,url.startsWith('/build/')?stage.assets[url.slice(7)]:crypto.createHash('sha256').update(fs.readFileSync(path.join(ROOT,'public',url.slice(1)))).digest('hex'));}proof.checks.production_assets_identical_no_mixed_content=true; assert(proof.tls.length&&proof.tls.every(t=>/TLS 1\.[23]/.test(t.protocol)));proof.checks.tls12_or_newer=true; proof.result='passed';save();console.log(JSON.stringify({result:'passed',origin:BASE,runtime:proof.runtime,checks:Object.keys(proof.checks),assets:Object.keys(proof.assets).length,active_writes:0})); }catch(e){proof.result='failed';proof.failure=redact(e.message).slice(0,1400);save();console.log(JSON.stringify({result:'failed',failure:proof.failure}));process.exitCode=1;} finally{if(context)await context.close();await browser.close();} })().catch(e=>{console.error(redact(e.message).slice(0,500));process.exitCode=1;});