Files
xenia-pos-local/tests/e2e/lib/proc.mjs
T
bonaminandClaude Opus 5.5 3a522e457d feat(backend): support access by offline challenge codes replaces the master account
Platform v2 step 1.10 (APPS_PLATFORM D-16, section 6.5).
- POST /api/auth/support/challenge (public): an 8-character challenge, stored 15 min
  (support_challenges, revision 0009; at most 5 open). POST /api/auth/support/verify
  {challenge, code}: code = base32(HMAC(SUPPORT_SECRET, site_id + challenge))[:10];
  single use, 5 wrong codes burn the challenge. Opens a 4 h support session
  (client=support, synthetic superadmin) with a hard end: sessions.expires_at.
- core/support_codes.py (stdlib only) is the derivation; tools/support_code.py
  (--init, --site-secret <SITE_ID>, <SITE_ID> <CHALLENGE>) uses it on the builder's
  machine with the master key in %USERPROFILE%/.xenia/support_master_key.txt.
- MASTER_USERNAME/MASTER_PASSWORD removed (config, login, docker-compose.yml,
  .env.example); SUPPORT_SECRET added; install.sh asks for it.
- e2e: backends get SUPPORT_SECRET from a test master key and log in with challenge
  codes (lib/support.mjs, license_e2e.py); install.mjs expects the new prompt.
- Pack rule CS-15.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 10:52:16 +02:00

160 lines
8.1 KiB
JavaScript

// 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, OUT, PYTHON, WAITER, sleep } from './env.mjs'
import { SUPPORT_MASTER, siteSecret, supportLogin } from './support.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')
// A template seeded by v1 code has no alembic_version: v2 refuses it (CS-1), so reseed
if (existsSync(template)) {
const v2 = execFileSync(PYTHON, ['-c', 'import sqlite3, sys; print(sqlite3.connect(sys.argv[1]).execute("select count(*) from sqlite_master where name=?", ("alembic_version",)).fetchone()[0])', template], { encoding: 'utf8' })
if (!Number(v2)) { console.log(' seed.db was made by v1 code - reseeding'); rmSync(template, { force: true }) }
}
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',
// No cloud = a test backend: licensing off (every module). The license suite passes a cloudUrl.
LICENSE_MODE: cloudUrl ? 'enforced' : 'off',
SUPPORT_SECRET: siteSecret(SUPPORT_MASTER, siteId), ...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(() => {}) } }
}
/** A superadmin token for a test backend, through support access (challenge code). */
export const login = baseUrl => supportLogin(baseUrl)
/** 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',
LICENSE_MODE: 'off',
HOST_IP: '10.0.2.2', TLS_PORT: https, HTTP_PORT: http, SUPPORT_SECRET: siteSecret(SUPPORT_MASTER, siteId),
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 {}
}
},
}
}