Merge control portal work from RPGTheory/aeternalis-portal
RPGTheory/aeternalis-portal had diverged from this repo (the git/CI/CD copy) with an in-progress control portal feature that was never synced back here, so none of it had gone through CI or been deployed: - New site/game/control routing split: index.html becomes a world directory landing page (site.ts), game.html is the renamed former index.html (main.ts), control.html is a new admin panel (control.ts, portal-shared.ts, portal.css). - Server: new internal/store/portal.go (character/world registry, command queue, admin grants) and internal/transport/control.go (portal API routes), plus a new internal/gitops package that lets the portal provision new worlds via a GitOps repo commit. - game.World gains BornAt/DiedAt/DeathReason and an operator Control() path (close/open admissions, awaken boss, end world, per-character rename/heal/unstuck/retire); death no longer reuses the same character id on rejoin, matching the "new life" permadeath model in Plan.md rather than the old bypass-prevention test's expectations. - deploy/: new control-egress network policy and portal/control values (admin role, GitOps repo/branch/values file/CIDRs). - New e2e coverage: tests/portal.spec.ts, tools/capture-world.mjs. Verified this repo's own independent commits (800ms movement-staleness window, 20s boss-attack poll, SRS/TLS deploy values, ubuntu-22.04 runner pin, DOCKER_HOST fix) were already present in the portal copy before merging, so nothing here regresses them. `tsc --noEmit`, the vite client build, and the protocol contract check all pass; no go.mod changes. Could not run `go build`/`go test` locally (no Go toolchain on PATH, Docker daemon not running) — every new/changed Go symbol was manually cross-referenced and resolves, but this should still be built and tested in CI before merging to master. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><meta name="theme-color" content="#122b24"/><title>Aeternalis | Control</title><link rel="icon" href="data:,"/></head>
|
||||
<body class="control-site">
|
||||
<aside class="control-sidebar"><a class="wordmark" href="/">AETERNALIS<span>Control</span></a><nav aria-label="Control navigation"><button class="nav-item active" data-tab="worlds"><i data-lucide="globe-2"></i>Worlds</button><button class="nav-item" data-tab="characters"><i data-lucide="users"></i>Characters</button><button class="nav-item" data-tab="audit"><i data-lucide="scroll-text"></i>Audit log</button></nav><div class="sidebar-bottom"><a href="/"><i data-lucide="arrow-up-right"></i>Public site</a><a href="/game"><i data-lucide="play"></i>Game</a></div></aside>
|
||||
<main class="control-main"><header class="control-header"><div><p class="eyebrow">OPERATIONS</p><h1 id="view-title">Worlds</h1></div><div class="heading-tools"><span id="updated" class="muted"></span><button id="refresh" class="icon-button" title="Refresh" aria-label="Refresh"><i data-lucide="refresh-cw"></i></button><button id="create-world" class="button" disabled><i data-lucide="plus"></i>New world</button><button id="admin-signout" class="icon-button" title="Sign out" aria-label="Sign out" hidden><i data-lucide="log-out"></i></button></div></header>
|
||||
<div id="access" class="access-state"><i data-lucide="shield-check"></i><h2 id="access-title">Checking access</h2><p id="access-message"></p><a id="admin-login" class="button" href="/auth/login?return=%2Fcontrol" hidden>Sign in<i data-lucide="log-in"></i></a></div>
|
||||
<div id="workspace" hidden><section class="metrics" aria-label="World summary"><div><span>Worlds online</span><strong id="metric-worlds">0</strong></div><div><span>Living characters</span><strong id="metric-living">0</strong></div><div><span>Fallen characters</span><strong id="metric-dead">0</strong></div><div><span>Pending actions</span><strong id="metric-pending">0</strong></div></section>
|
||||
<div id="control-message" class="message" role="status" hidden></div>
|
||||
<div class="table-tools"><label class="search-field"><i data-lucide="search"></i><input id="search" type="search" aria-label="Search records" placeholder="Search worlds"/></label><label>World<select id="world-filter"><option value="">All worlds</option></select></label><label>State<select id="state-filter"><option value="">All states</option></select></label><span id="record-count" class="muted"></span></div>
|
||||
<section id="records" class="table-wrap" aria-label="Records"></section>
|
||||
<p id="table-note" class="table-note"></p>
|
||||
</div>
|
||||
</main>
|
||||
<dialog id="command-dialog" class="command-dialog"><form id="command-form"><header><h2 id="command-title">New world</h2><button type="button" id="close-command" class="icon-button" aria-label="Close dialog" title="Close"><i data-lucide="x"></i></button></header><p id="command-context" class="muted"></p><label id="world-input-label">World ID<input id="world-input" pattern="[a-z][a-z0-9-]{0,30}" maxlength="31" autocomplete="off"/></label><label id="value-input-label"><span id="value-caption">Seed</span><input id="value-input" autocomplete="off"/></label><label>Reason<textarea id="reason-input" required minlength="5" maxlength="240" rows="3"></textarea></label><label id="confirm-input-label" hidden><span id="confirm-caption">Confirm target</span><input id="confirm-input" autocomplete="off"/></label><p id="command-error" class="error" role="alert"></p><footer><button type="button" id="cancel-command" class="button secondary">Cancel</button><button type="submit" id="submit-command" class="button"><i data-lucide="check"></i><span>Queue action</span></button></footer></form></dialog>
|
||||
<dialog id="character-dialog" class="character-dialog"><header><div><p class="eyebrow">CHARACTER RECORD</p><h2 id="detail-name"></h2></div><button id="close-character" class="icon-button" aria-label="Close character" title="Close"><i data-lucide="x"></i></button></header><div id="character-detail"></div></dialog>
|
||||
<script type="module" src="/src/control.ts"></script>
|
||||
</body></html>
|
||||
@@ -0,0 +1,35 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||
<meta name="theme-color" content="#172725" />
|
||||
<title>Aeternalis</title>
|
||||
<link rel="icon" href="data:," />
|
||||
</head>
|
||||
<body>
|
||||
<canvas id="world" aria-label="Aeternalis 3D world"></canvas>
|
||||
<div id="hud">
|
||||
<header class="topbar">
|
||||
<div class="brand"><a class="brand-mark" href="/" title="World directory" aria-label="World directory">A</a><div><strong>AETERNALIS</strong><span id="world-name">The First Reach</span></div></div>
|
||||
<div class="compass"><span>W</span><span>NW</span><b>N</b><span>NE</span><span>E</span></div>
|
||||
<div class="connection"><i id="connection-dot"></i><span id="connection-status">Connecting</span><button id="settings-toggle" class="icon" title="Display settings" aria-label="Display settings"><i data-lucide="settings-2"></i></button></div>
|
||||
</header>
|
||||
<section id="season" class="season"><div><span id="phase-label">THE GATHERING</span><strong id="season-clock">7d 00h</strong></div><span id="season-detail">Until the Harbinger</span><div class="thin-track"><i id="season-progress"></i></div></section>
|
||||
<section id="boss-bar" class="boss-bar" hidden><button id="target-boss" title="Target Harbinger" aria-label="Target Harbinger"><i data-lucide="crosshair"></i> THE HARBINGER</button><div class="bar"><i id="boss-health"></i></div><small id="boss-count"></small></section>
|
||||
<aside id="settings" class="panel settings" hidden><div class="panel-title"><h2>Display</h2><button data-close="settings" class="icon" title="Close" aria-label="Close display settings"><i data-lucide="x"></i></button></div><label>Detail <select id="quality"><option value="high">High</option><option value="low">Low</option></select></label><label>Camera distance <input id="zoom" type="range" min="30" max="100" value="62" /></label><button id="dev-boss" hidden><i data-lucide="flame"></i> Awaken Harbinger</button><button id="logout"><i data-lucide="log-out"></i> Sign out</button></aside>
|
||||
<aside id="inventory" class="panel inventory" hidden><div class="panel-title"><h2>Inventory</h2><button data-close="inventory" class="icon" title="Close" aria-label="Close inventory"><i data-lucide="x"></i></button></div><div id="inventory-items" class="inventory-items"></div><h3>Crafting</h3><div id="recipes"></div><h3>Skills</h3><div id="skills" class="skills"></div></aside>
|
||||
<div id="target" class="target" hidden><span id="target-name"></span><span id="target-health"></span></div>
|
||||
<div id="notice" role="status" class="notice" hidden></div>
|
||||
<footer class="bottom" id="game-controls" hidden>
|
||||
<section class="vitals"><div><strong id="character-name">Traveler</strong><span id="health-number">100 / 100</span></div><div class="bar"><i id="health-fill"></i></div><div class="vital-detail"><span><i data-lucide="hourglass"></i><span id="play-time">2h left today</span></span><span id="kills">0 kills</span></div></section>
|
||||
<nav class="actions" aria-label="Actions"><button id="attack" title="Attack" aria-label="Attack"><i data-lucide="swords"></i></button><button id="gather" title="Gather" aria-label="Gather"><i data-lucide="pickaxe"></i></button><button id="heal" title="Use bandage" aria-label="Use bandage"><i data-lucide="heart-pulse"></i><small id="bandage-count">0</small></button><button id="keystone" title="Return with keystone" aria-label="Return with keystone"><i data-lucide="gem"></i></button><span></span><button id="inventory-toggle" title="Inventory and crafting" aria-label="Inventory and crafting"><i data-lucide="backpack"></i></button></nav>
|
||||
<section class="location"><canvas id="minimap" width="140" height="140" aria-label="World map"></canvas><span id="coordinates">0, 0</span><small id="chunk-count">9 chunks</small></section>
|
||||
</footer>
|
||||
<nav id="movement" class="movement" aria-label="Movement" hidden><button data-move="up" aria-label="Move north"><i data-lucide="chevron-up"></i></button><button data-move="left" aria-label="Move west"><i data-lucide="chevron-left"></i></button><button data-move="down" aria-label="Move south"><i data-lucide="chevron-down"></i></button><button data-move="right" aria-label="Move east"><i data-lucide="chevron-right"></i></button></nav>
|
||||
</div>
|
||||
<dialog id="arrival" open><div class="eyebrow">THE FIRST REACH</div><h1>Aeternalis</h1><p id="arrival-status">One life. A world on borrowed time.</p><form id="join-form"><label for="name">Character name</label><input id="name" name="name" autocomplete="nickname" minlength="2" maxlength="24" placeholder="Traveler" required value="Traveler" /><button id="join" type="submit">Enter world <i data-lucide="arrow-right"></i></button></form><a id="login" class="command" href="/auth/login" hidden>Sign in <i data-lucide="arrow-right"></i></a><div id="passages"></div><p id="arrival-error" class="error" role="alert"></p></dialog>
|
||||
<dialog id="ending"><div class="eyebrow" id="ending-eyebrow">JOURNEY ENDED</div><h1 id="ending-title">Your story remains.</h1><p id="ending-detail"></p><div id="destinations"></div><button id="new-character" hidden>New character <i data-lucide="arrow-right"></i></button><button id="reconnect" hidden>Reconnect <i data-lucide="refresh-cw"></i></button><a href="/" class="command">World directory</a></dialog>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
+10
-33
@@ -1,35 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||
<meta name="theme-color" content="#172725" />
|
||||
<title>Aeternalis</title>
|
||||
<link rel="icon" href="data:," />
|
||||
</head>
|
||||
<body>
|
||||
<canvas id="world" aria-label="Aeternalis 3D world"></canvas>
|
||||
<div id="hud">
|
||||
<header class="topbar">
|
||||
<div class="brand"><span class="brand-mark">A</span><div><strong>AETERNALIS</strong><span id="world-name">The First Reach</span></div></div>
|
||||
<div class="compass"><span>W</span><span>NW</span><b>N</b><span>NE</span><span>E</span></div>
|
||||
<div class="connection"><i id="connection-dot"></i><span id="connection-status">Connecting</span><button id="settings-toggle" class="icon" title="Display settings" aria-label="Display settings"><i data-lucide="settings-2"></i></button></div>
|
||||
</header>
|
||||
<section id="season" class="season"><div><span id="phase-label">THE GATHERING</span><strong id="season-clock">7d 00h</strong></div><span id="season-detail">Until the Harbinger</span><div class="thin-track"><i id="season-progress"></i></div></section>
|
||||
<section id="boss-bar" class="boss-bar" hidden><button id="target-boss" title="Target Harbinger" aria-label="Target Harbinger"><i data-lucide="crosshair"></i> THE HARBINGER</button><div class="bar"><i id="boss-health"></i></div><small id="boss-count"></small></section>
|
||||
<aside id="settings" class="panel settings" hidden><div class="panel-title"><h2>Display</h2><button data-close="settings" class="icon" title="Close" aria-label="Close display settings"><i data-lucide="x"></i></button></div><label>Detail <select id="quality"><option value="high">High</option><option value="low">Low</option></select></label><label>Camera distance <input id="zoom" type="range" min="30" max="100" value="62" /></label><button id="dev-boss" hidden><i data-lucide="flame"></i> Awaken Harbinger</button><button id="logout"><i data-lucide="log-out"></i> Sign out</button></aside>
|
||||
<aside id="inventory" class="panel inventory" hidden><div class="panel-title"><h2>Inventory</h2><button data-close="inventory" class="icon" title="Close" aria-label="Close inventory"><i data-lucide="x"></i></button></div><div id="inventory-items" class="inventory-items"></div><h3>Crafting</h3><div id="recipes"></div><h3>Skills</h3><div id="skills" class="skills"></div></aside>
|
||||
<div id="target" class="target" hidden><span id="target-name"></span><span id="target-health"></span></div>
|
||||
<div id="notice" role="status" class="notice" hidden></div>
|
||||
<footer class="bottom" id="game-controls" hidden>
|
||||
<section class="vitals"><div><strong id="character-name">Traveler</strong><span id="health-number">100 / 100</span></div><div class="bar"><i id="health-fill"></i></div><div class="vital-detail"><span><i data-lucide="hourglass"></i><span id="play-time">2h left today</span></span><span id="kills">0 kills</span></div></section>
|
||||
<nav class="actions" aria-label="Actions"><button id="attack" title="Attack" aria-label="Attack"><i data-lucide="swords"></i></button><button id="gather" title="Gather" aria-label="Gather"><i data-lucide="pickaxe"></i></button><button id="heal" title="Use bandage" aria-label="Use bandage"><i data-lucide="heart-pulse"></i><small id="bandage-count">0</small></button><button id="keystone" title="Return with keystone" aria-label="Return with keystone"><i data-lucide="gem"></i></button><span></span><button id="inventory-toggle" title="Inventory and crafting" aria-label="Inventory and crafting"><i data-lucide="backpack"></i></button></nav>
|
||||
<section class="location"><canvas id="minimap" width="140" height="140" aria-label="World map"></canvas><span id="coordinates">0, 0</span><small id="chunk-count">9 chunks</small></section>
|
||||
</footer>
|
||||
<nav id="movement" class="movement" aria-label="Movement" hidden><button data-move="up" aria-label="Move north"><i data-lucide="chevron-up"></i></button><button data-move="left" aria-label="Move west"><i data-lucide="chevron-left"></i></button><button data-move="down" aria-label="Move south"><i data-lucide="chevron-down"></i></button><button data-move="right" aria-label="Move east"><i data-lucide="chevron-right"></i></button></nav>
|
||||
</div>
|
||||
<dialog id="arrival" open><div class="eyebrow">THE FIRST REACH</div><h1>Aeternalis</h1><p id="arrival-status">One life. A world on borrowed time.</p><form id="join-form"><label for="name">Character name</label><input id="name" name="name" autocomplete="nickname" minlength="2" maxlength="24" placeholder="Traveler" required value="Traveler" /><button id="join" type="submit">Enter world <i data-lucide="arrow-right"></i></button></form><a id="login" class="command" href="/auth/login" hidden>Sign in <i data-lucide="arrow-right"></i></a><div id="passages"></div><p id="arrival-error" class="error" role="alert"></p></dialog>
|
||||
<dialog id="ending"><div class="eyebrow" id="ending-eyebrow">JOURNEY ENDED</div><h1 id="ending-title">Your story remains.</h1><p id="ending-detail"></p><div id="destinations"></div><button id="reconnect" hidden>Reconnect <i data-lucide="refresh-cw"></i></button></dialog>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
<head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><meta name="theme-color" content="#122b24"/><title>Aeternalis | Worlds</title><link rel="icon" href="data:,"/></head>
|
||||
<body class="public-site">
|
||||
<header class="site-header"><a class="wordmark" href="/">AETERNALIS<span>Survival worlds</span></a><nav aria-label="Main navigation"><a href="#worlds">Worlds</a><a href="#journey">My journey</a><a id="control-link" href="/control" hidden>Control</a><button id="account-button" class="button secondary"><i data-lucide="log-in"></i><span>Sign in</span></button></nav></header>
|
||||
<main>
|
||||
<section class="world-hero"><img src="/images/world.png" alt="The procedural forests and highlands of Aeternalis"/><div class="hero-shade"></div><div class="hero-copy"><p class="eyebrow">A WORLD ON BORROWED TIME</p><h1>Aeternalis</h1><p>The Harbinger is coming. Every life leaves a story.</p><a class="button light" href="#worlds">Choose a world<i data-lucide="arrow-down"></i></a></div><span class="hero-caption">THE FIRST REACH / IN-GAME TERRAIN</span></section>
|
||||
<section id="worlds" class="site-section"><div class="section-heading"><div><p class="eyebrow">THE REALMS</p><h2>Worlds</h2></div><div class="heading-tools"><span id="world-count" class="muted">Loading</span><button id="refresh" class="icon-button" aria-label="Refresh worlds" title="Refresh worlds"><i data-lucide="refresh-cw"></i></button></div></div><div id="site-message" class="message" role="status" hidden></div><div id="world-list" class="world-list" aria-live="polite"><p class="empty">Loading worlds...</p></div></section>
|
||||
<section id="journey" class="site-section journey-section"><div class="section-heading"><div><p class="eyebrow">ONE LIVING CHARACTER</p><h2>Your journey</h2></div></div><div id="active-character"></div><div id="character-history"><p class="empty">Sign in to see your characters.</p></div></section>
|
||||
</main><footer class="site-footer"><span>AETERNALIS</span><span>One character. One life. Another beginning.</span><a href="/control">Control portal</a></footer>
|
||||
<script type="module" src="/src/site.ts"></script>
|
||||
</body></html>
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 284 KiB |
@@ -0,0 +1,123 @@
|
||||
import './portal.css';
|
||||
import { $, api, APIError, badge, cell, date, el, gameURL, icons, icon, table, type Command, type RecordCharacter, type World } from './portal-shared';
|
||||
|
||||
type Data = { worlds: World[]; characters: RecordCharacter[]; commands: Command[]; provisioningEnabled: boolean; characterLimit: number; auditLimit: number };
|
||||
type Draft = { id: string; worldId: string; op: string; target: string; value: string };
|
||||
let data: Data;
|
||||
let tab = 'worlds';
|
||||
let busy = false;
|
||||
let draft: Draft;
|
||||
const labels: Record<string, string> = { 'create-world': 'New world', 'close-admissions': 'Close arrivals', 'open-admissions': 'Open arrivals', 'awaken-boss': 'Awaken Harbinger', 'end-world': 'End world permanently', rename: 'Rename character', heal: 'Restore health', unstuck: 'Return to sanctuary', retire: 'Retire character permanently', 'revoke-sessions': 'Revoke account sessions' };
|
||||
function notify(message: string) { $('control-message').textContent = message; $('control-message').hidden = false; }
|
||||
function openCommand(op: string, worldId = '', target = '', value = '') {
|
||||
draft = { id: crypto.randomUUID(), worldId, op, target, value };
|
||||
$<HTMLFormElement>('command-form').reset();
|
||||
const create = op === 'create-world', rename = op === 'rename';
|
||||
$('command-title').textContent = labels[op];
|
||||
$('command-context').textContent = create ? 'Deployment: GitOps / ArgoCD' : `${worldId}${target ? ` / ${target}` : ''}`;
|
||||
$('world-input-label').hidden = !create;
|
||||
$<HTMLInputElement>('world-input').required = create;
|
||||
$('value-input-label').hidden = !create && !rename;
|
||||
$('value-caption').textContent = create ? 'Seed' : 'Character name';
|
||||
const input = $<HTMLInputElement>('value-input'); input.required = create || rename; input.value = create ? String(crypto.getRandomValues(new Uint32Array(1))[0]) : value;
|
||||
input.pattern = create ? '[0-9]{1,15}' : '[A-Za-z0-9][A-Za-z0-9 _-]{1,23}'; input.maxLength = create ? 15 : 24;
|
||||
const dangerous = ['awaken-boss', 'end-world', 'retire'].includes(op);
|
||||
$('confirm-input-label').hidden = !dangerous;
|
||||
$('confirm-caption').textContent = `Confirm ${op === 'retire' ? 'character ID' : 'world ID'}: ${op === 'retire' ? target : worldId}`;
|
||||
$<HTMLInputElement>('confirm-input').required = dangerous;
|
||||
$('submit-command').classList.toggle('danger', dangerous);
|
||||
$('command-error').textContent = '';
|
||||
$<HTMLDialogElement>('command-dialog').showModal();
|
||||
}
|
||||
function actions(world: string, options: string[], target = '', value = '', disabled = false) {
|
||||
const parent = el('div', '', 'row-actions'); const select = el('select'); select.setAttribute('aria-label', `Action for ${target || world}`);
|
||||
select.append(new Option('Actions', ''));
|
||||
for (const op of options) select.append(new Option(labels[op], op));
|
||||
select.disabled = disabled;
|
||||
select.onchange = () => { const op = select.value; select.value = ''; if (op) openCommand(op, world, target, value); };
|
||||
parent.append(select); return parent;
|
||||
}
|
||||
function detail(r: RecordCharacter) {
|
||||
$('detail-name').textContent = r.name;
|
||||
const parent = $('character-detail'); parent.replaceChildren();
|
||||
const list = el('dl', '', 'details'); const v = r.character.view;
|
||||
const pairs: [string, string][] = [['Character ID', r.id], ['Account ID', r.account], ['World', r.worldId], ['State', r.state], ['Health', `${v.entity.hp} / ${v.entity.maxHp}`], ['Position', `${Math.round(v.entity.position.x)}, ${Math.round(v.entity.position.y)}, ${Math.round(v.entity.position.z)}`], ['Played today', `${Math.floor(r.character.dailySeconds / 60)} min`], ['Born', date(r.character.bornAt)], ['Died', r.character.diedAt ? date(r.character.diedAt) : '-'], ['Cause', r.character.deathReason || '-']];
|
||||
for (const [key,value] of pairs) list.append(el('dt', key), el('dd', value)); parent.append(list);
|
||||
for (const [heading, items] of [['Inventory', v.inventory], ['Skills', v.skills]] as const) { parent.append(el('h3', heading)); const section = el('div', '', 'item-list'); for (const [key,value] of Object.entries(items)) { const item = el('span', key.replaceAll('_', ' ')); item.append(el('b', String(value))); section.append(item); } if (!section.children.length) section.append(el('span', 'None', 'muted')); parent.append(section); }
|
||||
$<HTMLDialogElement>('character-dialog').showModal();
|
||||
}
|
||||
function render() {
|
||||
if (!data) return;
|
||||
const search = $<HTMLInputElement>('search').value.trim().toLowerCase(), world = $<HTMLSelectElement>('world-filter').value, state = $<HTMLSelectElement>('state-filter').value;
|
||||
const matches = (fields: string[], recordWorld: string, recordState: string) => (!world || world === recordWorld) && (!state || state === recordState) && fields.join(' ').toLowerCase().includes(search);
|
||||
const parent = $('records'); parent.replaceChildren();
|
||||
let count = 0;
|
||||
if (tab === 'worlds') {
|
||||
const { node, body } = table(['World', 'Status', 'Living / capacity', 'Fallen', 'Harbinger arrives', 'Actions']);
|
||||
for (const w of data.worlds.filter(w => matches([w.id,w.phase], w.id, w.phase))) {
|
||||
const row = body.insertRow(); const link = el('a', w.id, 'record-link'); link.href = gameURL(w.id); cell(row, link);
|
||||
const status = el('div', '', 'badge-group'); status.append(badge(w.phase)); if (!w.available) status.append(badge('offline')); else if (w.closed) status.append(badge('closed'));
|
||||
cell(row, status); cell(row, `${w.living} / ${w.capacity}`); cell(row, String(w.dead)); cell(row, date(w.bossAt));
|
||||
const options = [w.closed ? 'open-admissions' : 'close-admissions']; if (w.phase === 'gathering') options.push('awaken-boss'); options.push('end-world');
|
||||
cell(row, actions(w.id, options, '', '', !w.available || ['won','lost'].includes(w.phase))); count++;
|
||||
}
|
||||
parent.append(node); $('table-note').textContent = 'Availability reflects the world-owner lease. Living counts include offline characters.';
|
||||
} else if (tab === 'characters') {
|
||||
const { node, body } = table(['Character', 'World', 'State', 'Health', 'Played today', 'Actions']);
|
||||
for (const r of data.characters.filter(r => matches([r.id,r.account,r.name,r.worldId], r.worldId,r.state))) {
|
||||
const row = body.insertRow(); const button = el('button', r.name, 'record-link'); button.onclick = () => detail(r); cell(row, button); cell(row, r.worldId); cell(row, badge(r.state)); cell(row, `${Math.ceil(r.character.view.entity.hp)} / ${r.character.view.entity.maxHp}`); cell(row, `${Math.floor(r.character.dailySeconds/60)} min`);
|
||||
const controls = actions(r.worldId, ['rename','heal','unstuck','retire'], r.id, r.name, r.state !== 'alive' || !data.worlds.find(w => w.id === r.worldId)?.available);
|
||||
const revoke = el('button', '', 'icon-button'); revoke.title = `Revoke sessions for ${r.name}`; revoke.setAttribute('aria-label', revoke.title); revoke.append(icon('log-out')); revoke.onclick = () => openCommand('revoke-sessions', r.worldId, r.account); controls.append(revoke); cell(row, controls); count++;
|
||||
}
|
||||
parent.append(node); $('table-note').textContent = `Up to ${data.characterLimit} records per world filter. Dead characters remain in history.`;
|
||||
} else {
|
||||
const { node, body } = table(['Requested', 'Action', 'World / target', 'Status', 'Reason / result']);
|
||||
for (const c of data.commands.filter(c => matches([c.id,c.actor,c.op,c.target,c.reason,c.result], c.worldId === '_provision' ? c.target : c.worldId,c.status))) {
|
||||
const row = body.insertRow(); cell(row, date(c.createdAt)); const op = el('div', labels[c.op] || c.op); op.title = `Request ${c.id}\nActor ${c.actor}`; cell(row, op); const target = el('div', c.worldId === '_provision' ? c.target : c.worldId); if (c.target && c.worldId !== '_provision') target.append(el('small', c.target, 'muted block')); cell(row, target); cell(row, badge(c.status)); const reason = el('div', c.reason); if (c.result) reason.append(el('small', c.result, 'muted block')); cell(row, reason); count++;
|
||||
}
|
||||
parent.append(node); $('table-note').textContent = `Latest ${data.auditLimit} actions. Completed provisioning means committed to Git; world availability confirms startup.`;
|
||||
}
|
||||
if (!count) parent.append(el('p', 'No matching records.', 'empty'));
|
||||
$('record-count').textContent = `${count} records`; icons();
|
||||
}
|
||||
function options(select: HTMLSelectElement, values: string[], all: string) {
|
||||
const current = select.value; select.replaceChildren(new Option(all, '')); for (const v of [...new Set(values)]) select.append(new Option(v, v)); select.value = values.includes(current) ? current : '';
|
||||
}
|
||||
async function refresh() {
|
||||
if (busy) return; busy = true;
|
||||
try {
|
||||
const world = $<HTMLSelectElement>('world-filter').value;
|
||||
data = await api<Data>(`/api/control?world=${encodeURIComponent(world)}`);
|
||||
$('access').hidden = true; $('workspace').hidden = false; $('admin-signout').hidden = false;
|
||||
const create = $<HTMLButtonElement>('create-world'); create.disabled = !data.provisioningEnabled; create.title = data.provisioningEnabled ? 'Provision world through GitOps' : 'GitOps provisioning is not configured';
|
||||
$('metric-worlds').textContent = String(data.worlds.filter(w => w.available).length);
|
||||
$('metric-living').textContent = String(data.worlds.reduce((n,w) => n+w.living, 0)); $('metric-dead').textContent = String(data.worlds.reduce((n,w) => n+w.dead, 0)); $('metric-pending').textContent = String(data.commands.filter(c => c.status === 'pending').length);
|
||||
options($<HTMLSelectElement>('world-filter'), data.worlds.map(w => w.id), 'All worlds');
|
||||
options($<HTMLSelectElement>('state-filter'), tab === 'worlds' ? ['gathering','cataclysm','won','lost'] : tab === 'characters' ? ['alive','dead','eligible'] : ['pending','completed','rejected'], 'All states');
|
||||
$('updated').textContent = `Updated ${new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`;
|
||||
render();
|
||||
} catch (e) {
|
||||
if (!data || (e instanceof APIError && [401,403].includes(e.status))) {
|
||||
$('workspace').hidden = true; $('access').hidden = false; $('create-world').setAttribute('disabled', '');
|
||||
$('access-title').textContent = e instanceof APIError && e.status === 403 ? 'Administrator access required' : e instanceof APIError && e.status === 401 ? 'Sign in to Control' : 'Control unavailable';
|
||||
$('access-message').textContent = (e as Error).message; $('admin-login').hidden = false;
|
||||
} else notify((e as Error).message);
|
||||
} finally { busy = false; icons(); }
|
||||
}
|
||||
document.querySelectorAll<HTMLButtonElement>('[data-tab]').forEach(button => button.onclick = () => {
|
||||
tab = button.dataset.tab!; document.querySelectorAll('[data-tab]').forEach(b => b.classList.toggle('active', b === button));
|
||||
$('view-title').textContent = tab === 'audit' ? 'Audit log' : tab === 'characters' ? 'Characters' : 'Worlds';
|
||||
$<HTMLInputElement>('search').placeholder = `Search ${tab}`; $<HTMLSelectElement>('state-filter').value = ''; void refresh();
|
||||
});
|
||||
$('search').oninput = render; $('state-filter').onchange = render; $('world-filter').onchange = () => void refresh(); $('refresh').onclick = () => void refresh(); $('create-world').onclick = () => openCommand('create-world');
|
||||
for (const id of ['close-command','cancel-command']) $(id).onclick = () => $<HTMLDialogElement>('command-dialog').close();
|
||||
$('close-character').onclick = () => $<HTMLDialogElement>('character-dialog').close();
|
||||
$<HTMLFormElement>('command-form').onsubmit = async event => {
|
||||
event.preventDefault(); const submit = $<HTMLButtonElement>('submit-command'); submit.disabled = true;
|
||||
const body = { ...draft, worldId: draft.op === 'create-world' ? $<HTMLInputElement>('world-input').value : draft.worldId, value: ['rename','create-world'].includes(draft.op) ? $<HTMLInputElement>('value-input').value : '', reason: $<HTMLTextAreaElement>('reason-input').value, confirm: $<HTMLInputElement>('confirm-input').value };
|
||||
try { await api('/api/control/commands', body); $<HTMLDialogElement>('command-dialog').close(); notify('Action queued. Execution status is recorded in the audit log.'); await refresh(); }
|
||||
catch (e) { $('command-error').textContent = (e as Error).message; }
|
||||
finally { submit.disabled = false; }
|
||||
};
|
||||
$('admin-signout').onclick = async () => { try { await api('/auth/logout', {}); location.href = '/'; } catch(e) { notify((e as Error).message); } };
|
||||
icons(); void refresh(); setInterval(() => { if (!document.hidden && !$<HTMLDialogElement>('command-dialog').open && !$<HTMLDialogElement>('character-dialog').open) void refresh(); }, 5000);
|
||||
+12
-3
@@ -21,9 +21,11 @@ let pendingAction: { op: string; target: string } | undefined;
|
||||
let requestedClose = false;
|
||||
const keys = new Set<string>();
|
||||
let view: WorldView;
|
||||
const selectedWorld = new URLSearchParams(location.search).get('world');
|
||||
const worldPrefix = selectedWorld && /^[a-z][a-z0-9-]{0,30}$/.test(selectedWorld) ? `/worlds/${selectedWorld}` : '';
|
||||
|
||||
async function api<T>(path: string, body?: unknown): Promise<T> {
|
||||
const response = await fetch(path, { method: body === undefined ? 'GET' : 'POST', credentials: 'same-origin', headers: body === undefined ? {} : { 'Content-Type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) });
|
||||
const response = await fetch(path.startsWith('/api/') ? worldPrefix + path : path, { method: body === undefined ? 'GET' : 'POST', credentials: 'same-origin', headers: body === undefined ? {} : { 'Content-Type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) });
|
||||
const result = await response.json();
|
||||
if (!response.ok) throw new Error(result.error ?? `Request failed (${response.status})`);
|
||||
return result as T;
|
||||
@@ -54,7 +56,7 @@ function action(op: string) {
|
||||
function connect() {
|
||||
requestedClose = false; sequence = 0;
|
||||
const ending = $<HTMLDialogElement>('ending'); ending.close();
|
||||
ws = new WebSocket(`${location.protocol === 'https:' ? 'wss:' : 'ws:'}//${location.host}/ws`);
|
||||
ws = new WebSocket(`${location.protocol === 'https:' ? 'wss:' : 'ws:'}//${location.host}${worldPrefix}/ws`);
|
||||
ws.onopen = () => { $('connection-status').textContent = 'Connected'; $('connection-dot').parentElement!.classList.remove('offline'); };
|
||||
ws.onmessage = event => {
|
||||
const value = JSON.parse(event.data) as Snapshot;
|
||||
@@ -84,6 +86,7 @@ function showEnding(title: string, detail: string, survivor: boolean) {
|
||||
}
|
||||
if (survivor && destinations.children.length === 0) { const p = document.createElement('p'); p.textContent = 'Your passage is saved. No destination world is open yet.'; destinations.append(p); }
|
||||
visible('reconnect', false);
|
||||
visible('new-character', snapshot?.self.entity.state === 'dead' && ['gathering','cataclysm'].includes(snapshot.world.phase));
|
||||
$<HTMLDialogElement>('ending').show();
|
||||
}
|
||||
function inventory(c: Character) {
|
||||
@@ -141,6 +144,7 @@ function updateHUD(s: Snapshot) {
|
||||
if (s.message && s.message !== lastNotice) { notice(s.message); lastNotice = s.message; }
|
||||
}
|
||||
async function boot() {
|
||||
$<HTMLAnchorElement>('login').href = `/auth/login?return=${encodeURIComponent(location.pathname + location.search)}`;
|
||||
createIcons({ icons: { Crosshair, Settings2, X, Flame, LogOut, Hourglass, Swords, Pickaxe, HeartPulse, Gem, Backpack, ChevronUp, ChevronDown, ChevronLeft, ChevronRight, ArrowRight, RefreshCw } });
|
||||
view = new WorldView($<HTMLCanvasElement>('world'));
|
||||
view.start(dt => {
|
||||
@@ -165,7 +169,7 @@ async function boot() {
|
||||
view.addChunks(chunks); view.updateEntities(chunks.flatMap(c => c.resources));
|
||||
$('connection-status').textContent = 'World online';
|
||||
visible('dev-boss', config.development);
|
||||
let me: { character: Character | null } | undefined;
|
||||
let me: { character: Character | null; active?: { worldId: string; state: string; name: string } } | undefined;
|
||||
try { me = await api('/api/me'); } catch { if (config.development) { await api('/auth/dev', {}); me = await api('/api/me'); } }
|
||||
if (!me && !config.development) { visible('join-form', false); visible('login', true); }
|
||||
else if (me?.character) {
|
||||
@@ -174,6 +178,10 @@ async function boot() {
|
||||
else if (me.character.entity.state === 'eligible') showEnding('A passage forward.', 'Your survivor passage is saved.', true);
|
||||
else connect();
|
||||
} else {
|
||||
if (me?.active) {
|
||||
visible('join-form', false);
|
||||
const link = document.createElement('a'); link.href = `/game?world=${encodeURIComponent(me.active.worldId)}`; link.className = 'command'; link.textContent = `Continue ${me.active.name} in ${me.active.worldId}`; $('passages').append(link);
|
||||
}
|
||||
const passages = await api<{ characterId: string; sourceWorld: string; name: string }[]>('/api/passages').catch(() => []);
|
||||
for (const passage of passages.filter(p => p.sourceWorld !== config.worldId)) {
|
||||
const button = document.createElement('button'); button.textContent = `Continue as ${passage.name}`;
|
||||
@@ -193,6 +201,7 @@ async function boot() {
|
||||
$('target-boss').onclick = () => { selection(snapshot?.entities.find(e => e.id === 'boss')); walkTo = { x: 0, z: 0 }; pendingAction = { op: 'attack', target: 'boss' }; };
|
||||
$('dev-boss').onclick = () => void api('/api/dev/boss', {}).catch(e => notice(e.message));
|
||||
$('reconnect').onclick = () => location.reload();
|
||||
$('new-character').onclick = () => { requestedClose = true; ws?.close(); location.reload(); };
|
||||
$('logout').onclick = async () => { requestedClose = true; await api('/auth/logout', {}); ws?.close(); location.reload(); };
|
||||
$<HTMLSelectElement>('quality').onchange = event => view.quality((event.target as HTMLSelectElement).value === 'high');
|
||||
$<HTMLInputElement>('zoom').oninput = event => { view.distance = Number((event.target as HTMLInputElement).value); view.resize(); };
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { createIcons, ArrowDown, ArrowRight, ArrowUpRight, Check, Globe2, HeartPulse, LogIn, LogOut, MapPin, MoreHorizontal, Play, Plus, RefreshCw, ScrollText, Search, ShieldCheck, Users, X } from 'lucide';
|
||||
import type { Character } from './generated';
|
||||
|
||||
export type RecordCharacter = { id: string; account: string; worldId: string; name: string; state: string; character: { view: Character; bornAt: string; diedAt?: string; deathReason?: string; dailySeconds: number } };
|
||||
export type World = { id: string; phase: string; living: number; dead: number; capacity: number; createdAt: string; bossAt: string; closed: boolean; available: boolean; revision: number };
|
||||
export type Command = { id: string; worldId: string; actor: string; op: string; target: string; value: string; reason: string; status: string; result: string; createdAt: number; completedAt: number };
|
||||
export const $ = <T extends HTMLElement = HTMLElement>(id: string) => document.getElementById(id) as T;
|
||||
export const el = <K extends keyof HTMLElementTagNameMap>(tag: K, text = '', className = '') => { const node = document.createElement(tag); node.textContent = text; node.className = className; return node; };
|
||||
export function icons() { createIcons({ icons: { ArrowDown, ArrowRight, ArrowUpRight, Check, Globe2, HeartPulse, LogIn, LogOut, MapPin, MoreHorizontal, Play, Plus, RefreshCw, ScrollText, Search, ShieldCheck, Users, X } }); }
|
||||
export function icon(name: string) { const node = el('i'); node.dataset.lucide = name; return node; }
|
||||
export function badge(state: string) { return el('span', state.replaceAll('-', ' '), `badge state-${state}`); }
|
||||
export function date(value: string | number) { return value ? new Date(typeof value === 'number' ? value * 1000 : value).toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }) : 'Unknown'; }
|
||||
export function gameURL(world: string) { return `/game?world=${encodeURIComponent(world)}`; }
|
||||
export class APIError extends Error { constructor(message: string, public status: number) { super(message); } }
|
||||
export async function api<T>(path: string, body?: unknown): Promise<T> {
|
||||
const response = await fetch(path, { method: body === undefined ? 'GET' : 'POST', credentials: 'same-origin', signal: AbortSignal.timeout(15000), headers: body === undefined ? {} : { 'Content-Type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) });
|
||||
const value = await response.json().catch(() => ({ error: `Request failed (${response.status})` }));
|
||||
if (!response.ok) throw new APIError(value.error || `Request failed (${response.status})`, response.status);
|
||||
return value;
|
||||
}
|
||||
export function table(headers: string[]) { const node = el('table'); const head = node.createTHead().insertRow(); for (const label of headers) { const th = el('th', label); th.scope = 'col'; head.append(th); } const body = node.createTBody(); return { node, body }; }
|
||||
export function cell(row: HTMLTableRowElement, content: string | Node) { const td = row.insertCell(); typeof content === 'string' ? td.textContent = content : td.append(content); return td; }
|
||||
@@ -0,0 +1,10 @@
|
||||
:root { font-family: Inter, 'Segoe UI', sans-serif; color: #202923; background: #f8faf9; font-synthesis: none; letter-spacing: 0; --line: #dce3df; --muted: #66736d; --green: #215944; --red: #a83543; }
|
||||
* { box-sizing: border-box; } body { margin: 0; } [hidden] { display: none !important; } button, input, select, textarea { font: inherit; } button, a, input, select, textarea { -webkit-tap-highlight-color: transparent; } a { color: inherit; text-decoration: none; } button { cursor: pointer; } button:disabled, .disabled { opacity: .45; cursor: not-allowed; } :focus-visible { outline: 3px solid #81b9a3; outline-offset: 3px; } h1,h2,h3,p { margin: 0; } h1 { font-size: 28px; } h2 { font-size: 25px; font-weight: 600; } h3 { font-size: 18px; font-weight: 600; } svg { width: 18px; height: 18px; flex-shrink: 0; } .muted { color: var(--muted); font-size: 13px; } .block { display: block; margin-top: 5px; } .eyebrow { font-size: 11px; font-weight: 650; color: var(--muted); margin-bottom: 9px; } .button { display: inline-flex; align-items: center; justify-content: center; gap: 9px; min-height: 40px; padding: 10px 17px; border: 1px solid transparent; border-radius: 5px; background: var(--green); color: #fff; font-size: 13px; font-weight: 600; white-space: nowrap; } .button:hover:not(:disabled):not(.disabled) { background: #183e30; } .button.secondary { background: #fff; color: #253c31; border-color: var(--line); } .button.secondary:hover { background: #edf3ef; } .button.light { background: #fff; color: #233d30; } .button.danger { background: var(--red); } .icon-button { display: inline-flex; align-items: center; justify-content: center; width: 36px; height: 36px; padding: 0; border: 1px solid var(--line); border-radius: 4px; background: #fff; color: #48564d; flex-shrink: 0; } .icon-button:hover { background: #edf3ef; } .heading-tools { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; } .wordmark { display: block; font-weight: 750; font-size: 18px; } .wordmark span { display: block; font-size: 11px; font-weight: 400; color: var(--muted); margin-top: 4px; } .empty { padding: 32px 0; font-size: 14px; color: var(--muted); } .message { padding: 12px 16px; margin: 16px 0; background: #edf3ef; border-left: 3px solid #408362; font-size: 13px; overflow-wrap: anywhere; } .error { color: var(--red); font-size: 13px; min-height: 20px; }
|
||||
.site-header { min-height: 82px; display: flex; align-items: center; justify-content: space-between; padding: 18px 5%; gap: 24px; background: #fff; } .site-header nav { display: flex; align-items: center; gap: 26px; font-size: 13px; } .world-hero { position: relative; height: 420px; max-height: 58vh; min-height: 300px; overflow: hidden; background: #244d3a; color: #fff; } .world-hero > img { width: 100%; height: 100%; object-fit: cover; object-position: center 45%; } .hero-shade { position: absolute; inset: 0; background: linear-gradient(90deg, #071810b8 0%, #07181035 48%, transparent 100%); } .hero-copy { position: absolute; inset: auto 5% 48px; max-width: 560px; } .hero-copy .eyebrow { color: #d6e9dc; } .hero-copy h1 { font-family: Georgia, serif; font-size: 64px; font-weight: 400; line-height: 1.1; } .hero-copy > p:not(.eyebrow) { margin: 14px 0 25px; font-size: 16px; line-height: 1.6; } .hero-caption { position: absolute; bottom: 22px; right: 5%; font-size: 10px; color: #eff8f1; } .site-section { padding: 40px 5%; } .section-heading { display: flex; align-items: center; justify-content: space-between; gap: 20px; margin-bottom: 24px; } .world-list { border-top: 1px solid var(--line); } .world-row { display: grid; grid-template-columns: 56px minmax(120px, 1fr) minmax(100px, .65fr) minmax(175px, 1fr) auto; gap: 22px; align-items: center; padding: 23px 0; border-bottom: 1px solid var(--line); } .world-emblem { display: grid; place-items: center; width: 52px; height: 52px; background: #e7efe9; border-radius: 5px; color: #366d53; } .world-emblem svg { width: 25px; height: 25px; } .world-name h3 { margin-bottom: 9px; overflow-wrap: anywhere; } .world-stat span { display: block; font-size: 11px; color: var(--muted); margin-bottom: 8px; } .world-stat strong { font-size: 13px; font-weight: 550; } .journey-section { background: #edf2ef; } .active-life { display: flex; justify-content: space-between; gap: 20px; align-items: center; padding: 0 0 28px; } .active-life p { margin-top: 9px; } .site-footer { display: flex; align-items: center; justify-content: space-between; padding: 30px 5%; gap: 22px; font-size: 12px; color: var(--muted); } .site-footer > span:first-child { font-weight: 700; color: #34483c; }
|
||||
.control-site { display: grid; grid-template-columns: 204px minmax(0, 1fr); min-height: 100vh; background: #fff; } .control-sidebar { border-right: 1px solid var(--line); background: #f5f8f6; display: flex; flex-direction: column; padding: 28px 18px; } .control-sidebar .wordmark { padding: 0 10px; margin-bottom: 42px; } .control-sidebar nav { display: grid; gap: 7px; } .nav-item { display: flex; align-items: center; gap: 11px; width: 100%; padding: 12px; background: transparent; color: #657169; border: 0; text-align: left; border-radius: 4px; font-size: 13px; } .nav-item:hover { background: #eaf0ec; } .nav-item.active { background: #dfece4; color: #234b36; font-weight: 600; } .sidebar-bottom { margin-top: auto; padding: 40px 10px 0; display: grid; gap: 18px; } .sidebar-bottom a { display: flex; gap: 10px; align-items: center; font-size: 12px; color: var(--muted); } .control-main { min-width: 0; padding: 30px 32px; } .control-header { display: flex; align-items: center; justify-content: space-between; gap: 20px; min-height: 65px; margin-bottom: 28px; } .control-header h1 { font-size: 27px; font-weight: 600; } .metrics { display: grid; grid-template-columns: repeat(4, minmax(0,1fr)); border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); padding: 24px 0; margin-bottom: 30px; } .metrics > div { padding: 0 22px; border-right: 1px solid var(--line); } .metrics > div:first-child { padding-left: 0; } .metrics > div:last-child { border-right: 0; } .metrics span { display: block; font-size: 12px; color: var(--muted); margin-bottom: 10px; } .metrics strong { font-size: 28px; font-weight: 550; } .table-tools { display: flex; align-items: center; gap: 18px; flex-wrap: wrap; padding-bottom: 18px; } .table-tools label { display: flex; align-items: center; gap: 8px; font-size: 12px; color: var(--muted); } input,select,textarea { background: #fff; color: #25362b; border: 1px solid #cfdad3; border-radius: 4px; padding: 9px 10px; font-size: 13px; max-width: 100%; } select { min-height: 36px; } .search-field { position: relative; flex: 1; min-width: 160px; max-width: 340px; } .search-field svg { position: absolute; left: 11px; } .search-field input { width: 100%; padding-left: 35px; } .table-tools > .muted { margin-left: auto; } .table-wrap { width: 100%; overflow-x: auto; } table { width: 100%; border-collapse: collapse; text-align: left; font-size: 12px; } th { color: var(--muted); font-size: 11px; font-weight: 550; background: #f6f8f7; padding: 13px 14px; border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); white-space: nowrap; } td { padding: 17px 14px; border-bottom: 1px solid #e6ebe8; line-height: 1.5; min-width: 95px; max-width: 360px; overflow-wrap: anywhere; } tbody tr:hover { background: #f8faf9; } .record-link { border: 0; padding: 0; background: none; color: #225e43; font-size: inherit; font-weight: 650; text-align: left; } .record-link:hover { text-decoration: underline; } .row-actions { display: flex; align-items: center; gap: 7px; } .row-actions select { min-width: 110px; max-width: 166px; font-size: 11px; } .badge { display: inline-flex; align-items: center; gap: 6px; padding: 4px 7px; background: #eef1ef; color: #56665b; border-radius: 3px; font-size: 10px; white-space: nowrap; text-transform: capitalize; } .badge::before { content: ''; width: 5px; height: 5px; border-radius: 50%; background: currentColor; } .state-alive,.state-gathering,.state-completed { background: #e4f2e9; color: #28714c; } .state-eligible,.state-won { background: #e3eef6; color: #326e94; } .state-cataclysm,.state-pending,.state-closed { background: #faf0db; color: #986412; } .state-dead,.state-lost,.state-rejected { background: #fae9eb; color: #a24554; } .badge-group { display: flex; flex-wrap: wrap; gap: 5px; } .table-note { padding-top: 18px; font-size: 11px; color: var(--muted); line-height: 1.6; } .access-state { padding: 100px 20px; text-align: center; } .access-state > svg { width: 34px; height: 34px; color: #587864; margin-bottom: 22px; } .access-state h2 { font-size: 23px; } .access-state p { font-size: 13px; color: var(--muted); margin: 16px auto 24px; max-width: 440px; line-height: 1.7; }
|
||||
dialog { width: min(510px, calc(100vw - 32px)); max-height: calc(100dvh - 40px); overflow-y: auto; border: 1px solid var(--line); border-radius: 7px; padding: 26px; color: #24352b; box-shadow: 0 18px 70px #11251a25; } dialog::backdrop { background: #0f211b70; } dialog header { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin-bottom: 18px; } dialog h2 { font-size: 21px; overflow-wrap: anywhere; } dialog h3 { font-size: 14px; margin: 24px 0 12px; } dialog label { display: flex; flex-direction: column; gap: 8px; font-size: 12px; margin-top: 20px; overflow-wrap: anywhere; } dialog input,dialog textarea { width: 100%; } dialog footer { display: flex; justify-content: flex-end; gap: 10px; margin-top: 22px; } dialog .error { margin-top: 18px; } #command-context { overflow-wrap: anywhere; line-height: 1.6; } .details { display: grid; grid-template-columns: 115px minmax(0,1fr); gap: 14px; font-size: 12px; } .details dt { color: var(--muted); } .details dd { margin: 0; overflow-wrap: anywhere; } .item-list { display: grid; gap: 10px; font-size: 12px; } .item-list span { display: flex; justify-content: space-between; gap: 14px; }
|
||||
@media(min-width:1600px) { .site-section { padding-left: max(5%, calc((100% - 1440px) / 2)); padding-right: max(5%, calc((100% - 1440px) / 2)); } }
|
||||
@media(max-width:1100px) { .control-site { grid-template-columns: 174px minmax(0,1fr); } .control-main { padding: 26px 22px; } .world-row { grid-template-columns: 44px 1fr 100px 180px; gap: 16px; } .world-row > .button { grid-column: 2 / -1; justify-self: start; } .control-header #updated { display: none; } }
|
||||
@media(max-width:720px) { .site-header { padding: 16px 5%; flex-wrap: wrap; gap: 18px; } .site-header nav { gap: 17px; width: 100%; justify-content: space-between; } .site-header nav > a { font-size: 12px; } .wordmark { font-size: 17px; } .world-hero { min-height: 300px; max-height: none; height: 350px; } .hero-copy { bottom: 45px; right: 6%; } .hero-copy h1 { font-size: 47px; } .hero-copy > p:not(.eyebrow) { font-size: 14px; max-width: 260px; } .hero-caption { font-size: 8px; } .site-section { padding-top: 30px; padding-bottom: 30px; } .section-heading h2 { font-size: 23px; } .world-row { grid-template-columns: 42px minmax(0,1fr) auto; gap: 17px 12px; } .world-emblem { width: 38px; height: 42px; } .world-name h3 { font-size: 16px; } .world-row .world-stat:nth-child(4) { grid-column: 2; } .world-row > .button { grid-column: 3; font-size: 11px; padding: 9px; } .world-stat strong { font-size: 12px; } .world-stat span { margin-bottom: 4px; } .active-life { align-items: flex-start; flex-wrap: wrap; } .site-footer { flex-wrap: wrap; } .site-footer > span:nth-child(2) { order: 3; width: 100%; } .control-site { display: block; } .control-sidebar { padding: 18px; border-right: 0; border-bottom: 1px solid var(--line); } .control-sidebar .wordmark { margin-bottom: 18px; padding: 0; } .control-sidebar nav { grid-template-columns: repeat(3,minmax(0,1fr)); gap: 3px; } .nav-item { justify-content: center; padding: 11px 4px; gap: 6px; font-size: 12px; } .sidebar-bottom { display: none; } .control-main { padding: 22px 16px; } .control-header { margin-bottom: 20px; gap: 12px; } .control-header h1 { font-size: 24px; } .control-header .heading-tools { gap: 6px; } #admin-signout { display: none; } #create-world { padding: 10px; font-size: 12px; } .metrics { grid-template-columns: repeat(2,minmax(0,1fr)); gap: 20px 0; padding: 20px 0; margin-bottom: 20px; } .metrics > div { padding: 0 16px; } .metrics > div:nth-child(3) { padding-left: 0; } .metrics > div:nth-child(2) { border-right: 0; } .metrics strong { font-size: 24px; } .metrics span { font-size: 11px; } .table-tools { gap: 12px; } .search-field { flex-basis: 100%; max-width: none; } .table-tools > .muted { font-size: 11px; } .table-tools label { font-size: 11px; } .table-tools select { max-width: 135px; font-size: 12px; } th,td { padding: 12px 10px; } .access-state { padding: 65px 5px; } dialog { padding: 21px; } }
|
||||
.button.secondary:hover:not(:disabled):not(.disabled), .button.light:hover:not(:disabled):not(.disabled) { background: #edf3ef; color: #253c31; }
|
||||
@media(prefers-reduced-motion:reduce) { * { scroll-behavior: auto !important; } }
|
||||
@@ -0,0 +1,58 @@
|
||||
import './portal.css';
|
||||
import { $, api, APIError, badge, cell, date, el, gameURL, icons, icon, table, type RecordCharacter, type World } from './portal-shared';
|
||||
|
||||
type Account = { active: RecordCharacter | null; characters: RecordCharacter[]; admin: boolean };
|
||||
let account: Account | null = null;
|
||||
let development = false;
|
||||
let busy = false;
|
||||
function renderWorlds(worlds: World[]) {
|
||||
const list = $('world-list'); list.replaceChildren();
|
||||
$('world-count').textContent = `${worlds.filter(w => w.available).length} online / ${worlds.length} worlds`;
|
||||
if (!worlds.length) list.append(el('p', 'No worlds are open yet.', 'empty'));
|
||||
for (const world of worlds) {
|
||||
const row = el('article', '', 'world-row');
|
||||
const emblem = el('div', '', 'world-emblem'); emblem.append(icon('globe-2'));
|
||||
const heading = el('div', '', 'world-name'); heading.append(el('h3', world.id), badge(!world.available ? 'offline' : world.phase));
|
||||
const population = el('div', '', 'world-stat'); population.append(el('span', 'Living'), el('strong', `${world.living} / ${world.capacity}`));
|
||||
const clock = el('div', '', 'world-stat'); clock.append(el('span', world.phase === 'gathering' ? 'Harbinger arrives' : 'Season'), el('strong', world.phase === 'gathering' ? date(world.bossAt) : world.phase === 'cataclysm' ? 'The world is collapsing' : 'Ended'));
|
||||
const active = account?.active;
|
||||
const resume = active?.worldId === world.id;
|
||||
const transfer = active?.state === 'eligible' && active.worldId !== world.id && world.phase === 'gathering';
|
||||
const open = world.available && (resume || (!world.closed && world.living < world.capacity && ['gathering', 'cataclysm'].includes(world.phase) && (!active || transfer)));
|
||||
const action = el('a', resume ? 'Continue' : transfer ? 'Use passage' : 'Enter world', `button ${open ? '' : 'disabled'}`);
|
||||
if (open) action.href = gameURL(world.id); else { action.setAttribute('aria-disabled', 'true'); action.title = active && !resume && !transfer ? `Living character in ${active.worldId}` : 'World unavailable for arrivals'; }
|
||||
action.append(icon('arrow-right')); row.append(emblem, heading, population, clock, action); list.append(row);
|
||||
}
|
||||
}
|
||||
function renderAccount() {
|
||||
const parent = $('active-character'); parent.replaceChildren();
|
||||
const history = $('character-history'); history.replaceChildren();
|
||||
$('control-link').hidden = !account?.admin;
|
||||
$('account-button').replaceChildren(icon(account ? 'log-out' : 'log-in'), el('span', account ? 'Sign out' : 'Sign in'));
|
||||
if (!account) { history.append(el('p', 'Sign in to see your characters.', 'empty')); return; }
|
||||
if (account.active) { const r = account.active; const summary = el('div', '', 'active-life'); const title = el('div'); title.append(el('h3', r.name), el('p', `${r.worldId} / ${r.state === 'eligible' ? 'Passage earned' : `${Math.ceil(r.character.view.entity.hp)} health`}`, 'muted')); const link = el('a', 'Continue journey', 'button'); link.href = gameURL(r.worldId); link.append(icon('arrow-right')); summary.append(title, link); parent.append(summary); }
|
||||
else parent.append(el('p', 'Your next life is waiting in an open world.', 'empty'));
|
||||
if (!account.characters.length) return;
|
||||
const { node, body } = table(['Character', 'World', 'State', 'Journey ended', 'Cause']);
|
||||
for (const r of [...account.characters].sort((a,b) => (b.character.diedAt || b.character.bornAt).localeCompare(a.character.diedAt || a.character.bornAt))) {
|
||||
const row = body.insertRow(); cell(row, r.name); cell(row, r.worldId); cell(row, badge(r.state)); cell(row, r.character.diedAt ? date(r.character.diedAt) : '-'); cell(row, r.character.deathReason || '-');
|
||||
}
|
||||
const wrapper = el('div', '', 'table-wrap'); wrapper.append(node); history.append(wrapper);
|
||||
}
|
||||
async function refresh() {
|
||||
if (busy) return; busy = true;
|
||||
try {
|
||||
const worlds = await api<World[]>('/api/worlds');
|
||||
try { account = await api<Account>('/api/account'); } catch (e) { if (e instanceof APIError && e.status === 401) account = null; else throw e; }
|
||||
renderAccount(); renderWorlds(worlds); $('site-message').hidden = true; icons();
|
||||
} catch (e) { $('site-message').textContent = (e as Error).message; $('site-message').hidden = false; }
|
||||
finally { busy = false; }
|
||||
}
|
||||
$('refresh').onclick = () => void refresh();
|
||||
$('account-button').onclick = async () => {
|
||||
try { if (account) { await api('/auth/logout', {}); await refresh(); } else if (development) { await api('/auth/dev', {}); await refresh(); } else location.href = '/auth/login'; }
|
||||
catch (e) { $('site-message').hidden = false; $('site-message').textContent = (e as Error).message; }
|
||||
};
|
||||
icons();
|
||||
void api<{ development: boolean }>('/api/config').then(c => { development = c.development; }).catch(() => {});
|
||||
void refresh(); setInterval(() => { if (!document.hidden) void refresh(); }, 15000);
|
||||
@@ -1,10 +1,11 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
export default defineConfig({
|
||||
root: 'client',
|
||||
build: { outDir: 'dist', target: 'es2022', chunkSizeWarningLimit: 650 },
|
||||
build: { outDir: 'dist', target: 'es2022', chunkSizeWarningLimit: 650, rollupOptions: { input: { site: resolve('client/index.html'), game: resolve('client/game.html'), control: resolve('client/control.html') } } },
|
||||
server: {
|
||||
port: 5175, strictPort: true,
|
||||
proxy: { '/api': 'http://127.0.0.1:18080', '/auth': 'http://127.0.0.1:18080', '/ws': { target: 'ws://127.0.0.1:18080', ws: true } },
|
||||
proxy: { '/worlds': { target: 'http://127.0.0.1:18080', ws: true }, '/api': 'http://127.0.0.1:18080', '/auth': 'http://127.0.0.1:18080', '/ws': { target: 'ws://127.0.0.1:18080', ws: true } },
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
{{- if and .Values.networkPolicy.enabled .Values.control.existingSecret }}
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: NetworkPolicy
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-control-gitops
|
||||
spec:
|
||||
podSelector:
|
||||
matchLabels:
|
||||
app.kubernetes.io/instance: {{ .Release.Name | quote }}
|
||||
aeternalis.world: {{ .Values.portal.primaryWorld | quote }}
|
||||
policyTypes: [Egress]
|
||||
egress:
|
||||
{{- range .Values.control.gitopsCIDRs }}
|
||||
- to: [{ ipBlock: { cidr: {{ . | quote }} } }]
|
||||
ports: [{ protocol: TCP, port: 443 }]
|
||||
{{- else }}
|
||||
[]
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
@@ -1,9 +1,16 @@
|
||||
{{- $root := . -}}
|
||||
{{- $directory := list -}}
|
||||
{{- $ids := dict -}}
|
||||
{{- range .Values.worlds -}}
|
||||
{{- $directory = append $directory (dict "id" .id "url" (printf "https://%s" .host)) -}}
|
||||
{{- if hasKey $ids .id -}}{{- fail "world IDs must be unique" -}}{{- end -}}
|
||||
{{- $_ := set $ids .id true -}}
|
||||
{{- $host := default .host $root.Values.portal.host -}}
|
||||
{{- $directory = append $directory (dict "id" .id "url" (printf "https://%s/game?world=%s" $host .id)) -}}
|
||||
{{- end -}}
|
||||
{{- if and .Values.portal.host (not (hasKey $ids .Values.portal.primaryWorld)) -}}{{- fail "portal.primaryWorld must exist in worlds" -}}{{- end -}}
|
||||
{{- range .Values.worlds }}
|
||||
{{- $host := default .host $root.Values.portal.host -}}
|
||||
{{- $primary := eq .id $root.Values.portal.primaryWorld -}}
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
@@ -54,10 +61,20 @@ spec:
|
||||
- { name: LISTEN_ADDR, value: "0.0.0.0:8080" }
|
||||
- { name: WORLD_ID, value: {{ .id | quote }} }
|
||||
- { name: WORLD_SEED, value: {{ .seed | quote }} }
|
||||
- { name: PUBLIC_URL, value: {{ printf "https://%s" .host | quote }} }
|
||||
- { name: PUBLIC_URL, value: {{ printf "https://%s" $host | quote }} }
|
||||
- { name: WORLD_DIRECTORY, value: {{ $directory | toJson | quote }} }
|
||||
- { name: OIDC_ADMIN_ROLE, value: {{ $root.Values.control.adminRole | quote }} }
|
||||
- { name: CONTROL_PRIMARY, value: {{ $primary | quote }} }
|
||||
{{- if and $primary $root.Values.control.existingSecret }}
|
||||
- { name: CONTROL_GITOPS_REPOSITORY, value: {{ $root.Values.control.gitopsRepository | quote }} }
|
||||
- { name: CONTROL_GITOPS_BRANCH, value: {{ $root.Values.control.gitopsBranch | quote }} }
|
||||
- { name: CONTROL_GITOPS_VALUES_FILE, value: {{ $root.Values.control.gitopsValuesFile | quote }} }
|
||||
{{- end }}
|
||||
envFrom:
|
||||
- secretRef: { name: {{ $root.Values.existingSecret | quote }} }
|
||||
{{- if and $primary $root.Values.control.existingSecret }}
|
||||
- secretRef: { name: {{ $root.Values.control.existingSecret | quote }} }
|
||||
{{- end }}
|
||||
resources: {{ $root.Values.resources | toJson }}
|
||||
startupProbe: { httpGet: { path: /readyz, port: http }, periodSeconds: 5, failureThreshold: 24 }
|
||||
readinessProbe: { httpGet: { path: /readyz, port: http }, periodSeconds: 3, failureThreshold: 2 }
|
||||
@@ -76,7 +93,7 @@ kind: Ingress
|
||||
metadata:
|
||||
name: {{ $root.Release.Name }}-{{ .id }}
|
||||
annotations:
|
||||
{{- if $root.Values.ingress.clusterIssuer }}
|
||||
{{- if and $root.Values.ingress.clusterIssuer (or $primary (not $root.Values.portal.host)) }}
|
||||
cert-manager.io/cluster-issuer: {{ $root.Values.ingress.clusterIssuer | quote }}
|
||||
{{- end }}
|
||||
nginx.ingress.kubernetes.io/proxy-read-timeout: "3600"
|
||||
@@ -86,13 +103,19 @@ metadata:
|
||||
nginx.ingress.kubernetes.io/ssl-redirect: "true"
|
||||
spec:
|
||||
ingressClassName: {{ $root.Values.ingress.className | quote }}
|
||||
tls: [{ hosts: [{{ .host | quote }}], secretName: {{ $root.Values.ingress.tlsSecret | quote }} }]
|
||||
tls: [{ hosts: [{{ $host | quote }}], secretName: {{ $root.Values.ingress.tlsSecret | quote }} }]
|
||||
rules:
|
||||
- host: {{ .host | quote }}
|
||||
- host: {{ $host | quote }}
|
||||
http:
|
||||
paths:
|
||||
- path: {{ printf "/worlds/%s" .id }}
|
||||
pathType: Prefix
|
||||
backend:
|
||||
service: { name: {{ $root.Release.Name }}-{{ .id }}, port: { name: http } }
|
||||
{{- if or $primary (not $root.Values.portal.host) }}
|
||||
- path: /
|
||||
pathType: Prefix
|
||||
backend:
|
||||
service: { name: {{ $root.Release.Name }}-{{ .id }}, port: { name: http } }
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
"type": "object",
|
||||
"required": ["worlds", "existingSecret", "image"],
|
||||
"properties": {
|
||||
"portal": {"type":"object","required":["host","primaryWorld"],"properties":{"host":{"type":"string","pattern":"^([a-zA-Z0-9.-]+)?$"},"primaryWorld":{"type":"string","pattern":"^[a-z][a-z0-9-]{0,30}$"}}},
|
||||
"control": {"type":"object","required":["adminRole","existingSecret","gitopsCIDRs"],"properties":{"adminRole":{"type":"string","minLength":1},"existingSecret":{"type":"string"},"gitopsRepository":{"type":"string"},"gitopsBranch":{"type":"string"},"gitopsValuesFile":{"type":"string"},"gitopsCIDRs":{"type":"array","items":{"type":"string"}}}},
|
||||
"worlds": {"type": "array", "minItems": 1, "items": {"type": "object", "required": ["id", "seed", "host"], "properties": {"id": {"type": "string", "pattern": "^[a-z][a-z0-9-]{0,30}$"}, "seed": {"type": "string", "pattern": "^[0-9]{1,15}$"}, "host": {"type": "string", "minLength": 1}}}},
|
||||
"existingSecret": {"type": "string", "minLength": 1},
|
||||
"image": {"type": "object", "required": ["repository", "tag", "digest"], "properties": {"repository": {"type": "string", "minLength": 1}, "tag": {"type": "string", "minLength": 1}, "digest": {"type": "string", "pattern": "^(sha256:[a-f0-9]{64})?$"}}}
|
||||
|
||||
@@ -5,6 +5,16 @@ image:
|
||||
imagePullSecrets:
|
||||
- name: harbor-pull
|
||||
existingSecret: aeternalis-runtime
|
||||
portal:
|
||||
host: ""
|
||||
primaryWorld: world-001
|
||||
control:
|
||||
adminRole: aeternalis-admin
|
||||
existingSecret: ""
|
||||
gitopsRepository: ""
|
||||
gitopsBranch: master
|
||||
gitopsValuesFile: deploy/values-srs.yaml
|
||||
gitopsCIDRs: []
|
||||
databaseCA:
|
||||
configMap: ""
|
||||
externalDatabase:
|
||||
|
||||
@@ -6,6 +6,17 @@ image:
|
||||
imagePullSecrets:
|
||||
- name: harbor-pull
|
||||
existingSecret: aeternalis-runtime
|
||||
portal:
|
||||
host: srs.aeternalisgames.com
|
||||
primaryWorld: world-001
|
||||
control:
|
||||
adminRole: aeternalis-admin
|
||||
# Set existingSecret and gitopsCIDRs after provisioning a scoped GitOps token.
|
||||
existingSecret: ""
|
||||
gitopsRepository: https://git.aeternalisgames.com/Stone/aeternalis.git
|
||||
gitopsBranch: master
|
||||
gitopsValuesFile: deploy/values-srs.yaml
|
||||
gitopsCIDRs: []
|
||||
databaseCA:
|
||||
configMap: postgres-ca
|
||||
externalDatabase:
|
||||
|
||||
@@ -6,6 +6,6 @@ export default defineConfig({
|
||||
webServer: {
|
||||
command: 'node tools/dev-server.mjs', url: 'http://127.0.0.1:18089/readyz',
|
||||
timeout: 180000, reuseExistingServer: false,
|
||||
env: { PORT: '18089', E2E: 'true', WORLD_ID: 'e2e', DEV_SEASON_SECONDS: '3600' },
|
||||
env: { PORT: '18089', E2E: 'true', WORLD_ID: 'e2e', DEV_SEASON_SECONDS: '3600', DEV_ADMIN: 'true' },
|
||||
},
|
||||
});
|
||||
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
|
||||
"aeternalis/server/content"
|
||||
"aeternalis/server/internal/game"
|
||||
"aeternalis/server/internal/gitops"
|
||||
"aeternalis/server/internal/store"
|
||||
"aeternalis/server/internal/transport"
|
||||
)
|
||||
@@ -118,6 +119,8 @@ func run() error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
auth.AdminRole = env("OIDC_ADMIN_ROLE", "aeternalis-admin")
|
||||
auth.DevAdmin = dev && env("DEV_ADMIN", "false") == "true"
|
||||
worlds := []transport.Destination{}
|
||||
if raw := os.Getenv("WORLD_DIRECTORY"); raw != "" {
|
||||
if err = json.Unmarshal([]byte(raw), &worlds); err != nil {
|
||||
@@ -131,11 +134,18 @@ func run() error {
|
||||
}
|
||||
}
|
||||
svc := transport.NewService(w, lease)
|
||||
handler := transport.NewHTTP(svc, auth, env("CLIENT_DIR", "../client/dist"), worlds).Handler()
|
||||
server := &http.Server{Addr: listen, Handler: handler, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 15 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 16384}
|
||||
handler := transport.NewHTTP(svc, auth, env("CLIENT_DIR", "../client/dist"), worlds)
|
||||
if env("CONTROL_PRIMARY", "true") == "true" {
|
||||
handler.Provisioner, err = gitops.New(gitops.Config{Repository: os.Getenv("CONTROL_GITOPS_REPOSITORY"), Branch: os.Getenv("CONTROL_GITOPS_BRANCH"), File: os.Getenv("CONTROL_GITOPS_VALUES_FILE"), Token: os.Getenv("CONTROL_GITOPS_TOKEN"), PublicURL: base})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
server := &http.Server{Addr: listen, Handler: handler.Handler(), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 15 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 16384}
|
||||
runtimeCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
go svc.Run(runtimeCtx)
|
||||
go handler.RunProvisioning(runtimeCtx)
|
||||
errorsCh := make(chan error, 1)
|
||||
go func() {
|
||||
slog.Info("world listening", "url", base, "world", id, "development", dev)
|
||||
|
||||
@@ -27,6 +27,9 @@ type Character struct {
|
||||
MoveZ float64 `json:"-"`
|
||||
LastMove time.Time `json:"-"`
|
||||
Message string `json:"-"`
|
||||
BornAt time.Time `json:"bornAt"`
|
||||
DiedAt *time.Time `json:"diedAt,omitempty"`
|
||||
DeathReason string `json:"deathReason,omitempty"`
|
||||
}
|
||||
type Corpse struct {
|
||||
Entity p.Entity `json:"entity"`
|
||||
@@ -40,24 +43,25 @@ type Mob struct {
|
||||
RespawnAt float64 `json:"respawnAt"`
|
||||
}
|
||||
type World struct {
|
||||
Version int `json:"version"`
|
||||
ID string `json:"id"`
|
||||
Seed int64 `json:"seed"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
EndedAt *time.Time `json:"endedAt,omitempty"`
|
||||
Phase string `json:"phase"`
|
||||
Tick int64 `json:"tick"`
|
||||
BossHP float64 `json:"bossHp"`
|
||||
BossLastAttack float64 `json:"bossLastAttack"`
|
||||
Characters map[string]*Character `json:"characters"`
|
||||
Corpses map[string]*Corpse `json:"corpses"`
|
||||
Depleted map[string]float64 `json:"depleted"`
|
||||
Mobs map[string]*Mob `json:"mobs"`
|
||||
Balance content.Balance `json:"balance"`
|
||||
terrain *Terrain
|
||||
chunks map[string]p.Chunk
|
||||
now time.Time
|
||||
dirty bool
|
||||
Version int `json:"version"`
|
||||
ID string `json:"id"`
|
||||
Seed int64 `json:"seed"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
EndedAt *time.Time `json:"endedAt,omitempty"`
|
||||
Phase string `json:"phase"`
|
||||
AdmissionsClosed bool `json:"admissionsClosed"`
|
||||
Tick int64 `json:"tick"`
|
||||
BossHP float64 `json:"bossHp"`
|
||||
BossLastAttack float64 `json:"bossLastAttack"`
|
||||
Characters map[string]*Character `json:"characters"`
|
||||
Corpses map[string]*Corpse `json:"corpses"`
|
||||
Depleted map[string]float64 `json:"depleted"`
|
||||
Mobs map[string]*Mob `json:"mobs"`
|
||||
Balance content.Balance `json:"balance"`
|
||||
terrain *Terrain
|
||||
chunks map[string]p.Chunk
|
||||
now time.Time
|
||||
dirty bool
|
||||
}
|
||||
|
||||
func ID() string {
|
||||
@@ -122,18 +126,27 @@ func (w *World) Info() p.WorldInfo {
|
||||
}
|
||||
func (w *World) ForAccount(account string) *Character {
|
||||
for _, c := range w.Characters {
|
||||
if c.Account == account {
|
||||
if c.Account == account && c.View.Entity.State != "dead" {
|
||||
return c
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (w *World) LivingCount() int {
|
||||
n := 0
|
||||
for _, c := range w.Characters {
|
||||
if c.View.Entity.State != "dead" {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
func (w *World) spawn(exclude string) (p.Vec3, error) {
|
||||
for i := 0; i < 4096; i++ {
|
||||
radius := math.Sqrt(float64(i)) * w.Balance.SpawnSeparation * 0.6
|
||||
angle := float64(i) * 2.399963229728653
|
||||
pos := w.terrain.Position(math.Cos(angle)*radius, math.Sin(angle)*radius)
|
||||
if radius > w.Balance.WorldRadius-32 {
|
||||
if radius > math.Max(0, math.Min(w.Balance.WorldRadius-32, w.SafeRadius()-8)) {
|
||||
break
|
||||
}
|
||||
clear := true
|
||||
@@ -153,10 +166,10 @@ func (w *World) Join(account, name string) (*Character, error) {
|
||||
if c := w.ForAccount(account); c != nil {
|
||||
return c, nil
|
||||
}
|
||||
if w.Phase != "gathering" {
|
||||
if (w.Phase != "gathering" && w.Phase != "cataclysm") || w.AdmissionsClosed {
|
||||
return nil, errors.New("this world is closed to new arrivals")
|
||||
}
|
||||
if len(w.Characters) >= w.Balance.MaxPlayers {
|
||||
if w.LivingCount() >= w.Balance.MaxPlayers {
|
||||
return nil, errors.New("world capacity reached")
|
||||
}
|
||||
pos, err := w.spawn("")
|
||||
@@ -168,11 +181,12 @@ func (w *World) Join(account, name string) (*Character, error) {
|
||||
c.View.Inventory[k] = v
|
||||
}
|
||||
w.Characters[c.View.Entity.ID] = c
|
||||
c.BornAt = w.now
|
||||
w.dirty = true
|
||||
return c, nil
|
||||
}
|
||||
func (w *World) Import(c *Character) error {
|
||||
if w.Phase != "gathering" || w.ForAccount(c.Account) != nil || len(w.Characters) >= w.Balance.MaxPlayers {
|
||||
if w.Phase != "gathering" || w.AdmissionsClosed || w.ForAccount(c.Account) != nil || w.Characters[c.View.Entity.ID] != nil || w.LivingCount() >= w.Balance.MaxPlayers {
|
||||
return errors.New("destination cannot accept character")
|
||||
}
|
||||
if c.View.Entity.State != "eligible" || c.View.Entity.HP <= 0 {
|
||||
@@ -430,8 +444,57 @@ func (w *World) kill(c *Character, reason string) {
|
||||
c.ReturnPosition = nil
|
||||
c.View.HasKeystone = false
|
||||
c.Message = reason
|
||||
died := w.now
|
||||
c.DiedAt = &died
|
||||
c.DeathReason = reason
|
||||
w.dirty = true
|
||||
}
|
||||
|
||||
// Operator changes use the same simulation and persistence path as gameplay.
|
||||
func (w *World) Control(op, target, value, reason string) error {
|
||||
switch op {
|
||||
case "close-admissions", "open-admissions":
|
||||
if w.Phase == "won" || w.Phase == "lost" {
|
||||
return errors.New("world has ended")
|
||||
}
|
||||
w.AdmissionsClosed = op == "close-admissions"
|
||||
case "awaken-boss":
|
||||
return w.TriggerBoss()
|
||||
case "end-world":
|
||||
if w.Phase == "won" || w.Phase == "lost" {
|
||||
return errors.New("world has already ended")
|
||||
}
|
||||
for _, c := range w.Characters {
|
||||
w.kill(c, "World ended by an operator: "+reason)
|
||||
}
|
||||
w.Phase = "lost"
|
||||
ended := w.now
|
||||
w.EndedAt = &ended
|
||||
default:
|
||||
c := w.Characters[target]
|
||||
if c == nil {
|
||||
return errors.New("character not found")
|
||||
}
|
||||
if c.View.Entity.State != "alive" {
|
||||
return errors.New("only living characters in an active world may be changed")
|
||||
}
|
||||
switch op {
|
||||
case "rename":
|
||||
c.View.Entity.Name = value
|
||||
case "heal":
|
||||
c.View.Entity.HP = c.View.Entity.MaxHP
|
||||
case "unstuck":
|
||||
c.View.Entity.Position = w.terrain.Position(0, 0)
|
||||
c.MoveX, c.MoveZ = 0, 0
|
||||
case "retire":
|
||||
w.kill(c, "Character retired by an operator: "+reason)
|
||||
default:
|
||||
return errors.New("unknown control operation")
|
||||
}
|
||||
}
|
||||
w.dirty = true
|
||||
return nil
|
||||
}
|
||||
func (w *World) Advance(now time.Time, dt float64) {
|
||||
playedDT := math.Max(0, dt)
|
||||
w.now = now
|
||||
|
||||
@@ -131,8 +131,17 @@ func TestGatherCraftAndPermanentDeath(t *testing.T) {
|
||||
t.Fatal("dead character reconnected")
|
||||
}
|
||||
same, err := w.Join(c.Account, "Replacement")
|
||||
if err != nil || same.View.Entity.ID != id || same.View.Entity.State != "dead" {
|
||||
t.Fatal("death bypass by rejoining")
|
||||
if err != nil || same.View.Entity.ID == id || same.View.Entity.State != "alive" || c.View.Entity.State != "dead" {
|
||||
t.Fatal("replacement must be a new life, not a resurrection")
|
||||
}
|
||||
if same.DailySeconds != 0 || same.View.Inventory["spear"] != 0 || w.LivingCount() != 1 {
|
||||
t.Fatal("new life inherited old progress or incorrect capacity")
|
||||
}
|
||||
if again, _ := w.Join(c.Account, "Duplicate"); again.View.Entity.ID != same.View.Entity.ID {
|
||||
t.Fatal("second living character")
|
||||
}
|
||||
if c.DiedAt == nil || c.DeathReason != "test death" {
|
||||
t.Fatal("missing durable death record")
|
||||
}
|
||||
if len(c.View.Inventory) != 0 || w.Corpses["corpse:"+id].Inventory["spear"] != 1 {
|
||||
t.Fatal("corpse inventory")
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
package gitops
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.yaml.in/yaml/v3"
|
||||
)
|
||||
|
||||
type Config struct{ Repository, Branch, File, Token, PublicURL string }
|
||||
type Client struct {
|
||||
config Config
|
||||
endpoint string
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
var identifier = regexp.MustCompile(`^[a-z][a-z0-9-]{0,30}$`)
|
||||
var seedPattern = regexp.MustCompile(`^[0-9]{1,15}$`)
|
||||
|
||||
func New(c Config) (*Client, error) {
|
||||
if c.Repository == "" && c.Token == "" {
|
||||
return nil, nil
|
||||
}
|
||||
u, err := url.Parse(c.Repository)
|
||||
if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
|
||||
return nil, errors.New("CONTROL_GITOPS_REPOSITORY must be an HTTPS repository URL without credentials")
|
||||
}
|
||||
parts := strings.Split(strings.Trim(strings.TrimSuffix(u.Path, ".git"), "/"), "/")
|
||||
if len(parts) != 2 {
|
||||
return nil, errors.New("GitOps repository must have owner/repository path")
|
||||
}
|
||||
for _, p := range parts {
|
||||
if p == "." || p == ".." || !regexp.MustCompile(`^[A-Za-z0-9_.-]+$`).MatchString(p) {
|
||||
return nil, errors.New("invalid repository path")
|
||||
}
|
||||
}
|
||||
if c.Token == "" || c.Branch == "" || c.File == "" || path.Clean(c.File) != c.File || strings.HasPrefix(c.File, "/") || strings.Contains(c.File, "\\") || strings.HasPrefix(c.File, "..") || !strings.HasSuffix(c.File, ".yaml") {
|
||||
return nil, errors.New("GitOps requires token, branch, and repository-relative .yaml file")
|
||||
}
|
||||
public, err := url.Parse(c.PublicURL)
|
||||
if err != nil || public.Scheme != "https" || public.Host == "" || public.Path != "" || public.RawQuery != "" || public.User != nil {
|
||||
return nil, errors.New("GitOps requires an HTTPS public origin")
|
||||
}
|
||||
endpoint := u.Scheme + "://" + u.Host + "/api/v1/repos/" + url.PathEscape(parts[0]) + "/" + url.PathEscape(parts[1]) + "/contents/"
|
||||
for i, p := range strings.Split(c.File, "/") {
|
||||
if i > 0 {
|
||||
endpoint += "/"
|
||||
}
|
||||
endpoint += url.PathEscape(p)
|
||||
}
|
||||
return &Client{c, endpoint, &http.Client{Timeout: 15 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}, nil
|
||||
}
|
||||
func (c *Client) request(ctx context.Context, method string, body any) ([]byte, int, error) {
|
||||
var r io.Reader
|
||||
if body != nil {
|
||||
data, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
r = bytes.NewReader(data)
|
||||
}
|
||||
u := c.endpoint
|
||||
if method == http.MethodGet {
|
||||
u += "?ref=" + url.QueryEscape(c.config.Branch)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, u, r)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
req.Header.Set("Authorization", "token "+c.config.Token)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
res, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return nil, 0, errors.New("GitOps service unavailable")
|
||||
}
|
||||
defer res.Body.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(res.Body, 2<<20))
|
||||
if err != nil {
|
||||
return nil, res.StatusCode, errors.New("GitOps response unavailable")
|
||||
}
|
||||
return raw, res.StatusCode, nil
|
||||
}
|
||||
func mapping(n *yaml.Node, key string) *yaml.Node {
|
||||
if n.Kind != yaml.MappingNode {
|
||||
return nil
|
||||
}
|
||||
for i := 0; i < len(n.Content); i += 2 {
|
||||
if n.Content[i].Value == key {
|
||||
return n.Content[i+1]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func scalar(v string) *yaml.Node { return &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: v} }
|
||||
|
||||
// Only the worlds sequence is changed; image pins, comments and runtime settings
|
||||
// stay intact. Gitea's content SHA rejects concurrent image-promotion overwrites.
|
||||
func (c *Client) CreateWorld(ctx context.Context, id, seed string) (string, error) {
|
||||
if !identifier.MatchString(id) || !seedPattern.MatchString(seed) {
|
||||
return "", errors.New("invalid world ID or seed")
|
||||
}
|
||||
for attempt := 0; attempt < 3; attempt++ {
|
||||
raw, status, err := c.request(ctx, http.MethodGet, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if status != 200 {
|
||||
return "", fmt.Errorf("GitOps values could not be read (HTTP %d)", status)
|
||||
}
|
||||
var file struct {
|
||||
SHA string `json:"sha"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
if json.Unmarshal(raw, &file) != nil || file.SHA == "" {
|
||||
return "", errors.New("invalid GitOps file response")
|
||||
}
|
||||
data, err := base64.StdEncoding.DecodeString(strings.ReplaceAll(file.Content, "\n", ""))
|
||||
if err != nil {
|
||||
return "", errors.New("invalid GitOps file encoding")
|
||||
}
|
||||
var doc yaml.Node
|
||||
if yaml.Unmarshal(data, &doc) != nil || len(doc.Content) != 1 {
|
||||
return "", errors.New("invalid GitOps YAML")
|
||||
}
|
||||
root := doc.Content[0]
|
||||
worlds := mapping(root, "worlds")
|
||||
portal := mapping(root, "portal")
|
||||
public, _ := url.Parse(c.config.PublicURL)
|
||||
if portal == nil || mapping(portal, "host") == nil || mapping(portal, "host").Value != public.Host {
|
||||
return "", errors.New("GitOps portal.host must match PUBLIC_URL before provisioning")
|
||||
}
|
||||
if worlds == nil || worlds.Kind != yaml.SequenceNode {
|
||||
return "", errors.New("GitOps values must contain a worlds list")
|
||||
}
|
||||
for _, world := range worlds.Content {
|
||||
key := mapping(world, "id")
|
||||
if key != nil && key.Value == id {
|
||||
existing := mapping(world, "seed")
|
||||
if existing != nil && existing.Value == seed {
|
||||
return "World definition already committed; waiting for ArgoCD readiness.", nil
|
||||
}
|
||||
return "", errors.New("world ID already exists with a different seed")
|
||||
}
|
||||
}
|
||||
if len(worlds.Content) >= 50 {
|
||||
return "", errors.New("operator world limit reached (50)")
|
||||
}
|
||||
worlds.Content = append(worlds.Content, &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map", Content: []*yaml.Node{scalar("id"), scalar(id), scalar("seed"), scalar(seed), scalar("host"), scalar(public.Host)}})
|
||||
encoded, err := yaml.Marshal(&doc)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
body := map[string]string{"branch": c.config.Branch, "sha": file.SHA, "content": base64.StdEncoding.EncodeToString(encoded), "message": "Provision Aeternalis world " + id}
|
||||
_, status, err = c.request(ctx, http.MethodPut, body)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if status == 200 || status == 201 {
|
||||
return "World definition committed; waiting for ArgoCD readiness.", nil
|
||||
}
|
||||
if status != 409 && status != 422 {
|
||||
return "", fmt.Errorf("GitOps commit rejected (HTTP %d)", status)
|
||||
}
|
||||
}
|
||||
return "", errors.New("GitOps changed concurrently; retry the request")
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package gitops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go.yaml.in/yaml/v3"
|
||||
)
|
||||
|
||||
func TestCreateWorldPreservesValuesAndRetries(t *testing.T) {
|
||||
current := "# retained operator comment\nimage:\n digest: sha256:keep\nportal:\n host: srs.example.test\nworlds:\n - id: world-001\n seed: \"12\"\n host: srs.example.test\n"
|
||||
puts := 0
|
||||
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "token test-token" {
|
||||
t.Error("missing token")
|
||||
}
|
||||
if r.URL.Path != "/api/v1/repos/owner/game/contents/deploy/values.yaml" {
|
||||
t.Error("wrong path", r.URL.Path)
|
||||
}
|
||||
if r.Method == "GET" {
|
||||
if r.URL.Query().Get("ref") != "master" {
|
||||
t.Error("wrong branch")
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"sha": "revision", "content": base64.StdEncoding.EncodeToString([]byte(current))})
|
||||
return
|
||||
}
|
||||
var body map[string]string
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
if body["sha"] != "revision" || body["branch"] != "master" {
|
||||
t.Error("missing optimistic revision")
|
||||
}
|
||||
puts++
|
||||
if puts == 1 {
|
||||
w.WriteHeader(409)
|
||||
return
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(body["content"])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
current = string(raw)
|
||||
w.WriteHeader(200)
|
||||
_, _ = w.Write([]byte(`{}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
c, err := New(Config{server.URL + "/owner/game.git", "master", "deploy/values.yaml", "test-token", "https://srs.example.test"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.http = server.Client()
|
||||
if _, err = c.CreateWorld(context.Background(), "world-002", "42"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if puts != 2 || !strings.Contains(current, "retained operator comment") || !strings.Contains(current, "sha256:keep") {
|
||||
t.Fatal("unrelated values changed", current)
|
||||
}
|
||||
var values struct {
|
||||
Worlds []struct{ ID, Seed, Host string }
|
||||
}
|
||||
if err = yaml.Unmarshal([]byte(current), &values); err != nil || len(values.Worlds) != 2 || values.Worlds[1].Seed != "42" {
|
||||
t.Fatal("bad world definition", err, current)
|
||||
}
|
||||
if _, err = c.CreateWorld(context.Background(), "world-002", "42"); err != nil || puts != 2 {
|
||||
t.Fatal("retry duplicated world", err)
|
||||
}
|
||||
if _, err = c.CreateWorld(context.Background(), "world-002", "43"); err == nil {
|
||||
t.Fatal("existing ID reused")
|
||||
}
|
||||
if _, err = c.CreateWorld(context.Background(), "../bad", "42"); err == nil {
|
||||
t.Fatal("invalid ID accepted")
|
||||
}
|
||||
}
|
||||
func TestGitOpsConfigurationValidation(t *testing.T) {
|
||||
for _, repository := range []string{"http://example.test/o/r", "https://token@example.test/o/r", "https://example.test/only-one", "https://example.test/../repo"} {
|
||||
if _, err := New(Config{repository, "master", "deploy/values.yaml", "token", "https://srs.example.test"}); err == nil {
|
||||
t.Fatal("unsafe repository accepted", repository)
|
||||
}
|
||||
}
|
||||
for _, file := range []string{"../secret.yaml", "/absolute.yaml", "values.json", "a/../values.yaml"} {
|
||||
if _, err := New(Config{"https://example.test/o/r", "master", file, "token", "https://srs.example.test"}); err == nil {
|
||||
t.Fatal("unsafe file accepted", file)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"aeternalis/server/internal/game"
|
||||
)
|
||||
|
||||
var ErrLivingCharacter = errors.New("you already have a living character; continue that character or use its survivor passage")
|
||||
|
||||
type CharacterRecord struct {
|
||||
ID string `json:"id"`
|
||||
Account string `json:"account"`
|
||||
WorldID string `json:"worldId"`
|
||||
Name string `json:"name"`
|
||||
State string `json:"state"`
|
||||
Character *game.Character `json:"character"`
|
||||
}
|
||||
type WorldRecord struct {
|
||||
ID string `json:"id"`
|
||||
Phase string `json:"phase"`
|
||||
Living int `json:"living"`
|
||||
Dead int `json:"dead"`
|
||||
Capacity int `json:"capacity"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
BossAt time.Time `json:"bossAt"`
|
||||
Closed bool `json:"closed"`
|
||||
Available bool `json:"available"`
|
||||
Revision int64 `json:"revision"`
|
||||
}
|
||||
type Command struct {
|
||||
ID string `json:"id"`
|
||||
WorldID string `json:"worldId"`
|
||||
Actor string `json:"actor"`
|
||||
Op string `json:"op"`
|
||||
Target string `json:"target"`
|
||||
Value string `json:"value"`
|
||||
Reason string `json:"reason"`
|
||||
Status string `json:"status"`
|
||||
Result string `json:"result"`
|
||||
CreatedAt int64 `json:"createdAt"`
|
||||
CompletedAt int64 `json:"completedAt"`
|
||||
}
|
||||
|
||||
// Versioned, transactional backfill. Conflicting legacy lives fail closed rather
|
||||
// than choosing which player's character to destroy during an upgrade.
|
||||
func (d *DB) migrate(ctx context.Context) error {
|
||||
tx, err := d.sql.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if d.postgres {
|
||||
if _, err = tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(7362771)`); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, stmt := range []string{
|
||||
`CREATE TABLE IF NOT EXISTS schema_migrations(version INTEGER PRIMARY KEY)`,
|
||||
`CREATE TABLE IF NOT EXISTS character_records(character_id TEXT PRIMARY KEY, account_id TEXT NOT NULL, world_id TEXT NOT NULL, name TEXT NOT NULL, state TEXT NOT NULL, character TEXT NOT NULL)`,
|
||||
`CREATE UNIQUE INDEX IF NOT EXISTS one_living_character ON character_records(account_id) WHERE state IN ('alive','eligible')`,
|
||||
`CREATE INDEX IF NOT EXISTS characters_world ON character_records(world_id)`,
|
||||
`CREATE TABLE IF NOT EXISTS admin_sessions(token_hash TEXT PRIMARY KEY, expires BIGINT NOT NULL)`,
|
||||
`CREATE TABLE IF NOT EXISTS control_commands(id TEXT PRIMARY KEY, world_id TEXT NOT NULL, actor TEXT NOT NULL, op TEXT NOT NULL, target TEXT NOT NULL, value TEXT NOT NULL, reason TEXT NOT NULL, status TEXT NOT NULL, result TEXT NOT NULL, created_at BIGINT NOT NULL, completed_at BIGINT NOT NULL DEFAULT 0)`,
|
||||
`CREATE INDEX IF NOT EXISTS commands_pending ON control_commands(world_id,status,created_at)`,
|
||||
} {
|
||||
if _, err = tx.ExecContext(ctx, stmt); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
var version int
|
||||
err = tx.QueryRowContext(ctx, `SELECT version FROM schema_migrations WHERE version=1`).Scan(&version)
|
||||
if err == nil {
|
||||
return tx.Commit()
|
||||
}
|
||||
if !errors.Is(err, sql.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
rows, err := tx.QueryContext(ctx, `SELECT snapshot FROM worlds ORDER BY id`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var worlds []*game.World
|
||||
for rows.Next() {
|
||||
var raw string
|
||||
if err = rows.Scan(&raw); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
var w game.World
|
||||
if err = json.Unmarshal([]byte(raw), &w); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
worlds = append(worlds, &w)
|
||||
}
|
||||
err = rows.Err()
|
||||
rows.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, w := range worlds {
|
||||
for _, c := range w.Characters {
|
||||
var source string
|
||||
var claimed sql.NullString
|
||||
err = tx.QueryRowContext(ctx, d.q(`SELECT source_world,claimed_world FROM passages WHERE character_id=?`), c.View.Entity.ID).Scan(&source, &claimed)
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
if err == nil && ((claimed.Valid && claimed.String != w.ID) || (!claimed.Valid && source != w.ID)) {
|
||||
continue
|
||||
}
|
||||
if err = d.writeCharacter(ctx, tx, w.ID, c, false); err != nil {
|
||||
return fmt.Errorf("character migration conflict in world %s: %w; stop all old world pods and resolve duplicate living characters before upgrading", w.ID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, `INSERT INTO schema_migrations(version) VALUES(1)`); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
func (d *DB) writeCharacter(ctx context.Context, tx *sql.Tx, world string, c *game.Character, claim bool) error {
|
||||
raw, err := json.Marshal(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
where := "character_records.world_id=excluded.world_id"
|
||||
if claim {
|
||||
where = "character_records.account_id=excluded.account_id"
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, d.q(`INSERT INTO character_records(character_id,account_id,world_id,name,state,character) VALUES(?,?,?,?,?,?) ON CONFLICT(character_id) DO UPDATE SET world_id=excluded.world_id,name=excluded.name,state=excluded.state,character=excluded.character WHERE `+where), c.View.Entity.ID, c.Account, world, c.View.Entity.Name, c.View.Entity.State, string(raw))
|
||||
if err != nil && (strings.Contains(err.Error(), "one_living_character") || strings.Contains(err.Error(), "character_records.account_id")) {
|
||||
return ErrLivingCharacter
|
||||
}
|
||||
return err
|
||||
}
|
||||
func (d *DB) syncCharacters(ctx context.Context, tx *sql.Tx, w *game.World, claim string) error {
|
||||
// Release dead lives before reserving their replacements, independent of map order.
|
||||
characters := make([]*game.Character, 0, len(w.Characters))
|
||||
for _, c := range w.Characters {
|
||||
characters = append(characters, c)
|
||||
}
|
||||
sort.Slice(characters, func(i, j int) bool {
|
||||
a, b := characters[i], characters[j]
|
||||
if (a.View.Entity.State == "dead") != (b.View.Entity.State == "dead") {
|
||||
return a.View.Entity.State == "dead"
|
||||
}
|
||||
return a.View.Entity.ID < b.View.Entity.ID
|
||||
})
|
||||
for _, c := range characters {
|
||||
if err := d.writeCharacter(ctx, tx, w.ID, c, c.View.Entity.ID == claim && claim != ""); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (d *DB) ActiveCharacter(ctx context.Context, account string) (*CharacterRecord, error) {
|
||||
var r CharacterRecord
|
||||
var raw string
|
||||
err := d.sql.QueryRowContext(ctx, d.q(`SELECT character_id,account_id,world_id,name,state,character FROM character_records WHERE account_id=? AND state IN ('alive','eligible')`), account).Scan(&r.ID, &r.Account, &r.WorldID, &r.Name, &r.State, &raw)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = json.Unmarshal([]byte(raw), &r.Character); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &r, nil
|
||||
}
|
||||
func (d *DB) Characters(ctx context.Context, account, world string) ([]CharacterRecord, error) {
|
||||
query := `SELECT character_id,account_id,world_id,name,state,character FROM character_records WHERE 1=1`
|
||||
args := []any{}
|
||||
if account != "" {
|
||||
query += " AND account_id=?"
|
||||
args = append(args, account)
|
||||
}
|
||||
if world != "" {
|
||||
query += " AND world_id=?"
|
||||
args = append(args, world)
|
||||
}
|
||||
query += " ORDER BY world_id,name,character_id LIMIT 500"
|
||||
rows, err := d.sql.QueryContext(ctx, d.q(query), args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []CharacterRecord{}
|
||||
for rows.Next() {
|
||||
var r CharacterRecord
|
||||
var raw string
|
||||
if err = rows.Scan(&r.ID, &r.Account, &r.WorldID, &r.Name, &r.State, &raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = json.Unmarshal([]byte(raw), &r.Character); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, r)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
func (d *DB) Worlds(ctx context.Context) ([]WorldRecord, error) {
|
||||
rows, err := d.sql.QueryContext(ctx, `SELECT snapshot,revision,CASE WHEN owner<>'' AND lease_until>=`+d.now()+` THEN 1 ELSE 0 END FROM worlds ORDER BY id LIMIT 200`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []WorldRecord{}
|
||||
for rows.Next() {
|
||||
var raw string
|
||||
var r WorldRecord
|
||||
var available int
|
||||
if err = rows.Scan(&raw, &r.Revision, &available); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var w game.World
|
||||
if err = json.Unmarshal([]byte(raw), &w); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.ID = w.ID
|
||||
r.Phase = w.Phase
|
||||
r.Living = w.LivingCount()
|
||||
r.Dead = len(w.Characters) - r.Living
|
||||
r.Capacity = w.Balance.MaxPlayers
|
||||
r.CreatedAt = w.CreatedAt
|
||||
r.BossAt = w.CreatedAt.Add(time.Duration(w.Balance.SeasonSeconds) * time.Second)
|
||||
r.Closed = w.AdmissionsClosed
|
||||
r.Available = available == 1
|
||||
out = append(out, r)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
func (d *DB) GrantAdmin(ctx context.Context, token string, seconds int64) error {
|
||||
_, err := d.sql.ExecContext(ctx, d.q(`INSERT INTO admin_sessions(token_hash,expires) VALUES(?,`+d.now()+`+?) ON CONFLICT(token_hash) DO UPDATE SET expires=excluded.expires`), token, seconds)
|
||||
return err
|
||||
}
|
||||
func (d *DB) IsAdmin(ctx context.Context, token string) bool {
|
||||
var n int
|
||||
err := d.sql.QueryRowContext(ctx, d.q(`SELECT 1 FROM admin_sessions a JOIN sessions s ON s.token_hash=a.token_hash WHERE a.token_hash=? AND a.expires>`+d.now()+` AND s.expires>`+d.now()), token).Scan(&n)
|
||||
return err == nil && n == 1
|
||||
}
|
||||
func (d *DB) Enqueue(ctx context.Context, c Command) error {
|
||||
_, err := d.sql.ExecContext(ctx, d.q(`INSERT INTO control_commands(id,world_id,actor,op,target,value,reason,status,result,created_at) VALUES(?,?,?,?,?,?,?,'pending','',`+d.now()+`) ON CONFLICT(id) DO NOTHING`), c.ID, c.WorldID, c.Actor, c.Op, c.Target, c.Value, c.Reason)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var existing Command
|
||||
err = d.sql.QueryRowContext(ctx, d.q(`SELECT actor,world_id,op,target,value,reason FROM control_commands WHERE id=?`), c.ID).Scan(&existing.Actor, &existing.WorldID, &existing.Op, &existing.Target, &existing.Value, &existing.Reason)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if existing.Actor != c.Actor || existing.WorldID != c.WorldID || existing.Op != c.Op || existing.Target != c.Target || existing.Value != c.Value || existing.Reason != c.Reason {
|
||||
return errors.New("request ID already used")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (d *DB) Commands(ctx context.Context, world string, pending bool) ([]Command, error) {
|
||||
query := `SELECT id,world_id,actor,op,target,value,reason,status,result,created_at,completed_at FROM control_commands WHERE 1=1`
|
||||
args := []any{}
|
||||
if world != "" {
|
||||
query += " AND world_id=?"
|
||||
args = append(args, world)
|
||||
}
|
||||
if pending {
|
||||
query += " AND status='pending' ORDER BY created_at,id LIMIT 10"
|
||||
} else {
|
||||
query += " ORDER BY created_at DESC,id LIMIT 100"
|
||||
}
|
||||
rows, err := d.sql.QueryContext(ctx, d.q(query), args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []Command{}
|
||||
for rows.Next() {
|
||||
var c Command
|
||||
if err = rows.Scan(&c.ID, &c.WorldID, &c.Actor, &c.Op, &c.Target, &c.Value, &c.Reason, &c.Status, &c.Result, &c.CreatedAt, &c.CompletedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, c)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
func (d *DB) FinishProvision(ctx context.Context, id, result string, success bool) error {
|
||||
status := "rejected"
|
||||
if success {
|
||||
status = "completed"
|
||||
}
|
||||
_, err := d.sql.ExecContext(ctx, d.q(`UPDATE control_commands SET status=?,result=?,completed_at=`+d.now()+` WHERE id=? AND status='pending' AND op='create-world'`), status, result, id)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"aeternalis/server/content"
|
||||
"aeternalis/server/internal/game"
|
||||
)
|
||||
|
||||
func TestGlobalLivingCharacter(t *testing.T) {
|
||||
runGlobalLives(t, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "lives.db")))
|
||||
}
|
||||
func TestPostgresGlobalLivingCharacter(t *testing.T) {
|
||||
dsn := os.Getenv("TEST_DATABASE_URL")
|
||||
if dsn == "" {
|
||||
t.Skip("TEST_DATABASE_URL not configured")
|
||||
}
|
||||
runGlobalLives(t, dsn)
|
||||
}
|
||||
func runGlobalLives(t *testing.T, dsn string) {
|
||||
ctx := context.Background()
|
||||
db, err := Open(ctx, dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
b, _ := content.Load()
|
||||
prefix := game.ID()
|
||||
account := "lives:" + prefix
|
||||
worlds := []*game.World{game.New(prefix+"-a", 1, time.Now(), b), game.New(prefix+"-b", 2, time.Now(), b)}
|
||||
leases := make([]*Lease, 2)
|
||||
for i, w := range worlds {
|
||||
leases[i], _, err = db.Acquire(ctx, w)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = w.Join(account, "Traveler"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
results := make([]error, 2)
|
||||
for i := range worlds {
|
||||
wg.Add(1)
|
||||
go func(i int) { defer wg.Done(); results[i] = leases[i].Save(ctx, worlds[i], "") }(i)
|
||||
}
|
||||
wg.Wait()
|
||||
winner := -1
|
||||
loser := -1
|
||||
for i, err := range results {
|
||||
if err == nil {
|
||||
if winner != -1 {
|
||||
t.Fatal("two living characters committed")
|
||||
}
|
||||
winner = i
|
||||
} else {
|
||||
if !errors.Is(err, ErrLivingCharacter) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
loser = i
|
||||
}
|
||||
}
|
||||
if winner < 0 || loser < 0 {
|
||||
t.Fatal("expected exactly one committed life")
|
||||
}
|
||||
var raw string
|
||||
if err = db.sql.QueryRowContext(ctx, db.q(`SELECT snapshot FROM worlds WHERE id=?`), worlds[loser].ID).Scan(&raw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var durable game.World
|
||||
_ = json.Unmarshal([]byte(raw), &durable)
|
||||
if len(durable.Characters) != 0 {
|
||||
t.Fatal("failed join left a durable duplicate")
|
||||
}
|
||||
old := worlds[winner].ForAccount(account)
|
||||
if err = worlds[winner].Control("retire", old.View.Entity.ID, "", "test retirement"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = leases[winner].Save(ctx, worlds[winner], ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = leases[loser].Save(ctx, worlds[loser], ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
active, err := db.ActiveCharacter(ctx, account)
|
||||
if err != nil || active == nil || active.WorldID != worlds[loser].ID {
|
||||
t.Fatal("death did not release the living-character reservation")
|
||||
}
|
||||
if err = leases[winner].Save(ctx, worlds[winner], ""); err != nil {
|
||||
t.Fatal("old dead world interfered with replacement", err)
|
||||
}
|
||||
history, err := db.Characters(ctx, account, "")
|
||||
if err != nil || len(history) != 2 {
|
||||
t.Fatal("death history missing", err)
|
||||
}
|
||||
for _, l := range leases {
|
||||
_ = l.Release(ctx)
|
||||
}
|
||||
}
|
||||
func TestCommandAuditAtomicity(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, err := Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "audit.db")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
b, _ := content.Load()
|
||||
w := game.New("audit", 1, time.Now(), b)
|
||||
l, _, _ := db.Acquire(ctx, w)
|
||||
c := Command{ID: game.ID(), WorldID: w.ID, Actor: "admin", Op: "close-admissions", Reason: "maintenance test"}
|
||||
if err = db.Enqueue(ctx, c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = db.Enqueue(ctx, c); err != nil {
|
||||
t.Fatal("retry not idempotent", err)
|
||||
}
|
||||
if err = w.Control(c.Op, "", "", c.Reason); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = l.SaveCommand(ctx, w, "", &c, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
commands, _ := db.Commands(ctx, w.ID, false)
|
||||
if len(commands) != 1 || commands[0].Status != "completed" {
|
||||
t.Fatal("audit not completed")
|
||||
}
|
||||
if err = l.SaveCommand(ctx, w, "", &c, ""); err == nil {
|
||||
t.Fatal("command completed twice")
|
||||
}
|
||||
c.Actor = "different"
|
||||
if err = db.Enqueue(ctx, c); err == nil {
|
||||
t.Fatal("request ID could be reused")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOldSurvivorSnapshotCannotReclaimReplacement(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, err := Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "old-source.db")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
b, _ := content.Load()
|
||||
source := game.New("source", 1, time.Now(), b)
|
||||
sl, _, _ := db.Acquire(ctx, source)
|
||||
c, _ := source.Join("account", "Survivor")
|
||||
c.View.Entity.State = "eligible"
|
||||
source.Phase = "won"
|
||||
if err = sl.Save(ctx, source, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
target := game.New("target", 2, time.Now(), b)
|
||||
tl, _, _ := db.Acquire(ctx, target)
|
||||
copy, _ := db.ReadPassage(ctx, c.View.Entity.ID, c.Account)
|
||||
if err = target.Import(copy); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = tl.Save(ctx, target, c.View.Entity.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = target.Control("retire", c.View.Entity.ID, "", "test death"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = tl.Save(ctx, target, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
replacement, _ := target.Join(c.Account, "Replacement")
|
||||
if err = tl.Save(ctx, target, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = sl.Save(ctx, source, ""); err != nil {
|
||||
t.Fatal("old source blocked new life", err)
|
||||
}
|
||||
active, _ := db.ActiveCharacter(ctx, c.Account)
|
||||
if active == nil || active.ID != replacement.View.Entity.ID {
|
||||
t.Fatal("old survivor reclaimed character slot")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacySnapshotBackfill(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
dsn := "file:" + filepath.ToSlash(filepath.Join(t.TempDir(), "legacy.db"))
|
||||
db, err := Open(ctx, dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := content.Load()
|
||||
w := game.New("legacy", 1, time.Now(), b)
|
||||
l, _, _ := db.Acquire(ctx, w)
|
||||
c, _ := w.Join("account", "Legacy")
|
||||
if err = l.Save(ctx, w, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = l.Release(ctx)
|
||||
_, _ = db.sql.ExecContext(ctx, `DELETE FROM character_records`)
|
||||
_, _ = db.sql.ExecContext(ctx, `DELETE FROM schema_migrations`)
|
||||
_ = db.Close()
|
||||
db, err = Open(ctx, dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
active, err := db.ActiveCharacter(ctx, c.Account)
|
||||
if err != nil || active == nil || active.ID != c.View.Entity.ID {
|
||||
t.Fatal("legacy living character not backfilled", err)
|
||||
}
|
||||
}
|
||||
@@ -69,6 +69,10 @@ func Open(ctx context.Context, dsn string) (*DB, error) {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err = db.migrate(ctx); err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
return db, nil
|
||||
}
|
||||
func (d *DB) Close() error { return d.sql.Close() }
|
||||
@@ -128,6 +132,9 @@ func (d *DB) Acquire(ctx context.Context, w *game.World) (*Lease, []byte, error)
|
||||
return &Lease{d, w.ID, owner, revision}, []byte(snapshot), nil
|
||||
}
|
||||
func (l *Lease) Save(ctx context.Context, w *game.World, claimID string) error {
|
||||
return l.SaveCommand(ctx, w, claimID, nil, "")
|
||||
}
|
||||
func (l *Lease) SaveCommand(ctx context.Context, w *game.World, claimID string, command *Command, outcome string) error {
|
||||
data, err := json.Marshal(w)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -175,6 +182,28 @@ func (l *Lease) Save(ctx context.Context, w *game.World, claimID string) error {
|
||||
}
|
||||
}
|
||||
}
|
||||
if err = d.syncCharacters(ctx, tx, w, claimID); err != nil {
|
||||
return err
|
||||
}
|
||||
if command != nil {
|
||||
status := "completed"
|
||||
if outcome != "" {
|
||||
status = "rejected"
|
||||
}
|
||||
r, err := tx.ExecContext(ctx, d.q(`UPDATE control_commands SET status=?,result=?,completed_at=`+d.now()+` WHERE id=? AND world_id=? AND status='pending'`), status, outcome, command.ID, w.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, _ := r.RowsAffected()
|
||||
if n != 1 {
|
||||
return errors.New("command already processed")
|
||||
}
|
||||
if command.Op == "revoke-sessions" && outcome == "" {
|
||||
if _, err = tx.ExecContext(ctx, d.q(`DELETE FROM sessions WHERE account_id=?`), command.Target); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if err = tx.Commit(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -18,21 +19,24 @@ import (
|
||||
)
|
||||
|
||||
type Auth struct {
|
||||
db *store.DB
|
||||
dev bool
|
||||
base string
|
||||
oauth *oauth2.Config
|
||||
verifier *oidc.IDTokenVerifier
|
||||
mu sync.Mutex
|
||||
flows map[string]flow
|
||||
db *store.DB
|
||||
dev bool
|
||||
base string
|
||||
oauth *oauth2.Config
|
||||
verifier *oidc.IDTokenVerifier
|
||||
mu sync.Mutex
|
||||
flows map[string]flow
|
||||
AdminRole string
|
||||
DevAdmin bool
|
||||
}
|
||||
type flow struct {
|
||||
verifier string
|
||||
expires time.Time
|
||||
returnTo string
|
||||
}
|
||||
|
||||
func NewAuth(ctx context.Context, db *store.DB, dev bool, base, issuer, client, secret string) (*Auth, error) {
|
||||
a := &Auth{db: db, dev: dev, base: base, flows: map[string]flow{}}
|
||||
a := &Auth{db: db, dev: dev, base: base, flows: map[string]flow{}, AdminRole: "aeternalis-admin"}
|
||||
if dev {
|
||||
return a, nil
|
||||
}
|
||||
@@ -62,16 +66,25 @@ func (a *Auth) account(r *http.Request) (string, error) {
|
||||
return a.db.Session(r.Context(), hash(c.Value))
|
||||
}
|
||||
func (a *Auth) session(w http.ResponseWriter, r *http.Request, account string) error {
|
||||
return a.issueSession(w, r, account, false)
|
||||
}
|
||||
func (a *Auth) issueSession(w http.ResponseWriter, r *http.Request, account string, admin bool) error {
|
||||
token := game.ID() + game.ID()
|
||||
if err := a.db.CreateSession(r.Context(), hash(token), account); err != nil {
|
||||
return err
|
||||
}
|
||||
if admin {
|
||||
if err := a.db.GrantAdmin(r.Context(), hash(token), 600); err != nil {
|
||||
_ = a.db.DeleteSession(r.Context(), hash(token))
|
||||
return err
|
||||
}
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: a.cookieName(), Value: token, Path: "/", HttpOnly: true, Secure: !a.dev, SameSite: http.SameSiteLaxMode, MaxAge: 86400})
|
||||
return nil
|
||||
}
|
||||
func (a *Auth) login(w http.ResponseWriter, r *http.Request) {
|
||||
if a.dev {
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
http.Redirect(w, r, safeReturn(r.URL.Query().Get("return")), http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
state := game.ID() + game.ID()
|
||||
@@ -87,7 +100,7 @@ func (a *Auth) login(w http.ResponseWriter, r *http.Request) {
|
||||
fail(w, 503, "login capacity reached")
|
||||
return
|
||||
}
|
||||
a.flows[state] = flow{v, time.Now().Add(10 * time.Minute)}
|
||||
a.flows[state] = flow{v, time.Now().Add(10 * time.Minute), safeReturn(r.URL.Query().Get("return"))}
|
||||
a.mu.Unlock()
|
||||
http.SetCookie(w, &http.Cookie{Name: "__Host-aeternalis_login", Value: state, Path: "/", HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode, MaxAge: 600})
|
||||
http.Redirect(w, r, a.oauth.AuthCodeURL(state, oauth2.S256ChallengeOption(v), oidc.Nonce(state)), http.StatusSeeOther)
|
||||
@@ -128,12 +141,57 @@ func (a *Auth) callback(w http.ResponseWriter, r *http.Request) {
|
||||
fail(w, 401, "invalid identity token")
|
||||
return
|
||||
}
|
||||
if err = a.session(w, r, hash(identity.Issuer+"\x00"+identity.Subject)); err != nil {
|
||||
var claims roleClaims
|
||||
if err = identity.Claims(&claims); err != nil {
|
||||
fail(w, 401, "invalid identity claims")
|
||||
return
|
||||
}
|
||||
if err = a.issueSession(w, r, hash(identity.Issuer+"\x00"+identity.Subject), claims.admin(a.AdminRole, a.oauth.ClientID)); err != nil {
|
||||
fail(w, 503, "session unavailable")
|
||||
return
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: "__Host-aeternalis_login", Path: "/", HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode, MaxAge: -1})
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
http.Redirect(w, r, f.returnTo, http.StatusSeeOther)
|
||||
}
|
||||
|
||||
type roleSet struct {
|
||||
Roles []string `json:"roles"`
|
||||
}
|
||||
type roleClaims struct {
|
||||
Realm roleSet `json:"realm_access"`
|
||||
Clients map[string]roleSet `json:"resource_access"`
|
||||
}
|
||||
|
||||
func (c roleClaims) admin(role, client string) bool {
|
||||
return role != "" && (slices.Contains(c.Realm.Roles, role) || slices.Contains(c.Clients[client].Roles, role))
|
||||
}
|
||||
func (a *Auth) isAdmin(r *http.Request) bool {
|
||||
if _, err := a.account(r); err != nil {
|
||||
return false
|
||||
}
|
||||
if a.dev && a.DevAdmin {
|
||||
return true
|
||||
}
|
||||
c, err := r.Cookie(a.cookieName())
|
||||
return err == nil && a.db.IsAdmin(r.Context(), hash(c.Value))
|
||||
}
|
||||
func safeReturn(raw string) string {
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || u.IsAbs() || u.Host != "" || u.User != nil || u.Fragment != "" {
|
||||
return "/"
|
||||
}
|
||||
if u.Path == "/control" {
|
||||
return "/control"
|
||||
}
|
||||
if u.Path == "/game" {
|
||||
q := url.Values{}
|
||||
if world := u.Query().Get("world"); worldIDPattern.MatchString(world) {
|
||||
q.Set("world", world)
|
||||
}
|
||||
u.RawQuery = q.Encode()
|
||||
return u.String()
|
||||
}
|
||||
return "/"
|
||||
}
|
||||
func validOrigin(r *http.Request, base string) bool {
|
||||
origin := r.Header.Get("Origin")
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"aeternalis/server/internal/store"
|
||||
)
|
||||
|
||||
var worldIDPattern = regexp.MustCompile(`^[a-z][a-z0-9-]{0,30}$`)
|
||||
var namePattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9 _-]{1,23}$`)
|
||||
var requestIDPattern = regexp.MustCompile(`^[a-f0-9-]{32,36}$`)
|
||||
|
||||
func (h *HTTP) admin(w http.ResponseWriter, r *http.Request) (string, bool) {
|
||||
account, err := h.auth.account(r)
|
||||
if err != nil {
|
||||
fail(w, 401, "sign in required")
|
||||
return "", false
|
||||
}
|
||||
if !h.auth.isAdmin(r) {
|
||||
fail(w, 403, "Administrator access required. Sign in again with the configured Keycloak role.")
|
||||
return "", false
|
||||
}
|
||||
return account, true
|
||||
}
|
||||
func (h *HTTP) portalRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/worlds", func(w http.ResponseWriter, r *http.Request) {
|
||||
worlds, err := h.auth.db.Worlds(r.Context())
|
||||
if err != nil {
|
||||
fail(w, 503, "world directory unavailable")
|
||||
return
|
||||
}
|
||||
respond(w, 200, worlds)
|
||||
})
|
||||
mux.HandleFunc("GET /api/account", func(w http.ResponseWriter, r *http.Request) {
|
||||
account, err := h.auth.account(r)
|
||||
if err != nil {
|
||||
fail(w, 401, "sign in required")
|
||||
return
|
||||
}
|
||||
characters, err := h.auth.db.Characters(r.Context(), account, "")
|
||||
if err != nil {
|
||||
fail(w, 503, "character history unavailable")
|
||||
return
|
||||
}
|
||||
active, err := h.auth.db.ActiveCharacter(r.Context(), account)
|
||||
if err != nil {
|
||||
fail(w, 503, "character registry unavailable")
|
||||
return
|
||||
}
|
||||
respond(w, 200, map[string]any{"characters": characters, "active": active, "admin": h.auth.isAdmin(r)})
|
||||
})
|
||||
mux.HandleFunc("GET /api/control", func(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := h.admin(w, r); !ok {
|
||||
return
|
||||
}
|
||||
worlds, err := h.auth.db.Worlds(r.Context())
|
||||
if err != nil {
|
||||
fail(w, 503, "world directory unavailable")
|
||||
return
|
||||
}
|
||||
characters, err := h.auth.db.Characters(r.Context(), "", r.URL.Query().Get("world"))
|
||||
if err != nil {
|
||||
fail(w, 503, "character registry unavailable")
|
||||
return
|
||||
}
|
||||
commands, err := h.auth.db.Commands(r.Context(), "", false)
|
||||
if err != nil {
|
||||
fail(w, 503, "audit log unavailable")
|
||||
return
|
||||
}
|
||||
respond(w, 200, map[string]any{"worlds": worlds, "characters": characters, "commands": commands, "provisioningEnabled": h.Provisioner != nil, "characterLimit": 500, "auditLimit": 100})
|
||||
})
|
||||
mux.HandleFunc("POST /api/control/commands", func(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := h.admin(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
ID string `json:"id"`
|
||||
WorldID string `json:"worldId"`
|
||||
Op string `json:"op"`
|
||||
Target string `json:"target"`
|
||||
Value string `json:"value"`
|
||||
Reason string `json:"reason"`
|
||||
Confirm string `json:"confirm"`
|
||||
}
|
||||
if decode(w, r, &req) != nil {
|
||||
fail(w, 400, "invalid command")
|
||||
return
|
||||
}
|
||||
req.Reason = strings.TrimSpace(req.Reason)
|
||||
req.Value = strings.TrimSpace(req.Value)
|
||||
if !requestIDPattern.MatchString(req.ID) || !worldIDPattern.MatchString(req.WorldID) || len(req.Reason) < 5 || len(req.Reason) > 240 || len(req.Target) > 128 || len(req.Value) > 100 {
|
||||
fail(w, 400, "a valid request ID, world ID, and 5-240 character reason are required")
|
||||
return
|
||||
}
|
||||
switch req.Op {
|
||||
case "create-world":
|
||||
if h.Provisioner == nil {
|
||||
fail(w, 503, "GitOps provisioning is not configured")
|
||||
return
|
||||
}
|
||||
if !regexp.MustCompile(`^[0-9]{1,15}$`).MatchString(req.Value) {
|
||||
fail(w, 400, "seed must contain 1-15 digits")
|
||||
return
|
||||
}
|
||||
case "close-admissions", "open-admissions", "awaken-boss", "end-world", "heal", "unstuck", "retire", "revoke-sessions":
|
||||
case "rename":
|
||||
if !namePattern.MatchString(req.Value) {
|
||||
fail(w, 400, "name must be 2-24 letters, numbers, spaces or hyphens")
|
||||
return
|
||||
}
|
||||
default:
|
||||
fail(w, 400, "unknown command")
|
||||
return
|
||||
}
|
||||
if req.Op == "end-world" || req.Op == "awaken-boss" || req.Op == "retire" {
|
||||
expected := req.WorldID
|
||||
if req.Op == "retire" {
|
||||
expected = req.Target
|
||||
}
|
||||
if req.Confirm != expected {
|
||||
fail(w, 400, "confirmation does not match the target")
|
||||
return
|
||||
}
|
||||
}
|
||||
if req.Op != "create-world" {
|
||||
worlds, err := h.auth.db.Worlds(r.Context())
|
||||
if err != nil {
|
||||
fail(w, 503, "world directory unavailable")
|
||||
return
|
||||
}
|
||||
found := false
|
||||
for _, world := range worlds {
|
||||
if world.ID == req.WorldID && world.Available {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
fail(w, 409, "world owner is not available")
|
||||
return
|
||||
}
|
||||
}
|
||||
command := store.Command{ID: req.ID, WorldID: req.WorldID, Actor: actor, Op: req.Op, Target: req.Target, Value: req.Value, Reason: req.Reason}
|
||||
if req.Op == "create-world" {
|
||||
command.Target = req.WorldID
|
||||
command.WorldID = "_provision"
|
||||
}
|
||||
if err := h.auth.db.Enqueue(r.Context(), command); err != nil {
|
||||
fail(w, 409, "command could not be queued; request ID may already be used")
|
||||
return
|
||||
}
|
||||
respond(w, 202, map[string]string{"id": command.ID, "status": "pending"})
|
||||
})
|
||||
}
|
||||
func (h *HTTP) RunProvisioning(ctx context.Context) {
|
||||
if h.Provisioner == nil {
|
||||
return
|
||||
}
|
||||
ticker := time.NewTicker(2 * time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if !h.s.ready.Load() {
|
||||
return
|
||||
}
|
||||
commands, err := h.auth.db.Commands(ctx, "_provision", true)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, c := range commands {
|
||||
if c.Op != "create-world" {
|
||||
continue
|
||||
}
|
||||
request, cancel := context.WithTimeout(ctx, 45*time.Second)
|
||||
result, err := h.Provisioner.CreateWorld(request, c.Target, c.Value)
|
||||
cancel()
|
||||
if errors.Is(ctx.Err(), context.Canceled) {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
result = err.Error()
|
||||
}
|
||||
_ = h.auth.db.FinishProvision(ctx, c.ID, result, err == nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"aeternalis/server/content"
|
||||
"aeternalis/server/internal/game"
|
||||
"aeternalis/server/internal/store"
|
||||
)
|
||||
|
||||
func TestControlAuthorizationAndExecution(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, err := store.Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "control.db")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
b, _ := content.Load()
|
||||
w := game.New("control-test", 1, time.Now(), b)
|
||||
lease, _, err := db.Acquire(ctx, w)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
svc := NewService(w, lease)
|
||||
auth, _ := NewAuth(ctx, db, true, "http://127.0.0.1", "", "", "")
|
||||
assets := t.TempDir()
|
||||
for _, f := range []string{"index.html", "game.html", "control.html"} {
|
||||
if err = os.WriteFile(filepath.Join(assets, f), []byte("<!doctype html><title>"+f+"</title>"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
server := httptest.NewServer(NewHTTP(svc, auth, assets, nil).Handler())
|
||||
defer server.Close()
|
||||
auth.base = server.URL
|
||||
request := func(method, path, body, token, origin string) int {
|
||||
t.Helper()
|
||||
r, _ := http.NewRequest(method, server.URL+path, strings.NewReader(body))
|
||||
if token != "" {
|
||||
r.AddCookie(&http.Cookie{Name: auth.cookieName(), Value: token})
|
||||
}
|
||||
r.Header.Set("Origin", origin)
|
||||
response, err := server.Client().Do(r)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
return response.StatusCode
|
||||
}
|
||||
for _, path := range []string{"/", "/game", "/control", "/worlds/control-test/api/config"} {
|
||||
if status := request("GET", path, "", "", ""); status != 200 {
|
||||
t.Fatal(path, status)
|
||||
}
|
||||
}
|
||||
if status := request("GET", "/worlds/another/api/config", "", "", ""); status != 404 {
|
||||
t.Fatal("wrong world routed", status)
|
||||
}
|
||||
if request("GET", "/api/control", "", "", "") != 401 {
|
||||
t.Fatal("anonymous admin access")
|
||||
}
|
||||
token := game.ID() + game.ID()
|
||||
_ = db.CreateSession(ctx, hash(token), "operator")
|
||||
if request("GET", "/api/control", "", token, "") != 403 {
|
||||
t.Fatal("player has admin access")
|
||||
}
|
||||
_ = db.GrantAdmin(ctx, hash(token), 600)
|
||||
if request("GET", "/api/control", "", token, "") != 200 {
|
||||
t.Fatal("admin denied")
|
||||
}
|
||||
body := `{"id":"` + game.ID() + `","worldId":"control-test","op":"close-admissions","reason":"maintenance window"}`
|
||||
if request("POST", "/api/control/commands", body, token, "https://evil.example") != 403 {
|
||||
t.Fatal("cross-origin admin command")
|
||||
}
|
||||
if request("POST", "/api/control/commands", body, token, server.URL) != 202 {
|
||||
t.Fatal("command not queued")
|
||||
}
|
||||
if err = svc.controls(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !w.AdmissionsClosed {
|
||||
t.Fatal("command not applied by world owner")
|
||||
}
|
||||
commands, _ := db.Commands(ctx, w.ID, false)
|
||||
if len(commands) != 1 || commands[0].Status != "completed" {
|
||||
t.Fatal("command not audited")
|
||||
}
|
||||
bad := `{"id":"` + game.ID() + `","worldId":"control-test","op":"end-world","reason":"maintenance window"}`
|
||||
if request("POST", "/api/control/commands", bad, token, server.URL) != 400 {
|
||||
t.Fatal("destructive action without confirmation")
|
||||
}
|
||||
_ = db.DeleteSession(ctx, hash(token))
|
||||
if request("GET", "/api/control", "", token, "") != 401 {
|
||||
t.Fatal("revoked admin session accepted")
|
||||
}
|
||||
}
|
||||
func TestKeycloakRolesAndReturnURL(t *testing.T) {
|
||||
var claims roleClaims
|
||||
_ = json.Unmarshal([]byte(`{"realm_access":{"roles":["player"]},"resource_access":{"game":{"roles":["aeternalis-admin"]},"other":{"roles":["foreign-admin"]}}}`), &claims)
|
||||
if !claims.admin("aeternalis-admin", "game") || claims.admin("foreign-admin", "game") || claims.admin("", "game") {
|
||||
t.Fatal("role scope validation")
|
||||
}
|
||||
for _, raw := range []string{"https://evil.example", "//evil.example/game", "/\\evil", "/game#fragment", "/control?next=https://evil"} {
|
||||
if result := safeReturn(raw); result != "/" && result != "/control" {
|
||||
t.Fatal("unsafe return", raw, result)
|
||||
}
|
||||
}
|
||||
if safeReturn("/game?world=world-002&evil=value") != "/game?world=world-002" {
|
||||
t.Fatal("game return lost or untrusted query retained")
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"time"
|
||||
|
||||
"aeternalis/server/internal/game"
|
||||
"aeternalis/server/internal/gitops"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"github.com/coder/websocket"
|
||||
)
|
||||
@@ -24,12 +25,13 @@ type Destination struct {
|
||||
URL string `json:"url"`
|
||||
}
|
||||
type HTTP struct {
|
||||
s *Service
|
||||
auth *Auth
|
||||
assets string
|
||||
worlds []Destination
|
||||
mu sync.Mutex
|
||||
rates map[string]*bucket
|
||||
s *Service
|
||||
auth *Auth
|
||||
assets string
|
||||
worlds []Destination
|
||||
mu sync.Mutex
|
||||
rates map[string]*bucket
|
||||
Provisioner *gitops.Client
|
||||
}
|
||||
type bucket struct {
|
||||
tokens float64
|
||||
@@ -94,6 +96,7 @@ func (h *HTTP) allow(r *http.Request) bool {
|
||||
}
|
||||
func (h *HTTP) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
h.portalRoutes(mux)
|
||||
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.s.ready.Load() {
|
||||
fail(w, 503, "world frozen")
|
||||
@@ -164,13 +167,18 @@ func (h *HTTP) Handler() http.Handler {
|
||||
fail(w, 401, "sign in required")
|
||||
return
|
||||
}
|
||||
active, err := h.auth.db.ActiveCharacter(r.Context(), account)
|
||||
if err != nil {
|
||||
fail(w, 503, "character registry unavailable")
|
||||
return
|
||||
}
|
||||
h.s.mu.Lock()
|
||||
defer h.s.mu.Unlock()
|
||||
if c := h.s.world.ForAccount(account); c != nil {
|
||||
if c := h.s.world.ForAccount(account); c != nil && active != nil && active.WorldID == h.s.world.ID && active.ID == c.View.Entity.ID {
|
||||
respond(w, 200, map[string]any{"character": c.View, "world": h.s.world.Info()})
|
||||
return
|
||||
}
|
||||
respond(w, 200, map[string]any{"character": nil, "world": h.s.world.Info()})
|
||||
respond(w, 200, map[string]any{"character": nil, "world": h.s.world.Info(), "active": active})
|
||||
})
|
||||
mux.HandleFunc("POST /api/join", func(w http.ResponseWriter, r *http.Request) {
|
||||
account, err := h.auth.account(r)
|
||||
@@ -237,6 +245,12 @@ func (h *HTTP) Handler() http.Handler {
|
||||
respond(w, 200, map[string]bool{"ok": true})
|
||||
})
|
||||
mux.HandleFunc("GET /ws", h.socket)
|
||||
for route, file := range map[string]string{"/{$}": "index.html", "/game": "game.html", "/control": "control.html"} {
|
||||
mux.HandleFunc("GET "+route, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
http.ServeFile(w, r, filepath.Join(h.assets, file))
|
||||
})
|
||||
}
|
||||
files := http.FileServer(http.Dir(h.assets))
|
||||
mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
|
||||
clean := filepath.Clean(filepath.FromSlash(r.URL.Path))
|
||||
@@ -258,6 +272,17 @@ func (h *HTTP) Handler() http.Handler {
|
||||
files.ServeHTTP(w, r)
|
||||
})
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
prefix := "/worlds/" + h.s.world.ID
|
||||
if strings.HasPrefix(r.URL.Path, prefix+"/") {
|
||||
r = r.Clone(r.Context())
|
||||
u := *r.URL
|
||||
u.Path = strings.TrimPrefix(u.Path, prefix)
|
||||
u.RawPath = ""
|
||||
r.URL = &u
|
||||
} else if strings.HasPrefix(r.URL.Path, "/worlds/") {
|
||||
fail(w, 404, "unknown world route")
|
||||
return
|
||||
}
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Referrer-Policy", "no-referrer")
|
||||
w.Header().Set("X-Frame-Options", "DENY")
|
||||
@@ -307,6 +332,12 @@ func (h *HTTP) socket(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
id := c.View.Entity.ID
|
||||
active, err := h.auth.db.ActiveCharacter(r.Context(), account)
|
||||
if err != nil || active == nil || active.WorldID != h.s.world.ID || active.ID != id {
|
||||
h.s.mu.Unlock()
|
||||
fail(w, 409, "character is not active in this world")
|
||||
return
|
||||
}
|
||||
if h.s.peers[id] != nil {
|
||||
h.s.mu.Unlock()
|
||||
fail(w, 409, "character already connected")
|
||||
|
||||
@@ -22,13 +22,14 @@ type peer struct {
|
||||
close func()
|
||||
}
|
||||
type Service struct {
|
||||
mu sync.Mutex
|
||||
world *game.World
|
||||
lease *store.Lease
|
||||
peers map[string]*peer
|
||||
ready atomic.Bool
|
||||
lastSave time.Time
|
||||
done chan struct{}
|
||||
mu sync.Mutex
|
||||
world *game.World
|
||||
lease *store.Lease
|
||||
peers map[string]*peer
|
||||
ready atomic.Bool
|
||||
lastSave time.Time
|
||||
lastControl time.Time
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
func NewService(w *game.World, l *store.Lease) *Service {
|
||||
@@ -66,6 +67,14 @@ func (s *Service) Run(ctx context.Context) {
|
||||
}
|
||||
s.world.Advance(now, now.Sub(last).Seconds())
|
||||
last = now
|
||||
if now.Sub(s.lastControl) >= time.Second {
|
||||
if err := s.controls(ctx); err != nil {
|
||||
s.ready.Store(false)
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
s.lastControl = now
|
||||
}
|
||||
if s.world.Dirty() || now.Sub(s.lastSave) >= time.Second {
|
||||
saveCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
err := s.persist(saveCtx, "")
|
||||
@@ -125,6 +134,18 @@ func (s *Service) join(ctx context.Context, account, name, claim string) (p.Char
|
||||
}
|
||||
var c *game.Character
|
||||
var err error
|
||||
active, err := s.lease.DB.ActiveCharacter(ctx, account)
|
||||
if err != nil {
|
||||
return p.Character{}, errors.New("character registry unavailable")
|
||||
}
|
||||
if active != nil {
|
||||
transfer := claim != "" && active.ID == claim && active.State == "eligible" && active.WorldID != s.world.ID
|
||||
resume := claim == "" && active.WorldID == s.world.ID
|
||||
if !transfer && !resume {
|
||||
return p.Character{}, store.ErrLivingCharacter
|
||||
}
|
||||
}
|
||||
existing := s.world.ForAccount(account)
|
||||
if claim != "" {
|
||||
c, err = s.lease.DB.ReadPassage(ctx, claim, account)
|
||||
if err != nil {
|
||||
@@ -139,11 +160,62 @@ func (s *Service) join(ctx context.Context, account, name, claim string) (p.Char
|
||||
return p.Character{}, err
|
||||
}
|
||||
}
|
||||
if err = s.persist(ctx, claim); err != nil {
|
||||
if err = s.lease.Save(ctx, s.world, claim); err != nil {
|
||||
if errors.Is(err, store.ErrLivingCharacter) {
|
||||
if existing == nil {
|
||||
delete(s.world.Characters, c.View.Entity.ID)
|
||||
}
|
||||
return p.Character{}, err
|
||||
}
|
||||
s.ready.Store(false)
|
||||
for _, peer := range s.peers {
|
||||
peer.close()
|
||||
}
|
||||
return p.Character{}, errors.New("world persistence unavailable")
|
||||
}
|
||||
s.lastSave = time.Now()
|
||||
view := c.View
|
||||
view.Inventory = maps.Clone(view.Inventory)
|
||||
view.Skills = maps.Clone(view.Skills)
|
||||
return view, nil
|
||||
}
|
||||
|
||||
func (s *Service) controls(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
commands, err := s.lease.DB.Commands(ctx, s.world.ID, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, command := range commands {
|
||||
result := ""
|
||||
if time.Now().Unix()-command.CreatedAt > 900 {
|
||||
result = "command expired before execution"
|
||||
} else if command.Op == "revoke-sessions" {
|
||||
found := false
|
||||
for id, c := range s.world.Characters {
|
||||
if c.Account == command.Target {
|
||||
found = true
|
||||
s.world.Disconnect(id)
|
||||
if p := s.peers[id]; p != nil {
|
||||
p.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
result = "account not found in world"
|
||||
}
|
||||
} else if err = s.world.Control(command.Op, command.Target, command.Value, command.Reason); err != nil {
|
||||
result = err.Error()
|
||||
}
|
||||
if err = s.lease.SaveCommand(ctx, s.world, "", &command, result); err != nil {
|
||||
s.ready.Store(false)
|
||||
for _, peer := range s.peers {
|
||||
peer.close()
|
||||
}
|
||||
return err
|
||||
}
|
||||
s.lastSave = time.Now()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
async function enter(page, name = 'Wayfarer') {
|
||||
await page.goto('/');
|
||||
await page.goto('/game?world=e2e');
|
||||
await expect(page.locator('#connection-status')).toHaveText('World online');
|
||||
await page.getByLabel('Character name').fill(name);
|
||||
await page.getByRole('button', { name: 'Enter world' }).click();
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
test('public directory and account history fit desktop and mobile', async ({ page }) => {
|
||||
const errors: string[] = []; page.on('pageerror', e => errors.push(e.message));
|
||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
await page.goto('/');
|
||||
await expect(page.getByRole('heading', { name: 'Aeternalis', exact: true })).toBeVisible();
|
||||
await expect(page.locator('.world-row')).toHaveCount(1);
|
||||
await expect(page.locator('.world-hero img')).toBeVisible();
|
||||
await expect.poll(() => page.locator('.world-hero img').evaluate((img: HTMLImageElement) => img.naturalWidth)).toBeGreaterThan(100);
|
||||
await page.getByRole('button', { name: 'Sign in', exact: true }).click();
|
||||
await expect(page.getByRole('button', { name: 'Sign out', exact: true })).toBeVisible();
|
||||
await page.screenshot({ path: 'test-results/website-desktop.png', fullPage: true });
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);
|
||||
await page.screenshot({ path: 'test-results/website-mobile.png', fullPage: true });
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
test('admin actions are audited and death permits a distinct replacement', async ({ page }) => {
|
||||
const origin = 'http://127.0.0.1:18089';
|
||||
await page.request.post('/auth/dev', { data: {}, headers: { Origin: origin } });
|
||||
const joined = await page.request.post('/worlds/e2e/api/join', { data: { name: 'Portal life', passage: '' }, headers: { Origin: origin } });
|
||||
expect(joined.status()).toBe(200); const old = await joined.json();
|
||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
await page.goto('/control');
|
||||
await expect(page.locator('#workspace')).toBeVisible();
|
||||
await page.getByRole('button', { name: 'Characters', exact: true }).click();
|
||||
await expect(page.locator('#view-title')).toHaveText('Characters');
|
||||
await page.getByRole('searchbox', { name: 'Search records' }).fill('Portal life');
|
||||
await expect(page.locator('tbody tr')).toHaveCount(1);
|
||||
await page.getByRole('button', { name: 'Portal life', exact: true }).click();
|
||||
await expect(page.locator('#character-dialog')).toBeVisible();
|
||||
await expect(page.locator('#character-detail')).toContainText(old.entity.id);
|
||||
await page.getByRole('button', { name: 'Close character', exact: true }).click();
|
||||
await page.getByLabel(`Action for ${old.entity.id}`).selectOption('rename');
|
||||
await page.getByLabel('Character name', { exact: true }).fill('Portal renamed');
|
||||
await page.getByLabel('Reason', { exact: true }).fill('Rename verification');
|
||||
await page.getByRole('button', { name: 'Queue action' }).click();
|
||||
await expect.poll(async () => (await (await page.request.get('/api/account')).json()).active?.name).toBe('Portal renamed');
|
||||
await page.getByRole('searchbox', { name: 'Search records' }).fill('Portal renamed');
|
||||
await page.getByRole('button', { name: 'Refresh', exact: true }).click();
|
||||
await expect(page.locator('tbody tr')).toHaveCount(1);
|
||||
await page.screenshot({ path: 'test-results/control-desktop.png', fullPage: true });
|
||||
await page.getByLabel(`Action for ${old.entity.id}`).selectOption('retire');
|
||||
await page.getByLabel('Reason', { exact: true }).fill('Permanent death verification');
|
||||
await page.getByLabel(`Confirm character ID: ${old.entity.id}`).fill(old.entity.id);
|
||||
await page.getByRole('button', { name: 'Queue action' }).click();
|
||||
await expect.poll(async () => (await (await page.request.get('/api/account')).json()).active).toBeNull();
|
||||
await page.goto('/game?world=e2e');
|
||||
await expect(page.locator('#connection-status')).toHaveText('World online');
|
||||
await page.getByLabel('Character name', { exact: true }).fill('Portal second life');
|
||||
await page.getByRole('button', { name: 'Enter world' }).click();
|
||||
await expect(page.locator('#connection-status')).toHaveText('Connected');
|
||||
await expect.poll(() => page.evaluate(() => (window as any).__aeternalis?.snapshot?.self?.entity?.id)).toBeTruthy();
|
||||
const current = await page.evaluate(() => (window as any).__aeternalis.snapshot.self.entity.id);
|
||||
expect(current).not.toBe(old.entity.id);
|
||||
const account = await (await page.request.get('/api/account')).json();
|
||||
expect(account.characters.find(c => c.id === old.entity.id).state).toBe('dead');
|
||||
expect(account.characters.find(c => c.id === old.entity.id).character.deathReason).toContain('Permanent death verification');
|
||||
await page.goto('/control'); await page.getByRole('button', { name: 'Audit log', exact: true }).click();
|
||||
await expect(page.locator('tbody')).toContainText('Permanent death verification');
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);
|
||||
await page.screenshot({ path: 'test-results/control-mobile.png', fullPage: true });
|
||||
});
|
||||
|
||||
test('control gives anonymous visitors a sign-in state', async ({ page }) => {
|
||||
await page.goto('/control');
|
||||
await expect(page.getByRole('heading', { name: 'Sign in to Control' })).toBeVisible();
|
||||
await expect(page.locator('#workspace')).toBeHidden();
|
||||
expect((await page.request.get('/api/control')).status()).toBe(401);
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import { chromium } from '@playwright/test';
|
||||
import { mkdir } from 'node:fs/promises';
|
||||
const origin = process.env.CAPTURE_URL || 'http://127.0.0.1:18100';
|
||||
const url = new URL(origin);
|
||||
if (url.hostname !== '127.0.0.1') throw new Error('Capture only targets a loopback development world');
|
||||
const browser = await chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || 'msedge', args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader'] });
|
||||
try {
|
||||
const page = await browser.newPage({ viewport: { width: 1600, height: 900 }, deviceScaleFactor: 1 });
|
||||
await page.goto(`${origin}/game`);
|
||||
await page.waitForFunction(() => window.__aeternalis?.diagnostics().models === 6);
|
||||
await page.addStyleTag({ content: '#hud, dialog { display: none !important; }' });
|
||||
await page.waitForTimeout(400);
|
||||
await mkdir('client/public/images', { recursive: true });
|
||||
await page.locator('#world').screenshot({ path: 'client/public/images/world.png' });
|
||||
} finally { await browser.close(); }
|
||||
Reference in New Issue
Block a user