diff --git a/docs/DESIGN-history.md b/docs/DESIGN-history.md index aad7e8f..bea2dc8 100644 --- a/docs/DESIGN-history.md +++ b/docs/DESIGN-history.md @@ -77,6 +77,8 @@ same numbering. - v0.31 records #32 (the dispatch guard: the `internal` refusal code and unconditional rollback on every unwind path) in 4.2, 6.2, 6.5, 14 +- v0.32 records #35 (the opaque-object caps on wall `flags` and scene `extra`: 8 KB, 64 keys per + object, depth 8) in 6.1, 14 All of Q1-Q24 are RESOLVED or DEFERRED; none OPEN. @@ -855,6 +857,13 @@ helpers roll back on every unwind path (`Defect` included) so the shared connect the handler's own ack was already enqueued, it stands and no second ack is appended. `internal` is additive in proto 2. A `Defect` is bounded damage, not a restart policy. See current 4.2, 6.2, 6.5. +Owner also decided 2026-11-20 [FIXED (owner-delegated, 2026-11-20, #35)]: wall `flags` and scene +`extra` are opaque but capped uniformly, on the same measure as a prop value: serialized JSON at +most 8 KB, at most 64 keys per object (per object, not summed) and nesting depth at most 8 (a +top-level object is depth 1). At a cap is accepted; over is `invalid` and applies nothing. The caps +live next to the property caps and are read from one shared validator; token `flags`, props and +stored values above a cap are out of scope. See current 6.1. + ## D. Superseded statements removed from the current spec Each entry quotes the superseded statement (excerpt) and names the surviving rule. diff --git a/docs/DESIGN.md b/docs/DESIGN.md index d1712d8..b6796fe 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -1431,7 +1431,13 @@ switches, never `thickness`, `position` or `height` (#50). no sight, movement or status rule; a marker is emitted only for a wall that is both `player_marker:true` and derives `window` (5.8). - `flags` is a JSON object or absent (absent = `{}`); anything else is `invalid`. It is stored - verbatim and never interpreted — the switches are fields, not flags (5.8). + verbatim and never interpreted — the switches are fields, not flags (5.8). The object is opaque + but bounded [FIXED (owner-delegated), 2026-11-20, #35], on the same measure as a prop value: + serialized JSON is at most 8 KB, at most 64 keys per object, and nesting depth at most 8 (a + top-level object is depth 1, nested objects and arrays each add one). A value at every cap is + accepted; one byte, key or level over is `invalid` and nothing is stored. A refused value is + logged once with the field and the limit it broke, never its contents. A row already stored above + a cap is loaded and echoed as stored: the cap is an input rule, not a migration. - `wall.update` patches `a`, `b`, `thickness`, `position`, `height`, the switches except `open` (or one `preset`), `label` and `flags`; at least one of them is required, otherwise `invalid`. A patch is absolute, not additive: everything named is set to the value given (`null` clears `height` and @@ -1486,7 +1492,9 @@ switches, never `thickness`, `position` or `height` (#50). - `name`: the 6.5 text rule, 1..64 code points, already trimmed, no control characters. - `grid_size`: a finite number `>= 0` (0 = no grid; `classify` rejects NaN/Inf). - `vision_radius_default`, `token_radius_default`: a finite number `> 0`, no upper cap (#4). - - `extra`: a JSON object, stored verbatim and never interpreted; the GM sees it in `hello`. + - `extra`: a JSON object, stored verbatim and never interpreted; the GM sees it in `hello`. It + carries the same opaque caps as wall `flags` [FIXED (owner-delegated), 2026-11-20, #35]: 8 KB + serialized, 64 keys per object, depth 8; over a cap is `invalid` and applies none of the patch. - `w`, `h`, `tile_size`, `cell` and `art_version` are **not** patch fields (import is the M6 CLI): they are unknown fields and ignored (6.2), so a patch carrying only one of them has no field at all and is `invalid`. diff --git a/server/main.nim b/server/main.nim index fde7c85..67fe248 100644 --- a/server/main.nim +++ b/server/main.nim @@ -541,6 +541,12 @@ proc declared(env: Envelope, key: string): bool = ## `vision_radius: null` means "the scene default" (6.1), so both are real patch fields. not env.node.isNil and env.node.hasKey(key) +proc opaqueRefused(field: string, node: JsonNode) = + ## #35: one structured line naming the field and the limit it broke, never the contents. + let limit = props.checkOpaqueObject(node) + if limit != props.olOk: + app.lg.log(lvInfo, "opaque_refused", [("field", field), ("limit", props.limitName(limit))]) + # Wall payload fields (DESIGN 6.1, proto 2, #54). `kind` and (in an update) `open` are never read: # they are unknown fields and ignored (6.2). Absent and JSON null are the same field-absent for # every wall field except `height` and `label`, where an explicit null means "clear it". @@ -638,6 +644,8 @@ proc parseWallPatch(env: Envelope, patch: var WallPatch, allowOpen = false): boo if present(env, "flags"): let f = parseFlags(env.node{"flags"}) if f.isNone: return false + # #35: wall `flags` is opaque but bounded (token `flags` keeps its old, uncapped path). + if props.checkOpaqueObject(f.get) != props.olOk: return false patch.flags = f true @@ -1993,6 +2001,8 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = if not sceneOk(conn, env): return var patchOpt = parseScenePatch(env.node) if patchOpt.isNone: + if not env.node.isNil and env.node.hasKey("extra"): + opaqueRefused("extra", env.node{"extra"}) ackErr(conn, env.reqId, CodeInvalid) return var patch = patchOpt.get @@ -2056,6 +2066,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = # #55); `a` and `b` are the only required fields here. var patch: WallPatch if not parseWallPatch(env, patch, allowOpen = true): + if present(env, "flags"): opaqueRefused("flags", env.node{"flags"}) ackErr(conn, env.reqId, CodeInvalid) return if patch.a.isNone or patch.b.isNone: @@ -2112,6 +2123,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = return var patch: WallPatch if not parseWallPatch(env, patch): + if present(env, "flags"): opaqueRefused("flags", env.node{"flags"}) ackErr(conn, env.reqId, CodeInvalid) return if not wallPatchHasField(patch): diff --git a/server/props.nim b/server/props.nim index 5b5f888..1f6b695 100644 --- a/server/props.nim +++ b/server/props.nim @@ -54,6 +54,55 @@ const MaxPropValueBytes* = 8192 ## 6.1: a value's serialized JSON is at most 8 KB. + # Opaque authored objects (`wall.flags`, `scene.extra`) [FIXED (owner-delegated), 2026-11-20, + # #35]. The same 8 KB measure as a prop value, read from one place; the key and depth caps bound a + # pasted blob before it is stored and echoed to every GM connect. + MaxOpaqueObjectBytes* = 8192 + MaxOpaqueObjectKeys* = 64 + MaxOpaqueObjectDepth* = 8 + ## A top-level object is depth 1; depth counts nested objects and arrays along any path. + +type + OpaqueObjectLimit* = enum + olOk + olSize ## serialized JSON is over MaxOpaqueObjectBytes + olKeys ## one object has over MaxOpaqueObjectKeys keys + olDepth ## a container is deeper than MaxOpaqueObjectDepth + +proc limitName*(limit: OpaqueObjectLimit): string = + case limit + of olOk: "ok" + of olSize: "size" + of olKeys: "keys" + of olDepth: "depth" + + +proc valueBytes*(value: JsonNode): int = + ## The cap is on the serialized size (6.1), which is the number that actually crosses the wire. + if value.isNil: 0 else: ($value).len + +proc checkOpaqueObject*(node: JsonNode): OpaqueObjectLimit = + ## The one cap check for both call sites (wall `flags`, scene `extra`): size, key count and depth + ## in one walk. The contents stay uninterpreted; only these bounds are enforced. + if node.isNil: return olOk + if valueBytes(node) > MaxOpaqueObjectBytes: return olSize + proc walk(n: JsonNode, depth: int): OpaqueObjectLimit = + case n.kind + of JObject: + if depth > MaxOpaqueObjectDepth: return olDepth + if n.len > MaxOpaqueObjectKeys: return olKeys + for _, value in n: + let r = walk(value, depth + 1) + if r != olOk: return r + of JArray: + if depth > MaxOpaqueObjectDepth: return olDepth + for value in n: + let r = walk(value, depth + 1) + if r != olOk: return r + else: discard + olOk + walk(node, 1) + proc newProps*(): Props = for b in PropBucket: result[b] = newJObject() @@ -71,10 +120,6 @@ proc bucketName*(b: PropBucket): string = $b proc validPropKey*(key: string): bool = validText(key, MaxPropKeyLen) -proc valueBytes*(value: JsonNode): int = - ## The cap is on the serialized size (6.1), which is the number that actually crosses the wire. - if value.isNil: 0 else: ($value).len - proc defaultRegistry*(): Registry = ## v1's registry: nothing registered, every key accepted (DESIGN 8: props are not interpreted). Registry(fallback: PropSchema(kind: pkAny, bucket: none(PropBucket))) diff --git a/server/world.nim b/server/world.nim index 4cfc08a..b55fb12 100644 --- a/server/world.nim +++ b/server/world.nim @@ -32,7 +32,7 @@ ## no locking: the caller holds the global lock (4.3). import std/[json, math, options, strutils] import db_connector/db_sqlite -import db, geometry, text +import db, geometry, props, text type WallPosition* = enum @@ -344,6 +344,8 @@ proc parseScenePatch*(node: JsonNode): Option[ScenePatch] = if node.hasKey("extra"): let v = node["extra"] if v.kind != JObject: return none(ScenePatch) + # #35: the same opaque caps as wall `flags`; the contents stay uninterpreted. + if checkOpaqueObject(v) != olOk: return none(ScenePatch) p.extra = some(v) any = true if not any: return none(ScenePatch) diff --git a/tests/tprops.nim b/tests/tprops.nim index f1a09b5..587aad6 100644 --- a/tests/tprops.nim +++ b/tests/tprops.nim @@ -46,6 +46,50 @@ suite "caps (6.1, numbers FIXED owner-delegated by #22)": let big = %repeat("x", MaxPropValueBytes + 1) check valueBytes(big) > MaxPropValueBytes +suite "opaque object caps (6.1, FIXED owner-delegated by #35)": + proc objectWith(keys: int): JsonNode = + result = newJObject() + for i in 0 ..< keys: result["k" & $i] = %i + + proc nestedObjects(depth: int): JsonNode = + result = newJObject() + var cur = result + for _ in 1 ..< depth: + let child = newJObject() + cur["a"] = child + cur = child + + test "size: exactly 8 KB is accepted, one byte over is refused": + let atCap = %*{"blob": repeat("x", MaxOpaqueObjectBytes - 11)} + check ($atCap).len == MaxOpaqueObjectBytes + check checkOpaqueObject(atCap) == olOk + let over = %*{"blob": repeat("x", MaxOpaqueObjectBytes - 10)} + check ($over).len == MaxOpaqueObjectBytes + 1 + check checkOpaqueObject(over) == olSize + + test "keys: 64 per object is accepted, 65 is refused, and it is per object": + check checkOpaqueObject(objectWith(MaxOpaqueObjectKeys)) == olOk + check checkOpaqueObject(objectWith(MaxOpaqueObjectKeys + 1)) == olKeys + # a nested object has its own budget, not a shared one + var nested = objectWith(MaxOpaqueObjectKeys - 1) + nested["inner"] = objectWith(MaxOpaqueObjectKeys) + check checkOpaqueObject(nested) == olOk + nested["inner"] = objectWith(MaxOpaqueObjectKeys + 1) + check checkOpaqueObject(nested) == olKeys + + test "depth: 8 containers is accepted, 9 is refused": + check checkOpaqueObject(nestedObjects(MaxOpaqueObjectDepth)) == olOk + check checkOpaqueObject(nestedObjects(MaxOpaqueObjectDepth + 1)) == olDepth + # arrays are containers too + var deep = newJArray() + let root = newJObject() + root["a"] = deep + for _ in 1 ..< MaxOpaqueObjectDepth - 1: + let next = newJArray() + deep.add next + deep = next + check checkOpaqueObject(root) == olOk + suite "parseProps (the `props` field of token.create)": test "absent and null mean three empty buckets": for node in [JsonNode(nil), newJNull()]: diff --git a/tools/mutation.sh b/tools/mutation.sh index e1c58b6..8645f1c 100755 --- a/tools/mutation.sh +++ b/tools/mutation.sh @@ -209,10 +209,17 @@ run c3 "an out-of-grid tile coordinate is accepted" server/tiles.nim 's/^ x >= run c4 "a leading-zero tile coordinate is canonical" server/tiles.nim "s/ if raw\[0\] == '0' and raw.len > 1: return false/ discard/" "$TILE_ZERO" # slice 10 (#25): scene.set needs at least one patch field (server/world.nim parseScenePatch) run d3 "scene.set accepts a patch with no field" server/world.nim 's/^ if not any: return none(ScenePatch)$/ discard/' "a patch with none is invalid" +# #32: the rollback on a Defect, in both transaction helpers, and the one-ack decision +run e4 "a Defect skips the ordinary rollback" server/db.nim 's/^ except Exception:$/ except CatchableError:/' "rolls back a Defect and leaves" +run e5 "a Defect skips the authoring rollback" server/world.nim 's/^ except Exception:$/ except CatchableError:/' "authoringTransaction rolls back a Defect" +# #35: the three opaque-object caps (server/props.nim checkOpaqueObject) +run f1 "the opaque size cap is not enforced" server/props.nim 's/> MaxOpaqueObjectBytes: return olSize/> MaxOpaqueObjectBytes + 100000: return olSize/' "size: exactly 8 KB" +run f2 "the opaque key cap is not enforced" server/props.nim 's/if n\.len > MaxOpaqueObjectKeys: return olKeys/if false: return olKeys/' "keys: 64 per object" +run f3 "the opaque depth cap is not enforced" server/props.nim 's/if depth > MaxOpaqueObjectDepth: return olDepth/if false: return olDepth/' "depth: 8 containers" wait rc=0; : > "$LOG" -for id in control a b c d1 d2 d3 e e1 e2 e3 f g h i j k l m n o p q r s t u v w x y z z2 \ +for id in control a b c d1 d2 d3 e e1 e2 e3 e4 e5 f1 f2 f3 f g h i j k l m n o p q r s t u v w x y z z2 \ s1 s2 s3 s4 s5 s6 s7 aa ab ac ad ae af ag ah ai aj ak al am an ao ap aq ar as at au \ av aw ax ay az b1 b2 b3 b4 c1 c2 c3 c4; do [ -f "$T/$id/res" ] && cat "$T/$id/res" >> "$LOG" diff --git a/tools/scene.test.mjs b/tools/scene.test.mjs index 81072bc..13212ba 100644 --- a/tools/scene.test.mjs +++ b/tools/scene.test.mjs @@ -209,3 +209,66 @@ test('token_radius_default: a grow with no room on either side squeezes', async fs.rmSync(stateDir, { recursive: true, force: true }) } }) + +// #35: scene `extra` uses the same opaque caps as wall `flags` (8 KB, 64 keys per object, depth 8). +function extraObjectWithKeys(n) { + const o = {} + for (let i = 0; i < n; i++) o[`k${i}`] = i + return o +} +function extraNested(depth) { + let o = {} + const root = o + for (let i = 1; i < depth; i++) { o.a = {}; o = o.a } + return root +} + +test('scene.extra: size, key-count and depth caps, boundaries included (#35)', async () => { + const stateDir = makeStateDir() + const gmKey = gmKeyOf(stateDir) + const s = await startServer({ stateDir }) + try { + const gm = await gmConnect(s.origin, gmKey) + const atCap = { blob: 'x'.repeat(8192 - 11) } + const mark = gm.ws.messages.length + const ack = await gm.ws.request({ t: 'scene.set', scene: gm.sceneId, extra: atCap }) + assert.equal(ack.ok, true, JSON.stringify(ack)) + const hello = await after(gm.ws, mark, 'hello') + assert.equal(JSON.stringify(hello.extra).length, 8192, 'exactly 8 KB is echoed') + + // One byte over, with another declared field: `invalid`, and none of the patch is applied. + const refused = await gm.ws.request({ t: 'scene.set', scene: gm.sceneId, name: 'Nope', + extra: { blob: 'x'.repeat(8192 - 10) } }) + assert.equal(refused.code, 'invalid') + const mark2 = gm.ws.messages.length + assert.equal((await gm.ws.request({ t: 'scene.set', scene: gm.sceneId, + grid_size: 60 })).ok, true) + const hello2 = await after(gm.ws, mark2, 'hello') + assert.equal(hello2.scene.name, 'Scene', 'the refused patch applied no other field') + assert.equal(hello2.scene.grid_size, 60) + assert.match(s.log(), /opaque_refused field=extra limit=size/) + + // Key count: 64 accepted, 65 refused; per object, so a 64-key nested object is fine. + assert.equal((await gm.ws.request({ t: 'scene.set', scene: gm.sceneId, + extra: extraObjectWithKeys(64) })).ok, true) + assert.equal((await gm.ws.request({ t: 'scene.set', scene: gm.sceneId, + extra: extraObjectWithKeys(65) })).code, 'invalid') + const nested = extraObjectWithKeys(63) + nested.inner = extraObjectWithKeys(64) + assert.equal((await gm.ws.request({ t: 'scene.set', scene: gm.sceneId, + extra: nested })).ok, true) + nested.inner = extraObjectWithKeys(65) + assert.equal((await gm.ws.request({ t: 'scene.set', scene: gm.sceneId, + extra: nested })).code, 'invalid') + + // Depth: 8 accepted, 9 refused. + assert.equal((await gm.ws.request({ t: 'scene.set', scene: gm.sceneId, + extra: extraNested(8) })).ok, true) + assert.equal((await gm.ws.request({ t: 'scene.set', scene: gm.sceneId, + extra: extraNested(9) })).code, 'invalid') + gm.ws.close() + } finally { + await stopServer(s) + fs.rmSync(stateDir, { recursive: true, force: true }) + } +}) diff --git a/tools/walls.test.mjs b/tools/walls.test.mjs index 58a6eb8..9c55901 100644 --- a/tools/walls.test.mjs +++ b/tools/walls.test.mjs @@ -723,3 +723,69 @@ test('restart: the typed walls, door state and the id counter are identical afte fs.rmSync(stateDir, { recursive: true, force: true }) } }) + +// #35: wall `flags` is opaque but bounded: 8 KB serialized, 64 keys per object, depth 8. +function objectWithKeys(n) { + const o = {} + for (let i = 0; i < n; i++) o[`k${i}`] = i + return o +} +function nestedObjects(depth) { + let o = {} + const root = o + for (let i = 1; i < depth; i++) { o.a = {}; o = o.a } + return root +} +const atByteCap = () => ({ blob: 'x'.repeat(8192 - 11) }) +const overByteCap = () => ({ blob: 'x'.repeat(8192 - 10) }) + +test('wall.flags: size, key-count and depth caps, boundaries included (#35)', async () => { + await withGmServer(async (s, gmKey) => { + const gm = await gmConnect(s.origin, gmKey) + // Exactly 8 KB is accepted and echoed; one byte over is `invalid` and stores nothing. + const ok = await addWall(gm, { a: [10, 10], b: [100, 10], flags: atByteCap() }) + assert.equal(ok.ok, true, JSON.stringify(ok)) + const frame = await wallEffect(gm.ws, m => m.t === 'wall' && m.id === ok.id) + assert.equal(JSON.stringify(frame.flags).length, 8192) + const before = gm.ws.messages.filter(m => m.t === 'wall').length + const over = await addWall(gm, { a: [10, 20], b: [100, 20], flags: overByteCap() }) + assert.equal(over.code, 'invalid') + await sleep(80) + assert.equal(gm.ws.messages.filter(m => m.t === 'wall').length, before, + 'a refused add emits no wall frame') + assert.match(s.log(), /opaque_refused field=flags limit=size/) + assert.equal(s.log().includes('xxxxxxxx'), false, 'the refused value is never logged') + // The refused add consumes no wall id: the next wall follows the accepted one densely. + const next = await addWall(gm, { a: [10, 30], b: [100, 30] }) + assert.equal(next.id, ok.id + 1) + + // 64 keys per object accepted, 65 refused; the cap is per object, not per value. + assert.equal((await addWall(gm, { a: [5, 5], b: [60, 5], + flags: objectWithKeys(64) })).ok, true) + assert.equal((await addWall(gm, { a: [5, 15], b: [60, 15], + flags: objectWithKeys(65) })).code, 'invalid') + const nestedBase = objectWithKeys(63) + nestedBase.inner = objectWithKeys(64) + assert.equal((await addWall(gm, { a: [5, 25], b: [60, 25], flags: nestedBase })).ok, true) + nestedBase.inner = objectWithKeys(65) + assert.equal((await addWall(gm, { a: [5, 35], b: [60, 35], flags: nestedBase })).code, 'invalid') + + // Depth 8 accepted, 9 refused. + assert.equal((await addWall(gm, { a: [5, 45], b: [60, 45], + flags: nestedObjects(8) })).ok, true) + assert.equal((await addWall(gm, { a: [5, 55], b: [60, 55], + flags: nestedObjects(9) })).code, 'invalid') + + // A refused update leaves the previous flags intact. + const keep = await addWall(gm, { a: [200, 200], b: [300, 200], flags: { note: 'keep' } }) + const bad = await gm.ws.request({ t: 'wall.update', scene: gm.scene, id: keep.id, + flags: overByteCap() }) + assert.equal(bad.code, 'invalid') + const good = await gm.ws.request({ t: 'wall.update', scene: gm.scene, id: keep.id, + thickness: 5 }) + assert.equal(good.ok, true) + const after = await wallEffect(gm.ws, m => m.t === 'wall' && m.id === keep.id) + assert.deepEqual(after.flags, { note: 'keep' }) + gm.ws.close() + }) +})