Compare commits

...
5 Commits
Author SHA1 Message Date
bonaminandClaude Opus 5.5 584dd1e510 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>
2026-09-28 23:38:18 +03:00
bonaminandClaude Opus 5.5 f00c99fd36 test: unit tests for licensing, LAN IP, TLS identity and rediscovery
- local_backend/tests (pytest, 48 tests, <1s): license token verify/evaluate
  (tamper, other site/key, offline, grace, workday deferral, clock, transition),
  netinfo detection on fake sysfs (VPN/tunnel/WiFi/link-local), LAN-IP
  resolver priority + mismatch + staleness + override validation, TLS
  identity create/restart/renew-same-key/foreign cert (+ openssl pin check)
- waiter_pwa/tests (node --test, 7 tests): subnet candidates, scan picks only
  this venue, early stop, progress
- requirements-dev.txt (pytest), npm test, .pytest_cache ignored

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 23:33:16 +03:00
bonaminandClaude Opus 5.5 ffca0ace43 refactor: keep pure logic importable in tests on any OS
- netinfo_helper imports the Linux-only fcntl inside ipv4_of(), so detect()
  can be unit-tested on Windows/macOS
- SUPPORTED_API_VERSIONS moves to src/native/apiVersion.js (no Vite-only
  imports), so rediscovery.js runs under plain Node

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 23:33:16 +03:00
bonaminandClaude Opus 5.5 d80f53a31e fix(backend): licensing off when no CLOUD_URL is configured (pre-KI-006 parity)
Before KI-006 an install without CLOUD_URL (dev, demos, test stacks) was
simply licensed; after it, a SITE_ID without a cloud counted as
'unverified' and blocked everything. Real sites always have both set, and
blanking CLOUD_URL is no stronger than blanking SITE_ID (already possible).
verify_token() now reads the built-in public key at call time so the e2e
suite can swap it in-process for a throwaway key (never via configuration).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 23:33:16 +03:00
bonaminandClaude Opus 5.5 12fdea0914 fix(backend): demo_seed.py imports every model (crashed since pricing/deals)
order_items.deal_id references deals (models.pricing), which demo_seed never
imported, so create_all failed and the script could not seed a fresh DB.
Also registers prep_zone, chat and recovery_code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 23:33:16 +03:00
29 changed files with 1713 additions and 10 deletions
+3
View File
@@ -37,3 +37,6 @@ data/
certs/*.pem
certs/*.crt
certs/*.key
# Test caches
.pytest_cache/
+7 -1
View File
@@ -135,7 +135,13 @@ Every bundle must call `markBundleReady()` at start (`BundleSync` does this); ot
`android/app/src/main/assets/public` and the generated configs are rebuilt on every sync, so never edit them. Native changes go in `android/app/src/main/**` (manifest, res, java) or `capacitor.config.json`.
## Testing
There is no automated test suite yet. Before committing:
Automated tests cover the native-app/LAN work and licensing. See **[tests/e2e/README.md](../tests/e2e/README.md)**.
- **Unit (seconds):** `python -m pytest tests -q` in `local_backend/`, and `npm test` in `waiter_pwa/`.
- **End-to-end:** `node run-all.mjs` in `tests/e2e/`. That covers install.sh, licensing with a real cloud, browser modes, and the Android emulator suites. `--no-android` skips the emulator.
**CS-11. Tests follow the code.** When you change something a test covers (licensing, LAN IP, TLS, pairing, rediscovery, bundles, install.sh, the proxy config), run its suite and update the test in the same commit. Run `node run-all.mjs` before every release.
Everything else still needs manual checks before committing:
- the backend starts cleanly against an **existing** `pos.db` (this catches missing migrations)
- `npm run build` passes for any frontend you touched
- the flow was exercised by hand (the parent's `PLANS AND STRATEGIES/TESTING_CHECKLIST.md`)
+4
View File
@@ -49,6 +49,10 @@ import models.tabs # noqa: F401
import models.schedule # noqa: F401
import models.waste # noqa: F401
import models.reservation # noqa: F401
import models.pricing # noqa: F401 — order_items.deal_id → deals
import models.prep_zone # noqa: F401
import models.chat # noqa: F401
import models.recovery_code # noqa: F401
from models.user import User, WaiterZone
from models.table import TableGroup, Table
+3
View File
@@ -0,0 +1,3 @@
# Test-only dependencies (python -m pytest tests -q)
-r requirements.txt
pytest==8.3.3
+2 -2
View File
@@ -74,8 +74,8 @@ def _latest_activity(db) -> datetime | None:
def apply_license(now: datetime | None = None) -> None:
"""Re-evaluate the license from the stored signed token (no network)."""
if not settings.SITE_ID:
return # dev / unregistered install: licensing off, as before
if not settings.SITE_ID or not settings.CLOUD_URL:
return # dev / unregistered / no cloud configured: licensing off, as before KI-006
from database import SessionLocal
from models.business_day import BusinessDay
+5 -2
View File
@@ -58,8 +58,11 @@ def parse_dt(value) -> datetime | None:
return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
def verify_token(token: str | None, site_id: str, public_key_b64: str = LICENSE_PUBLIC_KEY) -> dict | None:
"""Payload of a genuine token for this site, else None."""
def verify_token(token: str | None, site_id: str, public_key_b64: str | None = None) -> dict | None:
"""Payload of a genuine token for this site, else None. The key defaults to
the built-in LICENSE_PUBLIC_KEY (read at call time, so the e2e suite can
swap it in-process for a throwaway test key — never via configuration)."""
public_key_b64 = public_key_b64 or LICENSE_PUBLIC_KEY
if not token or "." not in token:
return None
body, _, sig = token.partition(".")
+1 -1
View File
@@ -21,7 +21,6 @@ reports no IP instead of a wrong one.
Standalone on purpose: standard library only, no app imports, no database.
Run: python -m services.netinfo_helper
"""
import fcntl
import json
import os
import platform
@@ -37,6 +36,7 @@ SIOCGIFADDR = 0x8915
def ipv4_of(ifname: str) -> str | None:
"""Primary IPv4 address of an interface, or None if it has none."""
import fcntl # Linux-only; imported here so detect() stays testable anywhere
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
try:
packed = fcntl.ioctl(s.fileno(), SIOCGIFADDR, struct.pack("256s", ifname[:15].encode()))
+10
View File
@@ -0,0 +1,10 @@
"""Fast unit tests for local_backend — no server, no database, no network.
Run from local_backend/:
pip install -r requirements-dev.txt
python -m pytest tests -q
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+103
View File
@@ -0,0 +1,103 @@
"""Which LAN IP phones get: netinfo detection (fake sysfs) + resolver priority (services/lan_ip.py)."""
import json
import os
from datetime import datetime, timedelta, timezone
import pytest
from services.lan_ip import read_detected, resolve_lan_ip, validate_lan_ip
from services.netinfo_helper import detect
ADDRS = {"eth0": "10.98.20.70", "wlan0": "192.168.1.44", "wg0": "10.9.9.2", "docker0": "172.17.0.1",
"tailscale0": "100.101.1.2", "enp3s0": "169.254.10.1"}
def fake_host(tmp_path, physical, default_if):
"""sysfs where only `physical` interfaces have a device/ entry, and a route table."""
sysnet = tmp_path / "net"
for name in ["lo", "docker0", "wg0", "tailscale0"]:
(sysnet / name).mkdir(parents=True)
for name in physical:
(sysnet / name / "device").mkdir(parents=True)
route = tmp_path / "route"
lines = ["Iface\tDestination\tGateway\tFlags\tRefCnt\tUse\tMetric\tMask"]
if default_if:
lines.append(f"{default_if}\t00000000\t0114620A\t0003\t0\t0\t100\t00000000")
route.write_text("\n".join(lines) + "\n")
return str(sysnet), str(route)
# ── netinfo detection: physical NIC only, never a VPN ────────────────────────
@pytest.mark.parametrize("physical,default_if,want", [
(["eth0"], "eth0", "10.98.20.70"), # wg-quick full tunnel: main default via eth0
(["eth0"], "wg0", "10.98.20.70"), # tunnel owns the default route
(["eth0"], "tailscale0", "10.98.20.70"),
(["eth0"], None, "10.98.20.70"), # offline LAN-only box
(["wlan0"], "wlan0", "192.168.1.44"), # WiFi-only server
(["eth0", "wlan0"], "wlan0", "192.168.1.44"), # two NICs: the default-route one wins
(["enp3s0", "wlan0"], None, "192.168.1.44"), # link-local address ignored
([], "wg0", None), # no physical NIC → nothing (never the VPN)
])
def test_detect_physical_nic(tmp_path, physical, default_if, want):
sysnet, route = fake_host(tmp_path, physical, default_if)
assert detect(sysnet, route, ipv4=ADDRS.get)["ip"] == want
# ── resolver priority + mismatch ─────────────────────────────────────────────
FRESH = {"ip": "10.98.20.70", "candidates": [{"iface": "eth0", "ip": "10.98.20.70"}], "stale": False}
def test_detected_beats_stale_host_ip():
r = resolve_lan_ip(override=None, detected=FRESH, env="10.98.20.99")
assert (r["effective"], r["source"]) == ("10.98.20.70", "detected")
def test_override_wins_and_flags_mismatch():
r = resolve_lan_ip(override="192.168.1.50", detected=FRESH, env=None)
assert (r["effective"], r["source"], r["mismatch"]) == ("192.168.1.50", "override", True)
def test_override_matching_nic_no_mismatch():
assert resolve_lan_ip(override="10.98.20.70", detected=FRESH, env=None)["mismatch"] is False
def test_docker_desktop_falls_back_to_host_ip():
r = resolve_lan_ip(override=None, detected={"ip": None, "unsupported": "docker-desktop", "candidates": [], "stale": False},
env="10.98.20.70")
assert (r["effective"], r["source"], r["detection"]) == ("10.98.20.70", "env", "unsupported")
def test_stale_detection_ignored():
r = resolve_lan_ip(override=None, detected={**FRESH, "stale": True}, env="10.98.20.70")
assert (r["source"], r["detection"]) == ("env", "stale")
def test_nothing_known():
r = resolve_lan_ip(override=None, detected=None, env=None)
assert (r["effective"], r["source"], r["detection"]) == (None, None, "unavailable")
def test_read_detected_staleness(tmp_path):
f = tmp_path / "host_ip.json"
now = datetime.now(timezone.utc)
f.write_text(json.dumps({"ip": "10.98.20.70", "candidates": [], "detected_at": (now - timedelta(seconds=30)).isoformat()}))
assert read_detected(str(f), now)["stale"] is False
f.write_text(json.dumps({"ip": "10.98.20.70", "candidates": [], "detected_at": (now - timedelta(minutes=10)).isoformat()}))
assert read_detected(str(f), now)["stale"] is True
assert read_detected(os.path.join(tmp_path, "missing.json"), now) is None
# ── override validation ──────────────────────────────────────────────────────
@pytest.mark.parametrize("ip,ok", [
("192.168.1.50", True), (" 10.0.0.5 ", True), ("172.16.4.4", True),
("8.8.8.8", False), ("127.0.0.1", False), ("169.254.1.1", False), ("fd00::1", False), ("abc", False),
])
def test_validate_lan_ip(ip, ok):
if ok:
validate_lan_ip(ip)
else:
with pytest.raises(ValueError):
validate_lan_ip(ip)
+130
View File
@@ -0,0 +1,130 @@
"""Offline-capable licensing rules (services/license.py, KI-006).
Tokens are signed with a throwaway key here — the production signing key is
never needed; verify_token() takes the public key as a parameter.
"""
import base64
import json
from datetime import datetime, timedelta
import pytest
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from services.license import LICENSE_PUBLIC_KEY, evaluate, verify_token
KEY = Ed25519PrivateKey.generate()
PUB = base64.b64encode(KEY.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)).decode()
ISSUED = datetime.fromisoformat("2026-09-28T12:00:00+00:00")
EXPIRES = datetime.fromisoformat("2027-09-28T00:00:00+00:00")
def b64(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def make_token(signer=KEY, **overrides) -> str:
payload = {"v": 1, "site_id": "site-A", "active": True, "locked": False, "lock_reason": None,
"expires_at": EXPIRES.isoformat(), "issued_at": ISSUED.isoformat(), **overrides}
body = b64(json.dumps(payload, separators=(",", ":"), sort_keys=True).encode())
return f"{body}.{b64(signer.sign(body.encode()))}"
@pytest.fixture
def payload():
return verify_token(make_token(), "site-A", PUB)
# ── verify_token ─────────────────────────────────────────────────────────────
def test_genuine_token_accepted(payload):
assert payload is not None and payload["expires_at"] == EXPIRES.isoformat()
def test_edited_expiry_rejected(payload):
_, sig = make_token().split(".")
forged = b64(json.dumps({**payload, "expires_at": "2099-01-01T00:00:00+00:00"},
separators=(",", ":"), sort_keys=True).encode())
assert verify_token(f"{forged}.{sig}", "site-A", PUB) is None
def test_token_for_another_site_rejected():
assert verify_token(make_token(site_id="site-B"), "site-A", PUB) is None
def test_token_signed_by_another_key_rejected():
assert verify_token(make_token(signer=Ed25519PrivateKey.generate()), "site-A", PUB) is None
@pytest.mark.parametrize("junk", [None, "", "not.a.token", "abc"])
def test_garbage_rejected(junk):
assert verify_token(junk, "site-A", PUB) is None
def test_production_public_key_is_ed25519():
assert len(base64.b64decode(LICENSE_PUBLIC_KEY)) == 32
# ── evaluate: offline ────────────────────────────────────────────────────────
def test_364_days_offline_still_licensed(payload):
r = evaluate(payload, ISSUED + timedelta(days=364), ISSUED, workday_open=False)
assert (r["licensed"], r["license_problem"]) == (True, None)
# ── evaluate: expiry + grace, never mid-service ──────────────────────────────
def test_two_days_after_expiry_is_grace(payload):
r = evaluate(payload, EXPIRES + timedelta(days=2), ISSUED, workday_open=False)
assert (r["licensed"], r["grace_over"], r["grace_days_remaining"]) == (True, False, 3)
def test_grace_over_without_workday_blocks(payload):
r = evaluate(payload, EXPIRES + timedelta(days=6), ISSUED, workday_open=False)
assert (r["licensed"], r["license_problem"], r["grace_over"]) == (False, "expired", True)
def test_grace_over_with_open_workday_keeps_running(payload):
r = evaluate(payload, EXPIRES + timedelta(days=6), ISSUED, workday_open=True)
assert (r["licensed"], r["grace_over"]) == (True, True)
def test_deactivated_site_blocks():
p = verify_token(make_token(active=False), "site-A", PUB)
r = evaluate(p, ISSUED + timedelta(days=1), ISSUED, workday_open=False)
assert (r["licensed"], r["license_problem"]) == (False, "inactive")
# ── evaluate: clock set back ─────────────────────────────────────────────────
def test_clock_before_newest_activity_blocks(payload):
floor = ISSUED + timedelta(days=100)
r = evaluate(payload, floor - timedelta(days=30), floor, workday_open=False)
assert (r["licensed"], r["license_problem"]) == (False, "clock")
def test_small_clock_skew_tolerated(payload):
floor = ISSUED + timedelta(days=100)
assert evaluate(payload, floor - timedelta(hours=12), floor, workday_open=False)["licensed"]
def test_clock_before_signed_issue_time_blocks(payload):
r = evaluate(payload, ISSUED - timedelta(days=5), ISSUED, workday_open=False)
assert r["license_problem"] == "clock"
# ── evaluate: no genuine token ───────────────────────────────────────────────
def test_transition_old_cloud_recent_ok():
r = evaluate(None, ISSUED, None, False, legacy_ok_at=ISSUED - timedelta(hours=10))
assert (r["licensed"], r["license_problem"]) == (True, None)
def test_transition_old_cloud_stale():
r = evaluate(None, ISSUED, None, False, legacy_ok_at=ISSUED - timedelta(hours=80))
assert (r["licensed"], r["license_problem"]) == (False, "unverified")
def test_never_licensed_blocks():
r = evaluate(None, ISSUED, None, False)
assert (r["licensed"], r["license_problem"]) == (False, "unverified")
+61
View File
@@ -0,0 +1,61 @@
"""The server's self-managed TLS identity (services/tls_identity.py, plan step 7)."""
import shutil
import subprocess
from datetime import datetime, timedelta, timezone
import pytest
from cryptography import x509
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ec
from services.tls_identity import _issue_cert, ensure_tls_identity, spki_sha256
NOW = datetime.now(timezone.utc)
@pytest.fixture(autouse=True)
def host_ip(monkeypatch):
monkeypatch.setenv("HOST_IP", "192.168.1.50")
def cert_of(d):
return x509.load_pem_x509_certificate((d / "cert.pem").read_bytes())
def test_first_run_creates_ec_key_and_10y_cert(tmp_path):
r = ensure_tls_identity(tmp_path, NOW)
assert r["created"]
assert isinstance(serialization.load_pem_private_key((tmp_path / "key.pem").read_bytes(), None), ec.EllipticCurvePrivateKey)
assert round((cert_of(tmp_path).not_valid_after_utc - NOW).days / 365) == 10
sans = [str(n.value) for n in cert_of(tmp_path).extensions.get_extension_for_class(x509.SubjectAlternativeName).value]
assert "192.168.1.50" in sans
@pytest.mark.skipif(not shutil.which("openssl"), reason="openssl CLI not available")
def test_pin_matches_openssl_spki(tmp_path):
pin = ensure_tls_identity(tmp_path, NOW)["spki_sha256"]
cmd = ("openssl x509 -in cert.pem -pubkey -noout | openssl pkey -pubin -outform der"
" | openssl dgst -sha256 -binary | openssl base64 -A")
assert subprocess.run(cmd, shell=True, cwd=tmp_path, capture_output=True, text=True).stdout.strip() == pin
def test_restart_changes_nothing(tmp_path):
first = ensure_tls_identity(tmp_path, NOW)
again = ensure_tls_identity(tmp_path, NOW)
assert (again["created"], again["renewed"], again["spki_sha256"]) == (False, False, first["spki_sha256"])
def test_renewal_keeps_the_key(tmp_path):
first = ensure_tls_identity(tmp_path, NOW)
serial = cert_of(tmp_path).serial_number
later = ensure_tls_identity(tmp_path, NOW + timedelta(days=365 * 8 + 30)) # < 2 years left
assert later["renewed"] and later["spki_sha256"] == first["spki_sha256"]
assert cert_of(tmp_path).serial_number != serial
def test_foreign_cert_replaced(tmp_path):
first = ensure_tls_identity(tmp_path, NOW)
other = ec.generate_private_key(ec.SECP256R1())
(tmp_path / "cert.pem").write_bytes(_issue_cert(other, None, NOW).public_bytes(serialization.Encoding.PEM))
again = ensure_tls_identity(tmp_path, NOW)
assert spki_sha256(cert_of(tmp_path).public_key()) == first["spki_sha256"] == again["spki_sha256"]
+2
View File
@@ -0,0 +1,2 @@
node_modules/
out/
+58
View File
@@ -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.
+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)
+121
View File
@@ -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)
+64
View File
@@ -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)
+124
View File
@@ -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'))"
+41
View File
@@ -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() }
}
+71
View File
@@ -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
}
+154
View File
@@ -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 {}
}
},
}
}
+234
View File
@@ -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)
+47
View File
@@ -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"
}
}
}
}
+18
View File
@@ -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"
}
}
+26
View File
@@ -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)
+2 -1
View File
@@ -10,7 +10,8 @@
"preview": "vite preview",
"build:native": "vite build --mode native && cap sync android",
"apk:debug": "npm run build:native && node scripts/build-apk.mjs debug",
"apk:release": "npm run build:native && node scripts/build-apk.mjs release"
"apk:release": "npm run build:native && node scripts/build-apk.mjs release",
"test": "node --test \"tests/*.test.mjs\""
},
"dependencies": {
"@capacitor/android": "^8.5.2",
+3
View File
@@ -0,0 +1,3 @@
// api_version values (from /api/system/identity) this build can talk to.
// Own module (no Vite-only imports) so the pure native logic stays testable in Node.
export const SUPPORTED_API_VERSIONS = [1]
+3 -2
View File
@@ -13,8 +13,9 @@
import { deliveryMode, saveVenue } from '../config/server'
import { syncTrustedKeys, tlsBaseUrl } from './tls'
// api_version values (from /api/system/identity) this build can talk to.
export const SUPPORTED_API_VERSIONS = [1]
import { SUPPORTED_API_VERSIONS } from './apiVersion'
export { SUPPORTED_API_VERSIONS }
const PROBE_TIMEOUT_MS = 5000
+1 -1
View File
@@ -11,7 +11,7 @@
* (new router, different subnet) still has the manual fallback: scan the QR.
* Contract: docs/reference/lan-access.md
*/
import { SUPPORTED_API_VERSIONS } from './pairing'
import { SUPPORTED_API_VERSIONS } from './apiVersion.js'
const PROBE_TIMEOUT_MS = 1500
// The first TLS connection to a venue server in a fresh app process takes ~2s
+56
View File
@@ -0,0 +1,56 @@
// Server rediscovery scan (src/native/rediscovery.js, plan step 5) — pure logic, fake network.
// Run: npm test
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { scanForVenue, subnetCandidates } from '../src/native/rediscovery.js'
test('same-/24 candidates, nearest first, old host excluded', () => {
const c = subnetCandidates('http://192.168.1.50')
assert.equal(c.length, 253)
assert.deepEqual(c.slice(0, 4), ['http://192.168.1.49', 'http://192.168.1.51', 'http://192.168.1.48', 'http://192.168.1.52'])
assert.ok(!c.includes('http://192.168.1.50'))
})
test('scheme and port are kept (plain HTTP and the TLS entry)', () => {
assert.equal(subnetCandidates('http://10.0.0.7:8080')[0], 'http://10.0.0.6:8080')
assert.equal(subnetCandidates('https://10.0.0.7:8443')[0], 'https://10.0.0.6:8443')
})
test('hostnames and garbage are never scanned', () => {
assert.deepEqual(subnetCandidates('http://waiter.example.gr'), [])
assert.deepEqual(subnetCandidates('not a url'), [])
})
const network = {
'http://192.168.1.12': { app: 'xenia-pos', site_id: 'OTHER-venue', api_version: 1 },
'http://192.168.1.77': { app: 'xenia-pos', site_id: 'MY-venue', api_version: 1 },
}
function fakeProbe() {
const calls = { n: 0 }
const probe = async origin => { calls.n++; await new Promise(r => setTimeout(r, 1)); return network[origin] ?? null }
return { probe, calls }
}
test('finds this venue at its new address and stops early', async () => {
const { probe, calls } = fakeProbe()
assert.equal(await scanForVenue('http://192.168.1.50', 'MY-venue', { probe, concurrency: 8 }), 'http://192.168.1.77')
assert.ok(calls.n < 253)
})
test('another venue\'s server is never chosen', async () => {
const { probe } = fakeProbe()
assert.equal(await scanForVenue('http://192.168.1.50', 'NOBODY', { probe, concurrency: 8 }), null)
})
test('no site id → no scan', async () => {
const { probe, calls } = fakeProbe()
assert.equal(await scanForVenue('http://192.168.1.50', null, { probe }), null)
assert.equal(calls.n, 0)
})
test('progress is reported for every probe', async () => {
const { probe } = fakeProbe()
let progress = 0
await scanForVenue('http://192.168.1.50', 'NOBODY', { probe, concurrency: 16, onProgress: () => progress++ })
assert.equal(progress, 253)
})