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>
This commit is contained in:
dingo
2026-10-27 12:39:28 -04:00
co-authored by Claude Opus 5.5
parent 46e5ea6c5d
commit 54beceb823
36 changed files with 2331 additions and 37 deletions
+201
View File
@@ -0,0 +1,201 @@
// ADR-0182 read-only admin API and portal host for one world (DEV).
//
// evo-admin-api --listen ADDRESS:PORT --world N --jwks JSON --oidc-issuer URL
// --audience NAME --client NAME --role NAME --assets DIR
// --pg-passfile F --pg-service F [--region REGION=HOST:PORT ...]
//
// --assets holds the portal's index.html, app.js and style.css. Each --region names a
// region's operations address, whose /admin/view the portal may show. No token is printed.
#include "evo/persistence/postgres.hpp"
#include "evo/server/admin/admin_api.hpp"
#include <algorithm>
#include <charconv>
#include <chrono>
#include <csignal>
#include <cstdio>
#include <fstream>
#include <iterator>
#include <map>
#include <optional>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
namespace {
using namespace evo;
using namespace std::chrono_literals;
volatile std::sig_atomic_t stop_requested = 0;
void on_stop(int) {
stop_requested = 1;
}
struct Options {
std::string listen, jwks, oidc_issuer, audience, client, role, assets;
std::uint64_t world{};
std::map<std::uint64_t, std::string> regions; // Region to its operations address.
persistence::PgOptions pg;
};
std::optional<std::uint64_t> number(std::string_view text) {
std::uint64_t value{};
const auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), value);
if (error != std::errc{} || end != text.data() + text.size())
return std::nullopt;
return value;
}
std::optional<Options> parse(int argc, char** argv) {
Options o;
std::string pg_service, pg_passfile;
for (int i = 1; i + 1 < argc; i += 2) {
const std::string_view flag = argv[i];
const std::string_view value = argv[i + 1];
const auto n = number(value);
if (flag == "--listen")
o.listen = value;
else if (flag == "--world" && n && *n > 0)
o.world = *n;
else if (flag == "--jwks")
o.jwks = value;
else if (flag == "--oidc-issuer")
o.oidc_issuer = value;
else if (flag == "--audience")
o.audience = value;
else if (flag == "--client")
o.client = value;
else if (flag == "--role")
o.role = value;
else if (flag == "--assets")
o.assets = value;
else if (flag == "--pg-service")
pg_service = value;
else if (flag == "--pg-passfile")
pg_passfile = value;
else if (flag == "--region") {
const auto equals = value.find('=');
const auto region =
equals == std::string_view::npos ? std::nullopt : number(value.substr(0, equals));
const auto address =
equals == std::string_view::npos ? std::string_view{} : value.substr(equals + 1);
if (!region || *region == 0 || address.empty() || address.size() > 128 ||
!o.regions.emplace(*region, std::string(address)).second)
return std::nullopt;
} else
return std::nullopt;
}
// Names are embedded in the portal's JSON settings: printable ASCII without quotes.
const auto plain = [](std::string_view text) {
return !text.empty() && text.size() <= 256 && std::ranges::all_of(text, [](char ch) {
return ch > ' ' && ch <= '~' && ch != '"' && ch != '\\';
});
};
if (argc % 2 != 1 || o.listen.empty() || o.world == 0 || o.jwks.empty() ||
!plain(o.oidc_issuer) || !o.oidc_issuer.starts_with("https://") || !plain(o.audience) ||
!plain(o.client) || !plain(o.role) || o.assets.empty() || pg_service.empty() ||
pg_passfile.empty())
return std::nullopt;
auto service = persistence::read_pg_service(pg_service, "evolution");
if (!service)
return std::nullopt;
o.pg = *service;
o.pg.password_file = pg_passfile;
return o;
}
std::optional<std::string> read_file(const std::string& path) {
std::ifstream file{path, std::ios::binary};
if (!file)
return std::nullopt;
std::string body{std::istreambuf_iterator<char>{file}, std::istreambuf_iterator<char>{}};
if (body.empty() || body.size() > (std::size_t{1} << 20U))
return std::nullopt;
return body;
}
std::uint64_t wall_seconds() {
return static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch())
.count());
}
} // namespace
int main(int argc, char** argv) {
const auto options = parse(argc, argv);
if (!options) {
std::fputs("usage: evo-admin-api (see apps/evo-admin-api/main.cpp)\n", stderr);
return 2;
}
std::signal(SIGTERM, on_stop);
std::signal(SIGINT, on_stop);
std::signal(SIGPIPE, SIG_IGN);
auto verifier = server::broker::TokenVerifier::from_jwks(
options->jwks,
{options->oidc_issuer, options->audience, options->client, 30, options->role});
if (!verifier) {
std::puts("error jwks");
return 2;
}
std::vector<server::admin::AdminAsset> assets;
for (const auto& [name, type] : {std::pair{"index.html", "text/html; charset=utf-8"},
std::pair{"app.js", "text/javascript; charset=utf-8"},
std::pair{"style.css", "text/css; charset=utf-8"}}) {
auto body = read_file(options->assets + "/" + name);
if (!body) {
std::printf("error assets %s\n", name);
return 2;
}
assets.push_back({std::string("/") + name, type, std::move(*body)});
}
// The realm's origin: sign-in redirects there and the portal exchanges tokens with it.
const auto origin_end = options->oidc_issuer.find('/', std::string_view{"https://"}.size());
const auto origin = options->oidc_issuer.substr(0, origin_end);
server::admin::AdminConfig config;
config.world = options->world;
for (const auto& [region, address] : options->regions)
config.view_regions.push_back(region);
config.portal_config_json = "{\"issuer\":\"" + options->oidc_issuer + "\",\"client_id\":\"" +
options->client + "\",\"world\":" + std::to_string(options->world) +
"}\n";
config.content_security_policy =
"default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; "
"connect-src 'self' " +
origin + "; form-action 'self' " + origin + "; frame-ancestors 'none'; base-uri 'none'";
auto listening = server::OpsServer::listen(options->listen,
server::OpsServer::max_configurable_response_bytes);
if (!listening) {
std::puts("error listen");
return 2;
}
const auto pg = options->pg;
const auto regions = options->regions;
server::admin::AdminApi api{std::move(config), std::move(*verifier),
[pg]() -> std::unique_ptr<persistence::Postgres> {
auto db = persistence::Postgres::connect(pg, 3s);
return db ? std::move(*db) : nullptr;
},
[regions](std::uint64_t region) -> std::optional<std::string> {
const auto found = regions.find(region);
if (found == regions.end())
return std::nullopt;
return server::admin::http_get(
found->second, "/admin/view", 1500ms,
server::OpsServer::max_configurable_response_bytes);
},
std::move(assets)};
std::printf("admin api listening %u world %llu\n", static_cast<unsigned>((*listening)->port()),
static_cast<unsigned long long>(options->world));
std::fflush(stdout);
while (stop_requested == 0) {
(*listening)->serve_api([&](const server::ApiRequest& request) {
return api.handle(request, wall_seconds(), std::chrono::steady_clock::now());
});
std::this_thread::sleep_for(5ms);
}
std::puts("admin api stopped");
return 0;
}
+558
View File
@@ -0,0 +1,558 @@
// 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();
+30
View File
@@ -0,0 +1,30 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex">
<title>AEvolution Admin</title>
<link rel="stylesheet" href="/style.css">
<script type="module" src="/app.js"></script>
</head>
<body>
<header class="bar">
<a class="brand" href="#/accounts">AEvolution <span>admin</span></a>
<nav class="sections" aria-label="Sections">
<div class="section">
<span class="section-name">Cellular</span>
<a href="#/accounts" data-route="accounts">Accounts</a>
<a href="#/regions" data-route="regions">Regions</a>
</div>
</nav>
<div class="who">
<span id="who" class="muted"></span>
<button id="sign-out" class="ghost" hidden>Sign out</button>
</div>
</header>
<main id="main" tabindex="-1">
<p class="muted">Loading…</p>
</main>
</body>
</html>
+184
View File
@@ -0,0 +1,184 @@
/* ADR-0182 admin portal. Tokens first; dark is the default, light follows the system. */
:root {
--bg: #0f1419;
--panel: #161d24;
--panel-2: #1c252e;
--line: #2a3640;
--text: #dbe3ea;
--muted: #8a99a6;
--accent: #4fb3ff;
--good: #3ecf8e;
--warn: #f2b84b;
--bad: #ff6b6b;
--player: #4f8dff;
--online: #5ff2ff;
--wildlife: #3ecf8e;
--pool: rgba(120, 170, 255, 0.16);
--energy: #ffd84d;
--carbon: #b0b7bf;
--nitrogen: #9b7bff;
--phosphorus: #ff9a3c;
--other: #ff6fb5;
--radius: 8px;
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
color-scheme: dark;
}
@media (prefers-color-scheme: light) {
:root {
--bg: #f5f7f9;
--panel: #ffffff;
--panel-2: #eef2f5;
--line: #d6dde3;
--text: #18212a;
--muted: #5d6b77;
--accent: #0b6bcb;
--pool: rgba(30, 90, 200, 0.12);
--carbon: #59626b;
color-scheme: light;
}
}
* { box-sizing: border-box; }
html, body { margin: 0; }
body {
background: var(--bg);
color: var(--text);
font: 14px/1.45 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
}
a { color: var(--accent); text-decoration: none; }
a:hover { text-decoration: underline; }
button {
font: inherit;
color: var(--text);
background: var(--panel-2);
border: 1px solid var(--line);
border-radius: 6px;
padding: 5px 12px;
cursor: pointer;
}
button:hover { border-color: var(--accent); }
button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
button.ghost { background: transparent; }
input[type="search"] {
font: inherit;
color: var(--text);
background: var(--panel);
border: 1px solid var(--line);
border-radius: 6px;
padding: 5px 10px;
min-width: 240px;
}
.muted { color: var(--muted); }
.mono { font-family: var(--mono); font-size: 12.5px; }
.bar {
display: flex;
align-items: center;
gap: 24px;
padding: 10px 20px;
background: var(--panel);
border-bottom: 1px solid var(--line);
position: sticky;
top: 0;
z-index: 2;
}
.brand { font-weight: 700; color: var(--text); letter-spacing: 0.02em; }
.brand span { color: var(--accent); font-weight: 500; }
.sections { display: flex; gap: 20px; flex: 1; }
.section { display: flex; align-items: center; gap: 4px; }
.section-name {
text-transform: uppercase;
font-size: 11px;
letter-spacing: 0.08em;
color: var(--muted);
margin-right: 6px;
}
.section a { padding: 5px 10px; border-radius: 6px; color: var(--text); }
.section a.active { background: var(--panel-2); color: var(--accent); }
.who { display: flex; align-items: center; gap: 10px; }
main { padding: 20px; max-width: 1600px; margin: 0 auto; }
h1 { font-size: 20px; margin: 0 0 4px; }
h2 { font-size: 15px; margin: 20px 0 8px; }
.head { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; flex-wrap: wrap; margin-bottom: 14px; }
.tools { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
.card {
background: var(--panel);
border: 1px solid var(--line);
border-radius: var(--radius);
padding: 14px 16px;
}
.stats { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px; margin-bottom: 14px; }
.stat { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 10px 12px; }
.stat .label { font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); }
.stat .value { font-size: 18px; font-weight: 600; margin-top: 2px; }
.stat .value small { font-size: 12px; font-weight: 400; color: var(--muted); }
.table-wrap { overflow-x: auto; border: 1px solid var(--line); border-radius: var(--radius); }
table { border-collapse: collapse; width: 100%; background: var(--panel); }
th, td { text-align: left; padding: 7px 10px; border-bottom: 1px solid var(--line); white-space: nowrap; }
th { font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); background: var(--panel-2); cursor: pointer; user-select: none; }
th.sorted::after { content: " ▾"; }
th.sorted.up::after { content: " ▴"; }
td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
tbody tr:hover { background: var(--panel-2); }
tbody tr.clickable { cursor: pointer; }
.badge {
display: inline-block;
font-size: 11.5px;
padding: 1px 8px;
border-radius: 999px;
border: 1px solid var(--line);
color: var(--muted);
}
.badge.alive { color: var(--good); border-color: var(--good); }
.badge.dead { color: var(--bad); border-color: var(--bad); }
.badge.online { color: var(--online); border-color: var(--online); }
.badge.warn { color: var(--warn); border-color: var(--warn); }
dl.facts { display: grid; grid-template-columns: max-content 1fr; gap: 6px 18px; margin: 0; }
dl.facts dt { color: var(--muted); }
dl.facts dd { margin: 0; }
.region-layout { display: grid; grid-template-columns: minmax(0, 1fr) 320px; gap: 14px; }
@media (max-width: 1000px) { .region-layout { grid-template-columns: 1fr; } }
.canvas-wrap {
position: relative;
background: var(--panel);
border: 1px solid var(--line);
border-radius: var(--radius);
overflow: hidden;
aspect-ratio: 1 / 1;
max-height: calc(100vh - 230px);
width: 100%;
}
.canvas-wrap canvas { display: block; width: 100%; height: 100%; cursor: crosshair; }
.overlay-note { position: absolute; left: 10px; bottom: 8px; font-size: 12px; color: var(--muted); pointer-events: none; }
.tooltip {
position: absolute;
pointer-events: none;
background: var(--panel-2);
border: 1px solid var(--line);
border-radius: 6px;
padding: 6px 8px;
font-size: 12px;
max-width: 280px;
z-index: 1;
}
.side { display: flex; flex-direction: column; gap: 12px; }
.legend { display: grid; grid-template-columns: 14px 1fr; gap: 6px 8px; align-items: center; font-size: 13px; }
.swatch { width: 12px; height: 12px; border-radius: 50%; }
.swatch.player { background: var(--player); }
.swatch.online { background: var(--online); }
.swatch.wildlife { background: var(--wildlife); }
.swatch.pool { background: var(--pool); border: 1px solid var(--accent); }
.swatch.energy { background: var(--energy); }
.swatch.carbon { background: var(--carbon); }
.swatch.nitrogen { background: var(--nitrogen); }
.swatch.phosphorus { background: var(--phosphorus); }
.swatch.other { background: var(--other); }
.toggles { display: flex; flex-direction: column; gap: 6px; }
.toggles label { display: flex; gap: 8px; align-items: center; cursor: pointer; }
.error { color: var(--bad); }
.center { display: grid; place-items: center; min-height: 50vh; text-align: center; }
+18 -1
View File
@@ -55,6 +55,7 @@
#include "evo/biology/founder.hpp"
#include "evo/processes/development_opening.hpp"
#include "evo/server/cellular_session_batch.hpp"
#include "evo/server/lifecycle/cellular_admin_view.hpp"
#include "evo/server/lifecycle/cellular_schedule.hpp"
#include "evo/server/lifecycle/primitive_lives.hpp"
#include "evo/server/lifecycle/wildlife_controller.hpp"
@@ -925,7 +926,9 @@ int serve_cellular(Options& o) {
return 2;
std::unique_ptr<server::OpsServer> ops;
if (!o.ops_listen.empty()) {
auto listening = server::OpsServer::listen(o.ops_listen);
// Room for /admin/view (ADR-0182); probes and metrics stay small.
auto listening = server::OpsServer::listen(
o.ops_listen, server::OpsServer::max_configurable_response_bytes);
if (!listening) {
std::puts("error ops-listen");
return 2;
@@ -1092,6 +1095,20 @@ int serve_cellular(Options& o) {
counters.checkpoint_age_ms = schedule.status().head_age_us / 1000;
return {200, server::render_metrics(paced, counters)};
}
// ADR-0182: the admin portal's read-only region view. The port admits only
// Prometheus and the admin API (NetworkPolicy).
if (path == "/admin/view") {
const auto* state = host.state();
if (!current.ready || state == nullptr)
return {503, "not ready\n"};
const auto online = [&](const server::LifeAccount& account) {
network::AccountId id;
id.bytes = account;
return bridge->sessions().holder(id).has_value();
};
return {200, server::render_cellular_admin_view(*state, online),
"application/json"};
}
return {404, "not found\n"};
};
ops->serve(handler);