Files
FFF_vtt_frozen/server/main.nim
T

442 lines
15 KiB
Nim

## 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
## with connection caps and key/player revocation. Nothing game-specific yet.
## Wire codes/close codes and the rest of the envelope land in slice 3 (#18); this slice carries the
## minimum ack shape (DESIGN 6.1) for the three intents auth needs: key.create, key.replace,
## player.remove.
## 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 db_connector/db_sqlite
import mummy, mummy/routers
import config, db, eventlog, crypto, auth, conns, instancelock
const
CookieName* = "fff_session"
## FIXED (owner-delegated, #17); DESIGN 6.6 had it PROPOSED.
MaxJoinBody* = 1024
## DESIGN 6.6: the sign-in body is at most 1 KB.
ProtoAck* = "ack"
type
App = ref object
cfg: Config
lg: Logger
db: DbConn
dbLock: Lock
conns: Conns
instanceLock: InstanceLock
var appHandle: pointer
## The one App for the process. A plain pointer keeps worker-thread handlers `{.gcsafe.}`
## (mummy's handler types are non-closure procs, so the state cannot be captured).
template app(): App = cast[App](appHandle)
# ---------------------------------------------------------------------------------------------------
# HTTP helpers
proc formValue(body, name: string): string =
## application/x-www-form-urlencoded: first value of `name`, percent-decoded, '+' = space.
for pair in body.split('&'):
let eq = pair.find('=')
let rawName = if eq >= 0: pair[0 ..< eq] else: pair
if rawName != name: continue
let raw = if eq >= 0: pair[eq + 1 .. ^1] else: ""
result = ""
var i = 0
while i < raw.len:
if raw[i] == '+':
result.add ' '
inc i
elif raw[i] == '%' and i + 2 < raw.len:
let hex = raw[i + 1 .. i + 2]
try:
result.add char(parseHexInt(hex))
except ValueError:
result.add raw[i]
inc i
continue
i += 3
else:
result.add raw[i]
inc i
return
proc sessionCookie(request: Request): string =
## First `fff_session` cookie across all Cookie headers (mummy's [] returns only the first header).
for (name, value) in request.headers:
if name.toLowerAscii != "cookie": continue
for part in value.split(';'):
let p = part.strip
if p.startsWith(CookieName & "="): return p[CookieName.len + 1 .. ^1]
proc ackError(ws: WebSocket, reqId: int, code: string) =
ws.send($(%*{"t": ProtoAck, "reqId": reqId, "ok": false, "code": code}))
proc ackOk(ws: WebSocket, reqId: int, extra: JsonNode = newJObject()) =
var ack = newJObject()
ack["t"] = %ProtoAck
ack["reqId"] = %reqId
ack["ok"] = %true
for key, value in extra: ack[key] = value
ws.send($ack)
# ---------------------------------------------------------------------------------------------------
# HTTP handlers
proc healthz(request: Request) {.gcsafe.} =
## Liveness only in this slice. M5 makes it report the global lock as well (DESIGN 11.3).
var headers: HttpHeaders
headers["Content-Type"] = "application/json"
request.respond(200, headers, """{"status":"ok"}""")
proc join(request: Request) {.gcsafe.} =
## POST /join: the only way to get a session (DESIGN 3.2, 6.6). The key travels in the body only.
let contentType = request.headers["Content-Type"].toLowerAscii
if not contentType.startsWith("application/x-www-form-urlencoded"):
request.respond(400, body = "")
return
if request.body.len > MaxJoinBody:
request.respond(400, body = "")
return
let key = formValue(request.body, "key")
if key.len == 0 or key.len > MaxJoinBody:
request.respond(400, body = "")
return
var player: Option[Player]
var token = ""
withLock app.dbLock:
player = findPlayerByKey(app.db, key)
if player.isSome:
token = randomSessionToken()
createSession(app.db, player.get.id, sha256Hex(token))
if player.isNone:
# No key, no body, no detail: a wrong key and an unknown key look the same (T9 discipline).
app.lg.log(lvInfo, "join_refused")
request.respond(401, body = "")
return
# The token is deliberately never registered for redaction: sessions never expire, so a value
# registry would grow without bound. It is only ever written to the Set-Cookie header; if a future
# call site passes it to the logger, the `cookie`/`session` field-name mask is the net (11.3).
app.lg.log(lvInfo, "join_ok", [("player", $player.get.id)])
var headers: HttpHeaders
headers["Location"] = "/"
headers["Set-Cookie"] = CookieName & "=" & token &
"; HttpOnly; Secure; SameSite=Strict; Path=/"
headers["Referrer-Policy"] = "no-referrer"
request.respond(303, headers)
proc wsUpgrade(request: Request) {.gcsafe.} =
## GET /ws: Origin, then session, then the total cap, then the upgrade (DESIGN 6.5 rows 1-4).
if request.headers["Origin"] != app.cfg.publicOrigin:
request.respond(403, body = "")
return
let token = sessionCookie(request)
if token.len == 0:
request.respond(401, body = "")
return
var player: Option[Player]
withLock app.dbLock:
player = sessionPlayer(app.db, sha256Hex(token))
if player.isNone:
request.respond(401, body = "")
return
if not app.conns.reserve():
var headers: HttpHeaders
headers["Retry-After"] = "5"
app.lg.log(lvInfo, "conn_refused_total", [("player", $player.get.id)])
request.respond(503, headers, body = "")
return
var ws: WebSocket
try:
ws = request.upgradeToWebSocket()
except MummyError:
app.conns.cancelReserve()
request.respond(400, body = "")
return
let activated = app.conns.activate(player.get.id, player.get.role, ws)
# Close the replacement race: a key.replace between the lookup and the activation must not leave
# a live connection on a revoked session.
var stillValid = false
withLock app.dbLock:
stillValid = sessionPlayer(app.db, sha256Hex(token)).isSome
if not stillValid:
if app.conns.connById(activated.id).isSome:
app.conns.remove(activated.id)
ws.close()
return
if activated.evicted.isSome:
activated.evicted.get.close()
app.lg.log(lvInfo, "conn_evicted", [("player", $player.get.id),
("evicted_conn", $activated.evictedId.get)])
app.lg.log(lvInfo, "conn_open", [("player", $player.get.id), ("role", $player.get.role),
("conn", $activated.id), ("total", $app.conns.activeCount)])
# ---------------------------------------------------------------------------------------------------
# WebSocket intents needed by this slice. Slice 3 adds the full envelope, error frames, rate limits
# and unknown-type handling; anything else here is ignored on purpose.
proc handleIntent(conn: Conn, text: string) {.gcsafe.} =
var node: JsonNode
try:
node = parseJson(text)
except CatchableError:
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
of "key.create":
if conn.role != prGm:
ackError(conn.ws, reqId, "not-allowed")
return
var created: tuple[id: int, key: string]
var capped = false
withLock app.dbLock:
capped = playerCount(app.db) >= MaxPlayers
if not capped: created = createPlayerWithKey(app.db)
if capped:
ackError(conn.ws, reqId, "cap-reached")
return
app.lg.addSecret(created.key)
app.lg.log(lvInfo, "key_created", [("player", $created.id)])
ackOk(conn.ws, reqId, %*{"id": created.id, "key": created.key})
of "key.replace":
if conn.role != prGm:
ackError(conn.ws, reqId, "not-allowed")
return
let idNode = node{"id"}
if idNode.kind != JInt:
ackError(conn.ws, reqId, "invalid")
return
let id = idNode.getInt
var key: Option[string]
var notFound = false
var notAllowed = false
withLock app.dbLock:
let target = playerById(app.db, id)
if target.isNone:
notFound = true
elif target.get.role == prGm:
notAllowed = true # the GM's own key rotates only through the CLI (DESIGN 3.2)
else:
key = replacePlayerKey(app.db, id)
if notFound:
ackError(conn.ws, reqId, "not-found")
return
if notAllowed:
ackError(conn.ws, reqId, "not-allowed")
return
if key.isNone:
ackError(conn.ws, reqId, "not-found")
return
let closed = app.conns.revokePlayer(id)
for ws in closed: ws.close()
app.lg.addSecret(key.get)
app.lg.log(lvInfo, "key_replaced", [("player", $id), ("conns_closed", $closed.len)])
ackOk(conn.ws, reqId, %*{"key": key.get})
of "player.remove":
if conn.role != prGm:
ackError(conn.ws, reqId, "not-allowed")
return
let idNode = node{"id"}
if idNode.kind != JInt:
ackError(conn.ws, reqId, "invalid")
return
let id = idNode.getInt
var removed = false
var notFound = false
var notAllowed = false
withLock app.dbLock:
let target = playerById(app.db, id)
if target.isNone:
notFound = true
elif target.get.role == prGm:
notAllowed = true
else:
removed = removePlayer(app.db, id)
if notFound:
ackError(conn.ws, reqId, "not-found")
return
if notAllowed:
ackError(conn.ws, reqId, "not-allowed")
return
if not removed:
ackError(conn.ws, reqId, "not-found")
return
let closed = app.conns.revokePlayer(id)
for ws in closed: ws.close()
app.lg.log(lvInfo, "player_removed", [("player", $id), ("conns_closed", $closed.len)])
ackOk(conn.ws, reqId)
else:
discard # slice 3 answers unknown-type; this slice only carries the auth intents
proc websocketEvent(ws: WebSocket, event: WebSocketEvent, message: Message) {.gcsafe.} =
case event
of MessageEvent:
let conn = app.conns.connForWs(ws)
if conn.isNone: return
if message.kind == TextMessage:
handleIntent(conn.get, message.data)
of CloseEvent, ErrorEvent:
let conn = app.conns.connForWs(ws)
if conn.isSome:
app.conns.remove(conn.get.id)
app.lg.log(lvDebug, "conn_close", [("player", $conn.get.playerId),
("conn", $conn.get.id)])
else:
discard
# ---------------------------------------------------------------------------------------------------
# Startup and CLI
proc buildRouter(): Router =
result.get("/healthz", healthz)
result.post("/join", join)
result.get("/ws", wsUpgrade)
proc cliUsage(): string =
"""fff-vtt - server-authoritative vision VTT
Usage: fff-vtt [options]
fff-vtt gm-key [--new] [options]
Options:
--public-origin=<url> Browser origin the site is served from (default: http://localhost:8080).
Env: FFF_VTT_PUBLIC_ORIGIN
--port=<n> Listen port, 1..65535 (default: 9000). Env: FFF_VTT_PORT
--state-dir=<path> Directory holding state.db (default: run). Env: FFF_VTT_STATE_DIR
-h, --help Print this help and exit.
Commands:
gm-key Create the single GM if needed and print the GM key (same key on re-run).
gm-key --new Rotate the GM key and revoke all GM sessions. Refused while the server
holds the state-dir lock (stop the server first).
The bind address is fixed at 127.0.0.1 and is not a key: put nginx (or another TLS proxy) in front.
"""
proc runGmKey(rawArgs: seq[string]): int =
var rotate = false
var cfgArgs: seq[string]
for arg in rawArgs:
if arg == "--new": rotate = true
else: cfgArgs.add arg
var cfg: Config
try:
cfg = parseConfig(cfgArgs)
except ConfigError as e:
stderr.writeLine "fff-vtt gm-key: " & e.msg
return 2
if cfg.help:
stdout.write cliUsage()
return 0
try:
createDir(cfg.stateDir)
except CatchableError as e:
stderr.writeLine "fff-vtt gm-key: cannot create " & cfg.stateDir & ": " & e.msg
return 1
var lock: InstanceLock
if rotate:
lock = tryAcquire(cfg.stateDir)
if not lock.held:
stderr.writeLine "fff-vtt gm-key --new: the server is running on " & cfg.stateDir &
" (state-dir lock held); stop it first"
return 3
var conn: DbConn
try:
conn = openDatabase(cfg.dbPath)
except CatchableError as e:
stderr.writeLine "fff-vtt gm-key: cannot open " & cfg.dbPath & ": " & e.msg
return 1
defer: close(conn)
try:
discard migrate(conn)
let created = ensureGm(conn, rotate)
if created.rotated:
stdout.writeLine "GM key (new): " & created.key
else:
stdout.writeLine "GM key: " & created.key
stdout.flushFile()
except CatchableError as e:
stderr.writeLine "fff-vtt gm-key: " & e.msg
return 1
0
proc readRedactionSecrets(db: DbConn, lg: Logger) =
## The safety net behind "never log keys": register every stored key for redaction.
for row in db.getAllRows(sql"SELECT secret FROM player_key"):
if row.len > 0 and row[0].len >= MinSecretLen:
try: lg.addSecret(row[0])
except ValueError: discard
proc runServer(cfg: Config): int =
let lg = newLogger()
lg.log(lvInfo, "server_start", [("origin", cfg.publicOrigin), ("state_dir", cfg.stateDir),
("bind", BindAddress)])
try:
createDir(cfg.stateDir)
except CatchableError as e:
lg.log(lvError, "state_dir_failed", [("path", cfg.stateDir), ("error", e.msg)])
return 1
var instanceLock = tryAcquire(cfg.stateDir)
if not instanceLock.held:
lg.log(lvError, "state_dir_locked", [("path", cfg.stateDir)])
return 1
var conn: DbConn
try:
conn = openDatabase(cfg.dbPath)
except CatchableError as e:
lg.log(lvError, "db_open_failed", [("path", cfg.dbPath), ("error", e.msg)])
return 1
let applied = try: migrate(conn)
except CatchableError as e:
lg.log(lvError, "db_migrate_failed", [("path", cfg.dbPath), ("error", e.msg)])
return 1
lg.log(lvInfo, "db_ready", [("path", cfg.dbPath), ("schema_version", $schemaVersion(conn)),
("applied", $applied)])
let state = App(cfg: cfg, lg: lg, db: conn, conns: newConns(), instanceLock: instanceLock)
initLock(state.dbLock)
readRedactionSecrets(conn, lg)
appHandle = cast[pointer](state)
let server = newServer(buildRouter().toHandler(), websocketEvent)
lg.log(lvInfo, "listen", [("addr", BindAddress), ("port", $cfg.port)])
server.serve(Port(cfg.port), BindAddress)
0
proc main() =
let args = commandLineParams()
if args.len > 0 and args[0] == "gm-key":
quit runGmKey(if args.len > 1: args[1 .. ^1] else: @[])
var cfg: Config
try:
cfg = parseConfig(args)
except ConfigError as e:
stderr.writeLine "fff-vtt: " & e.msg
quit 2
if cfg.help:
stdout.write cliUsage()
quit 0
quit runServer(cfg)
when isMainModule:
main()