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:
@@ -0,0 +1,2 @@
|
||||
node_modules/
|
||||
out/
|
||||
@@ -0,0 +1,58 @@
|
||||
# client-services tests
|
||||
|
||||
Automated checks for everything built in the native-app / LAN plan (`docs/plans/native-waiter-app.md` in the parent repo) and for offline licensing (KI-006).
|
||||
Run them **before a release** and after changing anything they cover.
|
||||
|
||||
## Quick: unit tests (seconds, no servers)
|
||||
|
||||
```powershell
|
||||
cd client-services/local_backend
|
||||
pip install -r requirements-dev.txt # once
|
||||
python -m pytest tests -q # license rules, LAN-IP detection + priority, TLS identity
|
||||
|
||||
cd ../waiter_pwa
|
||||
npm test # server rediscovery scan
|
||||
```
|
||||
|
||||
## Full: end-to-end suites
|
||||
|
||||
```powershell
|
||||
cd client-services/tests/e2e
|
||||
npm install # once (Playwright, fflate)
|
||||
node run-all.mjs # everything, fastest first, with a summary
|
||||
node run-all.mjs --no-android # everything except the emulator
|
||||
```
|
||||
|
||||
Or run one suite at a time:
|
||||
|
||||
| Command | What it checks | Needs | Time |
|
||||
|---|---|---|---|
|
||||
| `node install.mjs` | `install.sh`: VPN-safe `HOST_IP` detection (simulated WireGuard/WiFi hosts); fresh install, upgrade, re-run; proxy config identical to `nginx-proxy/nginx.conf` | Docker | ~1 min |
|
||||
| `python license_e2e.py` | Offline licensing with a real cloud + site process: 400 days offline, tampered file, clock set back, expiry deferred to workday close, renewal, remote lock | Python deps of both backends | ~2 min |
|
||||
| `node browser.mjs` | Waiter web modes (same-origin, plain HTTP by LAN IP, venue mode), install dialog + drawer entry (Android / iPhone / desktop / no APK) | Docker, Edge | ~2 min |
|
||||
| `node android.mjs basics` | Pairing, wrong address / other venue's QR, login + live WS, back button, restart, two venues, camera permission | Android emulator | ~5 min |
|
||||
| `node android.mjs rediscovery` | Server IP change (logged in / out), server down + manual search, cold start while offline | Android emulator | ~4 min |
|
||||
| `node android.mjs stacks` | TLS pinning (wrong-key QR, impostor server, HTTP→TLS upgrade, cert renewal, rediscovery over TLS) and UI bundles (apply, staged, tampered, APK too old, rollback, two venues) on two docker-compose stacks built from this repo | Android emulator, Docker | ~20 min |
|
||||
|
||||
### Requirements
|
||||
- **Python** with `local_backend/requirements.txt` and `cloud-service/cloud_backend/requirements.txt` installed.
|
||||
- **Node 22+**, **Docker** (Docker Desktop is fine).
|
||||
- **Browser suite:** system **Edge** (default). Set `BROWSER_CHANNEL=` (empty) to use Playwright's own Chromium after `npx playwright install chromium`.
|
||||
- **Android suites:** the Android SDK (`ANDROID_HOME`, or the default location) and an emulator AVD. Default name `Xenia_Test_Phone` (Pixel 4a, API 35), override with `AVD=<name>`. The suite builds the debug APK itself (`SKIP_APK_BUILD=1` reuses the last one), and boots the emulator if none is attached.
|
||||
|
||||
### Settings (environment variables)
|
||||
| Variable | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `LAN_IP` | auto (first non-VPN, non-virtual adapter) | This PC's LAN address, for the "plain HTTP by LAN IP" checks |
|
||||
| `PYTHON` | `python` / `python3` | Python executable |
|
||||
| `BROWSER_CHANNEL` | `msedge` | Playwright browser channel |
|
||||
| `AVD` | `Xenia_Test_Phone` | Emulator to boot |
|
||||
| `SKIP_APK_BUILD` | unset | Reuse the last debug APK |
|
||||
| `CLOUD_DIR` | `../cloud-service/cloud_backend` | Cloud backend for the license suite |
|
||||
|
||||
### Good to know
|
||||
- **Test data:** suites never touch your databases. They start from a fresh copy of a demo-seeded database (`local_backend/demo_seed.py`), seeded once into `out/seed.db`. Delete it to reseed.
|
||||
- **Ports used:** 8055/8056 (backends), 8101 (cloud), 5180 (Vite), 15173/15174 (nginx), 18080–18444 and 28080–28443 (compose stacks). Your own dev stack's ports (80/443/8081/8443/5173/5174) are never used. Stop anything else on those ports first.
|
||||
- **Isolated stacks:** the compose stacks run under their own project names (`xenia-e2e-v1/v2`) with their own images and data. They're removed afterwards.
|
||||
- **Output:** screenshots and logs go to `out/`, which is gitignored.
|
||||
- **Licensing in tests:** the license suite signs with a throwaway key, and the production signing key is never needed. The other suites run their backends without a cloud URL, so licensing is off, as on any dev setup.
|
||||
@@ -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)
|
||||
@@ -0,0 +1,121 @@
|
||||
// Browser suite (Playwright + Edge): the waiter app's three web delivery modes
|
||||
// (plan step 2) and the install-app dialog / drawer entry (F-051).
|
||||
// Starts its own backend (:8055), nginx containers serving the production build
|
||||
// (:15173 with an APK, :15174 without) and a Vite dev server (:5180).
|
||||
// node browser.mjs
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { cpSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { chromium } from 'playwright'
|
||||
import { BROWSER_CHANNEL, OUT, WAITER, lanIp, reporter, sleep } from './lib/env.mjs'
|
||||
import { login, serveWaiterBuild, startBackend, startViteNative } from './lib/proc.mjs'
|
||||
|
||||
const LAN = lanIp()
|
||||
const ANDROID_UA = 'Mozilla/5.0 (Linux; Android 14; SM-A145R) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0 Mobile Safari/537.36'
|
||||
const IPHONE_UA = 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1'
|
||||
const DESKTOP_UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0 Safari/537.36'
|
||||
|
||||
console.log(' building the waiter app…')
|
||||
execFileSync('npm', ['run', 'build'], { cwd: WAITER, stdio: 'ignore', shell: process.platform === 'win32' })
|
||||
// Two copies of the build: one whose server offers the APK, one that doesn't
|
||||
const withApk = path.join(OUT, 'dist-with-apk'), noApk = path.join(OUT, 'dist-no-apk')
|
||||
for (const d of [withApk, noApk]) { rmSync(d, { recursive: true, force: true }); cpSync(path.join(WAITER, 'dist'), d, { recursive: true }) }
|
||||
mkdirSync(path.join(withApk, 'downloads'), { recursive: true })
|
||||
writeFileSync(path.join(withApk, 'downloads', 'xenia-waiter.apk'), Buffer.from('PK\x03\x04 test apk'))
|
||||
rmSync(path.join(noApk, 'downloads'), { recursive: true, force: true })
|
||||
|
||||
const backend = await startBackend({ port: 8055, siteId: 'test-site-1' })
|
||||
const web = await serveWaiterBuild({ name: 'xenia-e2e-waiter', port: 15173, dist: withApk })
|
||||
const webNoApk = await serveWaiterBuild({ name: 'xenia-e2e-waiter-noapk', port: 15174, dist: noApk })
|
||||
const vite = await startViteNative({ port: 5180, backendUrl: backend.url })
|
||||
const browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {})
|
||||
let failures = 0
|
||||
|
||||
try {
|
||||
const token = await login(backend.url)
|
||||
|
||||
// ── Web delivery modes ────────────────────────────────────────────────────
|
||||
const r1 = reporter('browser: web delivery modes')
|
||||
const modes = [
|
||||
{ name: 'same-origin (prod build, https-like localhost)', origin: 'http://localhost:15173', tokenKey: 'token', db: 'pos_snapshot', wsHost: 'localhost:15173', secure: true },
|
||||
{ name: 'plain HTTP by LAN IP (prod build)', origin: `http://${LAN}:15173`, tokenKey: 'token', db: 'pos_snapshot', wsHost: `${LAN}:15173`, secure: false },
|
||||
{ name: 'venue mode (dev build, VITE_SERVER_URL)', origin: 'http://localhost:5180', tokenKey: 'xenia:dev:token', db: 'pos_snapshot__dev', wsHost: '127.0.0.1:8055', secure: true },
|
||||
]
|
||||
for (const m of modes) {
|
||||
const page = await (await browser.newContext()).newPage()
|
||||
const frames = [], wsUrls = [], apiHosts = new Set()
|
||||
page.on('request', r => { if (['xhr', 'fetch'].includes(r.resourceType())) apiHosts.add(new URL(r.url()).host) })
|
||||
page.on('websocket', ws => { wsUrls.push(ws.url()); ws.on('framereceived', f => frames.push(String(f.payload))) })
|
||||
await page.goto(`${m.origin}/login`)
|
||||
await page.evaluate(([k, t]) => localStorage.setItem(k, t), [m.tokenKey, token])
|
||||
await page.goto(`${m.origin}/tables`)
|
||||
await sleep(6000)
|
||||
const dbs = await page.evaluate(async () => (await indexedDB.databases()).map(d => d.name))
|
||||
r1.check(`${m.name}: lands on /tables`, page.url().includes('/tables'), page.url())
|
||||
r1.check(`${m.name}: live WebSocket via ${m.wsHost}`, frames.some(f => f.includes('"ready"')) && wsUrls.some(u => new URL(u).host === m.wsHost))
|
||||
r1.check(`${m.name}: IndexedDB "${m.db}"`, dbs.includes(m.db), dbs.join(','))
|
||||
r1.check(`${m.name}: secure context = ${m.secure}`, (await page.evaluate(() => window.isSecureContext)) === m.secure)
|
||||
if (m.name.startsWith('venue')) r1.check(`${m.name}: API calls go to the venue server`, [...apiHosts].every(h => h === '127.0.0.1:8055'), [...apiHosts].join(','))
|
||||
await page.context().close()
|
||||
}
|
||||
failures += r1.done()
|
||||
|
||||
// ── Install-app dialog + drawer entry ─────────────────────────────────────
|
||||
const r2 = reporter('browser: install-app dialog')
|
||||
const phone = ua => browser.newContext({ userAgent: ua, viewport: { width: 393, height: 852 }, deviceScaleFactor: 2.75, isMobile: true, hasTouch: true })
|
||||
const dialog = page => page.getByRole('dialog', { name: 'Εφαρμογή Xenia' })
|
||||
const hamburger = page => page.locator('button').filter({ has: page.locator('svg') }).first()
|
||||
|
||||
let ctx = await phone(ANDROID_UA)
|
||||
let page = await ctx.newPage()
|
||||
await page.goto(`http://${LAN}:15173/?pair=test-site-1`)
|
||||
await sleep(3500)
|
||||
r2.check('first visit on Android: dialog opens by itself', await dialog(page).isVisible())
|
||||
const box = await dialog(page).boundingBox()
|
||||
r2.check('dialog is taller than wide', box && box.height > box.width, box ? `${Math.round(box.width)}×${Math.round(box.height)}` : '')
|
||||
r2.check('download link points at the APK', (await page.getByRole('link', { name: 'Λήψη εφαρμογής' }).getAttribute('href')) === '/downloads/xenia-waiter.apk')
|
||||
await page.screenshot({ path: path.join(OUT, 'install-dialog.png') })
|
||||
await page.getByRole('button', { name: 'Όχι τώρα' }).click()
|
||||
await sleep(400)
|
||||
await page.reload()
|
||||
await sleep(3500)
|
||||
r2.check('"Όχι τώρα" → never opens by itself again', !(await dialog(page).isVisible()))
|
||||
await page.evaluate(t => localStorage.setItem('token', t), token)
|
||||
await page.goto(`http://${LAN}:15173/tables`)
|
||||
await sleep(4000)
|
||||
await hamburger(page).click()
|
||||
await sleep(600)
|
||||
const install = page.getByRole('button', { name: 'Εγκατάσταση εφαρμογής' })
|
||||
const [ib, sb] = [await install.boundingBox(), await page.getByRole('button', { name: 'Settings' }).boundingBox()]
|
||||
r2.check('drawer shows "Εγκατάσταση εφαρμογής" right above Settings', !!(ib && sb && ib.y < sb.y && sb.y - ib.y < 80))
|
||||
await install.click()
|
||||
await sleep(500)
|
||||
r2.check('drawer entry reopens the dialog', await dialog(page).isVisible())
|
||||
await ctx.close()
|
||||
|
||||
for (const [label, ua] of [['desktop', DESKTOP_UA], ['iPhone', IPHONE_UA]]) {
|
||||
ctx = await phone(ua)
|
||||
page = await ctx.newPage()
|
||||
await page.goto(`http://${LAN}:15173/`)
|
||||
await page.evaluate(t => localStorage.setItem('token', t), token)
|
||||
await page.goto(`http://${LAN}:15173/tables`)
|
||||
await sleep(3500)
|
||||
const noDialog = !(await dialog(page).isVisible())
|
||||
await hamburger(page).click()
|
||||
await sleep(500)
|
||||
r2.check(`${label}: never offered (no dialog, no drawer entry)`, noDialog && !(await page.getByRole('button', { name: 'Εγκατάσταση εφαρμογής' }).isVisible()))
|
||||
await ctx.close()
|
||||
}
|
||||
ctx = await phone(ANDROID_UA)
|
||||
page = await ctx.newPage()
|
||||
await page.goto(`http://${LAN}:15174/`)
|
||||
await sleep(3500)
|
||||
r2.check('server without the APK: never offered', !(await dialog(page).isVisible()))
|
||||
await ctx.close()
|
||||
failures += r2.done()
|
||||
} finally {
|
||||
await browser.close()
|
||||
vite.stop(); web.stop(); webNoApk.stop()
|
||||
await backend.stop()
|
||||
}
|
||||
process.exit(failures ? 1 : 0)
|
||||
@@ -0,0 +1,64 @@
|
||||
// install.sh suite (Docker): runs the real install.sh inside a throwaway Debian
|
||||
// container — HOST_IP detection on simulated hosts (physical NIC only, never a
|
||||
// VPN) and the fresh-install / upgrade / re-run flows. `docker` is stubbed
|
||||
// inside the container, so nothing is started.
|
||||
// node install.mjs
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { copyFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { CS, OUT, reporter } from './lib/env.mjs'
|
||||
|
||||
const dir = path.join(OUT, 'install')
|
||||
mkdirSync(dir, { recursive: true })
|
||||
copyFileSync(path.join(CS, 'install.sh'), path.join(dir, 'install.sh'))
|
||||
copyFileSync(path.join(CS, '.env.example'), path.join(dir, '.env.example'))
|
||||
const fn = readFileSync(path.join(CS, 'install.sh'), 'utf8').replace(/\r/g, '').match(/^detect_host_ip\(\) \{[\s\S]*?^\}/m)[0]
|
||||
writeFileSync(path.join(dir, 'fn.sh'), fn + '\n')
|
||||
|
||||
writeFileSync(path.join(dir, 'run.sh'), `set -e
|
||||
apt-get update -qq >/dev/null && apt-get install -y -qq openssl >/dev/null 2>&1
|
||||
. /t/fn.sh
|
||||
mkdir -p /stub && export PATH=/stub:$PATH XENIA_SYS_NET=/tmp/sys
|
||||
cat > /stub/ip <<'IP'
|
||||
#!/bin/sh
|
||||
case "$*" in
|
||||
"route show default") echo "$DEFAULT_ROUTE" ;;
|
||||
"-4 -o addr show dev eth0") echo "2: eth0 inet 10.98.20.70/24 brd 10.98.20.255 scope global eth0" ;;
|
||||
"-4 -o addr show dev wlan0") echo "3: wlan0 inet 192.168.1.44/24 brd 192.168.1.255 scope global wlan0" ;;
|
||||
"-4 -o addr show dev wg0") echo "5: wg0 inet 10.9.9.2/24 scope global wg0" ;;
|
||||
"-4 -o addr show dev docker0") echo "4: docker0 inet 172.17.0.1/16 scope global docker0" ;;
|
||||
esac
|
||||
IP
|
||||
printf '#!/bin/sh\\necho "10.9.9.2 10.98.20.70 172.17.0.1"\\n' > /stub/hostname
|
||||
printf '#!/bin/sh\\necho "[stub docker] $*"\\n' > /stub/docker
|
||||
chmod +x /stub/*
|
||||
host() { rm -rf /tmp/sys; mkdir -p /tmp/sys; for i in docker0 wg0 lo; do mkdir -p /tmp/sys/$i; done; for i in "$@"; do mkdir -p /tmp/sys/$i/device; done; }
|
||||
host eth0; DEFAULT_ROUTE="default via 10.98.20.1 dev eth0"; echo "DETECT wg-full-tunnel=$(detect_host_ip)"
|
||||
host eth0; DEFAULT_ROUTE="default dev wg0 scope link"; echo "DETECT tunnel-owns-default=$(detect_host_ip)"
|
||||
host eth0; DEFAULT_ROUTE=""; echo "DETECT no-default-route=$(detect_host_ip)"
|
||||
host wlan0; DEFAULT_ROUTE="default via 192.168.1.1 dev wlan0"; echo "DETECT wifi-only=$(detect_host_ip)"
|
||||
# full install.sh flows (real ip/hostname again, docker stubbed)
|
||||
rm /stub/ip /stub/hostname; unset XENIA_SYS_NET
|
||||
cp -r /t /a && cd /a && printf 'site-123\\nkey-abc\\n\\n\\n' | bash install.sh >/dev/null
|
||||
echo "FRESH env=$(grep -cE '^(SITE_ID=site-123|SITE_KEY=key-abc|HOST_IP=.+)$' .env) cert=$(test -s certs/cert.pem && echo yes) keymode=$(stat -c %a certs/key.pem) conf=$(test -s nginx-proxy/nginx.conf && echo yes)"
|
||||
cp -r /t /b && cd /b && mkdir -p certs && cp /a/certs/* certs/ && grep -v '^HOST_IP' .env.example > .env
|
||||
bash install.sh >/dev/null; echo "UPGRADE hostip=$(grep -c '^HOST_IP=.\\+' .env)"
|
||||
bash install.sh >/dev/null; echo "RERUN hostip_lines=$(grep -c '^HOST_IP=' .env)"
|
||||
`)
|
||||
|
||||
const r = reporter('install.sh (Debian container)')
|
||||
const out = execFileSync('docker', ['run', '--rm', '-v', `${dir}:/t:ro`, 'debian:bookworm-slim', 'bash', '/t/run.sh'],
|
||||
{ encoding: 'utf8', env: { ...process.env, MSYS_NO_PATHCONV: '1' } })
|
||||
const val = key => out.match(new RegExp(`${key}=(\\S*)`))?.[1]
|
||||
r.check('HOST_IP: WireGuard full tunnel → physical NIC', val('DETECT wg-full-tunnel') === '10.98.20.70')
|
||||
r.check('HOST_IP: tunnel owns the default route → physical NIC', val('DETECT tunnel-owns-default') === '10.98.20.70')
|
||||
r.check('HOST_IP: no default route → physical NIC', val('DETECT no-default-route') === '10.98.20.70')
|
||||
r.check('HOST_IP: WiFi-only server', val('DETECT wifi-only') === '192.168.1.44')
|
||||
r.check('fresh install: .env filled (SITE_ID, SITE_KEY, HOST_IP)', val('env') === '3')
|
||||
r.check('fresh install: self-signed cert, key 600, proxy config written', val('cert') === 'yes' && val('keymode') === '600' && val('conf') === 'yes')
|
||||
r.check('upgrade: missing HOST_IP backfilled', val('UPGRADE hostip') === '1')
|
||||
r.check('re-run: HOST_IP not duplicated', val('RERUN hostip_lines') === '1')
|
||||
// the proxy config written by install.sh must be byte-identical to the repo copy (rule CS-5)
|
||||
const heredoc = readFileSync(path.join(CS, 'install.sh'), 'utf8').replace(/\r/g, '').match(/<< 'EOF'\n([\s\S]*?)\nEOF\n/)[1]
|
||||
r.check('install.sh proxy config == nginx-proxy/nginx.conf', heredoc === readFileSync(path.join(CS, 'nginx-proxy', 'nginx.conf'), 'utf8').replace(/\r/g, '').replace(/\n$/, ''))
|
||||
process.exit(r.done() ? 1 : 0)
|
||||
@@ -0,0 +1,124 @@
|
||||
// Driving the real app on an Android emulator: real taps/typing via adb,
|
||||
// state via the debug build's WebView DevTools (lib/cdp.mjs).
|
||||
import { execFileSync, spawn } from 'node:child_process'
|
||||
import { existsSync, readdirSync, statSync, writeFileSync } from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { connectWebView } from './cdp.mjs'
|
||||
import { OUT, WAITER, sleep } from './env.mjs'
|
||||
|
||||
export const APP_ID = 'gr.bonamin.xenia'
|
||||
const SDK = process.env.ANDROID_HOME || process.env.ANDROID_SDK_ROOT
|
||||
|| (process.platform === 'win32' ? path.join(process.env.LOCALAPPDATA || '', 'Android', 'Sdk') : path.join(os.homedir(), 'Android', 'Sdk'))
|
||||
const exe = name => path.join(SDK, ...name.split('/')) + (process.platform === 'win32' ? '.exe' : '')
|
||||
export const ADB = exe('platform-tools/adb')
|
||||
|
||||
export const adb = (...args) => execFileSync(ADB, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
|
||||
|
||||
/** Make sure a device is attached; boot the test AVD headless if none is. */
|
||||
export async function ensureDevice() {
|
||||
if (/\tdevice$/m.test(adb('devices'))) return
|
||||
const avd = process.env.AVD || 'Xenia_Test_Phone'
|
||||
console.log(` booting emulator ${avd} (headless)…`)
|
||||
spawn(exe('emulator/emulator'), ['-avd', avd, '-no-window', '-no-audio', '-no-boot-anim', '-gpu', 'swiftshader_indirect', '-no-snapshot'],
|
||||
{ detached: true, stdio: 'ignore' }).unref()
|
||||
for (let i = 0; i < 90; i++) {
|
||||
try { if (adb('shell', 'getprop', 'sys.boot_completed').trim() === '1') return } catch {}
|
||||
await sleep(3000)
|
||||
}
|
||||
throw new Error(`emulator ${avd} did not boot — create it in Android Studio or set AVD=<name>`)
|
||||
}
|
||||
|
||||
/** Newest debug APK from `npm run apk:debug` (WebView debugging needs a debug build). */
|
||||
export function debugApk() {
|
||||
const dir = path.join(WAITER, 'releases')
|
||||
const apks = existsSync(dir) ? readdirSync(dir).filter(f => f.endsWith('-debug.apk')) : []
|
||||
if (!apks.length) throw new Error('no debug APK — run `npm run apk:debug` in waiter_pwa first')
|
||||
return path.join(dir, apks.sort((a, b) => statSync(path.join(dir, b)).mtimeMs - statSync(path.join(dir, a)).mtimeMs)[0])
|
||||
}
|
||||
|
||||
export function installApp({ fresh = true } = {}) {
|
||||
if (fresh) { try { adb('uninstall', APP_ID) } catch {} }
|
||||
adb('install', '-r', debugApk())
|
||||
}
|
||||
|
||||
export const launch = () => adb('shell', 'monkey', '-p', APP_ID, '-c', 'android.intent.category.LAUNCHER', '1')
|
||||
export const home = () => adb('shell', 'input', 'keyevent', 'KEYCODE_HOME')
|
||||
export const back = () => adb('shell', 'input', 'keyevent', 'KEYCODE_BACK')
|
||||
export const clearData = () => adb('shell', 'pm', 'clear', APP_ID)
|
||||
export const focusedWindow = () => adb('shell', 'dumpsys', 'window').match(/mCurrentFocus=[^}]*\}/)?.[0] || ''
|
||||
export const shot = name => writeFileSync(path.join(OUT, `${name}.png`), execFileSync(ADB, ['exec-out', 'screencap', '-p']))
|
||||
|
||||
/** Attach to the app's WebView over DevTools (the socket changes when the process restarts). */
|
||||
export async function attach() {
|
||||
for (let i = 0; i < 40; i++) {
|
||||
const sock = adb('shell', 'cat', '/proc/net/unix').match(/webview_devtools_remote_\d+/)?.[0]
|
||||
if (sock) {
|
||||
adb('forward', 'tcp:9333', `localabstract:${sock}`)
|
||||
try { return await connectWebView() } catch {}
|
||||
}
|
||||
await sleep(750)
|
||||
}
|
||||
throw new Error('could not attach to the app WebView (is this a debug build?)')
|
||||
}
|
||||
|
||||
export async function relaunch() {
|
||||
adb('shell', 'am', 'force-stop', APP_ID)
|
||||
launch()
|
||||
await sleep(4000)
|
||||
return attach()
|
||||
}
|
||||
|
||||
/** Reload inside the running app (a force-stop right after a localStorage write can lose it). */
|
||||
export async function reloadApp(v, target = '/') {
|
||||
await v.evaluate(`setTimeout(() => location.replace(${JSON.stringify(target)}), 300)`)
|
||||
v.close()
|
||||
await sleep(3500)
|
||||
return attach()
|
||||
}
|
||||
|
||||
const statusBar = () => Number(adb('shell', 'dumpsys', 'window').match(/statusBars.*?frame=\[0,0\]\[\d+,(\d+)\]/s)?.[1] || 0)
|
||||
|
||||
/** Real tap on the element matching a CSS selector (and containing `text`). */
|
||||
export async function tap(v, selector, text = '', { last = false } = {}) {
|
||||
const r = await v.evaluate(`(() => {
|
||||
const els = [...document.querySelectorAll(${JSON.stringify(selector)})].filter(e => e.textContent.includes(${JSON.stringify(text)}))
|
||||
const b = els[${last ? 'els.length - 1' : '0'}]?.getBoundingClientRect()
|
||||
return b ? { x: b.x + b.width / 2, y: b.y + b.height / 2, dpr: devicePixelRatio } : null
|
||||
})()`)
|
||||
if (!r) throw new Error(`nothing to tap: ${selector} "${text}"`)
|
||||
adb('shell', 'input', 'tap', String(Math.round(r.x * r.dpr)), String(Math.round(r.y * r.dpr + statusBar())))
|
||||
}
|
||||
|
||||
/** Replace the first input's content by real typing. */
|
||||
export async function typeInto(v, text) {
|
||||
await tap(v, 'input')
|
||||
await sleep(300)
|
||||
await v.evaluate("document.querySelector('input').select()")
|
||||
adb('shell', 'input', 'keyevent', 'KEYCODE_DEL')
|
||||
adb('shell', `input text '${text}'`) // quoted for the device shell (& in URLs)
|
||||
}
|
||||
|
||||
/** Tap a system dialog button (e.g. the camera permission prompt) by its label. */
|
||||
export function tapDialogButton(label) {
|
||||
adb('shell', 'uiautomator', 'dump', '/sdcard/ui.xml')
|
||||
const xml = adb('shell', 'cat', '/sdcard/ui.xml')
|
||||
const m = xml.match(new RegExp(`text="${label}"[^>]*bounds="\\[(\\d+),(\\d+)\\]\\[(\\d+),(\\d+)\\]"`))
|
||||
if (!m) throw new Error(`dialog button not found: ${label}`)
|
||||
adb('shell', 'input', 'tap', String((+m[1] + +m[3]) >> 1), String((+m[2] + +m[4]) >> 1))
|
||||
}
|
||||
|
||||
/** Navigate inside the app without a reload. */
|
||||
export const goTo = (v, p) => v.evaluate(`history.pushState({}, '', ${JSON.stringify(p)}); dispatchEvent(new PopStateEvent('popstate'))`)
|
||||
|
||||
export const venuesState = async v => JSON.parse(await v.evaluate("localStorage.getItem('xenia.venues')"))
|
||||
export async function setVenues(v, state) {
|
||||
await v.evaluate(`localStorage.setItem('xenia.venues', ${JSON.stringify(JSON.stringify(state))})`)
|
||||
await sleep(1200)
|
||||
}
|
||||
|
||||
export const GREEN = 'rgb(34, 197, 94)'
|
||||
export const connectivityColor = v => v.evaluate("document.querySelector('.connectivity-bar') ? getComputedStyle(document.querySelector('.connectivity-bar')).backgroundColor : 'none'")
|
||||
|
||||
// @capgo/capacitor-updater from inside the page
|
||||
export const UPD = "(window.Capacitor.Plugins.CapacitorUpdater || window.Capacitor.registerPlugin('CapacitorUpdater'))"
|
||||
@@ -0,0 +1,41 @@
|
||||
// Minimal Chrome DevTools Protocol client for the app's Android WebView
|
||||
// (exposed with `adb forward tcp:9333 localabstract:webview_devtools_remote_<pid>`).
|
||||
// Playwright can't drive an Android WebView's browser context, so this speaks CDP directly.
|
||||
export async function connectWebView(port = 9333) {
|
||||
const targets = await fetch(`http://127.0.0.1:${port}/json`).then(r => r.json())
|
||||
const target = targets.find(t => t.type === 'page')
|
||||
if (!target) throw new Error('no WebView page target')
|
||||
const ws = new WebSocket(target.webSocketDebuggerUrl)
|
||||
await new Promise((resolve, reject) => { ws.onopen = resolve; ws.onerror = reject })
|
||||
|
||||
let id = 0
|
||||
const pending = new Map()
|
||||
const logs = []
|
||||
ws.onmessage = ev => {
|
||||
const msg = JSON.parse(ev.data)
|
||||
if (msg.id && pending.has(msg.id)) {
|
||||
const { resolve, reject } = pending.get(msg.id)
|
||||
pending.delete(msg.id)
|
||||
msg.error ? reject(new Error(msg.error.message)) : resolve(msg.result)
|
||||
} else if (msg.method === 'Runtime.consoleAPICalled') {
|
||||
logs.push(`[${msg.params.type}] ` + msg.params.args.map(a => a.value ?? a.description ?? '').join(' ').slice(0, 300))
|
||||
} else if (msg.method === 'Runtime.exceptionThrown') {
|
||||
const d = msg.params.exceptionDetails
|
||||
logs.push('EXCEPTION ' + (d.exception?.description || d.text).slice(0, 400))
|
||||
}
|
||||
}
|
||||
const send = (method, params = {}) => new Promise((resolve, reject) => {
|
||||
const msgId = ++id
|
||||
pending.set(msgId, { resolve, reject })
|
||||
ws.send(JSON.stringify({ id: msgId, method, params }))
|
||||
})
|
||||
await send('Runtime.enable')
|
||||
await send('Page.enable')
|
||||
|
||||
const evaluate = async expression => {
|
||||
const r = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true })
|
||||
if (r.exceptionDetails) throw new Error('eval failed: ' + (r.exceptionDetails.exception?.description || r.exceptionDetails.text))
|
||||
return r.result.value
|
||||
}
|
||||
return { send, evaluate, logs, close: () => ws.close() }
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
// Shared settings for the end-to-end suites. Everything is derived from the repo
|
||||
// layout or the environment — no machine-specific paths or IPs are hard-coded.
|
||||
import { mkdirSync } from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url))
|
||||
export const E2E = path.resolve(here, '..') // client-services/tests/e2e
|
||||
export const CS = path.resolve(E2E, '..', '..') // client-services
|
||||
export const REPO = path.resolve(CS, '..') // xenia-pos (parent)
|
||||
export const BACKEND = path.join(CS, 'local_backend')
|
||||
export const WAITER = path.join(CS, 'waiter_pwa')
|
||||
export const CLOUD = process.env.CLOUD_DIR || path.join(REPO, 'cloud-service', 'cloud_backend')
|
||||
export const OUT = path.join(E2E, 'out') // screenshots, logs, temp data (gitignored)
|
||||
mkdirSync(OUT, { recursive: true })
|
||||
|
||||
export const PYTHON = process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3')
|
||||
// Playwright browser: system Edge by default; BROWSER_CHANNEL= (empty) uses Playwright's own Chromium
|
||||
export const BROWSER_CHANNEL = process.env.BROWSER_CHANNEL ?? 'msedge'
|
||||
// Break-glass login the test backends are started with (never a real account)
|
||||
export const MASTER = { username: 'e2e', password: 'e2e-pass-123' }
|
||||
// The Android emulator reaches the host machine at this address
|
||||
export const EMULATOR_HOST = '10.0.2.2'
|
||||
|
||||
/**
|
||||
* This machine's LAN IPv4 — for "plain HTTP by LAN IP" browser tests.
|
||||
* LAN_IP wins; otherwise the first address on a non-virtual, non-VPN adapter.
|
||||
*/
|
||||
export function lanIp() {
|
||||
if (process.env.LAN_IP) return process.env.LAN_IP
|
||||
const skip = /vEthernet|WSL|docker|br-|veth|virtual|vmware|vbox|hyper-v|wireguard|wg\d|tailscale|zerotier|vpn|loopback/i
|
||||
for (const [name, addrs] of Object.entries(os.networkInterfaces())) {
|
||||
if (skip.test(name)) continue
|
||||
const a = (addrs || []).find(x => x.family === 'IPv4' && !x.internal && !x.address.startsWith('169.254.'))
|
||||
if (a) return a.address
|
||||
}
|
||||
throw new Error('Could not detect this machine\'s LAN IP — set LAN_IP=<ip>')
|
||||
}
|
||||
|
||||
/** Tiny PASS/FAIL reporter shared by the suites. */
|
||||
export function reporter(suite) {
|
||||
let failures = 0
|
||||
console.log(`\n── ${suite}`)
|
||||
return {
|
||||
check(name, ok, extra = '') {
|
||||
if (!ok) failures++
|
||||
console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${extra ? ' ' + extra : ''}`)
|
||||
},
|
||||
done() {
|
||||
console.log(failures ? `✗ ${suite}: ${failures} failure(s)` : `✓ ${suite}: all passed`)
|
||||
return failures
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export const sleep = ms => new Promise(r => setTimeout(r, ms))
|
||||
|
||||
export async function waitFor(fn, timeoutMs, stepMs = 1000) {
|
||||
const t0 = Date.now()
|
||||
while (Date.now() - t0 < timeoutMs) {
|
||||
try {
|
||||
const r = await fn()
|
||||
if (r) return r
|
||||
} catch {
|
||||
// not yet
|
||||
}
|
||||
await sleep(stepMs)
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
// Starting and stopping what the suites run against: local backends on a
|
||||
// seeded throwaway database, nginx containers serving the waiter build, the
|
||||
// Vite dev server, and isolated docker-compose stacks.
|
||||
import { execFileSync, spawn } from 'node:child_process'
|
||||
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { BACKEND, CS, MASTER, OUT, PYTHON, WAITER, sleep } from './env.mjs'
|
||||
|
||||
/** Kill a process and its children (npx/shell wrappers on Windows). */
|
||||
export function killTree(child) {
|
||||
if (!child || child.exitCode !== null) return
|
||||
if (process.platform === 'win32') {
|
||||
try { execFileSync('taskkill', ['/T', '/F', '/PID', String(child.pid)], { stdio: 'ignore' }) } catch {}
|
||||
} else {
|
||||
try { process.kill(-child.pid) } catch { child.kill() }
|
||||
}
|
||||
}
|
||||
|
||||
export async function waitHttp(url, up = true, timeoutMs = 60_000) {
|
||||
const t0 = Date.now()
|
||||
while (Date.now() - t0 < timeoutMs) {
|
||||
const ok = await fetch(url, { signal: AbortSignal.timeout(2000) }).then(() => true, () => false)
|
||||
if (ok === up) return
|
||||
await sleep(500)
|
||||
}
|
||||
throw new Error(`${url} did not ${up ? 'come up' : 'go down'} within ${timeoutMs / 1000}s`)
|
||||
}
|
||||
|
||||
/**
|
||||
* A fresh demo-seeded database (demo_seed.py: manager + 4 waiters, 13 tables,
|
||||
* order history). Seeded once into out/seed.db, then copied per test run.
|
||||
*/
|
||||
export function seededDataDir(label = 'data') {
|
||||
const template = path.join(OUT, 'seed.db')
|
||||
if (!existsSync(template)) {
|
||||
console.log(' seeding a demo database (once)…')
|
||||
const partial = `${template}.partial`
|
||||
rmSync(partial, { force: true })
|
||||
execFileSync(PYTHON, ['demo_seed.py'], {
|
||||
cwd: BACKEND, stdio: 'ignore',
|
||||
env: { ...process.env, DATABASE_URL: `sqlite:///${partial.replace(/\\/g, '/')}`, PYTHONIOENCODING: 'utf-8' },
|
||||
})
|
||||
// Only a database that really holds the demo data becomes the template
|
||||
const count = execFileSync(PYTHON, ['-c', 'import sqlite3, sys; print(sqlite3.connect(sys.argv[1]).execute("select count(*) from orders").fetchone()[0])', partial], { encoding: 'utf8' })
|
||||
if (!Number(count)) throw new Error('demo_seed.py produced no orders — check local_backend/demo_seed.py')
|
||||
renameSync(partial, template)
|
||||
}
|
||||
const dir = mkdtempSync(path.join(OUT, `${label}-`))
|
||||
copyFileSync(template, path.join(dir, 'pos.db'))
|
||||
return dir
|
||||
}
|
||||
|
||||
/** Local backend (uvicorn) on `port` with its own data dir. Returns { url, dataDir, stop() }. */
|
||||
export async function startBackend({ port = 8055, siteId = 'test-site-1', siteKey = 'x', cloudUrl = '', dataDir, env = {} } = {}) {
|
||||
dataDir ??= seededDataDir(`backend-${port}`)
|
||||
const log = openSync(path.join(dataDir, 'backend.log'), 'a')
|
||||
const child = spawn(PYTHON, ['-m', 'uvicorn', 'main:app', '--host', '0.0.0.0', '--port', String(port)], {
|
||||
cwd: BACKEND, stdio: ['ignore', log, log],
|
||||
env: {
|
||||
...process.env, DATABASE_URL: `sqlite:///${path.join(dataDir, 'pos.db').replace(/\\/g, '/')}`,
|
||||
SITE_ID: siteId, SITE_KEY: siteKey, CLOUD_URL: cloudUrl, SECRET_KEY: 'e2e-secret',
|
||||
MASTER_USERNAME: MASTER.username, MASTER_PASSWORD: MASTER.password, ...env,
|
||||
},
|
||||
})
|
||||
const url = `http://127.0.0.1:${port}`
|
||||
await waitHttp(`${url}/api/system/health`)
|
||||
return { url, dataDir, child, stop: async () => { killTree(child); await waitHttp(`${url}/api/system/health`, false).catch(() => {}) } }
|
||||
}
|
||||
|
||||
export async function login(baseUrl) {
|
||||
const r = await fetch(`${baseUrl}/api/auth/login`, {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(MASTER),
|
||||
})
|
||||
return (await r.json()).access_token
|
||||
}
|
||||
|
||||
/** nginx:alpine serving a waiter build (`dist`) with the waiter's own nginx.conf, /api → host backend. */
|
||||
export async function serveWaiterBuild({ name, port, dist = path.join(WAITER, 'dist'), backendPort = 8055 }) {
|
||||
const conf = path.join(OUT, `${name}.nginx.conf`)
|
||||
writeFileSync(conf, readFileSync(path.join(WAITER, 'nginx.conf'), 'utf8').replace(/http:\/\/backend:8000/g, `http://host.docker.internal:${backendPort}`))
|
||||
try { execFileSync('docker', ['rm', '-f', name], { stdio: 'ignore' }) } catch {}
|
||||
execFileSync('docker', ['run', '-d', '--rm', '--name', name, '--add-host', 'host.docker.internal:host-gateway',
|
||||
'-p', `${port}:80`, '-v', `${conf}:/etc/nginx/conf.d/default.conf:ro`, '-v', `${dist}:/usr/share/nginx/html:ro`, 'nginx:alpine'],
|
||||
{ stdio: 'ignore', env: { ...process.env, MSYS_NO_PATHCONV: '1' } })
|
||||
await waitHttp(`http://127.0.0.1:${port}/`)
|
||||
return { stop: () => { try { execFileSync('docker', ['rm', '-f', name], { stdio: 'ignore' }) } catch {} } }
|
||||
}
|
||||
|
||||
/** Vite dev server pointed at a backend by URL (VITE_SERVER_URL) — the "native-like" venue mode. */
|
||||
export async function startViteNative({ port = 5180, backendUrl }) {
|
||||
const log = openSync(path.join(OUT, `vite-${port}.log`), 'w')
|
||||
const child = spawn('npx', ['vite', '--port', String(port), '--strictPort'], {
|
||||
cwd: WAITER, shell: process.platform === 'win32', detached: process.platform !== 'win32',
|
||||
stdio: ['ignore', log, log], env: { ...process.env, VITE_SERVER_URL: backendUrl },
|
||||
})
|
||||
await waitHttp(`http://localhost:${port}/`)
|
||||
await fetch(`http://localhost:${port}/src/main.jsx`).catch(() => {}) // warm the first compile
|
||||
await sleep(3000)
|
||||
return { stop: () => killTree(child) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Isolated docker-compose stack built from this repo (its own project name,
|
||||
* images, data dir and host ports) — never touches a developer's running stack.
|
||||
*/
|
||||
export function composeStack({ project, version, siteId, http, https, manager, extraEnv = {} }) {
|
||||
const dir = path.join(OUT, project)
|
||||
mkdirSync(path.join(dir, 'data'), { recursive: true })
|
||||
mkdirSync(path.join(dir, 'fiscal'), { recursive: true })
|
||||
if (!existsSync(path.join(dir, 'data', 'pos.db'))) copyFileSync(path.join(seededDataDir(project), 'pos.db'), path.join(dir, 'data', 'pos.db'))
|
||||
copyFileSync(path.join(CS, 'logo.png'), path.join(dir, 'logo.png'))
|
||||
const fwd = p => p.replace(/\\/g, '/')
|
||||
const envFile = path.join(dir, 'e2e.env')
|
||||
writeFileSync(envFile, Object.entries({
|
||||
REGISTRY: 'e2e', VERSION: version, SITE_ID: siteId, SITE_KEY: 'x', CLOUD_URL: '', SECRET_KEY: 'e2e-secret',
|
||||
HOST_IP: '10.0.2.2', TLS_PORT: https, HTTP_PORT: http, MASTER_USERNAME: MASTER.username, MASTER_PASSWORD: MASTER.password,
|
||||
DATA_PATH: fwd(path.join(dir, 'data')), LOGO_PATH: fwd(path.join(dir, 'logo.png')), FISCAL_PATH: fwd(path.join(dir, 'fiscal')),
|
||||
...extraEnv,
|
||||
}).map(([k, v]) => `${k}=${v}`).join('\n') + '\n')
|
||||
const ports = path.join(dir, 'ports.yml')
|
||||
writeFileSync(ports, `services:
|
||||
backend:
|
||||
ports: !reset []
|
||||
waiter_pwa:
|
||||
ports: !reset []
|
||||
manager_dashboard:
|
||||
ports: !reset []
|
||||
netinfo:
|
||||
profiles: ["off"]
|
||||
proxy:
|
||||
ports: !override
|
||||
- "${http}:80"
|
||||
- "${manager}:8081"
|
||||
- "${https}:8443"
|
||||
`)
|
||||
const args = ['compose', '-p', project, '--env-file', envFile, '-f', 'docker-compose.yml', '-f', 'docker-compose.dev.yml', '-f', ports]
|
||||
const compose = (...a) => execFileSync('docker', [...args, ...a], { cwd: CS, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
|
||||
return {
|
||||
dir,
|
||||
compose,
|
||||
async up() {
|
||||
console.log(` building + starting stack ${project} (${version})…`)
|
||||
compose('build')
|
||||
compose('up', '-d', '--force-recreate')
|
||||
await waitHttp(`http://127.0.0.1:${http}/api/system/health`, true, 180_000)
|
||||
},
|
||||
down() {
|
||||
try { compose('down', '-v') } catch {}
|
||||
for (const s of ['backend', 'waiter', 'manager']) {
|
||||
try { execFileSync('docker', ['rmi', `e2e/pos-${s}:${version}`], { stdio: 'ignore' }) } catch {}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
"""License suite (KI-006): a real cloud process + a real site backend process.
|
||||
|
||||
Self-contained: a throwaway Ed25519 keypair signs the licenses — the cloud gets
|
||||
the private key via its normal LICENSE_SIGNING_KEY setting, the site gets the
|
||||
public key patched in-process by its launcher (never through configuration).
|
||||
Starts the cloud on :8101 and the site on :8055, on throwaway databases.
|
||||
|
||||
python license_e2e.py
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
||||
|
||||
E2E = Path(__file__).resolve().parent
|
||||
CS = E2E.parents[1]
|
||||
BACKEND = CS / "local_backend"
|
||||
CLOUD = Path(os.environ.get("CLOUD_DIR", CS.parent / "cloud-service" / "cloud_backend"))
|
||||
OUT = E2E / "out"
|
||||
CLOUD_URL, SITE_URL = "http://127.0.0.1:8101", "http://127.0.0.1:8055"
|
||||
MASTER = {"username": "e2e", "password": "e2e-pass-123"}
|
||||
|
||||
key = Ed25519PrivateKey.generate()
|
||||
PRIV = base64.b64encode(key.private_bytes(serialization.Encoding.Raw, serialization.PrivateFormat.Raw, serialization.NoEncryption())).decode()
|
||||
PUB = base64.b64encode(key.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)).decode()
|
||||
|
||||
OUT.mkdir(exist_ok=True)
|
||||
tmp = Path(tempfile.mkdtemp(prefix="license-", dir=OUT))
|
||||
(tmp / "data").mkdir()
|
||||
STATE = tmp / "data" / "license_state.json"
|
||||
fails = 0
|
||||
|
||||
|
||||
def seed_db(target: Path):
|
||||
template = OUT / "seed.db"
|
||||
if not template.exists():
|
||||
print(" seeding a demo database (once)…")
|
||||
partial = OUT / "seed.db.partial"
|
||||
partial.unlink(missing_ok=True)
|
||||
subprocess.run([sys.executable, "demo_seed.py"], cwd=BACKEND, check=True, stdout=subprocess.DEVNULL,
|
||||
env={**os.environ, "DATABASE_URL": f"sqlite:///{partial.as_posix()}", "PYTHONIOENCODING": "utf-8"})
|
||||
# Only a database that really holds the demo data becomes the template
|
||||
conn = sqlite3.connect(partial)
|
||||
orders = conn.execute("select count(*) from orders").fetchone()[0]
|
||||
conn.close() # Windows: the file can't be renamed while open
|
||||
if not orders:
|
||||
raise SystemExit("demo_seed.py produced no orders")
|
||||
partial.replace(template)
|
||||
shutil.copy(template, target)
|
||||
|
||||
|
||||
def check(name, got, want):
|
||||
global fails
|
||||
ok = got == want
|
||||
fails += not ok
|
||||
print(f"{'PASS' if ok else 'FAIL'} {name}: {got!r}" + ("" if ok else f" (want {want!r})"))
|
||||
|
||||
|
||||
def call(base, method, path, body=None, token=None, headers=None):
|
||||
req = urllib.request.Request(base + path, method=method, data=json.dumps(body).encode() if body is not None else None,
|
||||
headers={"Content-Type": "application/json", **({"Authorization": f"Bearer {token}"} if token else {}), **(headers or {})})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=15) as r:
|
||||
return r.status, json.loads(r.read() or b"null")
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, json.loads(e.read() or b"null")
|
||||
|
||||
|
||||
def wait_up(url):
|
||||
for _ in range(120):
|
||||
try:
|
||||
urllib.request.urlopen(url, timeout=2)
|
||||
return
|
||||
except Exception:
|
||||
time.sleep(0.5)
|
||||
raise SystemExit(f"{url} did not start")
|
||||
|
||||
|
||||
procs = {}
|
||||
|
||||
|
||||
def start_cloud():
|
||||
env = {**os.environ, "DATABASE_URL": f"sqlite:///{(tmp / 'cloud.db').as_posix()}", "ADMIN_USERNAME": "e2eadmin",
|
||||
"ADMIN_PASSWORD": "e2e-admin-pass", "SECRET_KEY": "e2e", "LICENSE_SIGNING_KEY": PRIV}
|
||||
procs["cloud"] = subprocess.Popen([sys.executable, "-m", "uvicorn", "main:app", "--port", "8101"], cwd=CLOUD, env=env,
|
||||
stdout=subprocess.DEVNULL, stderr=open(tmp / "cloud.log", "a"))
|
||||
wait_up(f"{CLOUD_URL}/docs")
|
||||
|
||||
|
||||
def start_site(site_id, site_key):
|
||||
env = {**os.environ, "DATABASE_URL": f"sqlite:///{(tmp / 'data' / 'pos.db').as_posix()}", "CLOUD_URL": CLOUD_URL,
|
||||
"SITE_ID": site_id, "SITE_KEY": site_key, "SECRET_KEY": "e2e-site",
|
||||
"MASTER_USERNAME": MASTER["username"], "MASTER_PASSWORD": MASTER["password"]}
|
||||
launcher = (f"import services.license as L; L.LICENSE_PUBLIC_KEY = {PUB!r}; "
|
||||
"import uvicorn; uvicorn.run('main:app', host='127.0.0.1', port=8055)")
|
||||
procs["site"] = subprocess.Popen([sys.executable, "-c", launcher], cwd=BACKEND, env=env,
|
||||
stdout=subprocess.DEVNULL, stderr=open(tmp / "site.log", "a"))
|
||||
wait_up(f"{SITE_URL}/api/system/health")
|
||||
time.sleep(2) # first heartbeat attempt + apply_license
|
||||
|
||||
|
||||
def stop(name):
|
||||
p = procs.pop(name, None)
|
||||
if p:
|
||||
p.terminate()
|
||||
p.wait(10)
|
||||
|
||||
|
||||
def status():
|
||||
_, tok = call(SITE_URL, "POST", "/api/auth/login", MASTER)
|
||||
return call(SITE_URL, "GET", "/api/system/status", token=tok["access_token"])[1], tok["access_token"]
|
||||
|
||||
|
||||
def edit_state(fn):
|
||||
s = json.loads(STATE.read_text())
|
||||
fn(s)
|
||||
STATE.write_text(json.dumps(s))
|
||||
|
||||
|
||||
try:
|
||||
seed_db(tmp / "data" / "pos.db")
|
||||
start_cloud()
|
||||
_, admin = call(CLOUD_URL, "POST", "/api/auth/login", {"username": "e2eadmin", "password": "e2e-admin-pass"})
|
||||
A = admin["access_token"]
|
||||
|
||||
def cloud_admin(method, path, body=None):
|
||||
code, out = call(CLOUD_URL, method, path, body, token=A)
|
||||
assert code == 200, f"cloud {method} {path} -> {code} {out}"
|
||||
return out
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
_, site = call(CLOUD_URL, "POST", "/api/sites/", {"name": "E2E Taverna", "owner_name": "x", "contact_email": "x@x.gr",
|
||||
"license_expires_at": (now + timedelta(days=730)).isoformat()}, token=A)
|
||||
SID, SKEY = site["site_id"], site["secret_key"]
|
||||
_, hb = call(CLOUD_URL, "POST", "/api/heartbeat/", {"version": "e2e"}, headers={"X-Site-ID": SID, "X-Site-Key": SKEY})
|
||||
check("cloud: heartbeat carries a signed license token", bool(hb.get("license_token")) and hb["license_token"].count(".") == 1, True)
|
||||
|
||||
print("── 1. online")
|
||||
start_site(SID, SKEY)
|
||||
st, tok = status()
|
||||
check("verified signed license, licensed", (st["license_verified"], st["licensed"], st["lock_reason"]), (True, True, None))
|
||||
check("state file in the data dir holds the token", STATE.exists() and bool(json.loads(STATE.read_text()).get("license_token")), True)
|
||||
|
||||
print("── 2. cloud gone, 400 days since last contact")
|
||||
stop("cloud"); stop("site")
|
||||
edit_state(lambda s: s.update(last_sync=(now - timedelta(days=400)).isoformat()))
|
||||
start_site(SID, SKEY)
|
||||
st, tok = status()
|
||||
check("still licensed (no 72h rule)", (st["licensed"], st["sync_failed"], st["offline_days"] >= 399), (True, True, True))
|
||||
check("…and fully usable", call(SITE_URL, "GET", "/api/tables/", token=tok)[0], 200)
|
||||
|
||||
print("── 3. tampered license file")
|
||||
stop("site")
|
||||
good = json.loads(STATE.read_text())["license_token"]
|
||||
|
||||
def tamper(s):
|
||||
body, sig = s["license_token"].split(".")
|
||||
p = json.loads(base64.urlsafe_b64decode(body + "=" * (-len(body) % 4)))
|
||||
p["expires_at"] = "2099-01-01T00:00:00+00:00"
|
||||
s["license_token"] = base64.urlsafe_b64encode(json.dumps(p).encode()).rstrip(b"=").decode() + "." + sig
|
||||
edit_state(tamper)
|
||||
start_site(SID, SKEY)
|
||||
st, tok = status()
|
||||
check("edited file → not licensed, 'unverified'", (st["licensed"], st["lock_reason"]), (False, "unverified"))
|
||||
check("…requests refused (402)", call(SITE_URL, "GET", "/api/tables/", token=tok)[0], 402)
|
||||
stop("site")
|
||||
edit_state(lambda s: s.update(license_token=good))
|
||||
|
||||
print("── 4. clock set back (newest order 30 days in the 'future')")
|
||||
db = sqlite3.connect(tmp / "data" / "pos.db")
|
||||
row = db.execute("SELECT id, opened_at FROM orders ORDER BY id DESC LIMIT 1").fetchone()
|
||||
db.execute("UPDATE orders SET opened_at=? WHERE id=?", ((now + timedelta(days=30)).strftime("%Y-%m-%d %H:%M:%S"), row[0]))
|
||||
db.commit()
|
||||
start_site(SID, SKEY)
|
||||
st, tok = status()
|
||||
check("blocked, reason 'clock'", (st["licensed"], st["lock_reason"]), (False, "clock"))
|
||||
stop("site")
|
||||
db.execute("UPDATE orders SET opened_at=? WHERE id=?", (row[1], row[0]))
|
||||
db.commit()
|
||||
db.close()
|
||||
edit_state(lambda s: s.update(time_high_water=None))
|
||||
|
||||
print("── 5. expired past grace while a workday is open")
|
||||
start_cloud()
|
||||
start_site(SID, SKEY)
|
||||
st, tok = status()
|
||||
check("licensed again after restore", st["licensed"], True)
|
||||
code, _ = call(SITE_URL, "POST", "/api/business-day/open", {}, token=tok)
|
||||
check("workday opened", code in (200, 201), True)
|
||||
cloud_admin("PUT", f"/api/sites/{SID}", {"license_expires_at": (now - timedelta(days=10)).isoformat()})
|
||||
call(SITE_URL, "POST", "/api/system/sync-license", token=tok)
|
||||
st, tok = status()
|
||||
check("grace over, workday open → keeps running", (st["licensed"], st["grace_over"]), (True, True))
|
||||
check("workday closed", call(SITE_URL, "POST", "/api/business-day/close", {"force": True}, token=tok)[0], 200)
|
||||
st, tok = status()
|
||||
check("after closing → blocked, 'expired'", (st["licensed"], st["lock_reason"]), (False, "expired"))
|
||||
|
||||
print("── 6. renewal")
|
||||
cloud_admin("PUT", f"/api/sites/{SID}", {"license_expires_at": (now - timedelta(days=2)).isoformat()})
|
||||
call(SITE_URL, "POST", "/api/system/sync-license", token=tok)
|
||||
st, tok = status()
|
||||
check("expired 2 days ago → grace, 3 days left", (st["licensed"], st["grace_days_remaining"]), (True, 3))
|
||||
cloud_admin("PUT", f"/api/sites/{SID}", {"license_expires_at": (now + timedelta(days=365)).isoformat()})
|
||||
call(SITE_URL, "POST", "/api/system/sync-license", token=tok)
|
||||
st, tok = status()
|
||||
check("renewed for a year", (st["licensed"], st["days_until_expiry"] in (363, 364)), (True, True))
|
||||
|
||||
print("── 7. remote lock")
|
||||
cloud_admin("POST", f"/api/sites/{SID}/lock", {"reason": "e2e"})
|
||||
call(SITE_URL, "POST", "/api/system/sync-license", token=tok)
|
||||
st, tok = status()
|
||||
check("cloud lock (no workday) → locked", (st["locked"], st["lock_reason"]), (True, "admin"))
|
||||
cloud_admin("POST", f"/api/sites/{SID}/unlock", None)
|
||||
call(SITE_URL, "POST", "/api/system/sync-license", token=tok)
|
||||
st, tok = status()
|
||||
check("cloud unlock → running again", (st["locked"], st["licensed"]), (False, True))
|
||||
finally:
|
||||
for n in list(procs):
|
||||
stop(n)
|
||||
|
||||
print(f"\n{'✗' if fails else '✓'} license: {fails} failure(s) | logs: {tmp}")
|
||||
sys.exit(1 if fails else 0)
|
||||
Generated
+47
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"name": "xenia-e2e",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "xenia-e2e",
|
||||
"dependencies": {
|
||||
"fflate": "^0.8.3",
|
||||
"playwright": "^1.63.0"
|
||||
}
|
||||
},
|
||||
"node_modules/fflate": {
|
||||
"version": "0.8.3",
|
||||
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
|
||||
"integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/playwright": {
|
||||
"version": "1.63.0",
|
||||
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz",
|
||||
"integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright-core": "1.63.0"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright-core": {
|
||||
"version": "1.63.0",
|
||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",
|
||||
"integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"playwright-core": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"name": "xenia-e2e",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "End-to-end suites for client-services (see README.md)",
|
||||
"scripts": {
|
||||
"all": "node run-all.mjs",
|
||||
"all:no-android": "node run-all.mjs --no-android",
|
||||
"install-sh": "node install.mjs",
|
||||
"license": "python license_e2e.py",
|
||||
"browser": "node browser.mjs",
|
||||
"android": "node android.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"playwright": "^1.63.0",
|
||||
"fflate": "^0.8.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// Runs every suite in order, fastest first, and prints a summary.
|
||||
// node run-all.mjs everything (Android included)
|
||||
// node run-all.mjs --no-android skip the emulator suite
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { BACKEND, E2E, PYTHON, WAITER } from './lib/env.mjs'
|
||||
|
||||
const shell = process.platform === 'win32'
|
||||
const suites = [
|
||||
['unit: local_backend (pytest)', PYTHON, ['-m', 'pytest', 'tests', '-q'], BACKEND],
|
||||
['unit: waiter_pwa (node --test)', 'npm', ['test', '--silent'], WAITER],
|
||||
['install.sh', 'node', ['install.mjs'], E2E],
|
||||
['license (cloud + site)', PYTHON, ['license_e2e.py'], E2E],
|
||||
['browser', 'node', ['browser.mjs'], E2E],
|
||||
]
|
||||
if (!process.argv.includes('--no-android')) suites.push(['android (emulator)', 'node', ['android.mjs'], E2E])
|
||||
|
||||
const results = []
|
||||
for (const [name, cmd, args, cwd] of suites) {
|
||||
console.log(`\n══════ ${name}`)
|
||||
const t0 = Date.now()
|
||||
const r = spawnSync(cmd, args, { cwd, stdio: 'inherit', shell, env: { ...process.env, PYTHONIOENCODING: 'utf-8' } })
|
||||
results.push([name, r.status === 0, Math.round((Date.now() - t0) / 1000)])
|
||||
}
|
||||
console.log('\n══════ summary')
|
||||
for (const [name, ok, s] of results) console.log(`${ok ? '✓' : '✗'} ${name.padEnd(34)} ${s}s`)
|
||||
process.exit(results.every(([, ok]) => ok) ? 0 : 1)
|
||||
Reference in New Issue
Block a user