diff --git a/server/protocol.nim b/server/protocol.nim new file mode 100644 index 0000000..99c5e90 --- /dev/null +++ b/server/protocol.nim @@ -0,0 +1,216 @@ +## The wire protocol shell (DESIGN 6, 6.2, 6.4, 6.5; M3 slice 3, issue #18). +## Pure, mummy-free logic: the frame catalogue answers, the envelope rules, the intent rate +## limiter and the malformed-flood window. main.nim only wires these to sockets. +## +## Numbers here are FIXED (owner-delegated, #15/#18) and mirrored in DESIGN: +## max inbound message 64 KB (mummy's own default, inbound only), intent bucket 30/s with a +## burst of 100 per connection, 10 malformed frames inside any 10 s close the connection. +## +## Close codes (DESIGN 6.5): mummy 0.4.8's `close(ws)` sends an EMPTY close frame, so a browser +## reports 1005 and the application codes 4001/4002/4003 cannot ride the close frame. Owner +## decision (#18, option A): the server sends one final `closing {reason, code}` message and then +## closes; the client reads the reason from that message and 1005 from the close event. +import std/[json, monotimes, unicode] + +const + ProtoVersion* = 1 + ## M3 ships proto 1 (DESIGN 6.2). The client announces it as `/ws?proto=N`. + MaxInboundBytes* = 64 * 1024 + ## DESIGN 6.4: mummy's `maxMessageLen`, inbound and cumulative across fragments. + RatePerSecond* = 30 + ## DESIGN 6.4: intents per second sustained, per connection, same for GM and players. + RateBurst* = 100 + ## DESIGN 6.4: bucket size; a burst of 100 is free, then 30/s. + MalformedFloodLimit* = 10 + ## DESIGN 6.5 row 8: this many malformed frames inside the window closes with 1008. + MalformedFloodWindowMs* = 10_000 + PingIntervalMs* = 20_000 + ## FIXED (owner-delegated, #18): the server pings every 20 s (a browser answers by itself). + ## Lag tracking and stop-feeding-on-no-pong stay M5 (DESIGN 4.3); this slice only keeps the + ## connection warm and gives the harness a frame to see. + MaxReqId* = (1 shl 31) - 1 + ## DESIGN 6: 0 <= reqId < 2^31. + + # Connection-level outcomes (DESIGN 6.5). The values are the app's range 4001-4003 plus the + # RFC 6455 standard 1008; they travel in `closing.code`, not in the close frame. + CloseRevoked* = 4001 + CloseEvicted* = 4002 + CloseProtoMismatch* = 4003 + CloseMalformedFlood* = 1008 + + # The static reason strings of 6.5, one per outcome. Never carry state. + ReasonRevoked* = "revoked" + ReasonEvicted* = "evicted" + ReasonProtoMismatch* = "proto-mismatch" + ReasonMalformedFlood* = "malformed-flood" + + # Ack / error codes (DESIGN 6.5, static strings, never carry state). + CodeRateLimited* = "rate-limited" + CodeUnknownType* = "unknown-type" + CodeNotAllowed* = "not-allowed" + CodeNotFound* = "not-found" + CodeInvalid* = "invalid" + CodeNameTaken* = "name-taken" + CodeCapReached* = "cap-reached" + CodeInUse* = "in-use" + CodeNoRules* = "no-rules" + CodeMalformed* = "malformed" + + # The complete M3 intent catalogue (DESIGN 6.1: 29 intents). A name in here but not yet built + # by its slice still gets exactly one ack; see `isImplementedIntent`. + IntentCatalogue* = [ + "conn.ping", "act.do", + "player.setname", "player.rename", "player.remove", + "key.create", "key.replace", "key.show", + "scene.set", "wall.add", "wall.update", "wall.remove", "door.set", + "token.create", "token.update", "token.move", "token.resize", "token.remove", + "status.set", "status.clear", "prop.set", "prop.unset", + "character.create", "character.update", "character.remove", "character.reassign", + "name.reveal", "name.reveal_all", "encountered.remove", + ] + ## 2 + 6 + 5 + 9 + 7 = 29 (DESIGN 6.1). + + GmOnlyIntents* = [ + "player.rename", "player.remove", "key.create", "key.replace", "key.show", + "scene.set", "wall.add", "wall.update", "wall.remove", "door.set", + "token.create", "token.update", "token.resize", "token.remove", + "status.set", "status.clear", "prop.set", "prop.unset", + "character.create", "character.update", "character.remove", "character.reassign", + "name.reveal", "name.reveal_all", "encountered.remove", + ] + + ImplementedIntents* = ["conn.ping", "act.do", "key.create", "key.replace", "player.remove"] + ## What this slice actually handles. The rest of the catalogue answers `unknown-type` until + ## its slice lands (DESIGN 6.1 note, #18). + +type + Envelope* = object + ok*: bool + ## false = the frame cannot be acked: it gets `error malformed` (DESIGN 6.5 step 2). + t*: string + reqId*: int + node*: JsonNode + + RateLimiter* = object + ## Token bucket per connection (DESIGN 6.4). `nowMs` is injected so tests need no clock. + tokens*: float + burst*: float + perSecond*: float + lastMs*: int64 + ## -1 = never used, so the first intent fills nothing and costs one token. + + FloodWindow* = object + ## Ring of the last MalformedFloodLimit malformed-frame timestamps (DESIGN 6.5 row 8). + times*: array[MalformedFloodLimit, int64] + count*: int + next*: int + +proc monotonicMs*(): int64 = + getMonoTime().ticks div 1_000_000 + +# --------------------------------------------------------------------------------------------------- +# Envelope (DESIGN 6, 6.5 step 2) + +proc parseEnvelope*(text: string): Envelope = + ## A readable intent: UTF-8 text, a JSON object, a string `t` and an integer `reqId` in range. + ## Anything else is "malformed": no reqId can be echoed, so the reply is an `error` frame. + if validateUtf8(text) != -1: return + var node: JsonNode + try: + node = parseJson(text) + except CatchableError: + return + if node.isNil or node.kind != JObject: return # parseJson("") yields nil, not an exception + let t = node{"t"} + let reqIdNode = node{"reqId"} + if t.isNil or reqIdNode.isNil: return + if t.kind != JString or reqIdNode.kind != JInt: return + let reqId = reqIdNode.getInt + if reqId < 0 or reqId > MaxReqId: return + Envelope(ok: true, t: t.getStr, reqId: reqId, node: node) + +proc isCatalogueIntent*(t: string): bool = + t in IntentCatalogue + +proc isGmOnlyIntent*(t: string): bool = + t in GmOnlyIntents + +proc isImplementedIntent*(t: string): bool = + t in ImplementedIntents + +# --------------------------------------------------------------------------------------------------- +# Server -> client frames (DESIGN 6.1). Every frame carries `n`, the per-connection counter: +# starts at 1 on the connection's first frame and counts server frames only. + +proc withN*(node: JsonNode, n: int): JsonNode = + result = node + result["n"] = %n + +proc helloFrame*(proto, n: int, role: string, playerId: int, name: JsonNode): JsonNode = + ## DESIGN 6.1 `hello`. The `scene` block and the world fields arrive with slice 5; M3 slice 3 + ## sends what exists: proto, role, me. + var me = newJObject() + me["id"] = %playerId + me["name"] = name # null while the player has no name yet + result = %*{"t": "hello", "proto": proto, "role": role, "me": me, "n": n} + +proc ackFrame*(reqId, n: int, extra: JsonNode = nil): JsonNode = + ## `ack {reqId, ok:true, ...result fields}`; `extra` holds `id`, `key`, `pos`, `ts`. + result = %*{"t": "ack", "reqId": reqId, "ok": true} + if not extra.isNil: + for key, value in extra: result[key] = value + result["n"] = %n + +proc nackFrame*(reqId, n: int, code: string): JsonNode = + ## `ack {reqId, ok:false, code}`: a static code, never state (T9). + %*{"t": "ack", "reqId": reqId, "ok": false, "code": code, "n": n} + +proc nackMoveFrame*(reqId, n: int, x, y: float): JsonNode = + ## The uniform move refusal of DESIGN 5.5/T9: `ok:false, pos` and NO code. Unused until + ## slice 5's `token.move`; kept with the frame builders so the shape has one definition. + %*{"t": "ack", "reqId": reqId, "ok": false, "pos": [x, y], "n": n} + +proc errorFrame*(code: string, n: int): JsonNode = + ## `error {code}`: only `malformed` and `rate-limited`, only for frames with no readable reqId. + %*{"t": "error", "code": code, "n": n} + +proc closingFrame*(reason: string, code, n: int): JsonNode = + ## The last frame before a server-initiated close (DESIGN 6.5, FIXED #18): it carries the + ## reason and the code the close frame cannot carry at the mummy pin. + %*{"t": "closing", "reason": reason, "code": code, "n": n} + +# --------------------------------------------------------------------------------------------------- +# Intent rate limit (DESIGN 6.4) + +proc newRateLimiter*(perSecond = RatePerSecond, burst = RateBurst): RateLimiter = + RateLimiter(tokens: float(burst), burst: float(burst), perSecond: float(perSecond), lastMs: -1) + +proc allow*(r: var RateLimiter, nowMs: int64): bool = + ## Takes one token if the bucket has one. Refill is continuous and capped at the burst size. + if r.lastMs < 0: + r.lastMs = nowMs + else: + let elapsed = nowMs - r.lastMs + if elapsed > 0: + r.tokens = min(r.burst, r.tokens + float(elapsed) * r.perSecond / 1000.0) + r.lastMs = nowMs + if r.tokens >= 1.0: + r.tokens -= 1.0 + return true + false + +proc available*(r: RateLimiter): float = + r.tokens + +# --------------------------------------------------------------------------------------------------- +# Malformed flood (DESIGN 6.5 row 8) + +proc recordMalformed*(f: var FloodWindow, nowMs: int64): bool = + ## Records one malformed frame; true = the flood rule fires now (10 inside any 10 s). + ## The counter is a ring of the last 10 timestamps: the frame that overwrites the oldest still + ## inside the window is the one that trips the limit, so the 10th malformed frame closes. + f.times[f.next] = nowMs + f.next = (f.next + 1) mod MalformedFloodLimit + if f.count < MalformedFloodLimit: inc f.count + let oldest = f.times[f.next] + result = f.count >= MalformedFloodLimit and (nowMs - oldest) <= MalformedFloodWindowMs diff --git a/tests/tprotocol.nim b/tests/tprotocol.nim new file mode 100644 index 0000000..2c42743 --- /dev/null +++ b/tests/tprotocol.nim @@ -0,0 +1,189 @@ +## Wire protocol shell unit tests (#18, DESIGN 6, 6.2, 6.4, 6.5). Pure logic, no sockets: +## the black-box behaviour over a real socket lives in tools/protocol.test.mjs. +import std/[json, unittest] +import protocol + +suite "envelope (6.5 step 2)": + test "a well-formed intent parses and keeps its reqId and node": + let e = parseEnvelope("""{"t":"conn.ping","reqId":7,"ts":123}""") + check e.ok + check e.t == "conn.ping" + check e.reqId == 7 + check e.node{"ts"}.getInt == 123 + + test "reqId boundaries: 0 and 2^31-1 pass, 2^31 and -1 are malformed": + check parseEnvelope("""{"t":"conn.ping","reqId":0}""").reqId == 0 + check parseEnvelope("""{"t":"conn.ping","reqId":2147483647}""").reqId == MaxReqId + check not parseEnvelope("""{"t":"conn.ping","reqId":2147483648}""").ok + check not parseEnvelope("""{"t":"conn.ping","reqId":-1}""").ok + + test "every unreadable frame is malformed, never an ack": + for text in [ + "", # empty + "not json", # not JSON + "[1,2,3]", # not an object + "123", # not an object + "null", + """{"reqId":1}""", # no t + """{"t":5,"reqId":1}""", # t is not a string + """{"t":"conn.ping"}""", # no reqId + """{"t":"conn.ping","reqId":"1"}""", # reqId is not an integer + """{"t":"conn.ping","reqId":1.5}""", # reqId is not an integer + """{"t":"conn.ping","reqId":null}""", + """{"t":"conn.ping","reqId":1""", # truncated JSON + ]: + check not parseEnvelope(text).ok + + test "a payload that is not UTF-8 is malformed even when it parses as JSON bytes": + check not parseEnvelope("{\"t\":\"conn.ping\",\"reqId\":1,\"x\":\"\xC3\x28\"}").ok + check parseEnvelope("{\"t\":\"conn.ping\",\"reqId\":1,\"x\":\"caf\xC3\xA9\"}").ok + + test "the catalogue is the 29 intents of 6.1 and the built set is a subset": + check IntentCatalogue.len == 29 + check ImplementedIntents.len == 5 + for t in ImplementedIntents: + check t in IntentCatalogue + check isCatalogueIntent(t) + check not isCatalogueIntent("token.teleport") + check not isCatalogueIntent("TOKEN.MOVE") + + test "role classes: the GM-only set never swallows the intents both roles may send": + for t in ["conn.ping", "act.do", "player.setname", "token.move"]: + check not isGmOnlyIntent(t) + for t in ["key.create", "key.replace", "player.remove", "wall.add"]: + check isGmOnlyIntent(t) + for t in GmOnlyIntents: + check isCatalogueIntent(t) + + test "only this slice's intents answer with a real handler": + check isImplementedIntent("conn.ping") + check isImplementedIntent("key.create") + check not isImplementedIntent("player.setname") + check not isImplementedIntent("wall.add") + +suite "intent rate limit (6.4: 30/s, burst 100)": + test "a fresh bucket allows exactly the burst, then refuses": + var r = newRateLimiter() + for i in 0 ..< RateBurst: + check r.allow(0) + check r.available < 1.0 + check not r.allow(0) + + test "refill is continuous at 30/s, capped at the burst": + var r = newRateLimiter() + for i in 0 ..< RateBurst: check r.allow(1000) + check not r.allow(1000) + check not r.allow(1032) # 32 ms -> 0.96 tokens: still empty + check r.allow(1034) # 34 ms -> 1.02 tokens: one intent + check not r.allow(1034) + check r.allow(1100) # +66 ms -> ~1.98 more: two intents + check r.allow(1100) + check not r.allow(1100) + check r.allow(2100) # a second of idle: 30 tokens + var taken = 1 + for i in 0 ..< 40: + if r.allow(2100): inc taken + check taken == 30 + + test "the refill never exceeds the burst, however long the connection idles": + var r = newRateLimiter() + for i in 0 ..< RateBurst: check r.allow(0) + discard r.allow(10_000_000) + check r.available < float(RateBurst) + var taken = 1 + for i in 0 ..< RateBurst * 3: + if r.allow(10_000_000): inc taken + check taken == RateBurst + + test "the bucket is per connection and starts full: no shared state": + var a = newRateLimiter() + var b = newRateLimiter() + for i in 0 ..< RateBurst: check a.allow(0) + check not a.allow(0) + check b.allow(0) + +suite "malformed flood (6.5 row 8: 10 inside any 10 s)": + test "nine malformed frames are tolerated, the tenth closes": + var f: FloodWindow + for i in 0 ..< MalformedFloodLimit - 1: + check not f.recordMalformed(int64(i * 100)) + check f.recordMalformed(int64((MalformedFloodLimit - 1) * 100)) + + test "a frame slower than the window does not count: 9 fast + 1 slow is not a flood": + var f: FloodWindow + for i in 0 ..< MalformedFloodLimit - 1: + check not f.recordMalformed(int64(i)) + check not f.recordMalformed(MalformedFloodWindowMs + 1000) + + test "the window slides: the flood fires again only on a fresh ten inside it": + var f: FloodWindow + for i in 0 ..< MalformedFloodLimit: + discard f.recordMalformed(int64(i)) + check not f.recordMalformed(MalformedFloodWindowMs + 5000) + # that frame is itself one of the next ten: the tenth fresh one inside the window trips it + for i in 0 ..< MalformedFloodLimit - 2: + check not f.recordMalformed(MalformedFloodWindowMs + 6000 + int64(i)) + check f.recordMalformed(MalformedFloodWindowMs + 6000 + int64(MalformedFloodLimit - 2)) + + test "a second connection has its own window": + var a, b: FloodWindow + for i in 0 ..< MalformedFloodLimit: discard a.recordMalformed(int64(i)) + check not b.recordMalformed(3) + +suite "server frames (6.1)": + test "hello carries proto, role, me and n; an unnamed player's name is null": + let h = helloFrame(ProtoVersion, 1, "player", 4, newJNull()) + check h["t"].getStr == "hello" + check h["proto"].getInt == 1 + check h["role"].getStr == "player" + check h["me"]["id"].getInt == 4 + check h["me"]["name"].kind == JNull + check h["n"].getInt == 1 + let named = helloFrame(ProtoVersion, 2, "gm", 1, %"GM") + check named["me"]["name"].getStr == "GM" + + test "ack ok carries its result fields and never a code": + let a = ackFrame(9, 3, %*{"key": "ABCD-EFGH"}) + check a["t"].getStr == "ack" + check a["reqId"].getInt == 9 + check a["ok"].getBool + check a["key"].getStr == "ABCD-EFGH" + check a["n"].getInt == 3 + check not a.hasKey("code") + let bare = ackFrame(9, 4) + check bare["ok"].getBool + check bare.len == 4 # t, reqId, ok, n + + test "a refusal is a static code and no state": + let r = nackFrame(9, 5, CodeRateLimited) + check r["ok"].getBool == false + check r["code"].getStr == "rate-limited" + check not r.hasKey("pos") + check r.len == 5 # t, reqId, ok, code, n + + test "the uniform move refusal carries pos and no code (5.5, T9)": + let m = nackMoveFrame(9, 6, 10.5, 20.25) + check m["ok"].getBool == false + check not m.hasKey("code") + check m["pos"][0].getFloat == 10.5 + check m["pos"][1].getFloat == 20.25 + + test "error and closing frames have no reqId": + let e = errorFrame(CodeMalformed, 7) + check e["t"].getStr == "error" + check not e.hasKey("reqId") + check e["code"].getStr == "malformed" + let c = closingFrame(ReasonRevoked, CloseRevoked, 8) + check c["t"].getStr == "closing" + check not c.hasKey("reqId") + check c["reason"].getStr == "revoked" + check c["code"].getInt == 4001 + check c["n"].getInt == 8 + + test "the close-code table of 6.5 is the app range plus 1008": + check CloseRevoked == 4001 + check CloseEvicted == 4002 + check CloseProtoMismatch == 4003 + check CloseMalformedFlood == 1008 + check [ReasonRevoked, ReasonEvicted, ReasonProtoMismatch, ReasonMalformedFlood] == + ["revoked", "evicted", "proto-mismatch", "malformed-flood"]