Files
openwaf/scripts/console-check.cjs
T
Pavlo Ratushnyi a77ab53ea8 A storage failure was reported to the operator as success, as their own bad request, and as ready
Measured on two shipped images of the same stand — openwaf:prefix built from
72d37ad and openwaf:ci built from this tree — with the block table and the
policy table dropped out from under a running edge that held 3 blocks and 1
policy row:

  DELETE /admin-api/blocks?source=operator   200 {"deleted":0}      -> 503 "NOTHING was deleted"
  DELETE /admin-api/blocks?key=203.0.113.201 200 {"deleted":0}      -> 503 "NOTHING was deleted"
  POST   /admin-api/blocks                   400 database error     -> 503 "the block is NOT in effect"
  PUT    /admin-api/policy {"mode":"Enforce"} 200, body mode=Observe -> 503 "the change is NOT in effect"
  GET    /admin-api/blocks                   500                    -> 500 (unchanged)
  GET    /readyz                             200 ready              -> 503
  GET    /healthz                            200                    -> 200 (unchanged: the recovery hatch)

Four separate lies, one class:

* BlockStore.DeleteAsync caught everything, logged a warning and returned 0, so
  the endpoint answered {"deleted":0} — the same bytes an empty list produces.
  A destructive command that could not run told the operator there was nothing
  to remove.
* BlockStore.AddOperatorAsync returned the string "database error" and the
  endpoint mapped it to 400, next to the real validation errors. A storage
  failure arrived as "your request is wrong", which invites a retry of the
  request while no block is in effect.
* PUT /admin-api/policy threw away SaveAsync's false and answered 200 with the
  policy body — showing the mode that had NOT been saved.
* /readyz used CanConnectAsync, which only proves the file opens. It kept
  answering 200 through all of the above.

The same stand, six concurrent POSTs for one address (no broken storage):
4x 204 and 2x 400 {"error":"database error"} before; 6x 204 after. The unique
index on (source key, provenance) made the loser of a race the API itself
started look like a caller who sent a bad request — which is what a double-click
on "block" in the console is. The write now retries against the winner's row.

The console had its own copy of the bug: every destructive row button wrote its
green note whatever came back, so a refused delete read as "deleted ? block(s)",
and load() — which runs after every action and on a 5 s interval — replaced the
error line with "refreshed" inside a second. The note now waits for an answer
that did not carry an error, and the refresh that follows a failed action holds
it. An empty 5xx body is now reported as an empty 5xx body instead of throwing
inside apiRaw and being swallowed.

Gates on this tree (macOS): build 0 warnings / 0 errors, unit 128/128,
integration 106/106 (7 new in StorageFailureHonestyTests), smoke 19/0,
compose 43/0, image 261 MB, console 45/45 (1 new assertion).
Dents: delete answers deleted:0 -> 2 fail; POST answers 400 -> 1; readyz trusts
CanConnectAsync -> 1; no retry after the unique-index loser -> 1; delete
swallows into a bare 0 -> 2; PUT /policy discards the save answer -> 1; console
writes the note whatever came back -> the console gate fails that assertion.
2026-10-02 04:22:07 +02:00

459 lines
26 KiB
JavaScript

// The console is a page, and a page fails in ways curl cannot see: a typo in the
// inline script, a fetch that 401s, a table that renders nothing while the
// summary looks fine. This drives it in a real Chromium and fails the run when
// the page is wrong, or when the page throws.
//
// Run it through scripts/console-smoke.sh, which starts the stack and seeds the
// state the assertions look for. It needs playwright-core: point PLAYWRIGHT_CORE
// at it, or install it locally and it resolves by name.
const EDGE = process.env.EDGE_URL || 'http://127.0.0.1:8080';
const TOKEN = process.env.OPENWAF_ADMIN_TOKEN || '';
// A path without an extension makes Chromium throw "unsupported mime type",
// which reads like a page failure and is not one.
const SCREENSHOT = process.env.SCREENSHOT
? (/\.[a-z0-9]+$/i.test(process.env.SCREENSHOT) ? process.env.SCREENSHOT : process.env.SCREENSHOT + '.png')
: '';
const SEED_SOURCE = process.env.SEED_SOURCE || '';
const SEED_BLOCK = process.env.SEED_BLOCK || '';
const SEED_ERROR = process.env.SEED_ERROR || '';
// A path an anonymous visitor asked for, and a block reason somebody typed.
// Both are API values that end up in a table cell; neither is authored by the
// person reading this page.
const SEED_MARKUP_PATH = process.env.SEED_MARKUP_PATH || '';
const SEED_MARKUP_BLOCK = process.env.SEED_MARKUP_BLOCK || '';
let chromium;
try {
chromium = (process.env.PLAYWRIGHT_CORE
? require(process.env.PLAYWRIGHT_CORE)
: require('playwright-core')).chromium;
} catch (e) {
console.error('playwright-core is not resolvable. Set PLAYWRIGHT_CORE=/path/to/playwright-core,');
console.error('or install it. This gate does not skip quietly: a run that asserts nothing');
console.error('and reports success is worse than no gate at all.');
process.exit(2);
}
// A page that cannot be driven at all is the failure worth seeing, and a stack
// trace from a click timeout says nothing about what the page looked like. The
// first version of the country bars did exactly this: the class name collided
// with the toolbar's own .bar, the toolbar collapsed to 0.55em tall, and every
// assertion after the token click died. Best-effort picture on the way out — a
// screenshot failure must not mask the real error.
const failures = [];
const check = (name, ok, detail) => {
console.log(` ${ok ? 'ok ' : 'FAIL'} ${name}${detail ? ' — ' + detail : ''}`);
if (!ok) failures.push(name);
};
// WCAG relative luminance, so the assertion is a number and not an opinion.
const luminance = ([r, g, b]) => {
const f = (c) => { c /= 255; return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4); };
return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b);
};
const contrast = (a, b) => {
const [x, y] = [luminance(a), luminance(b)].sort((p, q) => q - p);
return (x + 0.05) / (y + 0.05);
};
const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number);
(async () => {
const browser = await chromium.launch({ headless: true });
const page = await browser.newPage({ viewport: { width: 1280, height: 1100 } });
const jsProblems = [];
page.on('pageerror', (e) => jsProblems.push('pageerror: ' + e.message));
page.on('console', (m) => { if (m.type() === 'error') jsProblems.push('console.error: ' + m.text()); });
await page.goto(`${EDGE}/admin`, { waitUntil: 'domcontentloaded' });
await page.fill('#token', TOKEN);
await page.click('#save');
await page.waitForFunction(
() => /refreshed/.test(document.getElementById('status').textContent),
null, { timeout: 15000 });
const summary = (await page.textContent('#summary')).replace(/\s+/g, ' ').trim();
const cells = (sel) => page.$$eval(sel, (rows) => rows.map((tr) => [...tr.children].map((td) => td.textContent)));
const streakRows = await cells('#streaks tbody tr');
const blockRows = await cells('#blocks tbody tr');
const obsRows = await page.$$eval('#obs tbody tr', (r) => r.length);
const countryRows = await page.$$eval('#countries tbody tr', (r) => r.length);
const html = await page.content();
if (SCREENSHOT) await page.screenshot({ path: SCREENSHOT, fullPage: true });
check('the page authenticates and reads the state', /mode Enforce/.test(summary), summary);
// The age of the snapshot is meaningless without the TTL it is measured
// against, and on a single edge the TTL is otherwise invisible { yet it is the
// propagation delay for a ban behind a load balancer (OPEN-12/13).
check('the summary states the snapshot age against the configured TTL',
/snapshot [\d.]+s \/ ttl 30s/.test(summary), summary);
check('a standing streak is listed as current/threshold, not as a historical maximum',
streakRows.some((r) => r[0] === SEED_SOURCE && /2 \/ 3/.test(r[1] || '')),
JSON.stringify(streakRows.map((r) => [r[0], r[1]])));
check('the operator block is listed with its reason',
blockRows.some((r) => r[0] === SEED_BLOCK && /console gate/.test(r[2] || '')),
JSON.stringify(blockRows.map((r) => [r[0], r[2]])));
check('durable observations are listed', obsRows > 0, `${obsRows} rows`);
// The observation listing is capped server-side, and until the API said how
// many rows there are, a page of 25 and the whole window rendered the same
// sentence. Measured on the shipped image: 1103 recorded sources, limit=1000,
// 1000 rows back, no total and no flag.
const obsNote = (await page.textContent('#obsnote')).replace(/\s+/g, ' ').trim();
check('the observation table states how many sources were recorded, not only the rows it shows',
/^\d+ sources? the edge has recorded$/.test(obsNote) || /^newest \d+ of \d+ recorded sources/.test(obsNote),
obsNote);
const streakNote = (await page.textContent('#streaknote')).replace(/\s+/g, ' ').trim();
const standing = streakNote.match(/(\d+) of (\d+) standing streaks listed/);
check('the streak note counts standing streaks, and its listed count matches the table',
!!standing && Number(standing[1]) === streakRows.length && Number(standing[2]) >= Number(standing[1]),
streakNote);
check('the streak note keeps the map size separate, so tracked and standing are not confused',
/\d+ sources tracked, map capped at \d+/.test(streakNote), streakNote);
check('the per-country summary is listed', countryRows > 0, `${countryRows} rows`);
// The country table is the page's answer to "where is this coming from", and a
// column of numbers does not answer that. The bar has to be a real box with a
// real width — a span styled to nothing would still pass a text assertion.
const bars = await page.$$eval('#countries tbody tr .sharebar', (els) => els.map((e) => ({
w: e.clientWidth, cell: e.parentElement.clientWidth,
})));
const countrysum = (await page.textContent('#countrysum')).replace(/\s+/g, ' ').trim();
check('the country bars are boxes with real width',
bars.length > 0 && bars.every((b) => b.w >= 2), JSON.stringify(bars));
check('the busiest country fills its cell, so a bar is a share and not decoration',
bars.length > 0 && bars.some((b) => b.cell > 0 && b.w >= b.cell * 0.9), JSON.stringify(bars));
check('the country table states what it counted',
/^\d+ countr(y|ies), \d+ sources?, \d+ refusals? total$/.test(countrysum), countrysum);
// The alerting pillar's whole point is a human reading it, and until now no
// gate read /admin-api/alerts at all — the endpoint could have returned anything
// and every assertion would have stayed green. The seed hit /boom four times
// from an address chosen for this run, so a residue alert from an older run
// cannot satisfy this.
// Which geo database the edge is enforcing on is a question the operator can
// only answer from the running process { the pin ages with the image and a named
// volume is seeded once. /admin-api/geo had no gate at all before this.
check('the summary names the geo database, its build date and its age',
/geo DBIP-Country-Lite \u00b7 built \d{4}-\d{2}-\d{2} \u00b7 \d+(\.\d+)?d/.test(summary), summary);
const warnPills = await page.$$eval('#summary .pill.warn', (els) => els.map((e) => e.textContent.trim()));
check('a database inside the 90-day alarm is not marked stale',
!warnPills.some((x) => /geo/.test(x)), JSON.stringify(warnPills));
const alertRows = await cells('#alerts tbody tr');
const errAlerts = alertRows.filter((r) => r[0] === 'server_error_streak' && r[1] === SEED_ERROR);
check('the alerts table lists the server-error streak this run wrote',
errAlerts.length >= 1 && errAlerts.some((r) => Number(r[2]) >= 3),
JSON.stringify(errAlerts.map((r) => [r[2], r[3]])));
const alertnote = (await page.textContent('#alertnote')).replace(/\s+/g, ' ').trim();
check('the page says a server error is never a reason to ban',
/will not ban/.test(alertnote), alertnote);
const warnCells = await page.$$eval('#alerts tbody tr .warn', (els) => els.map((e) => e.textContent));
check('the kind an operator has to act on is marked, not only printed',
warnCells.includes('server_error_streak'), JSON.stringify(warnCells));
check('the token never appears in the markup', !html.includes(TOKEN));
// esc() is the only thing between an anonymous request and the one browser in
// this system that holds the admin token. The path in an observation row is
// whatever a visitor asked for and the reason on a block is a form field, so
// the assertion is not "the page looks fine" — it is "nothing from the API
// became an element, and the markup is still visible as text".
if (SEED_MARKUP_PATH) {
const decoded = decodeURIComponent(SEED_MARKUP_PATH);
const title = await page.title();
check('a markup path from an anonymous visitor did not execute in the operator page',
!/XSS/.test(title), `title: ${JSON.stringify(title)}`);
const injected = await page.$$eval('#obs tbody, #blocks tbody, #streaks tbody',
(bodies) => bodies.reduce((n, b) => n + b.querySelectorAll('img,svg,script,iframe,object,embed').length, 0));
check('no element was created out of a value that came from the API',
injected === 0, `${injected} injected elements`);
const obsCells = await page.$$eval('#obs tbody tr', (rows) =>
rows.map((tr) => [...tr.children].map((td) => td.textContent)));
check('the markup path is printed as the text it is',
obsCells.some((r) => (r[4] || '').includes(decoded)),
JSON.stringify(obsCells.filter((r) => (r[4] || '').includes('xss-probe')).map((r) => r[4])));
}
if (SEED_MARKUP_BLOCK) {
check('a markup block reason is printed as text too',
blockRows.some((r) => r[0] === SEED_MARKUP_BLOCK && /<svg onload=/.test(r[2] || '')),
JSON.stringify(blockRows.map((r) => [r[0], r[2]])));
}
check('the page threw no javascript', jsProblems.length === 0, jsProblems.join(' | '));
// The read side of the page is one thing; the write side is the part that can
// lock a real customer out. These drive the two forms an incident actually
// uses and then check the consequence on the wire, not just in the table: a
// ban drawn on the page has to make the edge answer 403 for that address, and
// the delete beside it has to stop it. The stack runs with trusted proxy
// headers, so X-Forwarded-For is how the gate becomes a different client.
const WRITE_IP = process.env.WRITE_IP || '203.0.113.99';
const WRITE_CIDR = process.env.WRITE_CIDR || '198.51.100.0/24';
// redirect:'manual' is not a detail. An operator block answers 301 to the
// policy's default redirect target (OperatorBlockStatus=301,
// DefaultRedirectTargets=[iana example]), and a fetch that follows redirects
// walks out to the public internet and comes back 200 — which is exactly how
// this check first read "the ban is not enforced" while the edge was refusing
// the client with a 301 the whole time.
const probe = async (ip) => {
const r = await fetch(`${EDGE}/probe`, { headers: { 'X-Forwarded-For': ip }, redirect: 'manual' });
await r.body.cancel();
return { status: r.status, location: r.headers.get('location') };
};
const open = await probe(WRITE_IP);
check('before the block, that address reaches the upstream',
open.status === 404, `probe from ${WRITE_IP} answered ${open.status}`);
await page.fill('#blockIp', WRITE_IP);
await page.fill('#blockReason', 'console gate: written from the page');
await page.click('#addBlock');
await page.waitForFunction(
(ip) => [...document.querySelectorAll('#blocks tbody tr')].some((tr) =>
tr.children[0].textContent === ip && /written from the page/.test(tr.children[2].textContent)),
WRITE_IP, { timeout: 15000 }).catch(() => {});
const afterBlock = await cells('#blocks tbody tr');
check('the page can write a ban, and lists it with its reason',
afterBlock.some((r) => r[0] === WRITE_IP && /written from the page/.test(r[2] || '')),
JSON.stringify(afterBlock.map((r) => [r[0], r[2]])));
let wire = await probe(WRITE_IP);
for (let i = 0; i < 10 && wire.status === 404; i++) { await new Promise((r) => setTimeout(r, 1000)); wire = await probe(WRITE_IP); }
check('the ban drawn on the page is enforced on the wire, not just in the table',
wire.status === 301 || wire.status === 403,
`probe from ${WRITE_IP} answered ${wire.status}${wire.location ? ' → ' + wire.location : ''}`);
await page.click(`#blocks tbody button[data-act="delblock"][data-k="${WRITE_IP}"]`);
await page.waitForFunction(
(ip) => ![...document.querySelectorAll('#blocks tbody tr')].some((tr) => tr.children[0].textContent === ip),
WRITE_IP, { timeout: 15000 }).catch(() => {});
const afterDelete = await cells('#blocks tbody tr');
let wire2 = await probe(WRITE_IP);
for (let i = 0; i < 10 && wire2.status !== 404; i++) { await new Promise((r) => setTimeout(r, 1000)); wire2 = await probe(WRITE_IP); }
check('the per-row delete removes that one ban from the table',
!afterDelete.some((r) => r[0] === WRITE_IP), JSON.stringify(afterDelete.map((r) => r[0])));
check('and the address reaches the upstream again once that row is gone',
wire2.status === 404, `probe from ${WRITE_IP} answered ${wire2.status}`);
await page.fill('#allowMatch', WRITE_CIDR);
await page.fill('#allowNote', 'console gate: allow entry');
await page.fill('#allowTtl', '60');
await page.click('#addAllow');
await page.waitForFunction(
(cidr) => [...document.querySelectorAll('#allow tbody tr')].some((tr) => tr.children[0].textContent === cidr),
WRITE_CIDR, { timeout: 15000 }).catch(() => {});
const allowRows = await cells('#allow tbody tr');
check('the page can write an allow entry and lists it with an expiry',
allowRows.some((r) => r[0] === WRITE_CIDR && /console gate/.test(r[1] || '') && /\d{4}-\d{2}-\d{2}/.test(r[2] || '')),
JSON.stringify(allowRows.map((r) => [r[0], r[2]])));
await page.click(`#allow tbody button[data-act="delallow"]`);
await page.waitForFunction(
(cidr) => ![...document.querySelectorAll('#allow tbody tr')].some((tr) => tr.children[0].textContent === cidr),
WRITE_CIDR, { timeout: 15000 }).catch(() => {});
check('the allow entry can be removed from the page too',
(await page.$$eval('#allow tbody tr', (r) => r.map((tr) => tr.children[0].textContent))).indexOf(WRITE_CIDR) === -1,
JSON.stringify(await page.$$eval('#allow tbody tr', (r) => r.map((tr) => tr.children[0].textContent))));
// The other quiet failure on this form: a TTL of 0. It used to fall through to
// null, and null is how the API says "never expires" — so a field left at zero
// bought the one exemption that outranks every ban. The API refuses it now, and
// the page refuses it before the round trip; empty is still "never", on purpose.
await page.fill('#allowMatch', WRITE_CIDR);
await page.fill('#allowNote', 'console gate: zero ttl');
await page.fill('#allowTtl', '0');
await page.click('#addAllow');
await page.waitForFunction(
() => /TTL in minutes/.test(document.getElementById('status').textContent),
null, { timeout: 5000 }).catch(() => {});
const ttlStatus = (await page.textContent('#status')).trim();
const rowsAfterZero = await page.$$eval('#allow tbody tr', (r) => r.map((tr) => tr.children[0].textContent));
check('a TTL of 0 is refused by the page instead of becoming a permanent exemption',
/TTL in minutes/.test(ttlStatus) && !rowsAfterZero.includes(WRITE_CIDR),
`${JSON.stringify(ttlStatus)} rows=${JSON.stringify(rowsAfterZero)}`);
await page.fill('#allowTtl', '');
await page.click('#addAllow');
await page.waitForFunction(
(cidr) => [...document.querySelectorAll('#allow tbody tr')].some((tr) => tr.children[0].textContent === cidr),
WRITE_CIDR, { timeout: 15000 }).catch(() => {});
const neverRows = await cells('#allow tbody tr');
check('leaving the TTL empty is still the way to ask for never',
neverRows.some((r) => r[0] === WRITE_CIDR && /never/.test(r[2] || '')),
JSON.stringify(neverRows.map((r) => [r[0], r[2]])));
await page.click('#allow tbody button[data-act="delallow"]');
await page.waitForFunction(
(cidr) => ![...document.querySelectorAll('#allow tbody tr')].some((tr) => tr.children[0].textContent === cidr),
WRITE_CIDR, { timeout: 15000 }).catch(() => {});
// The failure mode worth asserting on a write form is the quiet one: the
// operator believes they blocked an address and did not. A typo in the field
// must come back as the API's own error, not as a status line that says
// nothing and a table that gains no row.
await page.fill('#blockIp', 'not-an-ip');
await page.click('#addBlock');
await page.waitForFunction(
() => /not an IP address/.test(document.getElementById('status').textContent),
null, { timeout: 10000 }).catch(() => {});
const errStatus = (await page.textContent('#status')).replace(/\s+/g, ' ').trim();
const rowsAfterBad = await cells('#blocks tbody tr');
check('a bad address in the block form surfaces the API error instead of looking like success',
/not an IP address/.test(errStatus), errStatus);
check('and no phantom row appears for the address that was rejected',
!rowsAfterBad.some((r) => r[0] === 'not-an-ip'), JSON.stringify(rowsAfterBad.map((r) => r[0])));
// The country rule toggle is the one control here that changes policy for
// everyone, so the gate turns it and turns it back, and then removes it: PUT
// allowed=true leaves a row behind, and only DELETE takes the rule out.
const ruleOf = async (code) => page.$$eval('#countries tbody tr',
(rows, c) => { const r = rows.find((tr) => tr.children[0].textContent === c); return r ? r.children[4].textContent : 'no row'; }, code);
const waitRule = (code, want) => page.waitForFunction((a) => {
const rows = document.querySelectorAll('#countries tbody tr');
for (const tr of rows) {
if (tr.children[0].textContent === a.c) return tr.children[4].textContent === a.w;
}
return a.w === '—';
}, { c: code, w: want }, { timeout: 15000 }).catch(() => {});
const REMOVE_SEL = '#countries tbody button[data-act="countrydel"][data-k="US"]';
const hasRemove = () => page.$(REMOVE_SEL).then((h) => h !== null);
// Start from no rule at all. The gate used to depend on whatever a previous
// run left in the data volume: with a US rule already present the first click
// denied the country, and with a fresh volume it allowed it, so the old
// assertion only ever passed on residue.
if (await hasRemove()) {
await page.click(REMOVE_SEL);
await waitRule('US', '—');
}
const before = await ruleOf('US');
await page.click('#countries tbody button[data-act="country"][data-k="US"]');
await waitRule('US', 'allowed');
const first = await ruleOf('US');
await page.click('#countries tbody button[data-act="country"][data-k="US"]');
await waitRule('US', 'denied');
const second = await ruleOf('US');
check('a country rule can be written from the page and toggled both ways',
before === '—' && first === 'allowed' && second === 'denied',
`before ${before} → ${first} → ${second}`);
// Setting a rule back to "allowed" is not the same as having no rule: the row
// stays in the table and claims a policy that does nothing. The page has to be
// able to take it out.
check('a rule row offers removal only when a rule actually exists', await hasRemove(), REMOVE_SEL);
await page.click(REMOVE_SEL);
await waitRule('US', '—');
const afterRemove = await ruleOf('US');
check('a country rule can be removed from the page, not only flipped to allowed',
afterRemove === '—' && !(await hasRemove()),
`rule cell after remove: ${afterRemove}, remove button gone: ${!(await hasRemove())}`);
// Every destructive row button shares this one handler, and until now the
// handler wrote its green note whatever came back: a 400 whose body said
// "refusing to delete every block" still produced "deleted ? block(s)" in the
// success colour. The button is synthetic because the page only ever renders a
// remove button for a row that exists; the handler is delegated on the
// document, so this is the same code a real click runs. An empty key is the
// refused call — DELETE /admin-api/blocks?key= is the one destructive row
// request the API answers with a 400 and a reason. (A 404 would not do: the
// page reads every 404 as "the admin API is switched off", which is its own
// story and is recorded separately.)
await page.evaluate(() => {
const b = document.createElement('button');
b.id = 'c26-refused-remove';
b.dataset.act = 'delblock';
b.dataset.k = '';
document.body.appendChild(b);
});
await page.click('#c26-refused-remove');
await page.waitForFunction(
() => /refusing to delete every block/.test(document.getElementById('status').textContent),
null, { timeout: 10000 }).catch(() => {});
const refusedStatus = (await page.textContent('#status')).replace(/\s+/g, ' ').trim();
const refusedClass = await page.getAttribute('#status', 'class');
await page.evaluate(() => { const b = document.getElementById('c26-refused-remove'); if (b) b.remove(); });
check('a row action does not write a success note over an answer that said it failed',
/refusing to delete every block/.test(refusedStatus) && refusedClass === 'warn',
`${refusedClass}: ${refusedStatus}`);
// A phone in dark mode is the case an operator actually reaches the console
// from — the address that got them blocked is the one they are typing about.
// Both halves of this used to be broken and measured: the page overflowed a
// 375 px viewport to 520 px of sideways scroll, and the status line sat on the
// dark canvas at 2.82:1.
{
const phone = await browser.newPage({ viewport: { width: 375, height: 720 }, colorScheme: 'dark' });
const phoneProblems = [];
phone.on('pageerror', (e) => phoneProblems.push('pageerror: ' + e.message));
phone.on('console', (m) => { if (m.type() === 'error') phoneProblems.push('console.error: ' + m.text()); });
await phone.goto(`${EDGE}/admin`, { waitUntil: 'domcontentloaded' });
await phone.fill('#token', TOKEN);
await phone.click('#save');
await phone.waitForFunction(
() => /refreshed/.test(document.getElementById('status').textContent),
null, { timeout: 15000 });
const m = await phone.evaluate(() => {
const probe = document.createElement('div');
probe.style.cssText = 'position:absolute;left:-9999px;background:Canvas;color:CanvasText';
document.body.appendChild(probe);
const cs = getComputedStyle(probe);
const canvas = cs.backgroundColor;
const statusColor = getComputedStyle(document.getElementById('status')).color;
probe.remove();
const streakRow = [...document.querySelectorAll('#streaks tbody tr')]
.map((tr) => [...tr.children].map((td) => td.textContent));
return {
canvas, statusColor,
scrollWidth: document.documentElement.scrollWidth,
innerWidth: window.innerWidth,
html: document.documentElement.outerHTML,
streakRow,
barWidths: [...document.querySelectorAll('#countries tbody tr .sharebar')].map((e) => e.clientWidth),
};
});
const ratio = contrast(rgb(m.statusColor), rgb(m.canvas));
check('the page fits a 375 px phone without sideways document scroll',
m.scrollWidth <= m.innerWidth, `scrollWidth ${m.scrollWidth} vs viewport ${m.innerWidth}`);
check('the status line is readable on the dark canvas (WCAG AA 4.5:1)',
ratio >= 4.5, `contrast ${ratio.toFixed(2)}:1, status ${m.statusColor} on ${m.canvas}`);
check('the standing streak is still listed at phone width',
m.streakRow.some((r) => r[0] === SEED_SOURCE && /2 \/ 3/.test(r[1] || '')),
JSON.stringify(m.streakRow.map((r) => [r[0], r[1]])));
check('the token is not in the markup at phone width either', !m.html.includes(TOKEN));
const phoneAlertRows = await page.$$eval('#alerts tbody tr', (r) => r.length);
check('the alerts table is still there at phone width', phoneAlertRows > 0, `${phoneAlertRows} rows`);
check('the country bars survive the phone layout',
m.barWidths.length > 0 && m.barWidths.every((w) => w >= 2), JSON.stringify(m.barWidths));
check('the page threw no javascript at phone width', phoneProblems.length === 0, phoneProblems.join(' | '));
if (SCREENSHOT) await phone.screenshot({ path: SCREENSHOT.replace(/(\.[a-z0-9]+)$/i, '.phone$1'), fullPage: true });
await phone.close();
}
if (failures.length) {
// The two ways this gate goes red are different and both need a picture:
// "the page could not be driven" (the catch below) and "the page was driven
// and is wrong" (here). The first version only covered the first.
if (SCREENSHOT) {
try {
await page.screenshot({ path: SCREENSHOT.replace(/(\.[a-z0-9]+)$/i, '.failure$1'), fullPage: true });
} catch (e) { console.error(' (no failure screenshot: ' + e.message + ')'); }
}
console.error(`console check: ${failures.length} assertion(s) failed`);
await browser.close();
process.exit(1);
}
await browser.close();
console.log('console check: all assertions passed');
})().catch(async (e) => {
console.error('console check failed to run:', e.message);
if (SCREENSHOT) {
try {
const b = await chromium.launch({ headless: true });
const p2 = await b.newPage({ viewport: { width: 1280, height: 1100 } });
await p2.goto(`${EDGE}/admin`, { waitUntil: 'domcontentloaded' });
await p2.screenshot({ path: SCREENSHOT.replace(/(\.[a-z0-9]+)$/i, '.failure$1'), fullPage: true });
await b.close();
} catch (e2) { console.error(' (no failure screenshot: ' + e2.message + ')'); }
}
process.exit(1);
});