Phase 2: client military/social screens, WebSocket push, trade + endgame, review findings pending

Built: units/movements/reports/send/expansion screens, alliance/messages/rankings screens, ws client + server /ws push
(docs/PROTOCOL.md), Internet exchange trade, backbone endgame + world end, shared reports, buildDone relative levels.
Tested: npm test 175/175. Two adversarial reviews found issues (trade-leg recall exploit, __proto__ via validate.js,
rankings DoS, static headers, ...): fixes follow in the next commit.
NOT done: bots/balance, e2e suite, real-device checks.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
This commit is contained in:
jvanvik 2026-10-11 19:05:03 +02:00
parent 249818a7aa
commit b18645dca1
87 changed files with 10201 additions and 71 deletions

View file

@ -5,6 +5,7 @@
*
* App.registerScreen({
* id: 'pop', titleKey: 'screen.pop', navKey: 'nav.pop', icon: 'pop', // nav: false hides it from the nav
* navGroup: 'main' | 'more', // bar button (default) or behind the "More" sheet
* hud: true, // show the resource bar above it
* render(container) {}, // once, when the screen is first shown: build the persistent DOM
* onShow(params) {}, // every time it becomes visible
@ -13,6 +14,8 @@
* });
*
* Later stages add screens (units, reports, ...) the same way: one file, one registerScreen call, one script tag.
* The bar holds 5 slots; with any 'more' screen the 5th is the More button (see "Bottom nav with overflow" below).
* App.setBadge(screenId, n, 'alert'|'info') puts a count on a screen's nav button (the More button sums its screens).
* Everything time-based is computed from api.serverNow() (server clock), never from the device clock alone.
*/
(function () {
@ -94,32 +97,102 @@
const elApp = () => document.getElementById('app');
App.registerScreen = (def) => { App.screens.set(def.id, def); };
App.alertKinds = {}; // notification type -> describer, see screens/alerts.js
App.popSections = []; // extra cards of the POP screen: { slot: 'top' | 'main', render(townData) -> Node | null }
// Bottom nav with overflow. A screen picks where it lives with `navGroup`:
// 'main' (default) one of the primary screens in the bar (registration order)
// 'more' behind the "More" button, which opens a sheet listing these screens
// The bar holds NAV_SLOTS buttons. If any 'more' screen exists, or there are more 'main' screens than slots, the last slot
// becomes "More" and the surplus 'main' screens go into the sheet in front of the 'more' ones. Keep it to about 4 primary
// screens. Badges: App.setBadge(screenId, n, 'alert'|'info') shows a count on the screen's button; the More button
// shows the sum of its screens' badges (red if any of them is an alert). Add the screen's script tag and you are done.
const NAV_SLOTS = 5;
const badges = new Map(); // screen id -> { n, kind }
function navSplit() {
const all = Array.from(App.screens.values()).filter((d) => d.nav !== false);
const main = all.filter((d) => d.navGroup !== 'more'), more = all.filter((d) => d.navGroup === 'more');
if (!more.length && main.length <= NAV_SLOTS) return { bar: main, over: [] };
return { bar: main.slice(0, NAV_SLOTS - 1), over: main.slice(NAV_SLOTS - 1).concat(more) };
}
function navButton(def, onclick) {
const badge = h('span', { class: 'nav-badge', hidden: true, 'aria-hidden': 'true' });
return h('button', { class: 'nav-btn', type: 'button', dataset: { screen: def.id }, onclick },
h('span', { class: 'nav-ic' }, icon(def.icon), badge), h('span', { class: 'nav-lbl', text: App.t(def.navKey || def.titleKey) }));
}
function buildNav() {
const nav = elNav();
clear(nav);
nav.setAttribute('aria-label', App.t('nav.label'));
for (const def of App.screens.values()) {
if (def.nav === false) continue;
const badge = h('span', { class: 'nav-badge', hidden: true, 'aria-hidden': 'true' });
const btn = h('button', { class: 'nav-btn', type: 'button', dataset: { screen: def.id }, onclick: () => App.go(def.id) },
h('span', { class: 'nav-ic' }, icon(def.icon), badge), h('span', { class: 'nav-lbl', text: App.t(def.navKey || def.titleKey) }));
if (App.current && App.current.id === def.id) btn.setAttribute('aria-current', 'page');
const { bar, over } = navSplit();
for (const def of bar) nav.appendChild(navButton(def, () => App.go(def.id)));
if (over.length) {
const btn = navButton({ id: 'more', icon: 'more', navKey: 'nav.more' }, () => openMore());
btn.setAttribute('aria-haspopup', 'dialog');
nav.appendChild(btn);
}
updateBadge();
markCurrent();
updateBadges();
}
function updateBadge() {
const n = App.state.unread;
const b = elNav().querySelector('[data-screen="alerts"] .nav-badge');
function markCurrent() {
const id = App.current ? App.current.id : null;
const { over } = navSplit();
const inMore = over.some((d) => d.id === id);
for (const b of elNav().children) {
const on = b.dataset.screen === id || (b.dataset.screen === 'more' && inMore);
if (on) b.setAttribute('aria-current', 'page'); else b.removeAttribute('aria-current');
}
}
function openMore() {
const { over } = navSplit();
const list = h('div', { class: 'more-list' });
const sheet = UI.openSheet({ title: App.t('nav.more'), icon: 'more', closeLabel: App.t('common.close'), body: list });
for (const def of over) {
const bd = badges.get(def.id);
list.appendChild(h('button', { class: 'row-btn', type: 'button', onclick: () => { sheet.close(true); App.go(def.id); } },
h('span', { class: 'row-ic' }, icon(def.icon)),
h('span', { class: 'row-main' }, h('span', { class: 'row-title' }, h('b', { text: App.t(def.navKey || def.titleKey) }))),
bd && bd.n ? h('span', { class: 'pill ' + (bd.kind === 'alert' ? 'amber' : 'accent'), text: String(bd.n) }) : null));
}
}
function paintBadge(btn, n, kind, label) {
const b = btn.querySelector('.nav-badge');
if (!b) return;
b.hidden = !n;
b.textContent = n > 9 ? '9+' : String(n);
const btn = b.closest('button');
if (btn) btn.setAttribute('aria-label', App.t('nav.alerts') + (n ? ' (' + App.t('alerts.count', { n }) + ')' : ''));
b.classList.toggle('is-alert', kind === 'alert');
const lbl = btn.querySelector('.nav-lbl');
btn.setAttribute('aria-label', (lbl ? lbl.textContent : label || '') + (n ? ' (' + n + ')' : ''));
}
function updateBadges() {
const { over } = navSplit();
const overIds = new Set(over.map((d) => d.id));
let sum = 0, kind = 'info';
for (const [id, bd] of badges) {
if (overIds.has(id)) { sum += bd.n; if (bd.kind === 'alert' && bd.n) kind = 'alert'; }
}
for (const btn of elNav().children) {
const id = btn.dataset.screen;
if (id === 'more') paintBadge(btn, sum, kind);
else { const bd = badges.get(id); paintBadge(btn, bd ? bd.n : 0, bd ? bd.kind : 'info'); }
}
}
App.setBadge = (id, n, kind) => {
const prev = badges.get(id);
n = Math.max(0, Math.floor(n) || 0);
if (prev && prev.n === n && prev.kind === (kind || 'info')) return;
badges.set(id, { n, kind: kind || 'info' });
updateBadges();
};
const updateBadge = () => App.setBadge('alerts', App.state.unread, 'info'); // alerts feed unread count
function setTitle(def) { document.getElementById('title').textContent = def.id === 'auth' ? App.t('app.name') : App.t(def.titleKey); document.title = (def.id === 'auth' ? '' : App.t(def.titleKey) + ' · ') + 'UPSTREAM'; }
// Navigate. Sets the hash (so back/forward work); hashchange does the actual switch.
@ -150,7 +223,7 @@
app.dataset.screen = def.id;
app.dataset.state = App.state.user ? 'in' : 'out';
elNav().hidden = !App.state.user;
for (const b of elNav().children) { if (b.dataset.screen === def.id) b.setAttribute('aria-current', 'page'); else b.removeAttribute('aria-current'); }
markCurrent();
setTitle(def);
renderHud(false);
if (def.onShow) def.onShow(App.params);
@ -225,9 +298,16 @@
let rulesCache = null;
// The rules.js town shape from the API response: same function the server settles with, so the numbers agree.
App.rulesTown = () => {
const st = App.state, td = st.townData;
if (!td || !st.world) return null;
const td = App.state.townData;
if (!td || !App.state.world) return null;
if (rulesCache && rulesCache.src === td) return rulesCache.town;
const town = App.rulesTownFrom(td, App.fetchedServerTime || 0);
rulesCache = { src: td, town };
return town;
};
// Same for any POP payload of GET /towns/:id fetched at server time `at` (the send dialog looks at other POPs too).
App.rulesTownFrom = (td, at) => {
const st = App.state;
const buildings = {};
let bdraw = 0;
for (const b of td.buildings) {
@ -237,11 +317,10 @@
if (def && def.kind === 'infra') bdraw += def.draw * b.level;
}
const town = {
id: td.id, speed: st.world.speed, updatedAt: App.fetchedServerTime || 0,
id: td.id, speed: st.world.speed, updatedAt: at,
res: { fiber: td.resources.fiber.amount, hardware: td.resources.hardware.amount, capital: td.resources.capital.amount, battery: td.power.buffer },
footprint: td.footprint, buildings, unitDraw: Math.max(0, Math.round(td.power.draw - bdraw)), bonus: td.bonus || {},
};
rulesCache = { src: td, town };
return town;
};
@ -262,6 +341,8 @@
// ------------------------------------------------------------------ resource bar
const hudRefs = {};
App.on('towns', () => renderHud(true)); // POP list changed (founded / conquered / lost / renamed)
App.on('townchange', () => renderHud(true)); // the switcher shows the selected POP
function renderHud(rebuild) {
const hud = document.getElementById('hud');
@ -272,6 +353,12 @@
if (!want) return;
if (!rebuild && hud.firstChild) return;
clear(hud);
// POP switcher (only with more than one POP): every screen with the resource bar gets it
if (App.state.towns.length > 1) {
hud.appendChild(h('label', { class: 'hud-town' }, icon('pop'),
h('select', { 'aria-label': App.t('screen.pop'), onchange: (e) => App.setTown(Number(e.target.value)) },
App.state.towns.map((x) => h('option', { value: x.id, selected: x.id === App.state.townId, text: x.name + (x.isCapital ? ' ★' : '') })))));
}
for (const r of D.RESOURCES.concat(['power'])) {
const refs = {
val: h('b', { class: 'val' }), cap: h('span', { class: 'cap' }), rate: h('span', { class: 'rate' }), fill: h('i'),