server: hello, one ack per intent, proto check, rate limit, flood, ping (#18)

The protocol shell over the socket, in DESIGN 6.5 order: spend a token, parse, then
unknown type / unnamed player / role / fields / lookup / semantics. Every readable
intent gets exactly one ack with a 6.5 code; an unreadable frame gets one error.

- hello {proto, role, me} as the first frame (n = 1); the scene block lands in slice 5
- /ws?proto=N is required: 400 when absent or not an integer, 101 + closing 4003 on
  a mismatch (no hello, no state)
- intent bucket 30/s burst 100 and the 10-in-10-s malformed flood (closing 1008);
  a rate-limited intent applies nothing and the connection stays open
- mummy maxMessageLen stated explicitly (64 KB) and mummy's own log lines routed
  through the event log instead of stdout
- server Ping(seq) right after hello and every 20 s (lag enforcement stays M5);
  inbound Pings are answered with a Pong, which mummy does not do itself
- close reasons: every server-initiated close sends closing {reason, code} then the
  close frame, and slice 2's eviction/revocation paths do the same (FIXED, #18)
This commit is contained in:
2026-11-15 08:33:07 +01:00
parent 7e2d5b8dc0
commit 88dd27e2cc
+226 -78
View File
@@ -1,21 +1,24 @@
## fff-vtt entrypoint. M3 slice 2 (#17): getting in. Config, state dir + data-dir lock, SQLite ## fff-vtt entrypoint. M3 slice 2 (#17): getting in - config, state dir + data-dir lock, SQLite
## migrations, `fff-vtt gm-key`, `POST /join`, session cookies, and the authenticated `/ws` upgrade ## migrations, `fff-vtt gm-key`, `POST /join`, session cookies, the authenticated `/ws` upgrade
## with connection caps and key/player revocation. Nothing game-specific yet. ## with connection caps and key/player revocation.
## Wire codes/close codes and the rest of the envelope land in slice 3 (#18); this slice carries the ## M3 slice 3 (#18): the WS protocol shell - `hello`, the per-connection `n` counter, exactly one
## minimum ack shape (DESIGN 6.1) for the three intents auth needs: key.create, key.replace, ## `ack` per intent, `error` frames, the intent rate limit, the malformed-flood close, the proto
## player.remove. ## version check, the oversize frame limit (mummy's 64 KB) and the server Ping heartbeat.
## Close reasons (FIXED, owner decision #18): mummy 0.4.8 cannot put a code in the close frame, so
## every server-initiated close is preceded by a `closing {reason, code}` message and the client
## reads 1005 + that message (DESIGN 6.5).
## The listen address is the constant config.BindAddress (127.0.0.1): nginx is the only public face. ## The listen address is the constant config.BindAddress (127.0.0.1): nginx is the only public face.
import std/[json, locks, options, os, strutils] import std/[atomics, json, locks, options, os, strutils]
import std/typedthreads
import db_connector/db_sqlite import db_connector/db_sqlite
import mummy, mummy/routers import mummy, mummy/routers
import config, db, eventlog, crypto, auth, conns, instancelock import config, db, eventlog, crypto, auth, conns, instancelock, protocol
const const
CookieName* = "fff_session" CookieName* = "fff_session"
## FIXED (owner-delegated, #17); DESIGN 6.6 had it PROPOSED. ## FIXED (owner-delegated, #17); DESIGN 6.6 had it PROPOSED.
MaxJoinBody* = 1024 MaxJoinBody* = 1024
## DESIGN 6.6: the sign-in body is at most 1 KB. ## DESIGN 6.6: the sign-in body is at most 1 KB.
ProtoAck* = "ack"
type type
App = ref object App = ref object
@@ -31,6 +34,51 @@ var appHandle: pointer
## (mummy's handler types are non-closure procs, so the state cannot be captured). ## (mummy's handler types are non-closure procs, so the state cannot be captured).
template app(): App = cast[App](appHandle) template app(): App = cast[App](appHandle)
var heartbeatThread: Thread[void]
## The ping thread's handle must outlive the process (a global, not a stack local).
var pingCounter: Atomic[int64]
## Payload of the last server Ping; the client echoes it in its Pong (4.3). Atomic because the
## heartbeat thread and the upgrade handler (a worker thread) both send pings.
proc nextPingSeq(): int64 =
pingCounter.fetchAdd(1) + 1
# ---------------------------------------------------------------------------------------------------
# Frame senders. `n` is the per-connection counter (DESIGN 6): it is allocated under the registry
# lock, so two threads sending to one connection never collide, and a frame is dropped for a
# connection that is gone (nextFrameNo answers 0).
proc nextN(conn: Conn): int =
## 0 = the connection is gone: the frame is dropped.
app.conns.nextFrameNo(conn.id)
proc ackOk(conn: Conn, reqId: int, extra: JsonNode = nil) =
let n = nextN(conn)
if n > 0: conn.ws.send($ackFrame(reqId, n, extra))
proc ackErr(conn: Conn, reqId: int, code: string) =
let n = nextN(conn)
if n > 0: conn.ws.send($nackFrame(reqId, n, code))
proc sendError(conn: Conn, code: string) =
## Only for frames that cannot be acked (DESIGN 6.5).
let n = nextN(conn)
if n > 0: conn.ws.send($errorFrame(code, n))
proc closeRegistered(conn: Conn, reason: string, code: int) =
## A server-initiated close of a live connection: `closing` first (FIXED #18), then the close
## frame. The registry entry goes first so nothing else can be enqueued behind the reason.
let n = nextN(conn)
app.conns.remove(conn.id)
if n > 0: conn.ws.send($closingFrame(reason, code, n))
conn.ws.close()
proc closeGone(conn: Conn, reason: string, code: int) =
## Same, for a connection the registry already dropped (eviction, revocation). The snapshot's
## frame number still closes the sequence correctly.
conn.ws.send($closingFrame(reason, code, conn.frameNo))
conn.ws.close()
# --------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------
# HTTP helpers # HTTP helpers
@@ -69,16 +117,14 @@ proc sessionCookie(request: Request): string =
let p = part.strip let p = part.strip
if p.startsWith(CookieName & "="): return p[CookieName.len + 1 .. ^1] if p.startsWith(CookieName & "="): return p[CookieName.len + 1 .. ^1]
proc ackError(ws: WebSocket, reqId: int, code: string) = proc protoQuery(request: Request): int =
ws.send($(%*{"t": ProtoAck, "reqId": reqId, "ok": false, "code": code})) ## `/ws?proto=N` (DESIGN 6.2). -1 = absent or not a plain integer: HTTP 400, no upgrade (6.5 row 3).
let raw = request.queryParams["proto"]
proc ackOk(ws: WebSocket, reqId: int, extra: JsonNode = newJObject()) = if raw.len == 0 or raw.len > 9 or not raw.allCharsInSet(Digits): return -1
var ack = newJObject() try:
ack["t"] = %ProtoAck result = parseInt(raw)
ack["reqId"] = %reqId except ValueError:
ack["ok"] = %true return -1
for key, value in extra: ack[key] = value
ws.send($ack)
# --------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------
# HTTP handlers # HTTP handlers
@@ -128,7 +174,7 @@ proc join(request: Request) {.gcsafe.} =
request.respond(303, headers) request.respond(303, headers)
proc wsUpgrade(request: Request) {.gcsafe.} = proc wsUpgrade(request: Request) {.gcsafe.} =
## GET /ws: Origin, then session, then the total cap, then the upgrade (DESIGN 6.5 rows 1-4). ## GET /ws: Origin, session, proto, total cap, then the upgrade (DESIGN 6.5 rows 1-5).
if request.headers["Origin"] != app.cfg.publicOrigin: if request.headers["Origin"] != app.cfg.publicOrigin:
request.respond(403, body = "") request.respond(403, body = "")
return return
@@ -144,6 +190,11 @@ proc wsUpgrade(request: Request) {.gcsafe.} =
request.respond(401, body = "") request.respond(401, body = "")
return return
let proto = protoQuery(request)
if proto < 0:
request.respond(400, body = "")
return
if not app.conns.reserve(): if not app.conns.reserve():
var headers: HttpHeaders var headers: HttpHeaders
headers["Retry-After"] = "5" headers["Retry-After"] = "5"
@@ -159,7 +210,19 @@ proc wsUpgrade(request: Request) {.gcsafe.} =
request.respond(400, body = "") request.respond(400, body = "")
return return
let activated = app.conns.activate(player.get.id, player.get.role, ws) if proto != ProtoVersion:
# Row 5: a browser cannot read an HTTP status from a WebSocket, so the upgrade completes and
# the reason arrives as a `closing` message; no `hello`, no state (FIXED #18).
app.conns.cancelReserve()
ws.send($closingFrame(ReasonProtoMismatch, CloseProtoMismatch, 1))
ws.close()
app.lg.log(lvInfo, "conn_refused_proto", [("player", $player.get.id), ("proto", $proto)])
return
let pid = player.get.id
let role = player.get.role
let named = player.get.name.isSome
let activated = app.conns.activate(pid, role, ws, named)
# Close the replacement race: a key.replace between the lookup and the activation must not leave # Close the replacement race: a key.replace between the lookup and the activation must not leave
# a live connection on a revoked session. # a live connection on a revoked session.
var stillValid = false var stillValid = false
@@ -167,56 +230,77 @@ proc wsUpgrade(request: Request) {.gcsafe.} =
stillValid = sessionPlayer(app.db, sha256Hex(token)).isSome stillValid = sessionPlayer(app.db, sha256Hex(token)).isSome
if not stillValid: if not stillValid:
if app.conns.connById(activated.id).isSome: if app.conns.connById(activated.id).isSome:
app.conns.remove(activated.id) let live = app.conns.connById(activated.id).get
ws.close() closeRegistered(live, ReasonRevoked, CloseRevoked)
return return
if activated.evicted.isSome: if activated.evicted.isSome:
activated.evicted.get.close() let doomed = activated.evicted.get
app.lg.log(lvInfo, "conn_evicted", [("player", $player.get.id), closeGone(doomed, ReasonEvicted, CloseEvicted)
("evicted_conn", $activated.evictedId.get)]) app.lg.log(lvInfo, "conn_evicted", [("player", $pid), ("evicted_conn", $doomed.id)])
app.lg.log(lvInfo, "conn_open", [("player", $player.get.id), ("role", $player.get.role), app.lg.log(lvInfo, "conn_open", [("player", $pid), ("role", $role),
("conn", $activated.id), ("total", $app.conns.activeCount)]) ("conn", $activated.id), ("total", $app.conns.activeCount)])
# `hello` is the first frame on the connection (n = 1). The scene block and the resync sequence
# arrive with slice 5; this slice sends proto, role and me (DESIGN 6.1, 6.3). It is queued here,
# before the handler returns, and a browser cannot send anything before it has seen the 101, so
# in practice nothing can overtake it.
let me = if player.get.name.isSome: %player.get.name.get else: newJNull()
let helloN = app.conns.nextFrameNo(activated.id)
ws.send($helloFrame(ProtoVersion, helloN, $role, pid, me))
# One Ping right away, then one every PingIntervalMs: the browser answers without JS (4.3).
ws.send($nextPingSeq(), Ping)
# --------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------
# WebSocket intents needed by this slice. Slice 3 adds the full envelope, error frames, rate limits # Intent pipeline (DESIGN 6.5). Order: parse, rate limit, unknown type, unnamed player, role,
# and unknown-type handling; anything else here is ignored on purpose. # fields, lookup, semantics. Every readable intent gets exactly one `ack`; an unreadable frame gets
# exactly one `error`.
proc handleIntent(conn: Conn, text: string) {.gcsafe.} = proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
var node: JsonNode if not isCatalogueIntent(env.t):
try: ackErr(conn, env.reqId, CodeUnknownType)
node = parseJson(text) return
except CatchableError: if not conn.named and conn.role != prGm and env.t notin ["conn.ping", "player.setname"]:
# An unnamed player may only ping and set their name (DESIGN 6.1 Roles).
ackErr(conn, env.reqId, CodeNotAllowed)
return
if conn.role != prGm and isGmOnlyIntent(env.t):
ackErr(conn, env.reqId, CodeNotAllowed)
return return
if node.kind != JObject: return
let t = node{"t"}
let reqIdNode = node{"reqId"}
if t.kind != JString or reqIdNode.kind != JInt: return
let reqId = reqIdNode.getInt
case t.getStr case env.t
of "key.create": of "conn.ping":
if conn.role != prGm: let ts = env.node{"ts"}
ackError(conn.ws, reqId, "not-allowed") if ts.isNil or ts.kind != JInt:
ackErr(conn, env.reqId, CodeInvalid)
return return
ackOk(conn, env.reqId, %*{"ts": ts.getInt})
return
of "act.do":
# Reserved for the FFF hook (DESIGN 9): always refused, never ok. Its fields are not validated
# in M3 because the answer is the same for every readable envelope; the hook's field schema is
# part of the FFF work (9).
ackErr(conn, env.reqId, CodeNoRules)
return
of "key.create":
var created: tuple[id: int, key: string] var created: tuple[id: int, key: string]
var capped = false var capped = false
withLock app.dbLock: withLock app.dbLock:
capped = playerCount(app.db) >= MaxPlayers capped = playerCount(app.db) >= MaxPlayers
if not capped: created = createPlayerWithKey(app.db) if not capped: created = createPlayerWithKey(app.db)
if capped: if capped:
ackError(conn.ws, reqId, "cap-reached") ackErr(conn, env.reqId, CodeCapReached)
return return
app.lg.addSecret(created.key) app.lg.addSecret(created.key)
app.lg.log(lvInfo, "key_created", [("player", $created.id)]) app.lg.log(lvInfo, "key_created", [("player", $created.id)])
ackOk(conn.ws, reqId, %*{"id": created.id, "key": created.key}) ackOk(conn, env.reqId, %*{"id": created.id, "key": created.key})
return
of "key.replace": of "key.replace":
if conn.role != prGm: let idNode = env.node{"id"}
ackError(conn.ws, reqId, "not-allowed") if idNode.isNil or idNode.kind != JInt:
return ackErr(conn, env.reqId, CodeInvalid)
let idNode = node{"id"}
if idNode.kind != JInt:
ackError(conn.ws, reqId, "invalid")
return return
let id = idNode.getInt let id = idNode.getInt
var key: Option[string] var key: Option[string]
@@ -231,27 +315,25 @@ proc handleIntent(conn: Conn, text: string) {.gcsafe.} =
else: else:
key = replacePlayerKey(app.db, id) key = replacePlayerKey(app.db, id)
if notFound: if notFound:
ackError(conn.ws, reqId, "not-found") ackErr(conn, env.reqId, CodeNotFound)
return return
if notAllowed: if notAllowed:
ackError(conn.ws, reqId, "not-allowed") ackErr(conn, env.reqId, CodeNotAllowed)
return return
if key.isNone: if key.isNone:
ackError(conn.ws, reqId, "not-found") ackErr(conn, env.reqId, CodeNotFound)
return return
let closed = app.conns.revokePlayer(id) let closed = app.conns.revokePlayer(id)
for ws in closed: ws.close() for doomed in closed: closeGone(doomed, ReasonRevoked, CloseRevoked)
app.lg.addSecret(key.get) app.lg.addSecret(key.get)
app.lg.log(lvInfo, "key_replaced", [("player", $id), ("conns_closed", $closed.len)]) app.lg.log(lvInfo, "key_replaced", [("player", $id), ("conns_closed", $closed.len)])
ackOk(conn.ws, reqId, %*{"key": key.get}) ackOk(conn, env.reqId, %*{"key": key.get})
return
of "player.remove": of "player.remove":
if conn.role != prGm: let idNode = env.node{"id"}
ackError(conn.ws, reqId, "not-allowed") if idNode.isNil or idNode.kind != JInt:
return ackErr(conn, env.reqId, CodeInvalid)
let idNode = node{"id"}
if idNode.kind != JInt:
ackError(conn.ws, reqId, "invalid")
return return
let id = idNode.getInt let id = idNode.getInt
var removed = false var removed = false
@@ -266,38 +348,91 @@ proc handleIntent(conn: Conn, text: string) {.gcsafe.} =
else: else:
removed = removePlayer(app.db, id) removed = removePlayer(app.db, id)
if notFound: if notFound:
ackError(conn.ws, reqId, "not-found") ackErr(conn, env.reqId, CodeNotFound)
return return
if notAllowed: if notAllowed:
ackError(conn.ws, reqId, "not-allowed") ackErr(conn, env.reqId, CodeNotAllowed)
return return
if not removed: if not removed:
ackError(conn.ws, reqId, "not-found") ackErr(conn, env.reqId, CodeNotFound)
return return
let closed = app.conns.revokePlayer(id) let closed = app.conns.revokePlayer(id)
for ws in closed: ws.close() for doomed in closed: closeGone(doomed, ReasonRevoked, CloseRevoked)
app.lg.log(lvInfo, "player_removed", [("player", $id), ("conns_closed", $closed.len)]) app.lg.log(lvInfo, "player_removed", [("player", $id), ("conns_closed", $closed.len)])
ackOk(conn.ws, reqId) ackOk(conn, env.reqId)
return
else: else:
discard # slice 3 answers unknown-type; this slice only carries the auth intents # A catalogue intent whose slice has not landed yet (#19-#25). It still gets its one ack, with
# a static code and no state; `unknown-type` is the honest answer until the handler exists
# (DESIGN 6.1, slice-3 note).
ackErr(conn, env.reqId, CodeUnknownType)
proc malformedFrame(conn: Conn, nowMs: int64) {.gcsafe.} =
## DESIGN 6.5 step 2 / row 8: one `error malformed`, and the tenth inside 10 s closes with 1008.
if app.conns.recordMalformed(conn.id, nowMs):
closeRegistered(conn, ReasonMalformedFlood, CloseMalformedFlood)
app.lg.log(lvWarn, "conn_malformed_flood", [("player", $conn.playerId), ("conn", $conn.id)])
else:
sendError(conn, CodeMalformed)
proc handleText(conn: Conn, text: string) {.gcsafe.} =
## DESIGN 6.5 steps 2 and 3: the bucket is spent by every inbound frame, readable or not.
let nowMs = monotonicMs()
let allowed = app.conns.takeIntentToken(conn.id, nowMs)
let env = parseEnvelope(text)
if not allowed:
if env.ok: ackErr(conn, env.reqId, CodeRateLimited)
else: sendError(conn, CodeRateLimited)
return
if not env.ok:
malformedFrame(conn, nowMs)
return
dispatch(conn, env)
proc websocketEvent(ws: WebSocket, event: WebSocketEvent, message: Message) {.gcsafe.} = proc websocketEvent(ws: WebSocket, event: WebSocketEvent, message: Message) {.gcsafe.} =
case event case event
of MessageEvent: of MessageEvent:
let conn = app.conns.connForWs(ws) let found = app.conns.connForWs(ws)
if conn.isNone: return if found.isNone: return
if message.kind == TextMessage: let conn = found.get
handleIntent(conn.get, message.data) case message.kind
of TextMessage:
handleText(conn, message.data)
of BinaryMessage:
# DESIGN 6: a binary frame counts as malformed.
malformedFrame(conn, monotonicMs())
of Ping:
# mummy does not answer client Pings itself; RFC 6455 requires a Pong with the same payload.
ws.send(message.data, Pong)
of Pong:
var seqNo: int64
try:
seqNo = int64(parseInt(message.data))
except ValueError:
seqNo = -1
app.conns.notePong(conn.id, seqNo, monotonicMs())
of CloseEvent, ErrorEvent: of CloseEvent, ErrorEvent:
let conn = app.conns.connForWs(ws) let found = app.conns.connForWs(ws)
if conn.isSome: if found.isSome:
app.conns.remove(conn.get.id) app.conns.remove(found.get.id)
app.lg.log(lvDebug, "conn_close", [("player", $conn.get.playerId), app.lg.log(lvDebug, "conn_close", [("player", $found.get.playerId),
("conn", $conn.get.id)]) ("conn", $found.get.id)])
else: else:
discard discard
# ---------------------------------------------------------------------------------------------------
# Heartbeat: a Ping every PingIntervalMs on every connection. Lag measurement and the stop-feeding
# rule are M5 (4.3); here the seq is only recorded when the Pong comes back.
proc heartbeat() {.thread.} =
while true:
sleep(PingIntervalMs)
if appHandle == nil: continue # no App yet: nothing to ping
let payload = $nextPingSeq()
for conn in app().conns.snapshot():
conn.ws.send(payload, Ping)
# --------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------
# Startup and CLI # Startup and CLI
@@ -327,6 +462,14 @@ Commands:
The bind address is fixed at 127.0.0.1 and is not a key: put nginx (or another TLS proxy) in front. The bind address is fixed at 127.0.0.1 and is not a key: put nginx (or another TLS proxy) in front.
""" """
proc mummyLog(level: LogLevel, args: varargs[string]) {.gcsafe.} =
## mummy's own lines (dropped oversize frame, bad frame) go through the event log, so nothing
## writes to stdout behind the logger's back (DESIGN 11.3). Details ride at debug level.
if appHandle == nil: return
var text = ""
for arg in args: text.add arg
app().lg.log(if level == ErrorLevel: lvWarn else: lvDebug, "mummy", [("msg", text)])
proc runGmKey(rawArgs: seq[string]): int = proc runGmKey(rawArgs: seq[string]): int =
var rotate = false var rotate = false
var cfgArgs: seq[string] var cfgArgs: seq[string]
@@ -416,7 +559,12 @@ proc runServer(cfg: Config): int =
readRedactionSecrets(conn, lg) readRedactionSecrets(conn, lg)
appHandle = cast[pointer](state) appHandle = cast[pointer](state)
let server = newServer(buildRouter().toHandler(), websocketEvent) createThread(heartbeatThread, heartbeat)
lg.log(lvInfo, "heartbeat", [("interval_ms", $PingIntervalMs), ("proto", $ProtoVersion)])
# maxMessageLen is DESIGN 6.4's 64 KB, stated explicitly rather than inherited from mummy.
let server = newServer(buildRouter().toHandler(), websocketEvent, mummyLog,
maxMessageLen = MaxInboundBytes)
lg.log(lvInfo, "listen", [("addr", BindAddress), ("port", $cfg.port)]) lg.log(lvInfo, "listen", [("addr", BindAddress), ("port", $cfg.port)])
server.serve(Port(cfg.port), BindAddress) server.serve(Port(cfg.port), BindAddress)
0 0