@capgo/capacitor-updater (MPL-2.0) in manual mode: autoUpdate off, stats/update/channel URLs empty (nothing contacts Capgo), appReadyTimeout 15s (auto rollback), resetWhenUpdate (APK update → built-in bundle, venue bundle re-fetched), autoDeletePrevious off (we keep one per venue). src/native/bundles.js syncVenueBundle(): - manifest fetched over the pinned TLS link; zip downloaded natively over the LAN HTTP port with the MANDATORY sha256 check - a tampered zip never runs - applied at once only when nobody is mid-service (after pairing / venue switch, or no one logged in); otherwise staged with next() → applied at the next background/restart; never a mid-service reload - APK too old for the bundle (min_shell_build) → skipped + update banner linking to the venue's /downloads/xenia-waiter.apk - a rolled-back version is blocklisted (attempt tracking + grace window) - without it the app re-applied the still-advertised broken bundle in a loop - server without bundles (404) → built-in UI; bundles no venue needs deleted BundleSync: notifyAppReady on start; sync at start, on resume, every 30 min. saveVenue merges fields (bundleVersion); switchVenue flags immediate apply. E2E (emulator vs two isolated venue stacks): fresh pairing applies the venue bundle and it stays healthy; logged-in update staged, applied after background, session kept; tampered zip refused; shell-too-old banner; broken bundle rolled back automatically and not retried (80s + resume); two venues each run their own bundle, round trips served from cache with 0 downloads, stale bundles cleaned; no *.capgo.app traffic. Step 5/7-era rediscovery + cold-start suites and web modes still pass. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
173 lines
6.3 KiB
JavaScript
173 lines
6.3 KiB
JavaScript
/**
|
|
* Server / venue configuration — the single place that knows WHERE the backend is.
|
|
*
|
|
* Two ways the waiter app runs:
|
|
*
|
|
* 1. Served by the venue's own server (https domain, or plain http://<LAN IP>).
|
|
* No venue is configured → every URL is same-origin and storage uses the
|
|
* original un-prefixed keys. Behaviour is identical to before venues existed,
|
|
* so existing installs keep their token and offline queue across the update.
|
|
*
|
|
* 2. Bundled in the native app (Capacitor), or a dev build with VITE_SERVER_URL.
|
|
* An active venue { siteId, name, baseUrl } → absolute URLs to that server,
|
|
* and all persistent storage (token, IndexedDB, per-venue prefs) is namespaced
|
|
* by siteId so several venues can live side by side on one phone.
|
|
*
|
|
* The active venue is resolved ONCE at module load. Switching venue reloads the
|
|
* app so every module-level singleton (Dexie db, auth store, persisted stores)
|
|
* re-initialises against the new namespace — no half-switched state.
|
|
*/
|
|
|
|
const VENUES_KEY = 'xenia.venues'
|
|
export const APPLY_BUNDLE_NOW_KEY = 'xenia.applyBundleNow'
|
|
|
|
function normalizeBaseUrl(url) {
|
|
const trimmed = String(url || '').trim().replace(/\/+$/, '')
|
|
if (!/^https?:\/\/[^/]+/i.test(trimmed)) {
|
|
throw new Error(`Invalid server URL: "${url}" (expected http(s)://host[:port])`)
|
|
}
|
|
return trimmed
|
|
}
|
|
|
|
function readState() {
|
|
try {
|
|
const parsed = JSON.parse(localStorage.getItem(VENUES_KEY) || 'null')
|
|
if (parsed && typeof parsed === 'object') {
|
|
return { active: parsed.active ?? null, venues: parsed.venues ?? {} }
|
|
}
|
|
} catch {
|
|
// corrupted or unavailable storage — fall through to empty state
|
|
}
|
|
return { active: null, venues: {} }
|
|
}
|
|
|
|
function writeState(state) {
|
|
localStorage.setItem(VENUES_KEY, JSON.stringify(state))
|
|
}
|
|
|
|
function resolveActiveVenue() {
|
|
// Dev convenience: point a `npm run dev` build at a real server on the LAN.
|
|
// Deliberately DEV-only — a URL/query-controlled server in production would let
|
|
// a crafted link send waiters' PINs to someone else's machine.
|
|
const devUrl = import.meta.env.DEV ? import.meta.env.VITE_SERVER_URL : ''
|
|
if (devUrl) {
|
|
return { siteId: 'dev', name: 'Dev server', baseUrl: normalizeBaseUrl(devUrl) }
|
|
}
|
|
const { active, venues } = readState()
|
|
return (active && venues[active]) || null
|
|
}
|
|
|
|
const ACTIVE_VENUE = resolveActiveVenue()
|
|
|
|
// ── Reading ───────────────────────────────────────────────────────────────────
|
|
|
|
/** The venue this app instance is talking to, or null when running same-origin. */
|
|
export function getActiveVenue() {
|
|
return ACTIVE_VENUE
|
|
}
|
|
|
|
/** All paired venues (used by the venue switcher). */
|
|
export function listVenues() {
|
|
return Object.values(readState().venues)
|
|
}
|
|
|
|
/** Base URL for REST calls: '' (same-origin) or 'http(s)://host[:port]'. */
|
|
export function apiBase() {
|
|
return ACTIVE_VENUE?.baseUrl ?? ''
|
|
}
|
|
|
|
/** Absolute ws(s):// URL for a backend path such as '/api/ws/connect?token=…'. */
|
|
export function wsUrl(path) {
|
|
if (ACTIVE_VENUE) {
|
|
return ACTIVE_VENUE.baseUrl.replace(/^http/i, 'ws') + path
|
|
}
|
|
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
|
|
return `${protocol}//${window.location.host}${path}`
|
|
}
|
|
|
|
/**
|
|
* URL for a backend-served asset (product images, avatars). The backend returns
|
|
* root-relative paths like '/static/product_images/x.jpg'; in native mode those
|
|
* must point at the venue server, not at the app bundle.
|
|
*/
|
|
export function assetUrl(url) {
|
|
if (!url || !ACTIVE_VENUE) return url
|
|
if (/^(https?:|data:|blob:)/i.test(url)) return url
|
|
return url.startsWith('/') ? ACTIVE_VENUE.baseUrl + url : url
|
|
}
|
|
|
|
/**
|
|
* localStorage key for per-venue data. Same-origin mode keeps the original
|
|
* un-prefixed key so existing installs don't lose their session.
|
|
*/
|
|
export function storageKey(name) {
|
|
return ACTIVE_VENUE ? `xenia:${ACTIVE_VENUE.siteId}:${name}` : name
|
|
}
|
|
|
|
/** IndexedDB (Dexie) database name — the original name in same-origin mode. */
|
|
export function dbName() {
|
|
return ACTIVE_VENUE ? `pos_snapshot__${ACTIVE_VENUE.siteId}` : 'pos_snapshot'
|
|
}
|
|
|
|
/**
|
|
* How the app is being delivered:
|
|
* 'native' — inside the Capacitor app
|
|
* 'secure-web' — https (or localhost): service worker, installable PWA
|
|
* 'plain-web' — plain http://<LAN IP>: no service worker, no real install
|
|
*/
|
|
export function deliveryMode() {
|
|
if (window.Capacitor?.isNativePlatform?.()) return 'native'
|
|
return window.isSecureContext ? 'secure-web' : 'plain-web'
|
|
}
|
|
|
|
// ── Writing (used by pairing / venue switcher in the native app) ─────────────
|
|
|
|
/**
|
|
* Add or update a paired venue without switching to it. Fields not passed are
|
|
* kept (e.g. `bundleVersion`, remembered by src/native/bundles.js).
|
|
* `spki` = the server's TLS public-key pin (native app, plan step 7).
|
|
*/
|
|
export function saveVenue({ siteId, name, baseUrl, spki, bundleVersion }) {
|
|
if (!siteId) throw new Error('saveVenue: siteId is required')
|
|
const state = readState()
|
|
const prev = state.venues[siteId] || {}
|
|
state.venues[siteId] = {
|
|
...prev,
|
|
siteId,
|
|
name: name || prev.name || siteId,
|
|
baseUrl: normalizeBaseUrl(baseUrl || prev.baseUrl),
|
|
...(spki ? { spki } : {}),
|
|
...(bundleVersion ? { bundleVersion } : {}),
|
|
}
|
|
writeState(state)
|
|
return state.venues[siteId]
|
|
}
|
|
|
|
/** Make a paired venue active and reload the app into it. */
|
|
export function switchVenue(siteId) {
|
|
const state = readState()
|
|
if (!state.venues[siteId]) throw new Error(`switchVenue: unknown venue ${siteId}`)
|
|
state.active = siteId
|
|
writeState(state)
|
|
// Nobody is mid-service right after a switch: the venue's own UI bundle may be
|
|
// applied immediately on the next start (src/native/bundles.js)
|
|
try {
|
|
sessionStorage.setItem(APPLY_BUNDLE_NOW_KEY, '1')
|
|
} catch {
|
|
// storage unavailable — the bundle is then applied at the next background/restart
|
|
}
|
|
window.location.replace('/')
|
|
}
|
|
|
|
/**
|
|
* Forget a paired venue. Its namespaced storage and IndexedDB are left in place
|
|
* on purpose — they may hold unsynced offline orders. Cleanup is an explicit,
|
|
* separate action (see the native app's venue manager).
|
|
*/
|
|
export function removeVenue(siteId) {
|
|
const state = readState()
|
|
delete state.venues[siteId]
|
|
if (state.active === siteId) state.active = null
|
|
writeState(state)
|
|
}
|