Files
bonaminandClaude Opus 5.5 78c8824356 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>
2026-11-13 20:38:31 +02:00

158 lines
7.8 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// createApiClient against a tiny HTTP server that answers like the backend.
// Uses the manager's real axios (the apps pass their own).
import assert from 'node:assert/strict'
import http from 'node:http'
import { createRequire } from 'node:module'
import { after, before, test } from 'node:test'
import { createApiClient, errorMessage, isError, parseError } from '../src/index.js'
const require = createRequire(new URL('../../../manager_dashboard/package.json', import.meta.url))
const axios = require('axios')
const err = (code, params, message) => ({ error: { code, params, message }, detail: message })
let server, base
const seen = []
before(async () => {
server = http.createServer((req, res) => {
let body = ''
req.on('data', c => { body += c })
req.on('end', () => {
seen.push({ method: req.method, url: req.url, headers: req.headers, body: body ? JSON.parse(body) : null })
const send = (status, obj) => { res.writeHead(status, { 'content-type': 'application/json' }); res.end(JSON.stringify(obj)) }
if (req.url === '/ok') return send(200, { ok: true })
if (req.url === '/old') return send(404, { detail: 'Not here' })
if (req.url === '/new') return send(404, err('order.not_found', { order_id: 7 }, 'Order 7 not found.'))
if (req.url === '/ended') return send(401, err('auth.session_ended', {}, 'Your session has ended.'))
if (req.url === '/api/orders/5/cancel') {
return req.headers['x-xenia-override'] === 'tok-1'
? send(200, { cancelled: true, body: body ? JSON.parse(body) : null })
: send(403, err('access.override_possible', { key: 'ordering.orders.cancel', reason: 'sent' }, 'A manager can approve this.'))
}
if (req.url === '/api/access/override') {
const b = JSON.parse(body)
if (b.pin === '9999') return send(429, err('access.override_rate_limited', {}, 'Too many wrong PINs.'))
return b.pin === '1234' && b.username === 'boss'
? send(200, { override_token: 'tok-1', key: b.key })
: send(401, err('auth.invalid_credentials', {}, 'Wrong username or password.'))
}
send(500, err('internal.error', { request_id: 'r1' }, 'Something went wrong'))
})
})
await new Promise(r => server.listen(0, '127.0.0.1', r))
base = `http://127.0.0.1:${server.address().port}`
})
after(() => server.close())
function make(extra = {}) {
const calls = { unauthorized: [], offline: [] }
const client = createApiClient({
axios, baseURL: base, getToken: () => 'jwt-1', getDeviceToken: () => 'dev-9',
onUnauthorized: x => calls.unauthorized.push(x.code), onOffline: x => calls.offline.push(x.code), ...extra,
})
return { client, calls }
}
test('sends the session and device headers', async () => {
const { client } = make()
await client.get('/ok')
const h = seen.at(-1).headers
assert.equal(h.authorization, 'Bearer jwt-1')
assert.equal(h['x-xenia-device'], 'dev-9')
})
test('baseURL can be a function (the waiter: active venue)', async () => {
let n = 0
const client = createApiClient({ axios, baseURL: () => { n++; return base } })
await client.get('/ok')
assert.equal(n, 1)
assert.equal(seen.at(-1).headers.authorization, undefined)
})
test('errors carry err.xenia: new codes and old detail-only errors', async () => {
const { client } = make()
const e1 = await client.get('/new').catch(e => e)
assert.deepEqual([e1.xenia.code, e1.xenia.params, e1.xenia.status], ['order.not_found', { order_id: 7 }, 404])
assert.equal(e1.response.data.detail, 'Order 7 not found.', 'v1 screens still read detail')
const e2 = await client.get('/old').catch(e => e)
assert.deepEqual([e2.xenia.code, e2.xenia.message], ['http.404', 'Not here'])
assert.ok(isError(e1, 'order.not_found'))
})
test('401 calls onUnauthorized unless the request opts out', async () => {
const { client, calls } = make()
await client.get('/ended').catch(() => {})
await client.get('/ended', { xenia: { ignoreUnauthorized: true } }).catch(() => {})
assert.deepEqual(calls.unauthorized, ['auth.session_ended'])
})
test('no response at all = network.offline + onOffline', async () => {
const calls = []
const client = createApiClient({ axios, baseURL: 'http://127.0.0.1:9', onOffline: x => calls.push(x.code) })
const e = await client.get('/ok').catch(x => x)
assert.equal(e.xenia.code, 'network.offline')
assert.ok(e.xenia.offline)
assert.deepEqual(calls, ['network.offline'])
})
test('override: wrong PIN, ask again, approve, retry once with the token', async () => {
const { client, calls } = make()
const asked = []
let finished = 0
const answers = [{ username: 'boss', pin: '0000' }, { username: 'boss', pin: '1234' }]
client.setOverrideHandler({ ask: async a => { asked.push(a); return answers.shift() }, finished: () => finished++ })
const res = await client.post('/api/orders/5/cancel', { reason: 'mistake' })
assert.deepEqual(res.data, { cancelled: true, body: { reason: 'mistake' } })
assert.deepEqual(asked.map(a => [a.key, a.params, a.error?.code ?? null]), [
['ordering.orders.cancel', { reason: 'sent' }, null],
['ordering.orders.cancel', { reason: 'sent' }, 'auth.invalid_credentials'],
])
assert.equal(finished, 1)
assert.deepEqual(calls.unauthorized, [], "a wrong manager PIN doesn't log the user out")
const grant = seen.filter(s => s.url === '/api/access/override').at(-1)
assert.deepEqual(grant.body, { key: 'ordering.orders.cancel', username: 'boss', pin: '1234' })
assert.equal(grant.headers.authorization, 'Bearer jwt-1', 'the override is asked for with the user\'s own session')
})
test('override cancelled → the original error, marked', async () => {
const { client } = make()
let finished = 0
client.setOverrideHandler({ ask: async () => null, finished: () => finished++ })
const e = await client.post('/api/orders/5/cancel').catch(x => x)
assert.equal(e.xenia.code, 'access.override_possible')
assert.equal(e.xenia.overrideCancelled, true)
assert.equal(finished, 1)
})
test('override: rate limited is shown, then the user can still cancel', async () => {
const { client } = make()
const errors = []
const answers = [{ username: 'boss', pin: '9999' }, null]
client.setOverrideHandler({ ask: async a => { errors.push(a.error?.code ?? null); return answers.shift() } })
const e = await client.post('/api/orders/5/cancel').catch(x => x)
assert.deepEqual(errors, [null, 'access.override_rate_limited'])
assert.equal(e.xenia.overrideCancelled, true)
})
test('without a handler, or with noOverride, the refusal is just an error', async () => {
const { client } = make()
const e1 = await client.post('/api/orders/5/cancel').catch(x => x)
assert.equal(e1.xenia.code, 'access.override_possible')
let asked = 0
const off = client.setOverrideHandler({ ask: async () => { asked++; return null } })
await client.post('/api/orders/5/cancel', null, { xenia: { noOverride: true } }).catch(() => {})
off()
await client.post('/api/orders/5/cancel').catch(() => {})
assert.equal(asked, 0)
})
test('errorMessage: translated code → backend message → generic', () => {
const t = (key, opts) => ({ 'errors:order.not_found': `Η παραγγελία ${opts.order_id} δεν βρέθηκε`, 'errors:generic': 'Κάτι πήγε στραβά' }[key] ?? opts.defaultValue)
const resp = (status, data) => ({ response: { status, data } })
assert.equal(errorMessage(resp(404, err('order.not_found', { order_id: 7 }, 'Order 7 not found.')), t), 'Η παραγγελία 7 δεν βρέθηκε')
assert.equal(errorMessage(resp(400, { detail: 'Old style text' }), t), 'Old style text')
assert.equal(errorMessage(resp(422, err('some.new_code', {}, 'English text')), t), 'Κάτι πήγε στραβά')
assert.equal(errorMessage(resp(422, err('some.new_code', {}, 'English text'))), 'English text')
assert.equal(parseError({ message: 'Network Error' }).code, 'network.offline')
})