prototype-server-vision: phase 2a (mummy server, nginx conf, neutral doors in tiles, smoke)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -5,3 +5,4 @@ nimble.paths
|
|||||||
tests/t[a-z]*
|
tests/t[a-z]*
|
||||||
!tests/*.nim
|
!tests/*.nim
|
||||||
server
|
server
|
||||||
|
run/
|
||||||
|
|||||||
@@ -9,3 +9,10 @@
|
|||||||
|
|
||||||
## Layout
|
## Layout
|
||||||
- Hand-authored (no RNG): reproducible by construction. 6 rooms, 7 corridors, 1 pillar (R1), T-junction (partition at x=3000 in R3 ends mid south wall), collinear split (R3 north wall at x=3200), long thin corridor (R2-R5, 1024x64), doors: R2 west (closed), R5 north (open).
|
- Hand-authored (no RNG): reproducible by construction. 6 rooms, 7 corridors, 1 pillar (R1), T-junction (partition at x=3000 in R3 ends mid south wall), collinear split (R3 north wall at x=3200), long thin corridor (R2-R5, 1024x64), doors: R2 west (closed), R5 north (open).
|
||||||
|
|
||||||
|
## Phase 2a (server)
|
||||||
|
- Port 8080 was taken on dev box (docker puma): `PORT=8088 devbox run server|nginx` (sed into run/nginx.conf; server prints invite origin from PORT). Default 8080.
|
||||||
|
- Verified: WS path tricks rejected (webby 400 on %2f/%00); `/_tiles/` 404 when hit directly.
|
||||||
|
- Non-owned move => `error` (not moveAck: server pos of an unseen token would leak).
|
||||||
|
- `by` = "gm"|"A"|"B" (conn role name).
|
||||||
|
- Smoke: `PORT=8088 devbox run -- node tools/smoke.mjs` (server+nginx up, run/invites.txt written by server).
|
||||||
|
|||||||
@@ -1,12 +1,18 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://raw.githubusercontent.com/jetify-com/devbox/0.17.2/.schema/devbox.schema.json",
|
"$schema": "https://raw.githubusercontent.com/jetify-com/devbox/0.17.2/.schema/devbox.schema.json",
|
||||||
"packages": [
|
"packages": {
|
||||||
"nim@2",
|
"nim": "2",
|
||||||
"nimble@latest",
|
"nimble": "latest",
|
||||||
"sqlite@latest",
|
"nginx": "latest",
|
||||||
"nginx@latest",
|
"nodejs": "latest",
|
||||||
"nodejs@latest"
|
"sqlite": {
|
||||||
],
|
"version": "latest",
|
||||||
|
"outputs": [
|
||||||
|
"out",
|
||||||
|
"bin"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
"shell": {
|
"shell": {
|
||||||
"init_hook": [],
|
"init_hook": [],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -19,6 +25,16 @@
|
|||||||
"test": [
|
"test": [
|
||||||
"node tools/genmap.mjs",
|
"node tools/genmap.mjs",
|
||||||
"nimble test"
|
"nimble test"
|
||||||
|
],
|
||||||
|
"server": [
|
||||||
|
"nimble build -d:release -y",
|
||||||
|
"mkdir -p run",
|
||||||
|
"./server"
|
||||||
|
],
|
||||||
|
"nginx": [
|
||||||
|
"mkdir -p run/temp client/dist",
|
||||||
|
"sed \"s/NGX_PORT/${PORT:-8080}/\" nginx/nginx.conf > run/nginx.conf",
|
||||||
|
"nginx -p \"$PWD/\" -c run/nginx.conf -e run/error.log"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
|
||||||
|
types {
|
||||||
|
text/html html htm shtml;
|
||||||
|
text/css css;
|
||||||
|
text/xml xml;
|
||||||
|
image/gif gif;
|
||||||
|
image/jpeg jpeg jpg;
|
||||||
|
application/javascript js;
|
||||||
|
application/atom+xml atom;
|
||||||
|
application/rss+xml rss;
|
||||||
|
|
||||||
|
text/mathml mml;
|
||||||
|
text/plain txt;
|
||||||
|
text/vnd.sun.j2me.app-descriptor jad;
|
||||||
|
text/vnd.wap.wml wml;
|
||||||
|
text/x-component htc;
|
||||||
|
|
||||||
|
image/avif avif;
|
||||||
|
image/png png;
|
||||||
|
image/svg+xml svg svgz;
|
||||||
|
image/tiff tif tiff;
|
||||||
|
image/vnd.wap.wbmp wbmp;
|
||||||
|
image/webp webp;
|
||||||
|
image/x-icon ico;
|
||||||
|
image/x-jng jng;
|
||||||
|
image/x-ms-bmp bmp;
|
||||||
|
|
||||||
|
font/woff woff;
|
||||||
|
font/woff2 woff2;
|
||||||
|
|
||||||
|
application/java-archive jar war ear;
|
||||||
|
application/json json;
|
||||||
|
application/mac-binhex40 hqx;
|
||||||
|
application/msword doc;
|
||||||
|
application/pdf pdf;
|
||||||
|
application/postscript ps eps ai;
|
||||||
|
application/rtf rtf;
|
||||||
|
application/vnd.apple.mpegurl m3u8;
|
||||||
|
application/vnd.google-earth.kml+xml kml;
|
||||||
|
application/vnd.google-earth.kmz kmz;
|
||||||
|
application/vnd.ms-excel xls;
|
||||||
|
application/vnd.ms-fontobject eot;
|
||||||
|
application/vnd.ms-powerpoint ppt;
|
||||||
|
application/vnd.oasis.opendocument.graphics odg;
|
||||||
|
application/vnd.oasis.opendocument.presentation odp;
|
||||||
|
application/vnd.oasis.opendocument.spreadsheet ods;
|
||||||
|
application/vnd.oasis.opendocument.text odt;
|
||||||
|
application/vnd.openxmlformats-officedocument.presentationml.presentation
|
||||||
|
pptx;
|
||||||
|
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
|
||||||
|
xlsx;
|
||||||
|
application/vnd.openxmlformats-officedocument.wordprocessingml.document
|
||||||
|
docx;
|
||||||
|
application/vnd.wap.wmlc wmlc;
|
||||||
|
application/wasm wasm;
|
||||||
|
application/x-7z-compressed 7z;
|
||||||
|
application/x-cocoa cco;
|
||||||
|
application/x-java-archive-diff jardiff;
|
||||||
|
application/x-java-jnlp-file jnlp;
|
||||||
|
application/x-makeself run;
|
||||||
|
application/x-perl pl pm;
|
||||||
|
application/x-pilot prc pdb;
|
||||||
|
application/x-rar-compressed rar;
|
||||||
|
application/x-redhat-package-manager rpm;
|
||||||
|
application/x-sea sea;
|
||||||
|
application/x-shockwave-flash swf;
|
||||||
|
application/x-stuffit sit;
|
||||||
|
application/x-tcl tcl tk;
|
||||||
|
application/x-x509-ca-cert der pem crt;
|
||||||
|
application/x-xpinstall xpi;
|
||||||
|
application/xhtml+xml xhtml;
|
||||||
|
application/xspf+xml xspf;
|
||||||
|
application/zip zip;
|
||||||
|
|
||||||
|
application/octet-stream bin exe dll;
|
||||||
|
application/octet-stream deb;
|
||||||
|
application/octet-stream dmg;
|
||||||
|
application/octet-stream iso img;
|
||||||
|
application/octet-stream msi msp msm;
|
||||||
|
|
||||||
|
audio/midi mid midi kar;
|
||||||
|
audio/mpeg mp3;
|
||||||
|
audio/ogg ogg;
|
||||||
|
audio/x-m4a m4a;
|
||||||
|
audio/x-realaudio ra;
|
||||||
|
|
||||||
|
video/3gpp 3gpp 3gp;
|
||||||
|
video/mp2t ts;
|
||||||
|
video/mp4 mp4;
|
||||||
|
video/mpeg mpeg mpg;
|
||||||
|
video/quicktime mov;
|
||||||
|
video/webm webm;
|
||||||
|
video/x-flv flv;
|
||||||
|
video/x-m4v m4v;
|
||||||
|
video/x-mng mng;
|
||||||
|
video/x-ms-asf asx asf;
|
||||||
|
video/x-ms-wmv wmv;
|
||||||
|
video/x-msvideo avi;
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# run via `devbox run nginx`; prefix = project root, all temp/log paths in run/
|
||||||
|
daemon off;
|
||||||
|
pid run/nginx.pid;
|
||||||
|
error_log run/error.log warn;
|
||||||
|
events {}
|
||||||
|
http {
|
||||||
|
access_log run/access.log;
|
||||||
|
client_body_temp_path run/temp/client_body;
|
||||||
|
proxy_temp_path run/temp/proxy;
|
||||||
|
fastcgi_temp_path run/temp/fastcgi;
|
||||||
|
uwsgi_temp_path run/temp/uwsgi;
|
||||||
|
scgi_temp_path run/temp/scgi;
|
||||||
|
server_tokens off;
|
||||||
|
include ../nginx/mime.types; # relative to the generated run/nginx.conf
|
||||||
|
map $http_upgrade $conn_up { default upgrade; '' close; }
|
||||||
|
server {
|
||||||
|
listen NGX_PORT; # sed-substituted from $PORT (default 8080)
|
||||||
|
server_name localhost;
|
||||||
|
root client/dist;
|
||||||
|
index index.html;
|
||||||
|
location /join/ { proxy_pass http://127.0.0.1:9000; }
|
||||||
|
location /tiles/ { proxy_pass http://127.0.0.1:9000; }
|
||||||
|
location /ws {
|
||||||
|
proxy_pass http://127.0.0.1:9000;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection $conn_up;
|
||||||
|
proxy_read_timeout 1h;
|
||||||
|
}
|
||||||
|
# only reachable via X-Accel-Redirect from Nim after its access check
|
||||||
|
location /_tiles/ { internal; alias data/tiles/; add_header Cache-Control "private, no-cache"; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1 +1,3 @@
|
|||||||
--path:"src"
|
--path:"src"
|
||||||
|
--threads:on
|
||||||
|
--mm:orc
|
||||||
|
|||||||
@@ -1,3 +1,320 @@
|
|||||||
# phase 1 stub: server lands in a later phase
|
## Server-authoritative vision. Players are untrusted: only what is in their vision reaches them.
|
||||||
|
## One global Lock: validate -> mutate -> recompute vision -> persist -> send, so gseq order == send order.
|
||||||
|
import std/[json, tables, sets, locks, os, monotimes, times, strutils, sysrand, strformat]
|
||||||
import mummy, db_connector/db_sqlite
|
import mummy, db_connector/db_sqlite
|
||||||
echo "todo"
|
import geometry
|
||||||
|
|
||||||
|
type
|
||||||
|
Tok = object
|
||||||
|
id, name, kind: string
|
||||||
|
pos: Vec
|
||||||
|
gmOnly: bool
|
||||||
|
Role = ref object # per player: shared by all that player's connections
|
||||||
|
polys: seq[seq[Vec]]
|
||||||
|
ver: int # bumped when polys change
|
||||||
|
explored: HashSet[int]
|
||||||
|
fresh: seq[int] # cells added by the current mutation
|
||||||
|
Conn = ref object
|
||||||
|
ws: WebSocket
|
||||||
|
role: string # "gm" | "A" | "B"
|
||||||
|
ver: int
|
||||||
|
known: Table[string, Vec] # tokens this client currently has
|
||||||
|
bytes: int
|
||||||
|
Ev = object # what the current mutation was
|
||||||
|
door: int
|
||||||
|
doorOpen: bool
|
||||||
|
moved, by: string
|
||||||
|
reqId: int
|
||||||
|
Stat = object
|
||||||
|
n: int
|
||||||
|
sum, worst: float
|
||||||
|
|
||||||
|
# nginx public port; 8080 per spec, PORT overrides when taken
|
||||||
|
let origin = "http://localhost:" & getEnv("PORT", "8080")
|
||||||
|
|
||||||
|
var
|
||||||
|
lk: Lock
|
||||||
|
db: DbConn
|
||||||
|
walls: seq[Wall] # index == wall id
|
||||||
|
toks: seq[Tok]
|
||||||
|
worldW, worldH, tileSize, cell, cw: int
|
||||||
|
radius: float
|
||||||
|
roles: Table[string, Role]
|
||||||
|
secrets: Table[string, string] # secret -> "gm"|"A"|"B"
|
||||||
|
conns: Table[string, Conn]
|
||||||
|
gseq: int
|
||||||
|
vstat, bstat: Table[string, Stat]
|
||||||
|
nMut: int
|
||||||
|
lk.initLock
|
||||||
|
|
||||||
|
proc add(s: var Stat, v: float) = inc s.n; s.sum += v; s.worst = max(s.worst, v)
|
||||||
|
|
||||||
|
proc printStats() =
|
||||||
|
for k, s in vstat: echo &"STATS vision_ms {k}: n={s.n} avg={s.sum / s.n.float:.3f} worst={s.worst:.3f}"
|
||||||
|
for k, s in bstat: echo &"STATS bytes/mutation client={k}: n={s.n} avg={s.sum / s.n.float:.1f} worst={s.worst:.0f}"
|
||||||
|
stdout.flushFile
|
||||||
|
|
||||||
|
# shortcut: WebSocket has no ==/hash and private fields; key by raw bytes, fine while the layout is plain POD
|
||||||
|
proc key(ws: WebSocket): string =
|
||||||
|
result = newString(sizeof(ws)); copyMem(addr result[0], unsafeAddr ws, sizeof(ws))
|
||||||
|
|
||||||
|
proc owns(role, id: string): bool = role == "gm" or role == id
|
||||||
|
proc pt(v: Vec): JsonNode = %[%v.x, %v.y]
|
||||||
|
proc tokIdx(id: string): int =
|
||||||
|
for i, t in toks:
|
||||||
|
if t.id == id: return i
|
||||||
|
-1
|
||||||
|
|
||||||
|
proc send(c: Conn, t: string, j: JsonNode) =
|
||||||
|
j["t"] = %t; j["gseq"] = %gseq
|
||||||
|
let s = $j
|
||||||
|
c.bytes += s.len
|
||||||
|
c.ws.send(s)
|
||||||
|
|
||||||
|
proc err(c: Conn, msg: string) = c.send("error", %*{"msg": msg})
|
||||||
|
|
||||||
|
proc recompute(rn: string) =
|
||||||
|
let r = roles[rn]
|
||||||
|
var np: seq[seq[Vec]]
|
||||||
|
for t in toks:
|
||||||
|
if owns(rn, t.id): np.add visibilityPolygon(t.pos, walls, radius)
|
||||||
|
if np == r.polys: return
|
||||||
|
r.polys = np; inc r.ver
|
||||||
|
for p in np:
|
||||||
|
for (ix, iy) in cellsTouched(p, cell.float):
|
||||||
|
if ix >= 0 and iy >= 0 and ix < cw and iy < cw:
|
||||||
|
let k = iy * cw + ix
|
||||||
|
if not r.explored.containsOrIncl(k): r.fresh.add k
|
||||||
|
|
||||||
|
proc persistCells(rn: string) =
|
||||||
|
for k in roles[rn].fresh: db.exec(sql"INSERT OR IGNORE INTO exp VALUES (?,?)", rn, k)
|
||||||
|
|
||||||
|
proc sync(c: Conn, ev: Ev, initial: bool) =
|
||||||
|
## bring one client up to date; diff against what it already has
|
||||||
|
let player = c.role != "gm"
|
||||||
|
var r: Role
|
||||||
|
if player:
|
||||||
|
r = roles[c.role]
|
||||||
|
if c.ver != r.ver:
|
||||||
|
c.ver = r.ver
|
||||||
|
var ps = newJArray()
|
||||||
|
for p in r.polys:
|
||||||
|
var a = newJArray()
|
||||||
|
for v in p: a.add pt(v)
|
||||||
|
ps.add a
|
||||||
|
c.send("vision", %*{"polys": ps})
|
||||||
|
var cells = newJArray()
|
||||||
|
if initial:
|
||||||
|
for k in r.explored: cells.add %[k mod cw, k div cw]
|
||||||
|
else:
|
||||||
|
for k in r.fresh: cells.add %[k mod cw, k div cw]
|
||||||
|
if cells.len > 0: c.send("explored", %*{"cells": cells})
|
||||||
|
elif ev.door >= 0:
|
||||||
|
c.send("door", %*{"id": ev.door, "open": ev.doorOpen})
|
||||||
|
for t in toks:
|
||||||
|
var vis = c.role == "gm" or t.id == c.role
|
||||||
|
if not vis:
|
||||||
|
for p in r.polys:
|
||||||
|
if inside(p, t.pos): vis = true; break
|
||||||
|
if vis:
|
||||||
|
if c.known.getOrDefault(t.id, (-1.0, -1.0)) != t.pos or initial:
|
||||||
|
c.known[t.id] = t.pos
|
||||||
|
let j = %*{"id": t.id, "name": t.name, "kind": t.kind, "pos": pt(t.pos), "mine": owns(c.role, t.id)}
|
||||||
|
if t.id == ev.moved and ev.reqId >= 0: j["by"] = %ev.by; j["reqId"] = %ev.reqId
|
||||||
|
c.send("token", j)
|
||||||
|
elif c.known.hasKey(t.id):
|
||||||
|
c.known.del t.id
|
||||||
|
c.send("remove", %*{"id": t.id})
|
||||||
|
|
||||||
|
proc finish(ev: Ev, kind: string, visMs: float, mover: Conn = nil) =
|
||||||
|
## send phase of a mutation (caller holds lk, DB already committed)
|
||||||
|
for c in conns.values:
|
||||||
|
if c != mover: c.bytes = 0
|
||||||
|
sync(c, ev, false)
|
||||||
|
for r in roles.values: r.fresh.setLen 0
|
||||||
|
vstat.mgetOrPut(kind, Stat()).add visMs
|
||||||
|
var line = &"MUT gseq={gseq} {kind} vision_ms={visMs:.3f}"
|
||||||
|
for c in conns.values:
|
||||||
|
bstat.mgetOrPut(c.role, Stat()).add c.bytes.float
|
||||||
|
line.add &" {c.role}:{c.bytes}B"
|
||||||
|
echo line
|
||||||
|
inc nMut
|
||||||
|
if nMut mod 100 == 0: printStats()
|
||||||
|
stdout.flushFile
|
||||||
|
|
||||||
|
proc handleMove(c: Conn, m: JsonNode) =
|
||||||
|
let p = m{"pos"}
|
||||||
|
if m{"reqId"}.isNil or m["reqId"].kind != JInt or m{"id"}.isNil or m["id"].kind != JString or
|
||||||
|
p.isNil or p.kind != JArray or p.len != 2 or p[0].kind notin {JInt, JFloat} or p[1].kind notin {JInt, JFloat}:
|
||||||
|
c.err("bad move"); return
|
||||||
|
let id = m["id"].getStr
|
||||||
|
let ti = tokIdx(id)
|
||||||
|
if ti < 0 or not owns(c.role, id): c.err("not yours"); return # no pos echoed: could leak unseen tokens
|
||||||
|
let reqId = m["reqId"].getInt
|
||||||
|
let np: Vec = (p[0].getFloat, p[1].getFloat)
|
||||||
|
let old = toks[ti].pos
|
||||||
|
if np.x < 0 or np.y < 0 or np.x > worldW.float or np.y > worldH.float or moveBlocked(walls, old, np):
|
||||||
|
c.send("moveAck", %*{"reqId": reqId, "ok": false, "pos": pt(old)}); return
|
||||||
|
toks[ti].pos = np
|
||||||
|
inc gseq
|
||||||
|
for x in conns.values: x.bytes = 0
|
||||||
|
let t0 = getMonoTime()
|
||||||
|
if roles.hasKey(id): recompute(id)
|
||||||
|
let visMs = (getMonoTime() - t0).inNanoseconds.float / 1e6
|
||||||
|
db.exec(sql"BEGIN")
|
||||||
|
db.exec(sql"INSERT OR REPLACE INTO tok VALUES (?,?,?)", id, np.x, np.y)
|
||||||
|
if roles.hasKey(id): persistCells(id)
|
||||||
|
db.exec(sql"COMMIT")
|
||||||
|
c.send("moveAck", %*{"reqId": reqId, "ok": true, "pos": pt(np)})
|
||||||
|
finish(Ev(door: -1, moved: id, by: c.role, reqId: reqId), "move", visMs, c)
|
||||||
|
|
||||||
|
proc handleDoor(c: Conn, m: JsonNode) =
|
||||||
|
if c.role != "gm": c.err("gm only"); return
|
||||||
|
if m{"id"}.isNil or m["id"].kind != JInt or m{"open"}.isNil or m["open"].kind != JBool:
|
||||||
|
c.err("bad door"); return
|
||||||
|
let id = m["id"].getInt
|
||||||
|
if id < 0 or id >= walls.len or not walls[id].door: c.err("not a door"); return
|
||||||
|
let open = m["open"].getBool
|
||||||
|
if walls[id].open == open: return
|
||||||
|
walls[id].open = open
|
||||||
|
inc gseq
|
||||||
|
for x in conns.values: x.bytes = 0
|
||||||
|
let t0 = getMonoTime()
|
||||||
|
for rn in roles.keys: recompute(rn)
|
||||||
|
let visMs = (getMonoTime() - t0).inNanoseconds.float / 1e6
|
||||||
|
db.exec(sql"BEGIN")
|
||||||
|
db.exec(sql"INSERT OR REPLACE INTO door VALUES (?,?)", id, ord(open))
|
||||||
|
for rn in roles.keys: persistCells(rn)
|
||||||
|
db.exec(sql"COMMIT")
|
||||||
|
finish(Ev(door: id, doorOpen: open, moved: "", reqId: -1), "door", visMs, c)
|
||||||
|
|
||||||
|
proc openConn(ws: WebSocket, role: string) =
|
||||||
|
let c = Conn(ws: ws, role: role, ver: -1)
|
||||||
|
conns[key(ws)] = c
|
||||||
|
let ids = newJArray()
|
||||||
|
for t in toks:
|
||||||
|
if owns(role, t.id): ids.add %t.id
|
||||||
|
c.send("hello", %*{"role": (if role == "gm": "gm" else: "player"), "tokens": ids,
|
||||||
|
"world": {"w": worldW, "h": worldH}, "tileSize": tileSize, "exploredCell": cell})
|
||||||
|
if role == "gm":
|
||||||
|
var ws = newJArray()
|
||||||
|
for i, w in walls: ws.add %*{"id": i, "a": pt(w.a), "b": pt(w.b), "door": w.door, "open": w.open}
|
||||||
|
c.send("walls", %*{"walls": ws})
|
||||||
|
sync(c, Ev(door: -1, reqId: -1), true)
|
||||||
|
|
||||||
|
proc wsHandler(ws: WebSocket, event: WebSocketEvent, message: Message) {.gcsafe.} =
|
||||||
|
{.gcsafe.}:
|
||||||
|
withLock lk:
|
||||||
|
case event
|
||||||
|
of MessageEvent:
|
||||||
|
let c = conns.getOrDefault(key(ws))
|
||||||
|
if c.isNil or message.kind != TextMessage: return
|
||||||
|
try:
|
||||||
|
let m = parseJson(message.data)
|
||||||
|
case m{"t"}.getStr
|
||||||
|
of "move": handleMove(c, m)
|
||||||
|
of "door": handleDoor(c, m)
|
||||||
|
else: c.err("unknown type")
|
||||||
|
except CatchableError:
|
||||||
|
c.err("malformed")
|
||||||
|
of CloseEvent, ErrorEvent: conns.del key(ws)
|
||||||
|
else: discard
|
||||||
|
|
||||||
|
proc cookieSecret(request: Request): string =
|
||||||
|
for (k, v) in request.headers:
|
||||||
|
if k.toLowerAscii == "cookie":
|
||||||
|
for part in v.split(';'):
|
||||||
|
let p = part.strip
|
||||||
|
if p.startsWith("sid="): return p[4 .. ^1]
|
||||||
|
|
||||||
|
proc handler(request: Request) {.gcsafe.} =
|
||||||
|
{.gcsafe.}:
|
||||||
|
let path = request.path
|
||||||
|
if path.startsWith("/join/") and request.httpMethod == "GET":
|
||||||
|
let s = path[6 .. ^1]
|
||||||
|
withLock lk:
|
||||||
|
if s notin secrets: request.respond(403); return
|
||||||
|
var h: HttpHeaders
|
||||||
|
h["Location"] = "/"
|
||||||
|
h["Set-Cookie"] = &"sid={s}; Path=/; HttpOnly; SameSite=Strict"
|
||||||
|
request.respond(302, h)
|
||||||
|
elif path == "/ws":
|
||||||
|
withLock lk:
|
||||||
|
let s = cookieSecret(request)
|
||||||
|
if s notin secrets: request.respond(403); return
|
||||||
|
openConn(request.upgradeToWebSocket(), secrets[s])
|
||||||
|
elif path.startsWith("/tiles/") and path.endsWith(".png"):
|
||||||
|
let parts = path[7 .. ^5].split('_')
|
||||||
|
if parts.len != 2 or parts[0].len notin 1..3 or parts[1].len notin 1..3 or
|
||||||
|
not parts[0].allCharsInSet(Digits) or not parts[1].allCharsInSet(Digits):
|
||||||
|
request.respond(404); return
|
||||||
|
let (tx, ty) = (parseInt(parts[0]), parseInt(parts[1]))
|
||||||
|
if tx >= worldW div tileSize or ty >= worldH div tileSize: request.respond(404); return
|
||||||
|
var ok = false
|
||||||
|
withLock lk:
|
||||||
|
let s = cookieSecret(request)
|
||||||
|
if s in secrets:
|
||||||
|
let rn = secrets[s]
|
||||||
|
ok = rn == "gm"
|
||||||
|
if not ok:
|
||||||
|
let per = tileSize div cell # shortcut: assumes tileSize % exploredCell == 0
|
||||||
|
for cy in ty * per ..< (ty + 1) * per:
|
||||||
|
for cx in tx * per ..< (tx + 1) * per:
|
||||||
|
if (cy * cw + cx) in roles[rn].explored: ok = true
|
||||||
|
if ok:
|
||||||
|
var h: HttpHeaders
|
||||||
|
h["X-Accel-Redirect"] = &"/_tiles/{tx}_{ty}.png"
|
||||||
|
request.respond(200, h)
|
||||||
|
else: request.respond(403)
|
||||||
|
else: request.respond(404)
|
||||||
|
|
||||||
|
proc loadState() =
|
||||||
|
let sc = parseFile("data/scene.json")
|
||||||
|
worldW = sc["world"]["w"].getInt; worldH = sc["world"]["h"].getInt
|
||||||
|
tileSize = sc["tileSize"].getInt; cell = sc["exploredCell"].getInt
|
||||||
|
radius = sc["visionRadius"].getFloat
|
||||||
|
cw = (worldW + cell - 1) div cell
|
||||||
|
for w in sc["walls"]:
|
||||||
|
walls.add Wall(a: (w["a"][0].getFloat, w["a"][1].getFloat), b: (w["b"][0].getFloat, w["b"][1].getFloat),
|
||||||
|
door: w["door"].getBool, open: w["open"].getBool)
|
||||||
|
for t in sc["tokens"]:
|
||||||
|
toks.add Tok(id: t["id"].getStr, name: t["name"].getStr, kind: t["kind"].getStr,
|
||||||
|
pos: (t["pos"][0].getFloat, t["pos"][1].getFloat), gmOnly: t["gmOnly"].getBool)
|
||||||
|
createDir "run"
|
||||||
|
db = open("run/state.db", "", "", "")
|
||||||
|
discard db.getAllRows(sql"PRAGMA journal_mode=WAL")
|
||||||
|
for s in ["CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT)",
|
||||||
|
"CREATE TABLE IF NOT EXISTS tok (id TEXT PRIMARY KEY, x REAL, y REAL)",
|
||||||
|
"CREATE TABLE IF NOT EXISTS door (id INTEGER PRIMARY KEY, open INTEGER)",
|
||||||
|
"CREATE TABLE IF NOT EXISTS exp (role TEXT, c INTEGER, PRIMARY KEY (role, c))"]:
|
||||||
|
db.exec(sql(s))
|
||||||
|
for r in db.getAllRows(sql"SELECT id,x,y FROM tok"):
|
||||||
|
toks[tokIdx(r[0])].pos = (parseFloat(r[1]), parseFloat(r[2]))
|
||||||
|
for r in db.getAllRows(sql"SELECT id,open FROM door"): walls[parseInt(r[0])].open = r[1] == "1"
|
||||||
|
var invites = ""
|
||||||
|
for rn in ["gm", "A", "B"]:
|
||||||
|
var s = db.getValue(sql"SELECT v FROM meta WHERE k=?", rn)
|
||||||
|
if s == "":
|
||||||
|
for b in urandom(16): s.add toHex(b.int, 2).toLowerAscii
|
||||||
|
db.exec(sql"INSERT INTO meta VALUES (?,?)", rn, s)
|
||||||
|
secrets[s] = rn
|
||||||
|
invites.add &"{rn} {origin}/join/{s}\n"
|
||||||
|
if rn != "gm":
|
||||||
|
roles[rn] = Role(ver: 0)
|
||||||
|
for r in db.getAllRows(sql"SELECT c FROM exp WHERE role=?", rn): roles[rn].explored.incl parseInt(r[0])
|
||||||
|
echo invites
|
||||||
|
writeFile("run/invites.txt", invites)
|
||||||
|
db.exec(sql"BEGIN")
|
||||||
|
for rn in roles.keys:
|
||||||
|
recompute(rn); persistCells(rn); roles[rn].fresh.setLen 0
|
||||||
|
db.exec(sql"COMMIT")
|
||||||
|
|
||||||
|
loadState()
|
||||||
|
setControlCHook(proc() {.noconv.} =
|
||||||
|
{.gcsafe.}:
|
||||||
|
printStats() # shortcut: reads stats without the lock; fine at exit
|
||||||
|
quit 0)
|
||||||
|
let server = newServer(handler, wsHandler, workerThreads = 8)
|
||||||
|
echo "listening 127.0.0.1:9000"
|
||||||
|
stdout.flushFile
|
||||||
|
server.serve(Port(9000), "127.0.0.1")
|
||||||
|
|||||||
@@ -83,7 +83,8 @@ function render(scene) {
|
|||||||
const HALF = 4
|
const HALF = 4
|
||||||
for (const w of scene.walls) {
|
for (const w of scene.walls) {
|
||||||
const [ax, ay] = w.a, [bx, by] = w.b
|
const [ax, ay] = w.a, [bx, by] = w.b
|
||||||
const col = w.door ? (w.open ? [90, 170, 90] : [150, 80, 30]) : [10, 10, 12]
|
// door look is state-independent: tiles must not reveal or go stale on open/closed
|
||||||
|
const col = w.door ? [150, 80, 30] : [10, 10, 12]
|
||||||
const dx = bx - ax, dy = by - ay, L2 = dx * dx + dy * dy
|
const dx = bx - ax, dy = by - ay, L2 = dx * dx + dy * dy
|
||||||
for (let y = Math.max(0, Math.min(ay, by) - HALF); y <= Math.min(SIZE - 1, Math.max(ay, by) + HALF); y++)
|
for (let y = Math.max(0, Math.min(ay, by) - HALF); y <= Math.min(SIZE - 1, Math.max(ay, by) + HALF); y++)
|
||||||
for (let x = Math.max(0, Math.min(ax, bx) - HALF); x <= Math.min(SIZE - 1, Math.max(ax, bx) + HALF); x++) {
|
for (let x = Math.max(0, Math.min(ax, bx) - HALF); x <= Math.min(SIZE - 1, Math.max(ax, bx) + HALF); x++) {
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
// node tools/smoke.mjs [pos] -- needs server+nginx up. Node 22 WebSocket (undici) accepts {headers}.
|
||||||
|
import fs from 'node:fs'
|
||||||
|
const O = `http://localhost:${process.env.PORT ?? 8080}`
|
||||||
|
const inv = Object.fromEntries(fs.readFileSync(new URL('../run/invites.txt', import.meta.url), 'utf8').trim().split('\n').map(l => l.split(' ')))
|
||||||
|
const ok = (c, m) => { console.log(c ? 'PASS' : 'FAIL', m); if (!c) process.exitCode = 1 }
|
||||||
|
const join = async u => { const r = await fetch(u, { redirect: 'manual' }); return r }
|
||||||
|
const ws = (cookie, ms = 800) => new Promise(res => {
|
||||||
|
const msgs = [], s = new WebSocket(O.replace('http', 'ws') + '/ws', { headers: cookie ? { Cookie: cookie } : {} })
|
||||||
|
s.onmessage = e => msgs.push(JSON.parse(e.data))
|
||||||
|
s.onerror = () => res({ s, msgs, failed: true })
|
||||||
|
setTimeout(() => res({ s, msgs, failed: false }), ms)
|
||||||
|
})
|
||||||
|
const nextAck = (s, reqId) => new Promise(res => s.addEventListener('message', function f(e) { const m = JSON.parse(e.data); if (m.t === 'moveAck' && m.reqId === reqId) { s.removeEventListener('message', f); res(m) } }))
|
||||||
|
|
||||||
|
const r1 = await join(inv.A.replace('A ', ''))
|
||||||
|
const cookie = r1.headers.get('set-cookie')?.split(';')[0]
|
||||||
|
if (process.argv[2] === 'pos') {
|
||||||
|
const a = await ws(cookie); console.log('A pos', a.msgs.find(m => m.t === 'token' && m.id === 'A').pos); process.exit()
|
||||||
|
}
|
||||||
|
ok(r1.status === 302 && /HttpOnly/i.test(r1.headers.get('set-cookie')) && /SameSite=Strict/i.test(r1.headers.get('set-cookie')), 'join A: 302 + HttpOnly SameSite cookie')
|
||||||
|
ok((await join(`${O}/join/deadbeef`)).status === 403, 'bad secret 403')
|
||||||
|
ok((await ws(null)).failed, 'ws without cookie refused')
|
||||||
|
ok((await ws('sid=nope')).failed, 'ws bad cookie refused')
|
||||||
|
const a = await ws(cookie)
|
||||||
|
const types = a.msgs.map(m => m.t)
|
||||||
|
console.log('player A msgs:', types.join(','))
|
||||||
|
ok(types[0] === 'hello' && a.msgs[0].role === 'player' && a.msgs[0].tokens[0] === 'A', 'hello first, player owns A')
|
||||||
|
ok(!types.includes('walls') && !types.includes('door'), 'no walls/door to player')
|
||||||
|
ok(types.includes('vision') && types.includes('explored'), 'vision + explored sent')
|
||||||
|
const toks = a.msgs.filter(m => m.t === 'token')
|
||||||
|
ok(toks.length === 1 && toks[0].id === 'A' && toks[0].mine, 'only own token visible')
|
||||||
|
const get = (p, c = cookie) => fetch(O + p, { headers: { Cookie: c } })
|
||||||
|
const t1 = await get('/tiles/1_1.png'); const b1 = await t1.arrayBuffer()
|
||||||
|
ok(t1.status === 200 && b1.byteLength > 100 && !t1.headers.get('x-accel-redirect'), `explored tile 200, ${b1.byteLength} bytes`)
|
||||||
|
ok((await get('/tiles/15_15.png')).status === 403, 'unexplored tile 403')
|
||||||
|
ok((await fetch(`${O}/tiles/1_1.png`)).status === 403, 'tile without cookie 403')
|
||||||
|
ok((await fetch(`${O}/_tiles/1_1.png`, { headers: { Cookie: cookie } })).status === 404, '/_tiles not reachable directly')
|
||||||
|
ok([400, 404].includes((await get('/tiles/..%2f..%2fscene.json')).status), 'path trick rejected')
|
||||||
|
const gmc = (await join(inv.gm)).headers.get('set-cookie').split(';')[0]
|
||||||
|
ok((await get('/tiles/15_15.png', gmc)).status === 200, 'GM gets any tile')
|
||||||
|
a.s.send(JSON.stringify({ t: 'move', reqId: 1, id: 'B', pos: [1, 1] }))
|
||||||
|
a.s.send(JSON.stringify({ t: 'door', id: 10, open: true }))
|
||||||
|
a.s.send('garbage{')
|
||||||
|
await new Promise(r => setTimeout(r, 300))
|
||||||
|
ok(a.msgs.filter(m => m.t === 'error').length === 3, 'steal/door/garbage -> 3 errors')
|
||||||
|
let p = nextAck(a.s, 2); a.s.send(JSON.stringify({ t: 'move', reqId: 2, id: 'A', pos: [1100, 400] }))
|
||||||
|
ok(!(await p).ok, 'move through wall rejected')
|
||||||
|
p = nextAck(a.s, 3); a.s.send(JSON.stringify({ t: 'move', reqId: 3, id: 'A', pos: [500, 450] }))
|
||||||
|
const ack = await p; ok(ack.ok && ack.pos[0] === 500, 'legal move acked')
|
||||||
|
const g = await ws(gmc)
|
||||||
|
ok(g.msgs.some(m => m.t === 'walls') && !g.msgs.some(m => m.t === 'explored') && g.msgs.filter(m => m.t === 'token').length === 8, 'GM: walls, all 8 tokens, no explored')
|
||||||
|
process.exit()
|
||||||
Reference in New Issue
Block a user