Platform v2 step 1.4 (APPS_PLATFORM D-3..D-6, D-21, §5). - core/modules/entitlements.py: compute() turns the evaluated license into per-module grants: the v2 token's `modules` map (own `exp` with the 5-day grace, never cut mid-service) + the free tier; no/invalid token, expired after grace, inactive, locked or clock tampering -> free tier only; core always. limit(module, name) with token value -> manifest licensed_default -> free value; None = unlimited. LICENSE_MODE=off (dev/test only) = everything - module gating says why: module.not_licensed (402, the first unlicensed module in the dependency chain) before module.disabled (403) - services/license.py accepts only v2 tokens with a modules map; the v1 "legacy unsigned 72h" path is gone - apply_license() always installs entitlements (startup before workers, every heartbeat, workday close); workers follow license changes - the global license middleware is deleted (no more whole-API 402/423); license_state moved to services/license_state.py - history_days enforced in every report/history endpoint: lower date bounds clamped (also when no "from" is given), and business days older than the limit refused by id (license.history_limited); data is never deleted - bootstrap/modules API show license mode, entitlement source and limit values - LICENSE_MODE=off in docker-compose.dev.yml and the e2e launchers; sites default to enforced - tests: entitlement rules, limits, the three done-when checks, signed-token apply_license path; license tests moved to v2 tokens Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
158 lines
7.7 KiB
JavaScript
158 lines
7.7 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, 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',
|
|
// No cloud = a test backend: licensing off (every module). The license suite passes a cloudUrl.
|
|
LICENSE_MODE: cloudUrl ? 'enforced' : 'off',
|
|
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',
|
|
LICENSE_MODE: 'off',
|
|
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 {}
|
|
}
|
|
},
|
|
}
|
|
}
|