diff --git a/client/control.html b/client/control.html new file mode 100644 index 0000000..2d29e22 --- /dev/null +++ b/client/control.html @@ -0,0 +1,18 @@ + + +Aeternalis | Control + + +

OPERATIONS

Worlds

+

Checking access

+ +
+

New world

+

CHARACTER RECORD

+ + diff --git a/client/game.html b/client/game.html new file mode 100644 index 0000000..baae5f8 --- /dev/null +++ b/client/game.html @@ -0,0 +1,35 @@ + + + + + + + Aeternalis + + + + +
+
+
A
AETERNALISThe First Reach
+
WNWNNEE
+
Connecting
+
+
THE GATHERING7d 00h
Until the Harbinger
+ + + + + + + +
+
THE FIRST REACH

Aeternalis

One life. A world on borrowed time.

+
JOURNEY ENDED

Your story remains.

World directory
+ + + diff --git a/client/index.html b/client/index.html index 3cbb3f7..c1c58f8 100644 --- a/client/index.html +++ b/client/index.html @@ -1,35 +1,12 @@ - - - - - Aeternalis - - - - -
-
-
A
AETERNALISThe First Reach
-
WNWNNEE
-
Connecting
-
-
THE GATHERING7d 00h
Until the Harbinger
- - - - - - - -
-
THE FIRST REACH

Aeternalis

One life. A world on borrowed time.

-
JOURNEY ENDED

Your story remains.

- - - +Aeternalis | Worlds + + +
+
The procedural forests and highlands of Aeternalis

A WORLD ON BORROWED TIME

Aeternalis

The Harbinger is coming. Every life leaves a story.

Choose a world
THE FIRST REACH / IN-GAME TERRAIN
+

THE REALMS

Worlds

Loading

Loading worlds...

+

ONE LIVING CHARACTER

Your journey

Sign in to see your characters.

+
+ + diff --git a/client/public/images/world.png b/client/public/images/world.png new file mode 100644 index 0000000..91bffee Binary files /dev/null and b/client/public/images/world.png differ diff --git a/client/src/control.ts b/client/src/control.ts new file mode 100644 index 0000000..27af360 --- /dev/null +++ b/client/src/control.ts @@ -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 = { '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 }; + $('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; + $('world-input').required = create; + $('value-input-label').hidden = !create && !rename; + $('value-caption').textContent = create ? 'Seed' : 'Character name'; + const input = $('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}`; + $('confirm-input').required = dangerous; + $('submit-command').classList.toggle('danger', dangerous); + $('command-error').textContent = ''; + $('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); } + $('character-dialog').showModal(); +} +function render() { + if (!data) return; + const search = $('search').value.trim().toLowerCase(), world = $('world-filter').value, state = $('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 = $('world-filter').value; + data = await api(`/api/control?world=${encodeURIComponent(world)}`); + $('access').hidden = true; $('workspace').hidden = false; $('admin-signout').hidden = false; + const create = $('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($('world-filter'), data.worlds.map(w => w.id), 'All worlds'); + options($('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('[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'; + $('search').placeholder = `Search ${tab}`; $('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 = () => $('command-dialog').close(); +$('close-character').onclick = () => $('character-dialog').close(); +$('command-form').onsubmit = async event => { + event.preventDefault(); const submit = $('submit-command'); submit.disabled = true; + const body = { ...draft, worldId: draft.op === 'create-world' ? $('world-input').value : draft.worldId, value: ['rename','create-world'].includes(draft.op) ? $('value-input').value : '', reason: $('reason-input').value, confirm: $('confirm-input').value }; + try { await api('/api/control/commands', body); $('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 && !$('command-dialog').open && !$('character-dialog').open) void refresh(); }, 5000); diff --git a/client/src/main.ts b/client/src/main.ts index 7eb4f33..9f8e85b 100644 --- a/client/src/main.ts +++ b/client/src/main.ts @@ -21,9 +21,11 @@ let pendingAction: { op: string; target: string } | undefined; let requestedClose = false; const keys = new Set(); 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(path: string, body?: unknown): Promise { - 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 = $('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)); $('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() { + $('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($('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(); }; $('quality').onchange = event => view.quality((event.target as HTMLSelectElement).value === 'high'); $('zoom').oninput = event => { view.distance = Number((event.target as HTMLInputElement).value); view.resize(); }; diff --git a/client/src/portal-shared.ts b/client/src/portal-shared.ts new file mode 100644 index 0000000..22f06e1 --- /dev/null +++ b/client/src/portal-shared.ts @@ -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 $ = (id: string) => document.getElementById(id) as T; +export const el = (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(path: string, body?: unknown): Promise { + 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; } diff --git a/client/src/portal.css b/client/src/portal.css new file mode 100644 index 0000000..928577b --- /dev/null +++ b/client/src/portal.css @@ -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; } } diff --git a/client/src/site.ts b/client/src/site.ts new file mode 100644 index 0000000..21f64e2 --- /dev/null +++ b/client/src/site.ts @@ -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('/api/worlds'); + try { account = await api('/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); diff --git a/client/vite.config.ts b/client/vite.config.ts index cdb2361..9941e0c 100644 --- a/client/vite.config.ts +++ b/client/vite.config.ts @@ -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 } }, }, }); diff --git a/deploy/chart/templates/control-egress.yaml b/deploy/chart/templates/control-egress.yaml new file mode 100644 index 0000000..d747566 --- /dev/null +++ b/deploy/chart/templates/control-egress.yaml @@ -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 }} diff --git a/deploy/chart/templates/worlds.yaml b/deploy/chart/templates/worlds.yaml index e76d98f..e19dc76 100644 --- a/deploy/chart/templates/worlds.yaml +++ b/deploy/chart/templates/worlds.yaml @@ -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 }} diff --git a/deploy/chart/values.schema.json b/deploy/chart/values.schema.json index 3e868db..8d45dba 100644 --- a/deploy/chart/values.schema.json +++ b/deploy/chart/values.schema.json @@ -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})?$"}}} diff --git a/deploy/chart/values.yaml b/deploy/chart/values.yaml index 5267658..b040207 100644 --- a/deploy/chart/values.yaml +++ b/deploy/chart/values.yaml @@ -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: diff --git a/deploy/values-srs.yaml b/deploy/values-srs.yaml index 84b9916..fa987de 100644 --- a/deploy/values-srs.yaml +++ b/deploy/values-srs.yaml @@ -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: diff --git a/playwright.config.ts b/playwright.config.ts index bbc8753..11282c6 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -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' }, }, }); diff --git a/server/cmd/world/main.go b/server/cmd/world/main.go index e956444..17a156e 100644 --- a/server/cmd/world/main.go +++ b/server/cmd/world/main.go @@ -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) diff --git a/server/internal/game/world.go b/server/internal/game/world.go index f56516f..b035f01 100644 --- a/server/internal/game/world.go +++ b/server/internal/game/world.go @@ -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 diff --git a/server/internal/game/world_test.go b/server/internal/game/world_test.go index 83d679f..537692c 100644 --- a/server/internal/game/world_test.go +++ b/server/internal/game/world_test.go @@ -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") diff --git a/server/internal/gitops/worlds.go b/server/internal/gitops/worlds.go new file mode 100644 index 0000000..55ba9bd --- /dev/null +++ b/server/internal/gitops/worlds.go @@ -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") +} diff --git a/server/internal/gitops/worlds_test.go b/server/internal/gitops/worlds_test.go new file mode 100644 index 0000000..9a6df9a --- /dev/null +++ b/server/internal/gitops/worlds_test.go @@ -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) + } + } +} diff --git a/server/internal/store/portal.go b/server/internal/store/portal.go new file mode 100644 index 0000000..d85df4c --- /dev/null +++ b/server/internal/store/portal.go @@ -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 +} diff --git a/server/internal/store/portal_test.go b/server/internal/store/portal_test.go new file mode 100644 index 0000000..965198f --- /dev/null +++ b/server/internal/store/portal_test.go @@ -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) + } +} diff --git a/server/internal/store/store.go b/server/internal/store/store.go index 923172c..571abea 100644 --- a/server/internal/store/store.go +++ b/server/internal/store/store.go @@ -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 } diff --git a/server/internal/transport/auth.go b/server/internal/transport/auth.go index ffe6173..d21e9a1 100644 --- a/server/internal/transport/auth.go +++ b/server/internal/transport/auth.go @@ -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") diff --git a/server/internal/transport/control.go b/server/internal/transport/control.go new file mode 100644 index 0000000..9e2351d --- /dev/null +++ b/server/internal/transport/control.go @@ -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) + } + } + } +} diff --git a/server/internal/transport/control_test.go b/server/internal/transport/control_test.go new file mode 100644 index 0000000..810c762 --- /dev/null +++ b/server/internal/transport/control_test.go @@ -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(""+f+""), 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") + } +} diff --git a/server/internal/transport/http.go b/server/internal/transport/http.go index a3848ea..79ee6f3 100644 --- a/server/internal/transport/http.go +++ b/server/internal/transport/http.go @@ -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") diff --git a/server/internal/transport/service.go b/server/internal/transport/service.go index 78e6091..8b07ed6 100644 --- a/server/internal/transport/service.go +++ b/server/internal/transport/service.go @@ -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 +} diff --git a/tests/game.spec.ts b/tests/game.spec.ts index 161c293..2016aab 100644 --- a/tests/game.spec.ts +++ b/tests/game.spec.ts @@ -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(); diff --git a/tests/portal.spec.ts b/tests/portal.spec.ts new file mode 100644 index 0000000..68e5189 --- /dev/null +++ b/tests/portal.spec.ts @@ -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); +}); diff --git a/tools/capture-world.mjs b/tools/capture-world.mjs new file mode 100644 index 0000000..f3fffc7 --- /dev/null +++ b/tools/capture-world.mjs @@ -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(); }