test: end-to-end suites (install.sh, licensing, browser, Android emulator) + runner

tests/e2e (see its README):
- install.mjs: real install.sh in a Debian container - VPN-safe HOST_IP
  detection on simulated hosts, fresh/upgrade/re-run, and the proxy config
  byte-identical to nginx-proxy/nginx.conf (guards rule CS-5)
- license_e2e.py: real cloud + site processes with a throwaway signing key -
  400 days offline, tampered file, clock rollback, expiry deferred to workday
  close, renewal, remote lock
- browser.mjs: web delivery modes (same-origin, plain HTTP by LAN IP, venue
  mode) and the install dialog on Android/iPhone/desktop/no-APK
- android.mjs basics|rediscovery|stacks: pairing, venues, camera, back
  button, restart; IP change / server down / cold start; TLS pinning
  (wrong-key QR, impostor, upgrade, renewal, rediscovery) and UI bundles
  (apply, staged, tampered, APK too old, rollback, two venues) on isolated
  compose stacks built from the repo
- lib/: env (paths, LAN IP autodetect, settings), proc (seeded throwaway
  DBs via demo_seed.py, backends, nginx, Vite, compose stacks), android
  (adb + WebView DevTools, boots the AVD), cdp
- run-all.mjs runs everything fastest-first with a summary
Nothing machine-specific is hard-coded; developer stacks/DBs are never touched.
Results on this machine: install 9/9, license 17/17, browser 22/22,
android basics 19/19, rediscovery 10/10, stacks 21/21.

Pack README: Testing section + rule CS-11 (tests follow the code; run
run-all before a release).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-28 23:38:18 +03:00
co-authored by Claude Opus 5.5
parent f00c99fd36
commit 584dd1e510
14 changed files with 1326 additions and 1 deletions
+359
View File
@@ -0,0 +1,359 @@
// Android suite: the real native app on an emulator — real taps/typing via adb,
// state via the debug build's WebView DevTools.
//
// node android.mjs [basics|rediscovery|stacks|all] (default: all)
//
// basics pairing, login + live WS, back button, restart, venues, camera (local backends :8055/:8056)
// rediscovery IP change logged in / logged out, server down, cold start (local backend :8055)
// stacks TLS pinning (plan step 7) + UI bundles (step 8) on isolated
// docker-compose stacks built from this repo (:18080/:18443, :28080/:28443)
//
// Builds the debug APK first (SKIP_APK_BUILD=1 to reuse the last one) and boots
// the emulator if none is attached (AVD=<name>, default Xenia_Test_Phone).
import { execFileSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import { mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs'
import path from 'node:path'
import { zipSync, strToU8 } from 'fflate'
import {
APP_ID, GREEN, UPD, adb, attach, back, clearData, connectivityColor, ensureDevice, focusedWindow, goTo, home,
installApp, launch, relaunch, reloadApp, setVenues, shot, tap, tapDialogButton, typeInto, venuesState,
} from './lib/android.mjs'
import { EMULATOR_HOST as H, OUT, PYTHON, BACKEND, WAITER, reporter, sleep, waitFor } from './lib/env.mjs'
import { composeStack, login, startBackend } from './lib/proc.mjs'
const which = process.argv[2] || 'all'
let failures = 0
// ── setup ────────────────────────────────────────────────────────────────────
if (!process.env.SKIP_APK_BUILD) {
console.log(' building the debug APK…')
execFileSync('npm', ['run', 'apk:debug'], { cwd: WAITER, stdio: 'ignore', shell: process.platform === 'win32' })
}
await ensureDevice()
installApp()
const venue = (siteId, baseUrl, extra = {}) => ({ siteId, name: siteId, baseUrl, ...extra })
async function freshApp() {
clearData()
launch()
await sleep(2000)
const v = await attach()
// first launch after install/boot can take a while — wait for the pairing screen
if (!(await waitFor(() => v.evaluate("!!document.querySelector('input')"), 30_000, 500))) throw new Error('pairing screen did not appear')
return v
}
// ════════════════════════════════════════════════════════════════════════════
async function basics() {
const r = reporter('android: pairing, venues, camera')
const b1 = await startBackend({ port: 8055, siteId: 'test-site-1' })
const b2 = await startBackend({ port: 8056, siteId: 'test-site-2' })
try {
const token = await login(b1.url)
let v = await freshApp()
await typeInto(v, `${H}:9999`)
await tap(v, 'button', 'Σύνδεση')
await sleep(6500)
r.check('wrong address → "no server" error', (await v.evaluate('document.body.innerText')).includes('Δεν βρέθηκε server'))
await typeInto(v, `http://${H}:8055/?pair=some-other-site`)
await tap(v, 'button', 'Σύνδεση')
await sleep(3000)
r.check("another venue's QR → refused", (await v.evaluate('document.body.innerText')).includes('διαφορετικό κατάστημα'))
await typeInto(v, `${H}:8055`)
await tap(v, 'button', 'Σύνδεση')
await sleep(5000)
v = await attach()
const st = await venuesState(v)
r.check('pairing saves and activates the venue', st?.active === 'test-site-1' && st.venues['test-site-1'].baseUrl.includes(`${H}:`), JSON.stringify(st))
r.check('login screen shows the venue + "Αλλαγή"', (await v.evaluate('document.body.innerText')).includes('Αλλαγή'))
await v.evaluate(`localStorage.setItem('xenia:test-site-1:token', ${JSON.stringify(token)})`)
v = await reloadApp(v, '/tables')
await sleep(7000)
r.check('logged in: /tables', (await v.evaluate('location.pathname')) === '/tables')
const dbs = await v.evaluate('indexedDB.databases().then(d => d.map(x => x.name))')
r.check('IndexedDB namespaced per venue', dbs.includes('pos_snapshot__test-site-1'), dbs.join(','))
r.check('live WebSocket (green bar)', (await connectivityColor(v)) === GREEN)
back()
await sleep(1500)
r.check('hardware back on /tables keeps the app open', focusedWindow().includes(APP_ID))
v = await relaunch()
await sleep(5000)
r.check('restart: still paired and logged in', (await v.evaluate('location.pathname')) === '/tables')
// venues
await tap(v, 'button[title="Μενού χρήστη"]')
await sleep(600)
await tap(v, 'button.user-menu-item', 'Κατάστημα')
await sleep(1200)
r.check('user menu → /venues', (await v.evaluate('location.pathname')) === '/venues')
back()
await sleep(1200)
r.check('back from /venues → /tables', (await v.evaluate('location.pathname')) === '/tables')
await goTo(v, '/venues')
await sleep(1000)
await typeInto(v, `${H}:8056`)
await tap(v, 'button', 'Σύνδεση')
await sleep(5000)
v = await attach()
let vs = await venuesState(v)
r.check('second venue paired and active', vs.active === 'test-site-2' && Object.keys(vs.venues).length === 2)
r.check('second venue starts logged out (own session)', (await v.evaluate('location.pathname')) === '/login')
await tap(v, 'button', 'Αλλαγή')
await sleep(1200)
await tap(v, 'button', `${H}:8055`)
await sleep(5000)
v = await attach()
await sleep(3000)
vs = await venuesState(v)
r.check('switching back keeps venue 1 logged in', vs.active === 'test-site-1' && (await v.evaluate('location.pathname')) === '/tables')
// camera permission
const resetCamera = () => {
try { adb('shell', 'pm', 'revoke', APP_ID, 'android.permission.CAMERA') } catch {}
adb('shell', 'pm', 'clear-permission-flags', APP_ID, 'android.permission.CAMERA', 'user-set', 'user-fixed')
}
for (const [label, button] of [['deny', 'Don’t allow'], ['allow', 'While using the app']]) {
resetCamera()
v = await relaunch()
await goTo(v, '/venues')
await sleep(1000)
await tap(v, 'button', 'Σάρωση QR')
await sleep(2500)
r.check(`camera ${label}: permission prompt shown`, /GrantPermissions/.test(focusedWindow()))
tapDialogButton(button)
await sleep(label === 'deny' ? 2000 : 4000)
if (label === 'deny') {
r.check('camera deny: asked only once', !/GrantPermissions/.test(focusedWindow()))
r.check('camera deny: explains the missing permission', (await v.evaluate('document.body.innerText')).includes('Δεν δόθηκε άδεια κάμερας'))
} else {
const video = await v.evaluate("(() => { const x = document.querySelector('video'); return { ready: x.readyState, w: x.videoWidth, paused: x.paused } })()")
r.check('camera allow: live preview', video.ready >= 2 && video.w > 0 && !video.paused, JSON.stringify(video))
shot('android-camera')
}
}
v.close()
} finally {
await b1.stop(); await b2.stop()
}
return r.done()
}
// ════════════════════════════════════════════════════════════════════════════
async function rediscovery() {
const r = reporter('android: rediscovery + cold start')
let backend = await startBackend({ port: 8055, siteId: 'test-site-1' })
try {
const token = await login(backend.url)
let v = await freshApp()
await setVenues(v, { active: 'test-site-1', venues: { 'test-site-1': venue('test-site-1', `http://${H}:8055`) } })
await v.evaluate(`localStorage.setItem('xenia:test-site-1:token', ${JSON.stringify(token)})`)
v = await reloadApp(v)
r.check('setup: paired and logged in', !!(await waitFor(async () => (await v.evaluate('location.pathname')) === '/tables', 30_000)))
const stale = async (vv) => {
await setVenues(vv, { active: 'test-site-1', venues: { 'test-site-1': venue('test-site-1', `http://${H.replace(/\d+$/, '99')}:8055`) } })
return reloadApp(vv)
}
const found = async () => waitFor(async () => {
try { return (await venuesState(v))?.venues['test-site-1']?.baseUrl === `http://${H}:8055` } catch { v = await attach(); return false }
}, 45_000, 500)
v = await stale(v)
r.check('logged in: server "moved" → found and saved', !!(await found()))
await sleep(4000); v = await attach(); await sleep(4000)
r.check('logged in: back on /tables, live', (await v.evaluate('location.pathname')) === '/tables' && (await connectivityColor(v)) === GREEN)
await v.evaluate("localStorage.removeItem('xenia:test-site-1:token')")
v = await stale(v)
r.check('logged out: found and saved', !!(await found()))
await sleep(4000); v = await attach(); await sleep(3000)
r.check('logged out: waiter list loads from the new address', (await v.evaluate('document.body.innerText')).includes('Manager'))
await backend.stop()
v = await stale(v)
await sleep(15000)
r.check('server really down: saved address untouched', (await venuesState(v)).venues['test-site-1'].baseUrl.includes('.99:'))
r.check('server really down: offline screen', (await v.evaluate('location.pathname')) === '/offline')
await v.evaluate("[...document.querySelectorAll('button')].find(e => e.textContent.includes('Αναζήτηση server')).click()")
const notFound = await waitFor(async () => (await v.evaluate('document.body.innerText')).includes('Ο server δεν βρέθηκε'), 60_000)
r.check('manual search ends with "not found" guidance', !!notFound)
// cold start while the server is down keeps the login
backend = await startBackend({ port: 8055, siteId: 'test-site-1', dataDir: backend.dataDir })
const token2 = await login(backend.url)
await setVenues(v, { active: 'test-site-1', venues: { 'test-site-1': venue('test-site-1', `http://${H}:8055`) } })
await v.evaluate(`localStorage.setItem('xenia:test-site-1:token', ${JSON.stringify(token2)})`)
await sleep(1500)
await backend.stop()
v = await relaunch()
await sleep(12000)
r.check('cold start with the server down: still logged in', await v.evaluate("!!localStorage.getItem('xenia:test-site-1:token')"))
backend = await startBackend({ port: 8055, siteId: 'test-site-1', dataDir: backend.dataDir })
const recovered = await waitFor(async () => (await v.evaluate('location.pathname')) === '/tables', 30_000)
r.check('server back → app lands on /tables by itself', !!recovered)
v.close()
} finally {
await backend.stop()
}
return r.done()
}
// ════════════════════════════════════════════════════════════════════════════
async function stacks() {
const r = reporter('android: TLS pinning + UI bundles (compose stacks)')
const s1 = composeStack({ project: 'xenia-e2e-v1', version: 'e2e1', siteId: 'test-site-1', http: 18080, https: 18443, manager: 18081 })
const s2 = composeStack({ project: 'xenia-e2e-v2', version: 'e2e9', siteId: 'test-site-2', http: 28080, https: 28443, manager: 28081 })
const impostorDir = path.join(OUT, 'impostor')
const WAITER1 = 'xenia-e2e-v1-waiter_pwa-1', DL = '/usr/share/nginx/html/downloads'
try {
await s1.up(); await s2.up()
// Impostor: same backend behind a TLS proxy with a DIFFERENT key (:18444)
mkdirSync(impostorDir, { recursive: true })
execFileSync(PYTHON, ['-c', `from pathlib import Path; from services.tls_identity import ensure_tls_identity; ensure_tls_identity(Path(r'${impostorDir}'))`], { cwd: BACKEND })
writeFileSync(path.join(impostorDir, 'nginx.conf'), `map $http_upgrade $connection_upgrade { default upgrade; '' close; }
server { listen 443 ssl; ssl_certificate /t/cert.pem; ssl_certificate_key /t/key.pem;
location / { proxy_pass http://host.docker.internal:18080; proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; } }`)
try { execFileSync('docker', ['rm', '-f', 'xenia-e2e-impostor'], { stdio: 'ignore' }) } catch {}
execFileSync('docker', ['run', '-d', '--rm', '--name', 'xenia-e2e-impostor', '--add-host', 'host.docker.internal:host-gateway', '-p', '18444:443',
'-v', `${impostorDir}:/t:ro`, '-v', `${path.join(impostorDir, 'nginx.conf')}:/etc/nginx/conf.d/default.conf:ro`, 'nginx:alpine'],
{ stdio: 'ignore', env: { ...process.env, MSYS_NO_PATHCONV: '1' } })
const identity = await fetch('http://127.0.0.1:18080/api/system/identity').then(x => x.json())
const pin = identity.tls.spki_sha256
const token = await login('http://127.0.0.1:18080')
const qr = key => `http://${H}:18080/?${new URLSearchParams({ pair: 'test-site-1', k: key })}`
// ── TLS ───────────────────────────────────────────────────────────────────
let v = await freshApp()
await typeInto(v, qr('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA='))
await tap(v, 'button', 'Σύνδεση')
await sleep(4000)
r.check('TLS: QR with a wrong key → refused', (await v.evaluate('document.body.innerText')).includes('κλειδί ασφαλείας'))
await typeInto(v, qr(pin))
await tap(v, 'button', 'Σύνδεση')
await sleep(6000)
v = await attach()
let ven = (await venuesState(v)).venues['test-site-1']
r.check('TLS: paired on the encrypted endpoint with the pin', ven.baseUrl === `https://${H}:18443` && ven.spki === pin, JSON.stringify(ven))
await v.evaluate(`localStorage.setItem('xenia:test-site-1:token', ${JSON.stringify(token)})`)
await sleep(1500)
v = await relaunch()
await waitFor(async () => (await v.evaluate('location.pathname')) === '/tables', 30_000)
r.check('TLS: /tables + live wss', (await connectivityColor(v)) === GREEN)
adb('logcat', '-c')
const impostor = await v.evaluate(`fetch('https://${H}:18444/api/system/identity').then(r => 'OK ' + r.status, () => 'FAILED')`)
const genuine = await v.evaluate(`fetch('https://${H}:18443/api/system/identity').then(r => 'OK ' + r.status, () => 'FAILED')`)
r.check('TLS: impostor with another key refused natively', impostor === 'FAILED' && adb('logcat', '-d', '-s', 'XeniaTLS').includes(':18444'))
r.check('TLS: genuine server still fine', genuine === 'OK 200')
await setVenues(v, { active: 'test-site-1', venues: { 'test-site-1': venue('test-site-1', `http://${H}:18080`) } })
v = await relaunch()
const upgraded = await waitFor(async () => { try { return (await venuesState(v)).venues['test-site-1'].baseUrl.startsWith('https://') } catch { v = await attach() } }, 20_000)
r.check('TLS: plain-HTTP venue upgraded to TLS on start', !!upgraded)
const certFile = path.join(s1.dir, 'data', 'tls', 'cert.pem')
const oldCert = readFileSync(certFile, 'utf8')
unlinkSync(certFile)
s1.compose('restart', 'backend'); await sleep(12000); s1.compose('restart', 'proxy'); await sleep(4000)
v = await relaunch()
await sleep(8000)
r.check('TLS: server renewed its cert (same key) → app keeps working', readFileSync(certFile, 'utf8') !== oldCert && (await connectivityColor(v)) === GREEN)
await setVenues(v, { active: 'test-site-1', venues: { 'test-site-1': venue('test-site-1', `https://${H.replace(/\d+$/, '99')}:18443`, { spki: pin }) } })
v = await relaunch()
const rediscovered = await waitFor(async () => { try { return (await venuesState(v)).venues['test-site-1'].baseUrl === `https://${H}:18443` } catch { v = await attach() } }, 60_000, 2000)
r.check('TLS: rediscovery over the pinned link', !!rediscovered)
// ── UI bundles ────────────────────────────────────────────────────────────
const manifest = JSON.parse(execFileSync('docker', ['exec', WAITER1, 'cat', `${DL}/waiter-bundle.json`], { encoding: 'utf8' }))
const serve = m => execFileSync('docker', ['exec', '-i', WAITER1, 'sh', '-c', `cat > ${DL}/waiter-bundle.json`], { input: JSON.stringify(m) })
const current = async () => { for (let i = 0; i < 3; i++) { try { return await v.evaluate(`${UPD}.current().then(r => r.bundle.version)`) } catch { await sleep(1000); v = await attach() } } }
const bgAndBack = async () => { home(); await sleep(2500); launch(); await sleep(1500) }
v = await freshApp()
await setVenues(v, { active: 'test-site-1', venues: { 'test-site-1': venue('test-site-1', `https://${H}:18443`, { spki: pin }) } })
await v.evaluate("sessionStorage.setItem('xenia.applyBundleNow', '1')")
await v.evaluate("location.replace('/')")
v.close()
const applied = await waitFor(async () => { v = await attach(); return (await current()) === manifest.version }, 60_000, 2000)
r.check('bundles: fresh pairing → venue bundle applied', !!applied)
await sleep(20000)
r.check('bundles: healthy (no rollback after 20s)', (await current()) === manifest.version)
await v.evaluate(`localStorage.setItem('xenia:test-site-1:token', ${JSON.stringify(token)})`)
await sleep(1200)
serve({ ...manifest, version: 'e2e-staged' })
await bgAndBack()
await sleep(12000)
v = await attach()
r.check('bundles: logged in → staged, not applied mid-service', (await current()) === manifest.version)
home(); await sleep(4000); launch()
const staged = await waitFor(async () => { v = await attach(); return (await current()) === 'e2e-staged' }, 30_000, 2000)
r.check('bundles: applied after background/return, session kept', !!staged && await v.evaluate("!!localStorage.getItem('xenia:test-site-1:token')"))
serve({ ...manifest, version: 'e2e-tampered', sha256: 'f'.repeat(64) })
await bgAndBack(); await sleep(15000); v = await attach()
r.check('bundles: tampered zip refused', (await current()) === 'e2e-staged')
serve({ ...manifest, version: 'e2e-new-apk', min_shell_build: 99 })
await bgAndBack(); await sleep(8000); v = await attach()
r.check('bundles: needs a newer APK → skipped + banner', (await current()) === 'e2e-staged' && (await v.evaluate('document.body.innerText')).includes('νεότερη έκδοση της εφαρμογής'))
const broken = zipSync({ 'index.html': strToU8('<!doctype html><html><body><h1>broken bundle</h1></body></html>') })
execFileSync('docker', ['exec', '-i', WAITER1, 'sh', '-c', `cat > ${DL}/waiter-bundle-broken.zip`], { input: Buffer.from(broken) })
serve({ ...manifest, version: 'e2e-broken', file: 'waiter-bundle-broken.zip', sha256: createHash('sha256').update(broken).digest('hex') })
await v.evaluate("localStorage.removeItem('xenia:test-site-1:token')")
await sleep(1200)
await bgAndBack()
await waitFor(async () => { v = await attach(); return (await v.evaluate('document.body.innerText')).includes('broken bundle') }, 40_000, 1500)
const rolledBack = await waitFor(async () => { v = await attach(); return (await current()) === 'e2e-staged' }, 60_000, 2000)
r.check('bundles: broken bundle rolled back automatically', !!rolledBack)
await sleep(70000); await bgAndBack(); await sleep(12000); v = await attach()
r.check('bundles: no retry loop, broken version blocklisted', (await current()) === 'e2e-staged' && (await v.evaluate("localStorage.getItem('xenia.bundleFailed') || ''")).includes('e2e-broken'))
serve(manifest)
// ── two venues, each on its own bundle ─────────────────────────────────────
const m2 = await fetch('http://127.0.0.1:28080/downloads/waiter-bundle.json').then(x => x.json())
const pin2 = (await fetch('http://127.0.0.1:28080/api/system/identity').then(x => x.json())).tls.spki_sha256
const state = async () => { const vv = await attach(); const s = { active: (await venuesState(vv)).active, current: await vv.evaluate(`${UPD}.current().then(r => r.bundle.version)`), bundles: await vv.evaluate(`${UPD}.list().then(r => r.bundles.map(b => b.version).sort().join(','))`) }; vv.close(); return s }
v = await attach()
await goTo(v, '/venues'); await sleep(1200)
await typeInto(v, `http://${H}:28080/?${new URLSearchParams({ pair: 'test-site-2', k: pin2 })}`)
await tap(v, 'button', 'Σύνδεση')
v.close()
let s = await waitFor(async () => { const st = await state(); return st.active === 'test-site-2' && st.current === m2.version && st }, 90_000, 2000)
r.check('bundles: pairing venue 2 → venue 2 bundle', !!s)
const switchTo = async (label, site, want) => {
const vv = await attach(); await goTo(vv, '/venues'); await sleep(1200); await tap(vv, 'button', label); vv.close()
return waitFor(async () => { const st = await state(); return st.active === site && st.current === want && st }, 90_000, 2000)
}
await switchTo(`${H}:18443`, 'test-site-1', manifest.version)
for (const [label, site, want] of [[`${H}:28443`, 'test-site-2', m2.version], [`${H}:18443`, 'test-site-1', manifest.version]]) {
adb('logcat', '-c')
s = await switchTo(label, site, want)
const downloads = (adb('logcat', '-d', '-s', 'CapgoUpdater').match(/Downloading /g) || []).length
r.check(`bundles: switch to ${site} served from cache (0 downloads)`, !!s && downloads === 0, `(${downloads})`)
}
const kept = (s?.bundles || '').split(',')
r.check('bundles: only bundles a venue needs are kept', kept.includes(manifest.version) && kept.includes(m2.version) && !kept.includes('e2e-staged'), s?.bundles)
r.check('bundles: nothing contacted *.capgo.app', !/capgo\.app/i.test(adb('logcat', '-d')))
} finally {
try { execFileSync('docker', ['rm', '-f', 'xenia-e2e-impostor'], { stdio: 'ignore' }) } catch {}
s1.down(); s2.down()
}
return r.done()
}
const groups = { basics, rediscovery, stacks }
for (const [name, fn] of Object.entries(groups)) {
if (which === 'all' || which === name) failures += await fn()
}
console.log(failures ? `\n✗ android: ${failures} failure(s)` : '\n✓ android: all passed')
process.exit(failures ? 1 : 0)