Add live world status panel and restore exchange navigation

This commit is contained in:
unimatrixgit 2026-10-18 20:04:24 +02:00
commit c864d4c447
10 changed files with 115 additions and 3 deletions

View file

@ -21,6 +21,8 @@ jobs:
node-version: '22'
- name: Build the illustrated website and API
run: node scripts/build.mjs
- name: Install website server dependencies
run: npm install --omit=dev --no-audit --no-fund
- name: Test feeds and compiled pages
run: node --test tests/*.test.mjs
- name: Upload website build

View file

@ -0,0 +1,55 @@
#!/usr/bin/env python3
"""Read-only Minecraft status agent. Firewall TCP 25572 to the website host only."""
import concurrent.futures,json,os,socket,struct,time
from http.server import BaseHTTPRequestHandler,ThreadingHTTPServer
TARGETS={"velocity":("127.0.0.1",25565),"spacing-guild":("127.0.0.1",25571),"arrakis":None,"caladan":None,"giedi-prime":None,"kaitain":None,"sigma-draconis-iv":None}
TARGETS.update(json.loads(os.environ.get("WORLD_TARGETS_JSON","{}")))
def varint(n):
out=bytearray()
while True:
part=n&127;n>>=7;out.append(part|(128 if n else 0))
if not n:return bytes(out)
def read_varint(sock):
n=0
for i in range(5):
data=sock.recv(1)
if not data:raise ValueError("short response")
n|=(data[0]&127)<<(7*i)
if data[0]<128:return n
raise ValueError("invalid packet")
def check(entry):
name,target=entry
if not target:return name,{"online":False,"configured":False}
try:
started=time.monotonic();host,port=target
with socket.create_connection((host,port),1.5) as sock:
sock.settimeout(1.5);address=host.encode();packet=b'\0'+varint(769)+varint(len(address))+address+struct.pack('>H',port)+b'\1'
sock.sendall(varint(len(packet))+packet+b'\1\0')
length=read_varint(sock)
if length>65536 or read_varint(sock)!=0:raise ValueError("invalid status")
size=read_varint(sock)
if size>65536:raise ValueError("oversized status")
data=b''
while len(data)<size:
part=sock.recv(size-len(data))
if not part:raise ValueError("short status")
data+=part
status=json.loads(data)
if not isinstance(status.get('version'),dict):raise ValueError("missing version")
players=status.get('players',{}).get('online',0)
return name,{"online":True,"configured":True,"players":players if isinstance(players,int) and players>=0 else 0,"latencyMs":round((time.monotonic()-started)*1000)}
except (OSError,ValueError,KeyError,TypeError):return name,{"online":False,"configured":True}
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path!='/status':self.send_error(404);return
with concurrent.futures.ThreadPoolExecutor(max_workers=7) as pool:worlds=dict(pool.map(check,TARGETS.items()))
body=json.dumps({"checkedAt":int(time.time()*1000),"servers":worlds}).encode()
self.send_response(200);self.send_header('Content-Type','application/json');self.send_header('Cache-Control','no-store');self.send_header('Content-Length',str(len(body)));self.end_headers();self.wfile.write(body)
def log_message(self,*args):pass
if __name__=='__main__':ThreadingHTTPServer(('0.0.0.0',25572),Handler).serve_forever()

View file

@ -11,3 +11,11 @@ MySQL stores forum discussions, profiles, private support tickets, accounts and
Validation: 39 local website tests passed, including rejection of forged identity headers, CSRF, privilege injection and expired logout sessions. Live MySQL tests covered registration, profile updates, private ticket create/read/reply/close, forum create/search/read/reply and cleanup of temporary records. Public domain returned the application and connected health check. The owner installed the TLS certificate; HTTPS verification and browser checks on the custom domain subsequently passed.
The exchange intentionally retains labelled demo offers until a game-market feed is configured. Connecting MySQL does not connect Minecraft market data. News and diplomacy feeds also require their configured sources. No existing ChatGPT-hosted account data was migrated.
## Live world status
The homepage and exchange show a translucent server panel over the hero artwork. `web/world-status.js` polls `/api/worlds` every 30 seconds while visible. The Node handler caches checks for 15 seconds and fetches the fixed `WORLD_STATUS_URL` configured by the operator. It does not accept probe addresses from visitors or disclose internal addresses. A missing, stale or unreachable monitor produces Unknown, never a fabricated Online/Offline result.
`network/live-lobby/status-agent.py` on the Minecraft VM performs the Minecraft Java status handshake against Velocity and the Paper lobby independently. Not-yet-configured planets show Offline; add their private host/port pairs through its `WORLD_TARGETS_JSON` environment setting when deployed. The read-only systemd service `dune-status` listens on TCP 25572; UFW allows only the website host to reach it. No game console or write endpoint is exposed. The website uses `WORLD_STATUS_URL=http://2.28.33.142:25572/status` in its private environment file.
The status deployment is release `20261018-status`; its node_modules symlink reuses the previously installed exact dependency version from `20261018-node`. Keep that earlier release while this dependency symlink is in use. For a standalone future release install dependencies in its own directory.

View file

@ -4,13 +4,16 @@ import {pathToFileURL} from 'node:url';
import worker from '../dist/server/index.js';
import {openDatabase} from './mysql.mjs';
import {createAuth,identity,safeReturn} from './auth.mjs';
import {createWorldStatus} from './world-status.mjs';
const root=new URL('./public/',import.meta.url);
const security={'X-Content-Type-Options':'nosniff','Referrer-Policy':'strict-origin-when-cross-origin','Content-Security-Policy':"default-src 'self'; img-src 'self' data:; style-src 'self' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; script-src 'self'; connect-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'self'"};
export function createApplication(db,settings={}) {
const origin=new URL(settings.PUBLIC_ORIGIN||'https://dunerealms.com').origin;
const auth=createAuth(db,origin);
const worldStatus=createWorldStatus(settings);
return async function handle(request) {
const url=new URL(request.url);
if(url.pathname==='/api/worlds')return request.method==='GET'?worldStatus():new Response('Method not allowed',{status:405});
if(url.pathname==='/signin-with-chatgpt')return Response.redirect(origin+'/login.html?return_to='+encodeURIComponent(safeReturn(url.searchParams.get('return_to'))),302);
if(url.pathname==='/healthz'){await db.prepare('SELECT 1 AS ok').first();return Response.json({status:'ok',database:'connected'},{headers:{'Cache-Control':'no-store'}});}
if(url.pathname.startsWith('/api/auth/'))return auth(request);

View file

@ -0,0 +1,19 @@
const names=[['spacing-guild','Spacing Guild'],['arrakis','Arrakis'],['caladan','Caladan'],['giedi-prime','Giedi Prime'],['kaitain','Kaitain'],['sigma-draconis-iv','Sigma Draconis IV'],['velocity','Velocity']];
export function createWorldStatus(settings,fetcher=fetch){
let cached,inflight,expires=0;
async function check(){
if(!settings.WORLD_STATUS_URL)return {checkedAt:null,available:false,servers:names.map(([id,name])=>({id,name,state:'unknown'}))};
try{
const response=await fetcher(settings.WORLD_STATUS_URL,{signal:AbortSignal.timeout(4500)});
if(!response.ok)throw Error('unavailable');
const data=await response.json();
if(!Number.isSafeInteger(data.checkedAt)||Math.abs(Date.now()-data.checkedAt)>60000||!data.servers)throw Error('stale');
const servers=names.map(([id,name])=>{const row=data.servers[id];if(typeof row?.online!=='boolean'||typeof row?.configured!=='boolean')throw Error('invalid');return {id,name,state:row.online?'online':'offline',configured:row.configured,...(row.online&&Number.isSafeInteger(row.players)&&row.players>=0?{players:row.players}:{})};});
return {checkedAt:data.checkedAt,available:true,servers};
}catch{return {checkedAt:null,available:false,servers:names.map(([id,name])=>({id,name,state:'unknown'}))};}
}
return async()=>{
if(!cached||Date.now()>=expires){inflight||=(async()=>{try{cached=await check();expires=Date.now()+15000;}finally{inflight=null;}})();await inflight;}
return Response.json(cached,{headers:{'Cache-Control':'no-store'}});
};
}

View file

@ -0,0 +1,11 @@
import test from 'node:test';import assert from 'node:assert/strict';import {createWorldStatus} from '../node/world-status.mjs';
const ids=['spacing-guild','arrakis','caladan','giedi-prime','kaitain','sigma-draconis-iv','velocity'];
test('Live status is cached and only known server fields reach the browser',async()=>{
let count=0;const servers=Object.fromEntries(ids.map(id=>[id,{online:id==='spacing-guild'||id==='velocity',configured:id==='spacing-guild'||id==='velocity',players:1,host:'private-host',secret:'never exposed'}]));
const status=createWorldStatus({WORLD_STATUS_URL:'http://agent/status'},async()=>{count++;return Response.json({checkedAt:Date.now(),servers});});
const a=await (await status()).json();await status();assert.equal(count,1);assert.equal(a.servers.length,7);assert.equal(a.servers[0].state,'online');assert.equal(a.servers[1].state,'offline');assert.equal(a.servers[1].configured,false);assert.ok(!JSON.stringify(a).includes('private-host'));assert.ok(!JSON.stringify(a).includes('secret'));
});
test('Missing, failed and stale monitoring never invent online or offline status',async()=>{
for(const fetcher of [async()=>{throw Error('down')},async()=>Response.json({checkedAt:1,servers:{}})]){const r=await (await createWorldStatus({WORLD_STATUS_URL:'http://agent/status'},fetcher)()).json();assert.equal(r.available,false);assert.ok(r.servers.every(s=>s.state==='unknown'));}
const r=await (await createWorldStatus({})()).json();assert.equal(r.available,false);
});

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1 @@
.world-status{position:absolute;z-index:3;top:40px;right:5%;width:300px;padding:24px 25px 18px;background:rgba(11,28,25,.67);border:1px solid rgba(213,171,99,.48);box-shadow:0 16px 50px #0003,inset 0 1px 0 #f5eddd12;backdrop-filter:blur(9px);-webkit-backdrop-filter:blur(9px);color:var(--paper)}.world-status .eyebrow{margin-bottom:8px;font-size:9px}.world-status h2{font-size:35px;margin:0 0 17px;letter-spacing:-.02em}.world-status-list{padding:0;margin:0;list-style:none}.world-status-list li{display:flex;justify-content:space-between;align-items:center;gap:12px;padding:9px 0;border-bottom:1px solid #d5ab6325;font-size:12px}.world-status-list li:last-child{border:0}.world-state{font-size:10px;letter-spacing:.03em;white-space:nowrap}.world-state.online{color:#b5d9a8}.world-state.offline{color:#d5b49e}.world-state.unknown{color:#c0c3b6}.world-status-note{font-size:9px;color:#c9c5b3;margin:15px 0 0;line-height:1.6}.choam-hero{position:relative}.choam-hero:has(.world-status){min-height:460px}.choam-hero .world-status{top:35px}.choam-hero:has(.world-status) h1,.choam-hero:has(.world-status) .choam-desc{max-width:calc(100% - 350px)}@media(min-width:721px) and (max-width:1100px){.hero:has(.world-status){height:auto;max-height:none;min-height:1000px}.hero .world-status{top:520px;width:290px}.choam-hero .world-status{position:relative;top:auto;right:auto;margin:30px 0 0;width:100%;max-width:440px}.choam-hero:has(.world-status) h1,.choam-hero:has(.world-status) .choam-desc{max-width:100%}}@media(max-width:720px){.hero:has(.world-status){height:auto;max-height:none;min-height:1100px}.world-status{position:relative;top:auto;right:auto;width:auto;margin:20px 7% 65px;padding:20px}.hero .world-status{margin-top:15px}.choam-hero .world-status{top:auto;margin:30px 0 0}.choam-hero:has(.world-status) h1,.choam-hero:has(.world-status) .choam-desc{max-width:100%}.world-status h2{font-size:32px}}

View file

@ -0,0 +1,13 @@
const panel=document.querySelector('.world-status');
if(panel){
const list=panel.querySelector('.world-status-list'),note=panel.querySelector('.world-status-note');
async function update(){
try{
const response=await fetch('/api/worlds',{cache:'no-store',signal:AbortSignal.timeout(7000)});if(!response.ok)throw Error();
const data=await response.json();list.replaceChildren();
for(const server of data.servers){const row=document.createElement('li'),name=document.createElement('span'),state=document.createElement('span');name.textContent=server.name;state.className='world-state '+server.state;state.textContent=server.state==='online'?'✓ Online':server.state==='offline'?'○ Offline':'— Unknown';if(server.state==='offline'&&!server.configured)state.title='Not deployed yet';row.append(name,state);list.append(row);}
note.textContent=data.available?'Live check · '+new Date(data.checkedAt).toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'})+' · updates every 30s':'Status check unavailable · retrying';
}catch{for(const state of list.querySelectorAll('.world-state')){state.className='world-state unknown';state.textContent='— Unknown';}note.textContent='Status check unavailable · retrying';}
}
update();setInterval(()=>{if(!document.hidden)update();},30000);
}