Add persistent dark mode and server-assigned content IDs

This commit is contained in:
dingo
2026-09-08 16:18:48 -04:00
parent 0780257eca
commit 39ddce5ddc
17 changed files with 406 additions and 44 deletions
+2 -2
View File
@@ -1,9 +1,9 @@
<!doctype html>
<html lang="en">
<head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><meta name="theme-color" content="#122b24"/><title>Aeternalis | Control</title><link rel="icon" href="data:,"/></head>
<head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><meta name="theme-color" content="#122b24"/><title>Aeternalis | Control</title><link rel="icon" href="data:,"/><script src="/theme-init.js"></script></head>
<body class="control-site">
<aside class="control-sidebar"><a class="wordmark" href="/">AETERNALIS<span>Control</span></a><nav aria-label="Control navigation"><button class="nav-item active" data-tab="worlds"><i data-lucide="globe-2"></i>Worlds</button><button class="nav-item" data-tab="characters"><i data-lucide="users"></i>Characters</button><button class="nav-item" data-tab="audit"><i data-lucide="scroll-text"></i>Audit log</button><button class="nav-item" data-tab="content"><i data-lucide="scroll-text"></i>Content</button></nav><div class="sidebar-bottom"><a href="/"><i data-lucide="arrow-up-right"></i>Public site</a><a href="/game"><i data-lucide="play"></i>Game</a></div></aside>
<main class="control-main"><header class="control-header"><div><p class="eyebrow">OPERATIONS</p><h1 id="view-title">Worlds</h1></div><div class="heading-tools"><span id="updated" class="muted"></span><button id="refresh" class="icon-button" title="Refresh" aria-label="Refresh"><i data-lucide="refresh-cw"></i></button><button id="create-world" class="button" disabled><i data-lucide="plus"></i>New world</button><button id="admin-signout" class="icon-button" title="Sign out" aria-label="Sign out" hidden><i data-lucide="log-out"></i></button></div></header>
<main class="control-main"><header class="control-header"><div><p class="eyebrow">OPERATIONS</p><h1 id="view-title">Worlds</h1></div><div class="heading-tools"><span id="updated" class="muted"></span><button type="button" class="icon-button theme-toggle" data-theme-toggle aria-label="Dark mode" aria-pressed="false" title="Switch to dark mode">☾</button><button id="refresh" class="icon-button" title="Refresh" aria-label="Refresh"><i data-lucide="refresh-cw"></i></button><button id="create-world" class="button" disabled><i data-lucide="plus"></i>New world</button><button id="admin-signout" class="icon-button" title="Sign out" aria-label="Sign out" hidden><i data-lucide="log-out"></i></button></div></header>
<div id="access" class="access-state"><i data-lucide="shield-check"></i><h2 id="access-title">Checking access</h2><p id="access-message"></p><a id="admin-login" class="button" href="/auth/login?return=%2Fcontrol" hidden>Sign in<i data-lucide="log-in"></i></a></div>
<div id="workspace" hidden><section class="metrics" aria-label="World summary"><div><span>Worlds online</span><strong id="metric-worlds">0</strong></div><div><span>Living characters</span><strong id="metric-living">0</strong></div><div><span>Fallen characters</span><strong id="metric-dead">0</strong></div><div><span>Pending actions</span><strong id="metric-pending">0</strong></div></section>
<div id="control-message" class="message" role="status" hidden></div>
+2 -2
View File
@@ -1,8 +1,8 @@
<!doctype html>
<html lang="en">
<head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><meta name="theme-color" content="#122b24"/><title>Aeternalis | Worlds</title><link rel="icon" href="data:,"/></head>
<head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><meta name="theme-color" content="#122b24"/><title>Aeternalis | Worlds</title><link rel="icon" href="data:,"/><script src="/theme-init.js"></script></head>
<body class="public-site">
<header class="site-header"><a class="wordmark" href="/">AETERNALIS<span>Survival worlds</span></a><nav aria-label="Main navigation"><a href="#worlds">Worlds</a><a href="#journey">My journey</a><a id="control-link" href="/control" hidden>Control</a><button id="account-button" class="button secondary"><i data-lucide="log-in"></i><span>Sign in</span></button></nav></header>
<header class="site-header"><a class="wordmark" href="/">AETERNALIS<span>Survival worlds</span></a><nav aria-label="Main navigation"><a href="#worlds">Worlds</a><a href="#journey">My journey</a><a id="control-link" href="/control" hidden>Control</a><button type="button" class="icon-button theme-toggle" data-theme-toggle aria-label="Dark mode" aria-pressed="false" title="Switch to dark mode">☾</button><button id="account-button" class="button secondary"><i data-lucide="log-in"></i><span>Sign in</span></button></nav></header>
<main>
<section class="world-hero"><img src="/images/world.png" alt="The procedural forests and highlands of Aeternalis"/><div class="hero-shade"></div><div class="hero-copy"><p class="eyebrow">A WORLD ON BORROWED TIME</p><h1>Aeternalis</h1><p>The Harbinger is coming. Every life leaves a story.</p><a class="button light" href="#worlds">Choose a world<i data-lucide="arrow-down"></i></a></div><span class="hero-caption">THE FIRST REACH / IN-GAME TERRAIN</span></section>
<section id="worlds" class="site-section"><div class="section-heading"><div><p class="eyebrow">THE REALMS</p><h2>Worlds</h2></div><div class="heading-tools"><span id="world-count" class="muted">Loading</span><button id="refresh" class="icon-button" aria-label="Refresh worlds" title="Refresh worlds"><i data-lucide="refresh-cw"></i></button></div></div><div id="site-message" class="message" role="status" hidden></div><div id="world-list" class="world-list" aria-live="polite"><p class="empty">Loading worlds...</p></div></section>
+7
View File
@@ -0,0 +1,7 @@
// Runs before page styles so a saved dark preference does not flash light.
(() => {
let preference;
try { preference = localStorage.getItem('aeternalis-theme'); } catch {}
const dark = preference === 'dark' || (preference !== 'light' && matchMedia('(prefers-color-scheme: dark)').matches);
document.documentElement.dataset.theme = dark ? 'dark' : 'light';
})();
+2 -2
View File
@@ -15,7 +15,7 @@ function field(label:string,input:HTMLElement){const wrap=node('label',label);wr
function text(value='',max=80){const i=node('input');i.value=value;i.maxLength=max;i.required=true;return i;}
function number(value:number,min=0,max=1000000,step='any'){const i=text(String(value));i.type='number';i.min=String(min);i.max=String(max);i.step=step;return i;}
function select(keys:string[],value=''){const i=node('select');for(const key of keys)i.append(new Option(statLabel(key),key));i.value=keys.includes(value)?value:keys[0];return i;}
function identity(){const group=node('div','','catalog-fields'),id=text('',64),name=text(),description=node('textarea');id.pattern='[a-z][a-z0-9_\\-]{0,63}';description.maxLength=500;description.rows=3;group.append(field('Permanent ID',id),field('Name',name),field('Description',description));return {node:group,read:()=>({id:id.value.trim(),name:name.value.trim(),description:description.value.trim()})};}
function identity(){const group=node('div','','catalog-fields'),name=text(),description=node('textarea');description.maxLength=500;description.rows=3;group.append(field('Name',name),field('Description',description),node('p','A permanent ID is assigned automatically when you publish.','muted'));return {node:group,read:()=>({name:name.value.trim(),description:description.value.trim()})};}
function repeat<T>(title:string,addLabel:string,make:(value?:T)=>{node:HTMLElement;read:()=>T},initial:T[]=[],max=64){
const group=node('fieldset','','catalog-repeatable'),rows=node('div'),entries:{node:HTMLElement;read:()=>T}[]=[];group.append(node('legend',title),rows);
const add=button(addLabel,()=>append());group.append(add);
@@ -64,7 +64,7 @@ function form(title:string,op:string,payload:()=>object){
function previewView(result:ContentPreview){
const root=node('div'),r=result.resolved;root.append(node('h4','Validated publication preview'),node('p',`Version ${result.basedOnVersion} → ${result.proposedVersion}. Nothing has been published.`));
const definition=r.title??r.item??r.requirementSet??r.effectSet;
if(definition)root.append(node('strong',`${definition.name} (${definition.id})`),node('p',definition.description));
if(definition)root.append(node('strong',definition.name),node('p',definition.description),node('p','Permanent ID assigned on publication.','muted'));
const requirements=r.title?.requirements??r.requirementSet?.requirements;
if(requirements)root.append(node('p',requirements.map(v=>`${statLabel(v.metric)} ≥ ${v.atLeast}`).join(' / ')));
if(r.item)root.append(node('p',`Requires level ${r.item.requirements.level}; ${Object.entries(r.item.requirements.stats??{}).map(([key,n])=>`${statLabel(key)} ≥ ${n}`).join(' / ')}`),node('p',`Required titles: ${(r.item.requirements.titles??[]).join(', ')||'None'}`));
+44 -4
View File
@@ -3,6 +3,7 @@ export interface Protocol {
catalog?: ContentCatalog;
catalogChange?: ContentChange;
catalogPreview?: ContentPreview;
catalogResult?: ContentResult;
intent: Intent;
snapshot: Snapshot;
}
@@ -80,17 +81,51 @@ export interface TitleEffects {
}
export interface ContentChange {
effectSet?: EffectSet;
effectSet?: EffectSetDraft;
effectSetIds?: string[];
expectedVersion: number;
id: string;
item?: ItemDefinition;
item?: ItemDraft;
op: string;
reason: string;
requirementSet?: RequirementSet;
requirementSet?: RequirementSetDraft;
requirementSetIds?: string[];
stats?: ContentStatsRules;
title?: TitleDefinition;
title?: TitleDraft;
}
export interface EffectSetDraft {
description: string;
id?: string;
modifiers: StatModifier[];
name: string;
}
export interface ItemDraft {
description: string;
dropChance: number;
id?: string;
modifiers: StatModifier[];
name: string;
requirements: ItemRequirements;
slot: string;
weight: number;
}
export interface RequirementSetDraft {
description: string;
id?: string;
name: string;
requirements: ContentRequirement[];
}
export interface TitleDraft {
description: string;
effects: TitleEffects;
id?: string;
name: string;
requirements: ContentRequirement[];
scope: string;
}
export interface ContentPreview {
@@ -99,6 +134,11 @@ export interface ContentPreview {
resolved: ContentChange;
}
export interface ContentResult {
id: string;
version: number;
}
export interface Intent {
op: string;
seq: number;
+1
View File
@@ -1,5 +1,6 @@
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';
import './theme';
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; catalogVersion: number };
+54
View File
@@ -0,0 +1,54 @@
:root[data-theme="light"] { color-scheme: light; }
.theme-toggle { font-size: 21px; line-height: 1; }
@media (max-width: 720px) { .site-header nav, .control-header { flex-wrap: wrap; } }
:root[data-theme="dark"] {
color-scheme: dark;
background: #111b17; color: #e3ece6;
--line: #34483c; --muted: #a5b8ac; --green: #337556; --red: #f094a2;
--progression-track: #2b4033; --progression-fill: #81c79e;
--progression-muted: #a5b8ac; --progression-border: #34483c;
--progression-positive: #88d5aa; --progression-negative: #f094a2;
}
[data-theme="dark"] .control-site { background: #111b17; }
[data-theme="dark"] .site-header,
[data-theme="dark"] .control-sidebar,
[data-theme="dark"] .journey-section,
[data-theme="dark"] dialog { background: #18251e; color: #e3ece6; }
[data-theme="dark"] dialog { box-shadow: 0 18px 70px #0008; }
[data-theme="dark"] dialog::backdrop { background: #060c09a6; }
[data-theme="dark"] input,
[data-theme="dark"] select,
[data-theme="dark"] textarea { background: #111b17; color: #e3ece6; border-color: #425a4a; }
[data-theme="dark"] ::placeholder { color: #99afa1; opacity: 1; }
[data-theme="dark"] .button.secondary,
[data-theme="dark"] .button.light,
[data-theme="dark"] .icon-button { background: #203227; color: #dfede4; border-color: var(--line); }
[data-theme="dark"] .button.secondary:hover:not(:disabled):not(.disabled),
[data-theme="dark"] .button.light:hover:not(:disabled):not(.disabled),
[data-theme="dark"] .icon-button:hover { background: #2c4535; color: #eff8f2; }
[data-theme="dark"] .button.danger { background: #a63249; color: #fff; }
[data-theme="dark"] .button.danger:hover:not(:disabled) { background: #85273a; }
[data-theme="dark"] .nav-item { color: #a5b8ac; }
[data-theme="dark"] .nav-item:hover { background: #203629; }
[data-theme="dark"] .nav-item.active { background: #284333; color: #bceace; }
[data-theme="dark"] .catalog-tabs button[aria-pressed="true"] { background: #326b4e; color: #fff; }
[data-theme="dark"] .message { background: #213b2c; border-color: #81c79e; }
[data-theme="dark"] th { background: #1c2b22; }
[data-theme="dark"] td { border-color: var(--line); }
[data-theme="dark"] tbody tr:hover { background: #1a2b21; }
[data-theme="dark"] .record-link { color: #9ad9b4; }
[data-theme="dark"] .world-emblem { background: #243c2d; color: #9ad9b4; }
[data-theme="dark"] .site-footer > span:first-child { color: #ccded2; }
[data-theme="dark"] .access-state > svg { color: #9ad9b4; }
[data-theme="dark"] .badge { background: #2b3830; color: #bacabf; }
[data-theme="dark"] .state-alive,
[data-theme="dark"] .state-gathering,
[data-theme="dark"] .state-completed { background: #203c2d; color: #98dfb5; }
[data-theme="dark"] .state-eligible,
[data-theme="dark"] .state-won { background: #223644; color: #a6d5f3; }
[data-theme="dark"] .state-cataclysm,
[data-theme="dark"] .state-pending,
[data-theme="dark"] .state-closed { background: #40351f; color: #f0ce88; }
[data-theme="dark"] .state-dead,
[data-theme="dark"] .state-lost,
[data-theme="dark"] .state-rejected { background: #412730; color: #f2a7b5; }
+27
View File
@@ -0,0 +1,27 @@
import './theme.css';
const key = 'aeternalis-theme';
const system = matchMedia('(prefers-color-scheme: dark)');
function read(): 'dark'|'light'|null {
try { const value = localStorage.getItem(key); return value === 'dark' || value === 'light' ? value : null; } catch { return null; }
}
let preference = read();
const toggles = document.querySelectorAll<HTMLButtonElement>('[data-theme-toggle]');
function apply() {
const dark = preference === 'dark' || (preference === null && system.matches);
document.documentElement.dataset.theme = dark ? 'dark' : 'light';
for (const button of toggles) {
button.setAttribute('aria-pressed',String(dark));
button.title = dark ? 'Switch to light mode' : 'Switch to dark mode';
button.textContent = dark ? '☀' : '☾';
}
document.querySelector('meta[name="theme-color"]')?.setAttribute('content',dark?'#111b17':'#f8faf9');
}
for (const button of toggles) button.addEventListener('click',() => {
preference = document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark';
try { localStorage.setItem(key,preference); } catch { /* Keep this tab usable without storage. */ }
apply();
});
system.addEventListener('change',() => { if(preference === null) apply(); });
window.addEventListener('storage',event => { if(event.key === key || event.key === null){preference=read();apply();} });
apply();
+26 -7
View File
@@ -21,12 +21,12 @@ sound hooks remain in milestone 4.5. Playwright authoring/runs remain deferred.
items/awards, or write an audit event. Form edits clear the previous preview.
- **Publish changes:** repeats the same content validation under the existing
catalog lock and writes the catalog version and audit atomically. Stale editors,
duplicate IDs, missing sets, mixed payloads, unsupported values, and repeated
missing sets, mixed payloads, unsupported values, and repeated
references are rejected. Identical publication retries return the original result.
Sets are expanded into concrete values at publication, not stored as live links on
acquired gear or earned titles. Published definitions/sets are append-only: use a new
ID for a variation. Sets cannot reference other sets, so recursive composition is
definition for a variation; its ID is assigned by the server. Sets cannot reference other sets, so recursive composition is
not supported. Old catalogs without these collections remain valid. No new table
or title-ownership migration is required for this milestone.
@@ -36,6 +36,21 @@ existing catalog publication path. Shared content API models are generated from
The read-only preview uses authenticated same-origin POST
`/api/control/catalog/preview` with the same draft body as publication.
## Follow-up: automatic IDs and dark mode
Content creation asks for names and properties only. The server assigns a random
permanent ID when publishing a title, item, requirement set, or effect set. Preview
does not reserve or display an ID. The audit stores the assigned identity, and an
identical request retry returns that same ID, including after restart. Public API
creation rejects client-supplied definition IDs. Existing catalog IDs/references
and trusted seed/import paths remain compatible. The hidden request UUID is only
an idempotency token, not a user-selected content identity.
The website and Control have a **Dark mode** toggle in their headers. The default
follows the device preference; choosing light/dark saves the preference for both
pages and syncs across tabs. Theme applies to forms, tables, dialogs, status badges,
stat breakdowns, and content previews. Gameplay rendering is unchanged.
## Input and menus
Keyboard and movement buttons feed named input actions rather than duplicating
@@ -55,20 +70,21 @@ in the catalog/audit. Arrival/death/disconnect screens retain their existing flo
## Manual test checklist
Use unique test IDs; published test content cannot currently be deleted.
Use recognizable test names; the server creates IDs. Published test content cannot
currently be deleted.
1. In **Control -> Content -> Requirement sets**, create `m2_level` with level >= 1.
1. In **Control -> Content -> Requirement sets**, name a set `M2 Level` with level >= 1.
Fill a reason, preview, and confirm the catalog version/audit has not changed.
Publish; refresh and confirm the new set and one audit/version increment.
2. Create effect set `m2_defence` with defence +2 flat and movement speed -5%.
2. Create effect set `M2 Defence` with defence +2 flat and movement speed -5%.
Preview/publish it. Create a ring with those two sets, drop chance 0, and any
inline modifiers you want to inspect. Preview shows the expanded requirements
and effects. Publish and confirm the equipment list contains the same values.
3. Use **Control -> Characters -> Manage items and titles** to give the ring to a
living character. Equip/unequip it in game and inspect the final stat breakdown.
Confirm existing inventory, titles, health, and daily usage were not reset.
4. Try publishing an already-used set ID: expect rejection and no version change.
For stale editing, open drafts in two Control tabs, publish one, then preview/
4. Confirm there is no permanent-ID input and publication shows an assigned ID in
the catalog/audit. For stale editing, open drafts in two Control tabs, publish one, then preview/
publish the other: expect a refresh conflict, not silent overwriting.
5. Open inventory and settings together. Focus a settings field and press Esc:
settings closes, inventory stays open. Press Esc again: inventory closes.
@@ -76,6 +92,9 @@ Use unique test IDs; published test content cannot currently be deleted.
6. Move with WASD/arrows and the on-screen controls, gather with E, attack with
Space. Opening a menu or switching tabs stops movement. Typing in fields must
not move/attack; returning focus must not leave a movement key stuck.
7. Toggle dark mode on the public site, open Control, and reload. Confirm the choice
persists and that dialogs, fields, stat rows, and badges remain readable. Switch
back to light mode and check that both pages follow the new preference.
## Verification and limits
+36 -3
View File
@@ -8,7 +8,8 @@
"snapshot": {"$ref": "#/definitions/Snapshot"},
"catalog": {"$ref": "#/definitions/ContentCatalog"},
"catalogChange": {"$ref": "#/definitions/ContentChange"},
"catalogPreview": {"$ref": "#/definitions/ContentPreview"}
"catalogPreview": {"$ref": "#/definitions/ContentPreview"},
"catalogResult": {"$ref": "#/definitions/ContentResult"}
},
"required": ["intent", "snapshot"],
"definitions": {
@@ -65,12 +66,44 @@
"type": "object", "additionalProperties": false,
"properties": {
"id": {"type": "string"}, "expectedVersion": {"type": "integer"}, "op": {"type": "string"}, "reason": {"type": "string"},
"title": {"$ref": "#/definitions/TitleDefinition"}, "item": {"$ref": "#/definitions/ItemDefinition"}, "stats": {"$ref": "#/definitions/ContentStatsRules"},
"requirementSet": {"$ref": "#/definitions/RequirementSet"}, "effectSet": {"$ref": "#/definitions/EffectSet"},
"title": {"$ref": "#/definitions/TitleDraft"}, "item": {"$ref": "#/definitions/ItemDraft"}, "stats": {"$ref": "#/definitions/ContentStatsRules"},
"requirementSet": {"$ref": "#/definitions/RequirementSetDraft"}, "effectSet": {"$ref": "#/definitions/EffectSetDraft"},
"requirementSetIds": {"type": "array", "items": {"type": "string"}}, "effectSetIds": {"type": "array", "items": {"type": "string"}}
},
"required": ["id", "expectedVersion", "op", "reason"]
},
"ContentResult": {
"type": "object", "additionalProperties": false,
"properties": {"version": {"type": "integer"}, "id": {"type": "string"}},
"required": ["version", "id"]
},
"TitleDraft": {
"type": "object", "additionalProperties": false,
"properties": {
"id": {"type": "string"}, "name": {"type": "string"}, "description": {"type": "string"}, "scope": {"type": "string"},
"requirements": {"type": "array", "items": {"$ref": "#/definitions/ContentRequirement"}}, "effects": {"$ref": "#/definitions/TitleEffects"}
},
"required": ["name", "description", "scope", "requirements", "effects"]
},
"ItemDraft": {
"type": "object", "additionalProperties": false,
"properties": {
"id": {"type": "string"}, "name": {"type": "string"}, "description": {"type": "string"}, "slot": {"type": "string"},
"weight": {"type": "number"}, "dropChance": {"type": "number"}, "requirements": {"$ref": "#/definitions/ItemRequirements"},
"modifiers": {"type": "array", "items": {"$ref": "#/definitions/StatModifier"}}
},
"required": ["name", "description", "slot", "weight", "dropChance", "requirements", "modifiers"]
},
"RequirementSetDraft": {
"type": "object", "additionalProperties": false,
"properties": {"id": {"type": "string"}, "name": {"type": "string"}, "description": {"type": "string"}, "requirements": {"type": "array", "items": {"$ref": "#/definitions/ContentRequirement"}}},
"required": ["name", "description", "requirements"]
},
"EffectSetDraft": {
"type": "object", "additionalProperties": false,
"properties": {"id": {"type": "string"}, "name": {"type": "string"}, "description": {"type": "string"}, "modifiers": {"type": "array", "items": {"$ref": "#/definitions/StatModifier"}}},
"required": ["name", "description", "modifiers"]
},
"ContentPreview": {
"type": "object", "additionalProperties": false,
"properties": {"basedOnVersion": {"type": "integer"}, "proposedVersion": {"type": "integer"}, "resolved": {"$ref": "#/definitions/ContentChange"}},
+51 -11
View File
@@ -5,6 +5,7 @@ type Protocol struct {
Catalog *ContentCatalog `json:"catalog,omitempty"`
CatalogChange *ContentChange `json:"catalogChange,omitempty"`
CatalogPreview *ContentPreview `json:"catalogPreview,omitempty"`
CatalogResult *ContentResult `json:"catalogResult,omitempty"`
Intent Intent `json:"intent"`
Snapshot Snapshot `json:"snapshot"`
}
@@ -82,17 +83,51 @@ type TitleEffects struct {
}
type ContentChange struct {
EffectSet *EffectSet `json:"effectSet,omitempty"`
EffectSetIDS []string `json:"effectSetIds,omitempty"`
ExpectedVersion int64 `json:"expectedVersion"`
ID string `json:"id"`
Item *ItemDefinition `json:"item,omitempty"`
Op string `json:"op"`
Reason string `json:"reason"`
RequirementSet *RequirementSet `json:"requirementSet,omitempty"`
RequirementSetIDS []string `json:"requirementSetIds,omitempty"`
Stats *ContentStatsRules `json:"stats,omitempty"`
Title *TitleDefinition `json:"title,omitempty"`
EffectSet *EffectSetDraft `json:"effectSet,omitempty"`
EffectSetIDS []string `json:"effectSetIds,omitempty"`
ExpectedVersion int64 `json:"expectedVersion"`
ID string `json:"id"`
Item *ItemDraft `json:"item,omitempty"`
Op string `json:"op"`
Reason string `json:"reason"`
RequirementSet *RequirementSetDraft `json:"requirementSet,omitempty"`
RequirementSetIDS []string `json:"requirementSetIds,omitempty"`
Stats *ContentStatsRules `json:"stats,omitempty"`
Title *TitleDraft `json:"title,omitempty"`
}
type EffectSetDraft struct {
Description string `json:"description"`
ID *string `json:"id,omitempty"`
Modifiers []StatModifier `json:"modifiers"`
Name string `json:"name"`
}
type ItemDraft struct {
Description string `json:"description"`
DropChance float64 `json:"dropChance"`
ID *string `json:"id,omitempty"`
Modifiers []StatModifier `json:"modifiers"`
Name string `json:"name"`
Requirements ItemRequirements `json:"requirements"`
Slot string `json:"slot"`
Weight float64 `json:"weight"`
}
type RequirementSetDraft struct {
Description string `json:"description"`
ID *string `json:"id,omitempty"`
Name string `json:"name"`
Requirements []ContentRequirement `json:"requirements"`
}
type TitleDraft struct {
Description string `json:"description"`
Effects TitleEffects `json:"effects"`
ID *string `json:"id,omitempty"`
Name string `json:"name"`
Requirements []ContentRequirement `json:"requirements"`
Scope string `json:"scope"`
}
type ContentPreview struct {
@@ -101,6 +136,11 @@ type ContentPreview struct {
Resolved ContentChange `json:"resolved"`
}
type ContentResult struct {
ID string `json:"id"`
Version int64 `json:"version"`
}
type Intent struct {
Op string `json:"op"`
Seq int64 `json:"seq"`
+11 -3
View File
@@ -30,8 +30,16 @@ type CatalogChange struct {
EffectSetIDs []string `json:"effectSetIds,omitempty"`
}
type CatalogResult struct {
Version int64 `json:"version"`
Version int64 `json:"version"`
ID string `json:"id"`
}
// Explicit definition IDs are reserved for trusted seed/import code. Browser
// publications omit them; the server assigns an ID after resolving request replay.
func (c CatalogChange) HasDefinitionID() bool {
return (c.Title != nil && c.Title.ID != "") || (c.Item != nil && c.Item.ID != "") || (c.RequirementSet != nil && c.RequirementSet.ID != "") || (c.EffectSet != nil && c.EffectSet.ID != "")
}
type CatalogAudit struct {
ID string `json:"id"`
Actor string `json:"actor"`
@@ -168,7 +176,7 @@ func (d *DB) PublishCatalog(ctx context.Context, actor string, change CatalogCha
}
var previousActor, previousRequest string
var result CatalogResult
err = tx.QueryRowContext(ctx, d.q(`SELECT actor,request_json,result_version FROM catalog_changes WHERE id=?`), change.ID).Scan(&previousActor, &previousRequest, &result.Version)
err = tx.QueryRowContext(ctx, d.q(`SELECT actor,request_json,result_version,target FROM catalog_changes WHERE id=?`), change.ID).Scan(&previousActor, &previousRequest, &result.Version, &result.ID)
if err == nil {
if previousActor != actor || previousRequest != string(request) {
return CatalogResult{}, ErrCatalogRequest
@@ -207,7 +215,7 @@ func (d *DB) PublishCatalog(ctx context.Context, actor string, change CatalogCha
if err = tx.Commit(); err != nil {
return CatalogResult{}, err
}
return CatalogResult{Version: catalog.Version}, nil
return CatalogResult{Version: catalog.Version, ID: target}, nil
}
func (d *DB) CatalogChanges(ctx context.Context) ([]CatalogAudit, error) {
rows, err := d.sql.QueryContext(ctx, `SELECT id,actor,op,target,reason,result_version,created_at FROM catalog_changes ORDER BY result_version DESC LIMIT 100`)
+92
View File
@@ -0,0 +1,92 @@
package store
import (
"aeternalis/server/content"
"aeternalis/server/internal/game"
"context"
"encoding/json"
"errors"
"path/filepath"
"testing"
)
func TestServerAssignedCatalogIDsSurviveReplayAndRestart(t *testing.T) {
ctx := context.Background()
dsn := "file:" + filepath.ToSlash(filepath.Join(t.TempDir(), "ids.db"))
db, err := Open(ctx, dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
catalog, err := db.Catalog(ctx)
if err != nil {
t.Fatal(err)
}
seen := map[string]bool{}
var last CatalogChange
var lastResult CatalogResult
for _, draft := range []CatalogChange{
{Op: "create-requirement-set", RequirementSet: &content.RequirementSet{Name: "Same name", Requirements: []content.TitleRequirement{{Metric: "level", AtLeast: 1}}}},
{Op: "create-effect-set", EffectSet: &content.EffectSet{Name: "Same name", Modifiers: []content.StatModifier{{Stat: "defence", Flat: 2}}}},
{Op: "create-title", Title: &content.Title{Name: "Same name", Scope: "personal", Requirements: []content.TitleRequirement{{Metric: "level", AtLeast: 2}}}},
{Op: "create-item", Item: &content.ItemDefinition{Name: "Same name", Slot: "ring", Requirements: content.ItemRequirements{Level: 1}}},
} {
for attempt := 0; attempt < 2; attempt++ {
draft.ID = game.ID()
draft.ExpectedVersion = catalog.Version
draft.Reason = "Server identity verification"
before, _ := json.Marshal(draft)
preview, err := db.PreviewCatalog(ctx, draft)
if err != nil {
t.Fatal(err)
}
if preview.Resolved.HasDefinitionID() {
t.Fatal("preview reserved or exposed a permanent ID")
}
after, _ := json.Marshal(draft)
if string(before) != string(after) {
t.Fatal("preview mutated submitted draft")
}
unchanged, err := db.Catalog(ctx)
if err != nil || unchanged.Version != catalog.Version {
t.Fatal("preview changed version", err)
}
result, err := db.PublishCatalog(ctx, "operator", draft)
if err != nil {
t.Fatal(err)
}
if result.ID == "" || seen[result.ID] {
t.Fatal("missing or reused generated ID", result)
}
seen[result.ID] = true
replay, err := db.PublishCatalog(ctx, "operator", draft)
if err != nil || replay != result {
t.Fatal("retry created a different identity", err)
}
if _, err = db.PublishCatalog(ctx, "other", draft); !errors.Is(err, ErrCatalogRequest) {
t.Fatal("different actor replay accepted", err)
}
catalog, err = db.Catalog(ctx)
if err != nil || catalog.Version != result.Version {
t.Fatal("version mismatch", err)
}
last, lastResult = draft, result
}
}
if err = db.Close(); err != nil {
t.Fatal(err)
}
reopened, err := Open(ctx, dsn)
if err != nil {
t.Fatal(err)
}
defer reopened.Close()
result, err := reopened.PublishCatalog(ctx, "operator", last)
if err != nil || result != lastResult {
t.Fatal("restart changed replay identity", err)
}
audits, err := reopened.CatalogChanges(ctx)
if err != nil || len(audits) != 8 || audits[0].Target != lastResult.ID {
t.Fatal("generated ID not persisted in audit", err)
}
}
+36 -4
View File
@@ -2,6 +2,7 @@ package store
import (
"aeternalis/server/content"
"aeternalis/server/internal/game"
"context"
"fmt"
"maps"
@@ -32,6 +33,21 @@ func (d *DB) PreviewCatalog(ctx context.Context, change CatalogChange) (CatalogP
if err != nil {
return CatalogPreview{}, err
}
// Preview validates a provisional identity but does not reserve or expose it.
if !change.HasDefinitionID() {
if resolved.Title != nil {
resolved.Title.ID = ""
}
if resolved.Item != nil {
resolved.Item.ID = ""
}
if resolved.RequirementSet != nil {
resolved.RequirementSet.ID = ""
}
if resolved.EffectSet != nil {
resolved.EffectSet.ID = ""
}
}
return CatalogPreview{BasedOnVersion: c.Version, ProposedVersion: next.Version, Resolved: resolved}, nil
}
@@ -51,6 +67,9 @@ func buildCatalog(c content.Catalog, change CatalogChange) (content.Catalog, str
switch change.Op {
case "create-title":
title := *change.Title
if title.ID == "" {
title.ID = "title_" + game.ID()
}
if len(title.Requirements) > 8 {
return invalid(fmt.Errorf("at most eight inline requirements are allowed"))
}
@@ -73,6 +92,9 @@ func buildCatalog(c content.Catalog, change CatalogChange) (content.Catalog, str
target = title.ID
case "create-item":
item := *change.Item
if item.ID == "" {
item.ID = "item_" + game.ID()
}
// Validate inline values before merging, so sets cannot mask invalid input.
if err := item.Validate(); err != nil {
return invalid(err)
@@ -97,11 +119,21 @@ func buildCatalog(c content.Catalog, change CatalogChange) (content.Catalog, str
case "update-stats":
c.Stats = *change.Stats
case "create-requirement-set":
c.RequirementSets = append(slices.Clone(c.RequirementSets), *change.RequirementSet)
target = change.RequirementSet.ID
set := *change.RequirementSet
if set.ID == "" {
set.ID = "requirement_" + game.ID()
}
resolved.RequirementSet = &set
c.RequirementSets = append(slices.Clone(c.RequirementSets), set)
target = set.ID
case "create-effect-set":
c.EffectSets = append(slices.Clone(c.EffectSets), *change.EffectSet)
target = change.EffectSet.ID
set := *change.EffectSet
if set.ID == "" {
set.ID = "effect_" + game.ID()
}
resolved.EffectSet = &set
c.EffectSets = append(slices.Clone(c.EffectSets), set)
target = set.ID
}
c.Version++
if err := c.Validate(); err != nil {
+4
View File
@@ -48,6 +48,10 @@ func (h *HTTP) catalogRoutes(mux *http.ServeMux) {
fail(w, 400, "invalid catalog change")
return
}
if change.HasDefinitionID() {
fail(w, 400, "Content IDs are assigned by the server. Refresh the editor and omit the definition ID.")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
var result any
+6 -1
View File
@@ -80,7 +80,12 @@ func TestControlAuthorizationAndExecution(t *testing.T) {
if request("GET", "/api/control", "", token, "") != 200 {
t.Fatal("admin denied")
}
previewBody := `{"id":"` + game.ID() + `","expectedVersion":1,"op":"create-effect-set","reason":"Preview effects","effectSet":{"id":"test_effect","name":"Test effect","description":"","modifiers":[{"stat":"strength","flat":2,"percent":0}]}}`
previewBody := `{"id":"` + game.ID() + `","expectedVersion":1,"op":"create-effect-set","reason":"Preview effects","effectSet":{"name":"Test effect","description":"","modifiers":[{"stat":"strength","flat":2,"percent":0}]}}`
for _, path := range []string{"/api/control/catalog", "/api/control/catalog/preview"} {
if request("POST", path, strings.Replace(previewBody, `"effectSet":{`, `"effectSet":{"id":"client_chosen",`, 1), token, server.URL) != 400 {
t.Fatal("client selected a permanent content ID")
}
}
if request("POST", "/api/control/catalog/preview", previewBody, token, "https://evil.example") != 403 {
t.Fatal("cross-origin preview")
}
+5 -5
View File
@@ -9,7 +9,6 @@ test('Control publishes title and equipment requirements, formulas and audit', a
await page.goto('/control');await page.getByRole('button',{name:'Content',exact:true}).click();
await page.getByRole('button',{name:'Create title',exact:true}).click();
const form=page.locator('.catalog-form');
await form.getByLabel('Permanent ID',{exact:true}).fill('control_trial');
await form.getByLabel('Name',{exact:true}).fill('Control Trial');
await form.getByLabel('Description',{exact:true}).fill('A test of authored requirements and effects.');
await form.getByLabel('Award scope').selectOption('global');
@@ -25,10 +24,10 @@ test('Control publishes title and equipment requirements, formulas and audit', a
await form.getByRole('button',{name:'Publish changes'}).click();
await expect(page.locator('.catalog-heading')).toContainText(`Catalog version ${initial+1}`);
let catalog=(await (await page.request.get('/api/control/catalog')).json()).catalog;
expect(catalog.titles.find(t=>t.id==='control_trial')).toMatchObject({scope:'global',requirements:[{metric:'level',atLeast:9999}],effects:{modifiers:[{stat:'strength',flat:3,percent:-10}]}});
const title=catalog.titles.find(t=>t.name==='Control Trial');
expect(title).toMatchObject({scope:'global',requirements:[{metric:'level',atLeast:9999}],effects:{modifiers:[{stat:'strength',flat:3,percent:-10}]}});
await page.locator('.catalog-tabs').getByRole('button',{name:'Equipment',exact:true}).click();
await page.getByRole('button',{name:'Create equipment',exact:true}).click();
await form.getByLabel('Permanent ID',{exact:true}).fill('control_ring');
await form.getByLabel('Name',{exact:true}).fill('Control Ring');
await form.getByLabel('Equipment slot').selectOption('ring');
await form.getByLabel('Required level').fill('2');
@@ -45,7 +44,8 @@ test('Control publishes title and equipment requirements, formulas and audit', a
await form.getByRole('button',{name:'Publish changes'}).click();
await expect(page.locator('.catalog-heading')).toContainText(`Catalog version ${initial+2}`);
catalog=(await (await page.request.get('/api/control/catalog')).json()).catalog;
expect(catalog.items.find(i=>i.id==='control_ring')).toMatchObject({slot:'ring',requirements:{level:2,stats:{strength:3},titles:['control_trial']},modifiers:[{stat:'luck',flat:2,percent:25}]});
const item=catalog.items.find(i=>i.name==='Control Ring');
expect(item).toMatchObject({slot:'ring',requirements:{level:2,stats:{strength:3},titles:[title.id]},modifiers:[{stat:'luck',flat:2,percent:25}]});
await page.locator('.catalog-tabs').getByRole('button',{name:'Stat formulas',exact:true}).click();
await page.getByRole('button',{name:'Edit stat formulas',exact:true}).click();
await form.getByLabel('Charisma base',{exact:true}).fill('1');
@@ -54,7 +54,7 @@ test('Control publishes title and equipment requirements, formulas and audit', a
await expect(page.locator('.catalog-heading')).toContainText(`Catalog version ${initial+3}`);
await page.locator('.catalog-tabs').getByRole('button',{name:'Content audit',exact:true}).click();
await expect(page.locator('.catalog-list')).toContainText('Formula editor verification');
await expect(page.locator('.catalog-list')).toContainText('control_ring');
await expect(page.locator('.catalog-list')).toContainText(item.id);
await page.setViewportSize({width:1440,height:1000});
await page.screenshot({path:'test-results/content-audit-desktop.png',fullPage:true});
await expect.poll(async()=>((await (await page.request.get('/api/control')).json()).worlds[0].catalogVersion)).toBe(initial+3);