feat(api): @xenia/api + @xenia/access; the manager logs in and loads bootstrap through them

Platform-v2 step 2.5 (APPS_PLATFORM D-7, D-10, §9):
- @xenia/api: createApiClient (app passes its axios; session/device headers,
  err.xenia codes, 401/offline hooks, manager-override retry: ask PIN, grant,
  retry once with X-Xenia-Override); errorMessage; createLiveClient = the
  waiter's WebSocket logic (cursor replay, backoff, online) moved unchanged
- @xenia/access: AccessProvider (bootstrap per session token, language +
  venue formats, translated ui labels, approval dialog), useAccess/useCan/
  useModule, Can, RequireModule
- i18n: errors namespace for every backend code (en/el, test vs core/errors.py),
  override/access texts
- manager: client from createApiClient, AccessProvider in a layout route,
  /kds behind RequireModule, usePermissions from bootstrap keys; login and
  unlock no longer treat a wrong password/PIN as "session ended" (a wrong
  lock-screen PIN used to log the manager out)
- waiter: useWebSocket is a thin wrapper over createLiveClient
- tests: api/access unit tests; new e2e suite tests/e2e/manager.mjs; CS-18

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-13 20:38:31 +02:00
co-authored by Claude Opus 5.5
parent dbb8d5f0f4
commit 78c8824356
35 changed files with 1419 additions and 196 deletions
+103
View File
@@ -0,0 +1,103 @@
// HTTP client for every frontend (plan step 2.5, APPS_PLATFORM §9).
//
// import axios from 'axios'
// const client = createApiClient({
// axios, // the app's own axios (each app pins its version)
// baseURL: '', // manager/terminal: same origin; waiter: () => apiBase() (CS-8)
// getToken: () => localStorage.getItem('manager_token'),
// getDeviceToken: () => …, // paired devices (D-8): X-Xenia-Device
// onUnauthorized: x => …, // a 401 (session ended, bad token)
// onOffline: x => …, // no response at all
// })
//
// Every rejected request carries err.xenia = parseError(err) ({ code, params, message, status, offline }).
// Manager override (D-10): when a request is refused with `access.override_possible`, the
// client asks the registered override handler (see @xenia/access <OverrideHost>) for a
// manager's username + PIN, gets a one-time token from POST /api/access/override, and
// retries the request ONCE with X-Xenia-Override. The token is bound to this session and
// key and valid for 60 s. Wrong PIN → the handler is asked again with the error; cancel →
// the original error is rejected with err.xenia.overrideCancelled = true.
//
// Per-request options (config.xenia): { ignoreUnauthorized: true } (don't call onUnauthorized,
// e.g. a login form's own 401), { noOverride: true } (never run the override flow).
import { parseError } from './errors.js'
export const DEVICE_HEADER = 'X-Xenia-Device'
export const OVERRIDE_HEADER = 'X-Xenia-Override'
export function createApiClient({
axios, baseURL = '', getToken, getDeviceToken, onUnauthorized, onOffline, timeout = 0,
} = {}) {
if (!axios?.create) throw new Error('createApiClient needs the app\'s axios: createApiClient({ axios, … })')
const client = axios.create({ baseURL: typeof baseURL === 'function' ? '' : baseURL, timeout })
let override = null // { ask, finished } from the UI, see setOverrideHandler
client.interceptors.request.use(config => {
if (typeof baseURL === 'function') config.baseURL = baseURL()
const token = getToken?.()
if (token && !config.headers.Authorization) config.headers.Authorization = `Bearer ${token}`
const device = getDeviceToken?.()
if (device) config.headers[DEVICE_HEADER] = device
return config
})
client.interceptors.response.use(
res => res,
async err => {
const x = parseError(err)
err.xenia = x
const opts = err.config?.xenia || {}
if (x.code === 'access.override_possible' && override && !opts.noOverride && !opts.overrideTried) {
return runOverride(err)
}
if (x.offline) onOffline?.(x)
else if (x.status === 401 && !opts.ignoreUnauthorized) onUnauthorized?.(x)
throw err
},
)
async function runOverride(original) {
const { key, ...params } = original.xenia.params || {}
const handler = override
let lastError = null
try {
for (;;) {
const creds = await handler.ask({ key, params, error: lastError })
if (!creds) {
original.xenia.overrideCancelled = true
throw original
}
let token
try {
const { data } = await client.post('/api/access/override',
{ key, username: creds.username, pin: creds.pin },
{ xenia: { noOverride: true, ignoreUnauthorized: true } })
token = data.override_token
} catch (e) {
lastError = parseError(e)
if (lastError.offline) throw e
continue // wrong PIN, approver lacks the key, rate limited… ask again (the user can cancel)
}
const config = original.config
return await client.request({
...config,
headers: { ...config.headers, [OVERRIDE_HEADER]: token },
xenia: { ...(config.xenia || {}), overrideTried: true },
})
}
} finally {
handler.finished?.()
}
}
/**
* The UI side of the override flow. handler.ask({ key, params, error }) → Promise<{ username, pin } | null>
* (null = cancelled); handler.finished() when the flow is over (approved or not).
* Returns a function that unregisters it.
*/
client.setOverrideHandler = handler => {
override = handler
return () => { if (override === handler) override = null }
}
return client
}
+51
View File
@@ -0,0 +1,51 @@
// Backend errors as data (APPS_PLATFORM D-12, §3.2; local_backend/core/errors.py).
//
// Every error response looks like
// { "error": { "code": "order.not_found", "params": { "order_id": 7 }, "message": "Order 7 not found." },
// "detail": "Order 7 not found." }
// Older endpoints still raise plain HTTPExceptions, which the backend wraps as "http.<status>"
// with their original `detail`. parseError() turns any axios error into one shape.
/**
* @returns {{ code: string, params: object, message: string, status: number|null, offline: boolean, detail: any }}
* offline: no response at all (network down, server unreachable, timeout) → code "network.offline"
*/
export function parseError(err) {
if (err?.xenia) return err.xenia
const res = err?.response
if (!res) {
return { code: 'network.offline', params: {}, message: err?.message || 'Network error', status: null, offline: true, detail: null }
}
const body = res.data && typeof res.data === 'object' ? res.data : {}
const e = body.error && typeof body.error === 'object' ? body.error : null
const detail = body.detail ?? null
return {
code: e?.code || `http.${res.status}`,
params: e?.params || {},
message: e?.message || (typeof detail === 'string' ? detail : '') || `HTTP ${res.status}`,
status: res.status,
offline: false,
detail,
}
}
/**
* A message for the user, in their language.
* errorMessage(err, t) with t from useTranslation() (@xenia/i18n has the `errors` namespace)
* Order: the translated code (errors:<code>, with the error's params) → the backend's English
* message → a generic text. Without `t`, the backend's English message.
*/
export function errorMessage(err, t) {
const x = parseError(err)
if (!t) return x.message
const key = `errors:${x.code}`
const translated = t(key, { ...x.params, defaultValue: '' })
if (translated && translated !== key) return translated
if (x.code.startsWith('http.') && x.message) return x.message
return t('errors:generic', { defaultValue: x.message })
}
/** True when the error is this code (works on axios errors and parsed ones). */
export function isError(err, code) {
return parseError(err).code === code
}
+13 -3
View File
@@ -1,3 +1,13 @@
// @xenia/api — HTTP client (base URL, auth/device/override headers, error codes) and the WebSocket client (plan step 2.5).
// Imported from source by Vite (no build step). Filled in by its plan step.
export {}
// @xenia/api — talking to the local backend, for every frontend (plan step 2.5,
// APPS_PLATFORM §9). Plain JavaScript (no React); imported from source by Vite.
//
// createApiClient({ axios, baseURL, getToken, getDeviceToken, onUnauthorized, onOffline })
// → an axios instance: auth/device headers, err.xenia on every error, manager-override retry
// parseError(err) / errorMessage(err, t) / isError(err, code)
// createLiveClient({ url, cursor, onEvent, onReady, onDisconnect }) WebSocket + cursor replay
//
// React glue (bootstrap, permissions, the override dialog) lives in @xenia/access.
export { createApiClient, DEVICE_HEADER, OVERRIDE_HEADER } from './client.js'
export { parseError, errorMessage, isError } from './errors.js'
export { createLiveClient, wsUrlFor, INITIAL_RECONNECT_DELAY, MAX_RECONNECT_DELAY } from './live.js'
+123
View File
@@ -0,0 +1,123 @@
// Live events over the backend WebSocket, with cursor replay (plan step 2.5).
// Lifted from waiter_pwa/src/hooks/useWebSocket.js without changing behaviour; the waiter's
// hook is now a thin wrapper around this. No React.
//
// Protocol (local_backend/routers/ws.py):
// 1. connect to ws[s]://host/api/ws/connect?token=<jwt>
// 2. send { cursor: <last seq> } at once (0 = first connect / no history)
// 3. the server replays missed events, then sends { type: "ready" }
// 4. live events: { seq, type, data }
// 5. keepalive: { type: "ping" } every 25 s (no answer needed)
// On close: reconnect after 2 s, then ×1.5 each time up to 30 s; a successful open resets
// it. The browser's `online` event reconnects at once. The cursor survives reloads through
// the `cursor` store the app provides (the waiter keeps it in IndexedDB).
//
// const live = createLiveClient({
// url: () => wsUrl(`/api/ws/connect?token=${encodeURIComponent(token)}`),
// cursor: { load: async () => seq, save: seq => … },
// onEvent: (type, data) => …, onReady: () => …, onDisconnect: () => …,
// })
// live.start(); …; live.reconnect(); …; live.stop()
export const INITIAL_RECONNECT_DELAY = 2_000
export const MAX_RECONNECT_DELAY = 30_000
/** ws(s)://<host of baseURL or the page>/<path> */
export function wsUrlFor(path, baseURL = '') {
const base = baseURL || (typeof location !== 'undefined' ? location.origin : 'http://localhost')
const u = new URL(path, base)
u.protocol = u.protocol === 'https:' ? 'wss:' : 'ws:'
return u.toString()
}
export function createLiveClient({
url, cursor, onEvent, onReady, onDisconnect,
WebSocketImpl = globalThis.WebSocket,
windowTarget = typeof window !== 'undefined' ? window : null,
timers = { setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: id => clearTimeout(id) },
}) {
let ws = null
let reconnectTimer = null
let reconnectDelay = INITIAL_RECONNECT_DELAY
let stopped = true
let lastSeq = 0
function connect() {
if (stopped) return
if (ws) {
ws.onclose = null // prevent a double reconnect
ws.close()
ws = null
}
const socket = new WebSocketImpl(typeof url === 'function' ? url() : url)
ws = socket
socket.onopen = () => {
reconnectDelay = INITIAL_RECONNECT_DELAY
socket.send(JSON.stringify({ cursor: lastSeq })) // the server replays what we missed
}
socket.onmessage = e => {
let msg
try { msg = JSON.parse(e.data) } catch { return }
if (msg.type === 'ping') return
if (msg.type === 'ready') { onReady?.(); return }
if (msg.seq && msg.seq > lastSeq) {
lastSeq = msg.seq
cursor?.save?.(msg.seq)
}
if (msg.type && msg.data !== undefined) onEvent?.(msg.type, msg.data)
}
socket.onerror = () => {} // onerror always comes before onclose; onclose reconnects
socket.onclose = () => {
ws = null
onDisconnect?.()
if (stopped) return
// wait the current delay, then grow it for the attempt after
reconnectTimer = timers.setTimeout(() => {
reconnectDelay = Math.min(reconnectDelay * 1.5, MAX_RECONNECT_DELAY)
connect()
}, reconnectDelay)
}
}
function onNetworkOnline() {
timers.clearTimeout(reconnectTimer)
reconnectDelay = INITIAL_RECONNECT_DELAY
connect()
}
return {
/** Load the saved cursor, then connect. */
async start() {
if (!stopped) return
stopped = false
windowTarget?.addEventListener('online', onNetworkOnline)
let seq = 0
try { seq = (await cursor?.load?.()) ?? 0 } catch { seq = 0 }
lastSeq = seq
if (!stopped) connect()
},
/** Close for good (no reconnect). */
stop() {
stopped = true
timers.clearTimeout(reconnectTimer)
windowTarget?.removeEventListener('online', onNetworkOnline)
if (ws) {
ws.onclose = null
ws.close()
ws = null
}
},
/** Reconnect now, with the backoff reset (e.g. the app came back to the foreground). */
reconnect() {
timers.clearTimeout(reconnectTimer)
reconnectDelay = INITIAL_RECONNECT_DELAY
connect()
},
get lastSeq() { return lastSeq },
get connected() { return !!ws && ws.readyState === 1 },
}
}