Files
aevolution/apps/evo-admin-api/portal/app.js
T
dingoandClaude Opus 5.5 54beceb823 feat(admin): read-only admin portal and API (ADR-0182 step 1, schema 61)
evo-admin-api serves the portal at srs.aeternalisgames.com and read-only JSON
for world 100 behind Keycloak (realm role aevolution-admin, audience
aevolution-admin, client aevolution-admin-portal): accounts with session,
status, lives, deaths, resets and mutation choices; one account's lives; the
world's regions; and a live 2D region view of cells, wildlife, pools and
bubbles. The portal is plain HTML/CSS/JS with PKCE sign-in, a strict CSP and
no third-party code.

- Schema 61: three bounded SECURITY DEFINER read functions, fenced in the
  privilege audit; no table or existing function changes.
- Cellular regions answer GET /admin/view on the ops port (NetworkPolicy:
  Prometheus and the admin portal only); CellularLives::extent_of reads the
  existing phenotype budget. No simulation, checkpoint or wire change.
- TokenVerifier takes an optional realm role and returns the email; the ops
  server's response bound is configurable (16 KiB default unchanged).
- DEV component admin-portal-dev (Deployment, Service, NetworkPolicies); the
  Ingress and the aevolution-admin-pg Secret are created out of band.
- CI scripts pinned to schema 60 now expect 61.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 12:39:28 -04:00

559 lines
28 KiB
JavaScript
Raw 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.
// ADR-0182 read-only admin portal. Keycloak sign-in (authorization code with PKCE), then the
// admin API on this origin. Tokens stay in this tab: the access token in memory, the refresh
// and ID tokens in sessionStorage so a reload keeps the session. No third-party code.
const store = {
get: (k) => { try { return sessionStorage.getItem(k); } catch { return null; } },
set: (k, v) => { try { sessionStorage.setItem(k, v); } catch { /* private mode */ } },
drop: (...ks) => { try { ks.forEach((k) => sessionStorage.removeItem(k)); } catch { /* */ } },
};
let config = null;
let access = null; // { token, expires (ms) }
let refreshing = null; // In-flight refresh promise.
// ---------- DOM helpers (textContent only: nothing from the API is parsed as HTML) ----------
function h(tag, attrs = {}, ...children) {
const el = document.createElement(tag);
for (const [k, v] of Object.entries(attrs)) {
if (v === null || v === undefined || v === false) continue;
if (k === 'class') el.className = v;
else if (k.startsWith('on')) el.addEventListener(k.slice(2), v);
else if (v === true) el.setAttribute(k, '');
else el.setAttribute(k, String(v));
}
for (const c of children.flat()) {
if (c === null || c === undefined || c === false) continue;
el.append(c instanceof Node ? c : document.createTextNode(String(c)));
}
return el;
}
const main = () => document.getElementById('main');
function show(...nodes) { main().replaceChildren(...nodes); }
// ---------- Formatting ----------
const fmtInt = (n) => (n === null || n === undefined ? '—' : Number(n).toLocaleString());
function fmtUnit(value, units) {
if (value === null || value === undefined) return '—';
let v = Number(value), i = 0;
while (Math.abs(v) >= 1000 && i < units.length - 1) { v /= 1000; i++; }
return `${v >= 100 || i === 0 ? Math.round(v) : v.toFixed(v >= 10 ? 1 : 2)} ${units[i]}`;
}
const fmtEnergy = (pj) => fmtUnit(pj, ['pJ', 'nJ', 'µJ', 'mJ', 'J']);
const fmtMass = (fg) => fmtUnit(fg, ['fg', 'pg', 'ng', 'µg', 'mg']);
const fmtLength = (um) => fmtUnit(um, ['µm', 'mm', 'm']);
function fmtTime(seconds) {
if (!seconds) return '—';
return new Date(seconds * 1000).toLocaleString();
}
function fmtAgo(seconds) {
if (!seconds) return '—';
const d = Math.round(Date.now() / 1000 - seconds);
if (Math.abs(d) < 60) return d >= 0 ? `${d}s ago` : `in ${-d}s`;
const m = Math.round(d / 60);
if (Math.abs(m) < 60) return m >= 0 ? `${m}m ago` : `in ${-m}m`;
const hr = Math.round(m / 60);
if (Math.abs(hr) < 48) return hr >= 0 ? `${hr}h ago` : `in ${-hr}h`;
return `${Math.round(hr / 24)}d ago`;
}
const short = (id) => (id ? `${id.slice(0, 8)}…` : '—');
// ---------- Sign-in ----------
function b64url(bytes) {
let s = '';
bytes.forEach((b) => { s += String.fromCharCode(b); });
return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
function randomText(n) {
const a = new Uint8Array(n);
crypto.getRandomValues(a);
return b64url(a);
}
const endpoint = (name) => `${config.issuer}/protocol/openid-connect/${name}`;
const redirectUri = () => `${location.origin}/`;
async function signIn() {
const verifier = randomText(48);
const state = randomText(16);
const challenge = b64url(new Uint8Array(
await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))));
store.set('pkce_verifier', verifier);
store.set('pkce_state', state);
store.set('return_to', location.hash || '#/accounts');
const url = new URL(endpoint('auth'));
url.search = new URLSearchParams({
client_id: config.client_id, redirect_uri: redirectUri(), response_type: 'code',
response_mode: 'query', scope: 'openid email', state, code_challenge: challenge,
code_challenge_method: 'S256',
});
location.assign(url);
}
async function tokenRequest(body) {
const res = await fetch(endpoint('token'), {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ client_id: config.client_id, ...body }),
});
if (!res.ok) throw new Error(`token endpoint ${res.status}`);
const t = await res.json();
access = { token: t.access_token, expires: Date.now() + (t.expires_in || 60) * 1000 };
if (t.refresh_token) store.set('refresh_token', t.refresh_token);
if (t.id_token) store.set('id_token', t.id_token);
return access.token;
}
async function finishSignIn() {
const params = new URLSearchParams(location.search);
const code = params.get('code');
if (!code && !params.get('error')) return false;
const expected = store.get('pkce_state');
const verifier = store.get('pkce_verifier');
const returnTo = store.get('return_to') || '#/accounts';
store.drop('pkce_state', 'pkce_verifier', 'return_to');
history.replaceState(null, '', `/${returnTo}`);
if (params.get('error') || !expected || params.get('state') !== expected || !verifier) {
throw new Error(`sign-in was not completed (${params.get('error') || 'state mismatch'})`);
}
await tokenRequest({ grant_type: 'authorization_code', code, redirect_uri: redirectUri(),
code_verifier: verifier });
return true;
}
async function token() {
if (access && access.expires - Date.now() > 30000) return access.token;
const refresh = store.get('refresh_token');
if (!refresh) return null;
refreshing = refreshing || tokenRequest({ grant_type: 'refresh_token', refresh_token: refresh })
.catch(() => { store.drop('refresh_token'); access = null; return null; })
.finally(() => { refreshing = null; });
return refreshing;
}
function signOut() {
const idToken = store.get('id_token');
store.drop('refresh_token', 'id_token');
access = null;
const url = new URL(endpoint('logout'));
url.search = new URLSearchParams({
client_id: config.client_id, post_logout_redirect_uri: redirectUri(),
...(idToken ? { id_token_hint: idToken } : {}),
});
location.assign(url);
}
class ApiError extends Error {
constructor(status, code) { super(code || `HTTP ${status}`); this.status = status; this.code = code; }
}
async function api(path, retry = true) {
const t = await token();
if (!t) throw new ApiError(401, 'signed_out');
const res = await fetch(path, { headers: { Authorization: `Bearer ${t}` }, cache: 'no-store' });
if (res.status === 401 && retry) { access = null; return api(path, false); }
if (!res.ok) {
let code = null;
try { code = (await res.json()).error; } catch { /* plain text */ }
throw new ApiError(res.status, code);
}
return res.json();
}
// ---------- Sortable tables ----------
function table(columns, rows, { onRow, sortKey, sortUp = false } = {}) {
let key = sortKey, up = sortUp;
const wrap = h('div', { class: 'table-wrap' });
const draw = () => {
const col = columns.find((c) => c.key === key);
const sorted = col ? [...rows].sort((a, b) => {
const va = col.sort ? col.sort(a) : a[col.key];
const vb = col.sort ? col.sort(b) : b[col.key];
const r = va === vb ? 0 : va === null || va === undefined ? 1 : vb === null || vb === undefined ? -1 : va < vb ? -1 : 1;
return up ? r : -r;
}) : rows;
const head = h('tr', {}, columns.map((c) => h('th', {
class: [c.num ? 'num' : '', c.key === key ? `sorted${up ? ' up' : ''}` : ''].join(' ').trim() || null,
onclick: () => { if (key === c.key) up = !up; else { key = c.key; up = !c.num; } draw(); },
}, c.label)));
const body = sorted.map((r) => h('tr', { class: onRow ? 'clickable' : null, onclick: onRow ? () => onRow(r) : null },
columns.map((c) => h('td', { class: c.num ? 'num' : null }, c.render ? c.render(r) : (r[c.key] ?? '—')))));
wrap.replaceChildren(h('table', {}, h('thead', {}, head), h('tbody', {}, body.length ? body
: h('tr', {}, h('td', { colspan: columns.length, class: 'muted' }, 'Nothing to show.')))));
};
draw();
return wrap;
}
function statusBadge(a) {
return h('span', { class: `badge ${a.status === 'alive' ? 'alive' : a.status === 'dead' ? 'dead' : ''}` },
a.status === 'no_life' ? 'no life' : a.status);
}
function sessionBadge(a) {
return a.logged_in ? h('span', { class: 'badge online' }, `online · region ${a.control_region}`)
: h('span', { class: 'muted' }, 'offline');
}
// ---------- Pages ----------
let stopPage = () => {};
async function accountsPage() {
const data = await api('/api/accounts');
const search = h('input', { type: 'search', placeholder: 'Filter by account, subject or status' });
const holder = h('div');
const columns = [
{ key: 'account', label: 'Account', render: (a) => h('span', { class: 'mono', title: a.account }, short(a.account)) },
{ key: 'subject', label: 'Keycloak subject', render: (a) => h('span', { class: 'mono muted', title: a.subject || '' }, a.subject ? short(a.subject) : '—') },
{ key: 'status', label: 'Status', render: statusBadge },
{ key: 'logged_in', label: 'Session', render: sessionBadge, sort: (a) => (a.logged_in ? 1 : 0) },
{ key: 'active_region', label: 'Region', render: (a) => a.active_region ?? '—', sort: (a) => Number(a.active_region ?? -1) },
{ key: 'lives', label: 'Lives', num: true },
{ key: 'deaths', label: 'Deaths', num: true },
{ key: 'resets', label: 'Resets', num: true },
{ key: 'mutation_choices', label: 'Mutation choices', num: true },
{ key: 'created_at', label: 'Created', render: (a) => (a.created_at ? fmtAgo(a.created_at) : '—'), sort: (a) => a.created_at ?? 0 },
];
const draw = () => {
const q = search.value.trim().toLowerCase();
const rows = data.accounts.filter((a) => !q || [a.account, a.subject, a.status].some((v) => (v || '').toLowerCase().includes(q)));
holder.replaceChildren(table(columns, rows, { sortKey: 'created_at', onRow: (a) => { location.hash = `#/accounts/${a.account}`; } }));
};
search.addEventListener('input', draw);
const n = data.accounts.length;
const online = data.accounts.filter((a) => a.logged_in).length;
const alive = data.accounts.filter((a) => a.status === 'alive').length;
show(
h('div', { class: 'head' }, h('div', {}, h('h1', {}, 'Accounts'), h('span', { class: 'muted' }, `World ${data.world}`)),
h('div', { class: 'tools' }, search, h('button', { onclick: () => route() }, 'Refresh'))),
h('div', { class: 'stats' },
stat('Accounts', fmtInt(n)), stat('Online', fmtInt(online)), stat('Alive', fmtInt(alive)),
stat('Deaths', fmtInt(data.accounts.reduce((s, a) => s + (a.deaths || 0), 0)))),
holder);
draw();
}
function stat(label, value, sub) {
return h('div', { class: 'stat' }, h('div', { class: 'label' }, label),
h('div', { class: 'value' }, value, sub ? h('small', {}, ` ${sub}`) : null));
}
// persistence::LifeRefusal.
const rejections = ['accepted', 'refused: not enough funding', 'refused: no placement', 'cancelled', 'refused: already alive'];
async function accountPage(id) {
const data = await api(`/api/accounts/${id}`);
const a = data.account;
const facts = h('dl', { class: 'facts' },
h('dt', {}, 'Account'), h('dd', { class: 'mono' }, a.account),
h('dt', {}, 'Keycloak subject'), h('dd', { class: 'mono' }, a.subject || '—'),
h('dt', {}, 'Issuer'), h('dd', { class: 'mono' }, a.issuer || '—'),
h('dt', {}, 'Status'), h('dd', {}, statusBadge(a)),
h('dt', {}, 'Session'), h('dd', {}, sessionBadge(a),
a.control_expires ? h('span', { class: 'muted' }, ` control ${a.logged_in ? 'until' : 'ended'} ${fmtTime(a.control_expires)}`) : null),
h('dt', {}, 'Active life'), h('dd', { class: 'mono' }, a.active_life ?? '—',
a.active_region ? h('span', {}, ' ', h('a', { href: `#/regions/${a.active_region}?account=${a.account}` }, `show in region ${a.active_region}`)) : null),
h('dt', {}, 'Created'), h('dd', {}, fmtTime(a.created_at)));
const lives = table([
{ key: 'request', label: 'Request', sort: (l) => Number(l.request) },
{ key: 'identity', label: 'Life', render: (l) => h('span', { class: 'mono' }, l.identity) },
{ key: 'region', label: 'Region' },
{ key: 'rejection', label: 'Outcome', render: (l) => (l.rejection ? h('span', { class: 'badge warn' }, rejections[l.rejection] || `refused ${l.rejection}`)
: l.born === null ? h('span', { class: 'muted' }, 'reserved') : l.ended_tick ? h('span', { class: 'badge dead' }, 'died') : h('span', { class: 'badge alive' }, 'alive')) },
{ key: 'born', label: 'Born (tick)', num: true, sort: (l) => Number(l.born ?? -1) },
{ key: 'ended_tick', label: 'Ended (tick)', num: true, sort: (l) => Number(l.ended_tick ?? -1) },
{ key: 'ended_at', label: 'Ended', render: (l) => fmtTime(l.ended_at), sort: (l) => l.ended_at ?? 0 },
], data.lives, { sortKey: 'request' });
show(
h('div', { class: 'head' }, h('div', {}, h('a', { href: '#/accounts' }, '← Accounts'), h('h1', {}, `Account ${short(a.account)}`))),
h('div', { class: 'stats' },
stat('Lives', fmtInt(a.lives)), stat('Deaths', fmtInt(a.deaths)), stat('Resets', fmtInt(a.resets)),
stat('Mutation choices', fmtInt(a.mutation_choices))),
h('div', { class: 'card' }, facts),
h('h2', {}, 'Lives'), lives,
h('p', { class: 'muted' }, 'Time played, bans, current mutations and living offspring arrive with the next admin phase (ADR-0182).'));
}
async function regionsPage() {
const data = await api('/api/regions');
show(
h('div', { class: 'head' }, h('div', {}, h('h1', {}, 'Regions'), h('span', { class: 'muted' }, `World ${data.world}`)),
h('div', { class: 'tools' }, h('button', { onclick: () => route() }, 'Refresh'))),
table([
{ key: 'region', label: 'Region', sort: (r) => Number(r.region) },
{ key: 'frame', label: 'Frame' },
{ key: 'lease_held', label: 'Lease', render: (r) => (r.lease_held ? h('span', { class: 'badge alive' }, `held · epoch ${r.lease_epoch}`) : h('span', { class: 'muted' }, 'free')) },
{ key: 'lease_expires', label: 'Lease expires', render: (r) => fmtAgo(r.lease_expires) },
{ key: 'tick', label: 'Head tick', num: true, render: (r) => fmtInt(r.tick), sort: (r) => Number(r.tick ?? -1) },
{ key: 'sequence', label: 'Commits', num: true, render: (r) => fmtInt(r.sequence), sort: (r) => Number(r.sequence ?? -1) },
{ key: 'committed_at', label: 'Last commit', render: (r) => fmtAgo(r.committed_at), sort: (r) => r.committed_at ?? 0 },
{ key: 'build', label: 'Build', render: (r) => h('span', { class: 'mono', title: r.build || '' }, r.build ? r.build.slice(0, 12) : '—') },
{ key: 'viewable', label: '', render: (r) => (r.viewable ? h('a', { href: `#/regions/${r.region}` }, 'Open view →') : h('span', { class: 'muted' }, 'no view')) },
], data.regions, { sortKey: 'region' }));
}
// ---------- Region view ----------
const channelNames = ['energy', 'carbon', 'nitrogen', 'phosphorus', 'other'];
const css = (name) => getComputedStyle(document.documentElement).getPropertyValue(`--${name}`).trim();
async function regionPage(region, params) {
const highlight = params.get('account') || '';
const canvas = h('canvas');
const tip = h('div', { class: 'tooltip', hidden: true });
const note = h('div', { class: 'overlay-note' }, 'Scroll to zoom, drag to pan, double-click to reset.');
const statsBox = h('div', { class: 'stats' });
const detail = h('div', { class: 'card' }, h('span', { class: 'muted' }, 'Select a cell to see it here.'));
const status = h('span', { class: 'muted' });
const show_ = { players: true, wildlife: true, pools: true, bubbles: true };
const toggle = (k, label) => h('label', {}, h('input', { type: 'checkbox', checked: true, onchange: (e) => { show_[k] = e.target.checked; paint(); } }), label);
const live = h('input', { type: 'checkbox', checked: true });
let view = null, selected = null, timer = null;
let zoom = 1, panX = 0, panY = 0, drag = null;
show(
h('div', { class: 'head' }, h('div', {}, h('a', { href: '#/regions' }, '← Regions'), h('h1', {}, `Region ${region}`), status),
h('div', { class: 'tools' }, h('label', {}, live, ' Live (1 s)'), h('button', { onclick: () => load() }, 'Refresh'))),
statsBox,
h('div', { class: 'region-layout' },
h('div', { class: 'canvas-wrap' }, canvas, tip, note),
h('div', { class: 'side' },
detail,
h('div', { class: 'card' }, h('h2', {}, 'Show'), h('div', { class: 'toggles' },
toggle('players', 'Player cells'), toggle('wildlife', 'Wildlife'), toggle('pools', 'Pools'), toggle('bubbles', 'Bubbles'))),
h('div', { class: 'card' }, h('h2', {}, 'Legend'), h('div', { class: 'legend' },
h('span', { class: 'swatch player' }), 'Player cell',
h('span', { class: 'swatch online' }), 'Player cell, connected',
h('span', { class: 'swatch wildlife' }), 'Wildlife',
h('span', { class: 'swatch pool' }), 'Pool',
...channelNames.flatMap((c) => [h('span', { class: `swatch ${c}` }), `Bubble, mostly ${c}`]))))));
const cellObj = (c) => ({
life: c[0], organism: c[1], account: c[2], x: c[3], y: c[4], extent: c[5], flags: c[6], members: c[7],
reserve: c.slice(8, 13), bodyMass: c[13],
});
const depObj = (d) => ({ id: d[0], kind: d[1], x: d[2], y: d[3], r: d[4], stock: d.slice(5, 10) });
function geometry() {
const rect = canvas.getBoundingClientRect();
const dpr = window.devicePixelRatio || 1;
const w = Math.max(1, Math.round(rect.width * dpr)), hgt = Math.max(1, Math.round(rect.height * dpr));
if (canvas.width !== w || canvas.height !== hgt) { canvas.width = w; canvas.height = hgt; }
const [aw, ah] = view ? view.area : [1, 1];
const base = Math.min(w / aw, hgt / ah);
const s = base * zoom;
const ox = (w - aw * s) / 2 + panX * dpr, oy = (hgt - ah * s) / 2 + panY * dpr;
// World y grows upward; the canvas grows downward.
return { dpr, s, toX: (x) => ox + x * s, toY: (y) => oy + (ah - y) * s, fromX: (px) => (px - ox) / s, fromY: (py) => ah - (py - oy) / s };
}
function paint() {
const ctx = canvas.getContext('2d');
const g = geometry();
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (!view) return;
const [aw, ah] = view.area;
ctx.strokeStyle = css('line');
ctx.lineWidth = g.dpr;
ctx.strokeRect(g.toX(0), g.toY(ah), aw * g.s, ah * g.s);
if (show_.pools) {
ctx.fillStyle = css('pool');
ctx.strokeStyle = css('accent');
for (const d of view.deps) if (d.kind !== 2) {
ctx.beginPath(); ctx.arc(g.toX(d.x), g.toY(d.y), Math.max(d.r * g.s, 2 * g.dpr), 0, Math.PI * 2); ctx.fill();
}
}
if (show_.bubbles) {
const colors = channelNames.map(css);
for (const d of view.deps) if (d.kind === 2) {
// Energy counts in pJ, matter in fg; ~17 pJ per fg of food, so compare on that scale.
const weights = [d.stock[0] / 17, d.stock[1], d.stock[2], d.stock[3], d.stock[4]];
const top = weights.indexOf(Math.max(...weights));
ctx.fillStyle = colors[top];
ctx.beginPath(); ctx.arc(g.toX(d.x), g.toY(d.y), Math.max(d.r * g.s, 1.5 * g.dpr), 0, Math.PI * 2); ctx.fill();
}
}
for (const c of view.cells) {
const wild = (c.flags & 1) !== 0;
if ((wild && !show_.wildlife) || (!wild && !show_.players)) continue;
const online = (c.flags & 2) !== 0, faded = (c.flags & 12) !== 0;
const size = Math.max(c.extent * g.s, 3 * g.dpr);
const x = g.toX(c.x + c.extent / 2), y = g.toY(c.y + c.extent / 2);
ctx.globalAlpha = faded ? 0.4 : 0.9;
ctx.fillStyle = wild ? css('wildlife') : online ? css('online') : css('player');
ctx.beginPath(); ctx.arc(x, y, size / 2, 0, Math.PI * 2); ctx.fill();
ctx.globalAlpha = 1;
const marked = (highlight && c.account === highlight) || (selected && selected.life === c.life);
if (marked) {
ctx.strokeStyle = css('warn'); ctx.lineWidth = 2 * g.dpr;
ctx.beginPath(); ctx.arc(x, y, size / 2 + 4 * g.dpr, 0, Math.PI * 2); ctx.stroke();
}
}
}
function hit(px, py) {
const g = geometry();
const wx = g.fromX(px * g.dpr), wy = g.fromY(py * g.dpr);
const slack = 4 / g.s * g.dpr;
for (const c of view ? view.cells : []) {
const wild = (c.flags & 1) !== 0;
if ((wild && !show_.wildlife) || (!wild && !show_.players)) continue;
if (wx >= c.x - slack && wx <= c.x + c.extent + slack && wy >= c.y - slack && wy <= c.y + c.extent + slack) return { cell: c };
}
if (show_.bubbles || show_.pools) {
for (const d of view ? view.deps : []) {
if ((d.kind === 2 && !show_.bubbles) || (d.kind !== 2 && !show_.pools)) continue;
const r = Math.max(d.r, slack);
if ((wx - d.x) ** 2 + (wy - d.y) ** 2 <= r * r) return { dep: d };
}
}
return null;
}
function cellLines(c) {
const kind = c.flags & 1 ? 'Wildlife' : c.flags & 2 ? 'Player (connected)' : 'Player';
return [
['Kind', kind], ['Life', c.life], ['Organism', c.organism], ['Account', c.account || '—'],
['Members', c.members], ['Size', fmtLength(c.extent)], ['Body mass', fmtMass(c.bodyMass)],
['Reserve energy', fmtEnergy(c.reserve[0])],
['Reserve C / N / P / other', c.reserve.slice(1).map(fmtMass).join(' / ')],
['Position', `${fmtLength(c.x)}, ${fmtLength(c.y)}`],
];
}
function showDetail(c) {
selected = c;
detail.replaceChildren(h('h2', {}, c.flags & 1 ? 'Wildlife cell' : 'Player cell'),
h('dl', { class: 'facts' }, cellLines(c).flatMap(([k, v]) => [h('dt', {}, k), h('dd', { class: k === 'Life' || k === 'Account' ? 'mono' : null }, v)])),
c.account ? h('p', {}, h('a', { href: `#/accounts/${c.account}` }, 'Open account →')) : null);
paint();
}
canvas.addEventListener('mousemove', (e) => {
const rect = canvas.getBoundingClientRect();
if (drag) {
panX = drag.panX + (e.clientX - drag.x); panY = drag.panY + (e.clientY - drag.y);
paint(); return;
}
const found = hit(e.clientX - rect.left, e.clientY - rect.top);
if (!found) { tip.hidden = true; return; }
const lines = found.cell
? cellLines(found.cell).slice(0, 7)
: [['Kind', found.dep.kind === 2 ? 'Bubble' : 'Pool'], ['Energy', fmtEnergy(found.dep.stock[0])],
['C / N / P / other', found.dep.stock.slice(1).map(fmtMass).join(' / ')], ['Radius', fmtLength(found.dep.r)]];
tip.replaceChildren(...lines.map(([k, v]) => h('div', {}, h('span', { class: 'muted' }, `${k}: `), String(v))));
tip.hidden = false;
tip.style.left = `${Math.min(e.clientX - rect.left + 14, rect.width - 290)}px`;
tip.style.top = `${e.clientY - rect.top + 14}px`;
});
canvas.addEventListener('mouseleave', () => { tip.hidden = true; drag = null; });
canvas.addEventListener('mousedown', (e) => { drag = { x: e.clientX, y: e.clientY, panX, panY, moved: false }; });
canvas.addEventListener('mouseup', (e) => {
const wasDrag = drag && (Math.abs(e.clientX - drag.x) > 3 || Math.abs(e.clientY - drag.y) > 3);
drag = null;
if (wasDrag) return;
const rect = canvas.getBoundingClientRect();
const found = hit(e.clientX - rect.left, e.clientY - rect.top);
if (found && found.cell) showDetail(found.cell);
});
canvas.addEventListener('wheel', (e) => {
e.preventDefault();
const rect = canvas.getBoundingClientRect();
const mx = e.clientX - rect.left - rect.width / 2, my = e.clientY - rect.top - rect.height / 2;
const factor = Math.exp(-e.deltaY * 0.0015);
const next = Math.min(64, Math.max(1, zoom * factor));
const k = next / zoom;
panX = mx - (mx - panX) * k; panY = my - (my - panY) * k;
zoom = next;
if (zoom === 1) { panX = 0; panY = 0; }
paint();
}, { passive: false });
canvas.addEventListener('dblclick', () => { zoom = 1; panX = 0; panY = 0; paint(); });
const onResize = () => paint();
window.addEventListener('resize', onResize);
async function load() {
try {
const raw = await api(`/api/regions/${region}/view`);
view = { ...raw, cells: raw.cells.map(cellObj), deps: raw.deposits.map(depObj) };
const players = view.cells.filter((c) => !(c.flags & 1));
const online = players.filter((c) => c.flags & 2).length;
const wild = view.cells.length - players.length;
const bubbles = view.deps.filter((d) => d.kind === 2).length;
const spentMatter = raw.spent.slice(1).reduce((s, v) => s + v, 0);
statsBox.replaceChildren(
stat('Tick', fmtInt(raw.tick)), stat('Cells', fmtInt(raw.cells_total)),
stat('Players', fmtInt(players.length), `${online} connected`), stat('Wildlife', fmtInt(wild)),
stat('Bubbles', fmtInt(bubbles), `${fmtInt(raw.deposits_total - bubbles)} pools`),
stat('Spent pool', fmtEnergy(raw.spent[0]), fmtMass(spentMatter)),
stat('Area', `${fmtLength(raw.area[0])} × ${fmtLength(raw.area[1])}`));
const truncated = raw.cells_total > raw.cells.length || raw.deposits_total > raw.deposits.length;
status.textContent = ` rules ${raw.rules}${truncated ? ' · view truncated' : ''} · updated ${new Date().toLocaleTimeString()}`;
status.className = truncated ? 'error' : 'muted';
if (selected) {
const again = view.cells.find((c) => c.life === selected.life);
if (again) showDetail(again); else { selected = null; detail.replaceChildren(h('span', { class: 'muted' }, 'The selected cell is gone (died or left).')); }
}
paint();
} catch (e) {
status.textContent = ` ${e.status === 503 ? 'region not ready or unreachable' : e.message}`;
status.className = 'error';
}
}
const tick = () => { timer = setTimeout(async () => { if (live.checked && !document.hidden) await load(); tick(); }, 1000); };
await load();
tick();
stopPage = () => { clearTimeout(timer); window.removeEventListener('resize', onResize); };
}
// ---------- Routing ----------
async function route() {
stopPage();
stopPage = () => {};
const [path, query] = (location.hash.slice(1) || '/accounts').split('?');
const parts = path.split('/').filter(Boolean);
const params = new URLSearchParams(query || '');
for (const a of document.querySelectorAll('[data-route]')) a.classList.toggle('active', a.dataset.route === parts[0]);
try {
if (parts[0] === 'accounts' && parts[1]) await accountPage(parts[1]);
else if (parts[0] === 'regions' && parts[1]) await regionPage(parts[1], params);
else if (parts[0] === 'regions') await regionsPage();
else await accountsPage();
main().focus({ preventScroll: true });
} catch (e) {
if (e instanceof ApiError && e.status === 401) return signedOut();
if (e instanceof ApiError && e.status === 403) {
return show(h('div', { class: 'center' }, h('div', {}, h('h1', {}, 'Not an administrator'),
h('p', { class: 'muted' }, 'Your account does not have the aevolution-admin role.'),
h('button', { onclick: signOut }, 'Sign out'))));
}
show(h('p', { class: 'error' }, `Could not load this page: ${e.message}`), h('button', { onclick: () => route() }, 'Try again'));
}
}
function signedOut() {
document.getElementById('who').textContent = '';
document.getElementById('sign-out').hidden = true;
show(h('div', { class: 'center' }, h('div', {}, h('h1', {}, 'AEvolution admin'),
h('p', { class: 'muted' }, 'Sign in with an account that has the aevolution-admin role.'),
h('button', { class: 'primary', onclick: signIn }, 'Sign in'))));
}
async function start() {
config = await (await fetch('/config.json', { cache: 'no-store' })).json();
document.getElementById('sign-out').addEventListener('click', signOut);
try {
await finishSignIn();
} catch (e) {
show(h('p', { class: 'error' }, e.message), h('button', { class: 'primary', onclick: signIn }, 'Sign in again'));
return;
}
if (!(await token())) return signedOut();
try {
const me = await api('/api/me');
document.getElementById('who').textContent = me.email || me.subject;
document.getElementById('sign-out').hidden = false;
} catch (e) {
if (e instanceof ApiError && e.status === 401) return signedOut();
}
window.addEventListener('hashchange', route);
await route();
}
start();