105 lines
9.4 KiB
JavaScript
105 lines
9.4 KiB
JavaScript
// Production asset rehearsal on the isolated restored database; authentication material stays local.
|
|
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 target = JSON.parse(fs.readFileSync(path.join(DIR, 'country-production-browser-target.json')));
|
|
const actor = JSON.parse(fs.readFileSync(target.credentials_path)), stage = JSON.parse(fs.readFileSync(path.join(DIR, 'country-production-stage-latest.json')));
|
|
const BASE = target.base, ID = target.target.database + ':' + target.target.port;
|
|
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(), offset = d[19] & 15;
|
|
return String((d.readUInt32BE(offset) & 0x7fffffff) % 1000000).padStart(6, '0');
|
|
}
|
|
const proof = { at: new Date().toISOString(), target: target.target, base: BASE, session_driver: target.session_driver, code_hash: target.code_hash, production_manifest_sha256: stage.build_manifest_sha256, other_flags_enabled: false, checks: {}, events: [], assets: {}, javascript_errors: [], active_writes: 0 };
|
|
const receipt = path.join(DIR, 'country-production-chromium-20261011.json');
|
|
if (fs.existsSync(receipt)) {
|
|
const previous = receipt.replace('.json', '-attempt-' + Date.now() + '.json');
|
|
fs.copyFileSync(receipt, previous); proof.prior_attempt = previous;
|
|
}
|
|
const save = () => fs.writeFileSync(receipt, JSON.stringify(proof, null, 2));
|
|
const pending = [];
|
|
(async () => {
|
|
const browser = await chromium.launch({ headless: true, executablePath: 'C:/Users/macbook/AppData/Local/ms-playwright/chromium-1243/chrome-win64/chrome.exe' });
|
|
try {
|
|
async function session() {
|
|
const ctx = await browser.newContext({ viewport: { width: 390, height: 900 }, locale: 'pt-MZ' });
|
|
await ctx.route('**/*', r => new URL(r.request().url()).origin === BASE ? r.continue() : r.abort());
|
|
const page = await ctx.newPage(); page.setDefaultTimeout(30000);
|
|
page.on('pageerror', () => proof.javascript_errors.push('Browser JavaScript error; no authentication details recorded'));
|
|
page.on('response', r => {
|
|
const u = new URL(r.url()); if (u.origin !== BASE) return;
|
|
proof.events.push({ path: u.pathname, method: r.request().method(), status: r.status() });
|
|
if (u.pathname.startsWith('/build/')) pending.push((async () => { const bytes = await r.body(); proof.assets[u.pathname] = { status: r.status(), sha256: crypto.createHash('sha256').update(bytes).digest('hex') }; })().catch(() => {}));
|
|
});
|
|
async function open(url) {
|
|
const r = await page.goto(BASE + url, { waitUntil: 'domcontentloaded' }); assert.equal(r.headers()['x-investmoz-qa-target'], ID); return r;
|
|
}
|
|
await open('/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', { waitUntil: 'domcontentloaded' });
|
|
if (!proof.checks.invalid_mfa_denied) {
|
|
await page.locator('input[name="code"]').fill('not-a-code'); await page.getByRole('button', { name: 'Continue', exact: true }).click();
|
|
await page.getByText('The provided two factor authentication code was invalid.').waitFor();
|
|
assert.equal(new URL(page.url()).pathname, '/two-factor-challenge'); proof.checks.invalid_mfa_denied = true;
|
|
}
|
|
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), { waitUntil: 'domcontentloaded' });
|
|
return { ctx, page, open };
|
|
}
|
|
let s = await session(); proof.checks.normal_mfa_without_040000 = true;
|
|
await s.open('/management/opportunity-resources-install/organization-country');
|
|
await s.page.getByRole('heading', { name: 'Instalação do país de constituição' }).waitFor();
|
|
const apply = s.page.getByRole('button', { name: 'Aplicar extensão do país', exact: true });
|
|
if (await s.page.getByText('Ainda não aplicado', { exact: false }).isVisible()) {
|
|
await s.page.getByLabel('Confirmo a aplicação deste plano').check();
|
|
await s.page.getByLabel('Fundamentação da instalação').fill('Synthetic QA production bundle rehearsal only; no active installation');
|
|
await apply.click();
|
|
}
|
|
await s.page.getByText(/Base:.*Instalado/).waitFor();
|
|
assert(await apply.isDisabled());
|
|
proof.checks.authenticated_install_visible = true;
|
|
await s.open('/investidor/profile');
|
|
await s.page.getByText('Sem representação organizacional registada para esta conta.').waitFor();
|
|
proof.checks.empty_master_controlled = true;
|
|
cp.execFileSync('C:/Users/macbook/.config/investmoz/php-8.5.11/php.exe', [path.join(ROOT, 'tools/portal-country-production-qa.php'), 'seed'], { stdio: 'pipe' });
|
|
await s.open('/investidor/profile');
|
|
const org = s.page.getByRole('region', { name: 'Cadastro mestre: Synthetic COUNTRY02 production bundle organization', exact: true });
|
|
const initialVersion = Number((await org.innerText()).match(/Versão (\d+)/)[1]);
|
|
await org.getByRole('combobox', { name: 'País de constituição da organização', exact: true }).selectOption('PT');
|
|
await org.getByLabel('Fonte ou referência deste país').fill('Synthetic QA declaration only; no organization created in active database');
|
|
await org.getByRole('button', { name: /Guardar país no/ }).click();
|
|
await org.getByText('Versão ' + (initialVersion + 1) + ';', { exact: false }).waitFor();
|
|
const shot = path.join(DIR, 'country-production-profile-390-20261011.png'); await s.page.screenshot({ path: shot, fullPage: true }); proof.screenshot = shot;
|
|
proof.checks.master_save_visible = true;
|
|
assert.equal(await org.getByRole('combobox').inputValue(), 'PT');
|
|
await s.ctx.close(); s = await session();
|
|
await s.open('/investidor/profile');
|
|
const recovered = s.page.getByRole('region', { name: 'Cadastro mestre: Synthetic COUNTRY02 production bundle organization', exact: true });
|
|
await recovered.waitFor(); assert.equal(await recovered.getByRole('combobox').inputValue(), 'PT');
|
|
proof.checks.fresh_session_recovery = true;
|
|
proof.checks.width_390_no_overflow = await s.page.evaluate(() => document.documentElement.scrollWidth <= innerWidth);
|
|
assert(proof.checks.width_390_no_overflow);
|
|
const replay = await s.page.evaluate(async () => {
|
|
const endpoint = '/management/opportunity-resources-install/organization-country';
|
|
const p = await (await fetch(endpoint, { headers: { Accept: 'application/json' } })).json();
|
|
const token = decodeURIComponent(document.cookie.split('; ').find(x => x.startsWith('XSRF-TOKEN=')).slice(11));
|
|
const key = crypto.randomUUID();
|
|
const body = { hash: p.hash, confirm: true, idempotency_key: key, reason: 'Synthetic QA repeat of authenticated country installation; no duplicate DDL' };
|
|
const request = () => fetch(endpoint, { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-XSRF-TOKEN': token }, body: JSON.stringify(body) });
|
|
const a = await request(), first = await a.json(), b = await request(), second = await b.json();
|
|
return { status: [a.status, b.status], first, second };
|
|
});
|
|
assert.deepEqual(replay.status, [200, 200]); assert.equal(replay.first.changed, false); assert.deepEqual(replay.first, replay.second);
|
|
proof.checks.no_duplicate_installation = replay;
|
|
await Promise.allSettled(pending);
|
|
assert.equal(proof.javascript_errors.length, 0); assert(Object.keys(proof.assets).length > 0);
|
|
for (const [url, a] of Object.entries(proof.assets)) { assert.equal(a.status, 200); assert.equal(a.sha256, stage.assets[url.slice('/build/'.length)]); }
|
|
proof.checks.production_assets_all_loaded_identical = true;
|
|
await s.ctx.close(); proof.result = 'passed'; save(); console.log(JSON.stringify({ result: proof.result, checks: Object.keys(proof.checks), loaded_assets: Object.keys(proof.assets).length, 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, 1300); save(); console.log(JSON.stringify({ result: 'failed', failure: proof.failure })); process.exitCode = 1;
|
|
} finally { await browser.close(); }
|
|
})();
|