@rbxts/netweave 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,593 @@
1
+ --!strict
2
+ --!optimize 2
3
+
4
+ --[=[
5
+ @class Protocol
6
+
7
+ What two peers must agree on before a single packet between them means anything, and a record of
8
+ who has agreed.
9
+
10
+ Internal. `nw.protocol()` is the public read of it.
11
+ ]=]
12
+
13
+ --[[
14
+ The hash covers the lowered IR, not the channel names — corrected in M3 phase 5 (`PLAN-M3` D-7).
15
+
16
+ Until then it was FNV-1a over the sorted qualified names, which catches a channel added, removed
17
+ or renamed and misses the change that actually bites: a **field's type**. Changing `seq` from
18
+ `t.u8` to `t.u16` left the hash identical, so a stale client connected successfully and was then
19
+ refused on every packet for the rest of the session, with nothing anywhere saying why. That is
20
+ the failure this file exists to convert into one legible line at join.
21
+
22
+ What goes in is everything both peers need in order to read each other's bytes:
23
+
24
+ * the qualified name, because that is what the id is sorted from
25
+ * the class, because a peer that thinks a channel is a `signal` where this one thinks it is a
26
+ `command` is running a different program
27
+ * the lowered node tree of every schema the channel carries — `data`, or `args` and `returns`,
28
+ and for `replicate` the **`subject`** as well as the patch layout derived from `data`. That
29
+ sentence was true of the code for every class but the seventh: `subject` was left out for the
30
+ whole of M4, so two builds differing only in it hashed identically while one of them read a
31
+ change one byte short (M4 phase 8, and `Protocol.signatureOf`)
32
+ * the derived layout numbers, which are a cross-check: if two peers' node trees somehow agree
33
+ while their framing or their maximum size does not, the lowering itself has diverged
34
+
35
+ What stays out is everything only one side enforces: `rate`, `burst`, `maxBytes`, `authorize`,
36
+ `audience`, `unreliable`. Those are the server's policy, and putting them in the hash would make
37
+ tuning a rate limit on the server force every client to redeploy — which would teach games to
38
+ stop tuning rate limits.
39
+
40
+ **32 bits, and that is a deploy-skew detector rather than a cryptographic claim.** Two genuinely
41
+ different protocols collide with probability 2^-32. Nothing here resists an adversary choosing a
42
+ collision, and nothing needs to: a client that forges a matching hash still has every field of
43
+ every packet validated against the schema it claims to share.
44
+ ]]
45
+
46
+ local Ir = require("../codec/Ir")
47
+
48
+ local Protocol = {}
49
+
50
+ --[=[
51
+ @interface Protocol
52
+ @within Protocol
53
+ .hash number -- FNV-1a over the lowered IR of every channel
54
+ .count number -- how many channels were numbered
55
+ .names { string } -- sorted, so `names[id]` is the channel with that id
56
+
57
+ What both peers must agree on before any packet is meaningful.
58
+ ]=]
59
+ export type Protocol = {
60
+ hash: number,
61
+ count: number,
62
+ names: { string },
63
+ --[[ One entry per namespace in name order, each hashing that namespace's channels alone, so a
64
+ mismatch can be named (`PLAN-M5` D-7). The whole `hash` still decides. ]]
65
+ namespaces: { NamespaceDigest },
66
+ }
67
+
68
+ --[=[
69
+ @interface NamespaceDigest
70
+ @within Protocol
71
+ .name string
72
+ .hash number -- FNV-1a over the signatures of that namespace's channels, in id order
73
+ ]=]
74
+ export type NamespaceDigest = { name: string, hash: number }
75
+
76
+ --[[
77
+ The node attributes that reach the wire, listed rather than walked.
78
+
79
+ A `Node` also carries `offset`, `chunkIndex`, `mask` and the rest of the bit-packing positions.
80
+ Those are derived deterministically from everything below, so two peers whose trees agree have
81
+ the same offsets, and including them would be noise. What is here is the set that *decides* the
82
+ bytes.
83
+
84
+ It is a hand-kept list, which is the shape that drifts — the phase 4 audit found `limitNames` in
85
+ `Config` missing an entry for exactly that reason. `tests/protocol_runtime.luau` is the guard: it
86
+ changes each attribute in turn and asserts the hash moves.
87
+ ]]
88
+ local ATTRIBUTES: { string } = {
89
+ "bits",
90
+ "fixedSize",
91
+ "instances",
92
+ "storage",
93
+ "min",
94
+ "max",
95
+ --[[ `t.string(1, 20, { pattern = "%d+" })` and a plain `t.string(1, 20)` are the same bytes and
96
+ different protocols: a peer without the pattern accepts what a peer with it refuses. Same
97
+ argument as `unit` on a vector, which has always been here. ]]
98
+ "utf8",
99
+ "pattern",
100
+ --[[ `t.quantized(-1, 1, 2 / 254)` and `t.quantized(-1, 1, 2 / 200)` lower to the same storage,
101
+ the same bounds and different meanings for every byte on the wire. Without this they hashed
102
+ identically and printed byte-identical signatures — the `subject` failure below, in a third
103
+ place. ]]
104
+ "step",
105
+ --[[ `t.u53` is an f64 on the wire with a wholeness check; `t.f64(0, 2^53)` is the same storage
106
+ without it. Same bytes, different protocols — one peer refuses 1.5 and the other delivers
107
+ it — and until M4-1 they hashed identically, the `step` failure above in a fourth place.
108
+ Every reader-side attribute belongs here for the same reason. ]]
109
+ "whole",
110
+ "unit",
111
+ "class",
112
+ "lengthStorage",
113
+ "count",
114
+ }
115
+ table.freeze(ATTRIBUTES)
116
+
117
+ local function describe(node: Ir.Node, out: { string })
118
+ table.insert(out, node.kind)
119
+ table.insert(out, "(")
120
+
121
+ for _, name in ATTRIBUTES do
122
+ local value: any = (node :: any)[name]
123
+
124
+ if value ~= nil then
125
+ table.insert(out, `{name}={tostring(value)};`)
126
+ end
127
+ end
128
+
129
+ --[[ With its type, because `tostring` folds `1` and `"1"` together and a peer declaring the
130
+ string where this one declares the number is a peer that disagrees. ]]
131
+ if node.literal ~= nil then
132
+ table.insert(out, `literal={typeof(node.literal)}:{tostring(node.literal)};`)
133
+ end
134
+
135
+ --[[ Same again: a default is read on one side and never sent, so the two declarations meet
136
+ only here. ]]
137
+ if node.default ~= nil then
138
+ table.insert(out, `default={typeof(node.default)}:{tostring(node.default)};`)
139
+ end
140
+
141
+ --[[ Variant order is the wire's tag order (`WIRE-FORMAT.md` §5), so it is written in the order
142
+ the lowering fixed rather than re-sorted here. ]]
143
+ if node.variants then
144
+ table.insert(out, "variants[")
145
+
146
+ for _, variant in node.variants :: { string } do
147
+ table.insert(out, `{variant};`)
148
+ end
149
+
150
+ table.insert(out, "]")
151
+ end
152
+
153
+ if node.inner then
154
+ table.insert(out, "inner:")
155
+ describe(node.inner :: Ir.Node, out)
156
+ end
157
+
158
+ if node.key then
159
+ table.insert(out, "key:")
160
+ describe(node.key :: Ir.Node, out)
161
+ end
162
+
163
+ if node.value then
164
+ table.insert(out, "value:")
165
+ describe(node.value :: Ir.Node, out)
166
+ end
167
+
168
+ if node.element then
169
+ table.insert(out, "element:")
170
+ describe(node.element :: Ir.Node, out)
171
+ end
172
+
173
+ --[[ A union's branch *names* come through `variants` above, which is the tag order. These are
174
+ what each name carries, and two builds that agree on the names and disagree on one branch's
175
+ schema is the same failure as two builds disagreeing on a struct field. ]]
176
+ if node.branches then
177
+ table.insert(out, "branches[")
178
+
179
+ for _, branch in node.branches :: { Ir.Field } do
180
+ table.insert(out, `{branch.name}:`)
181
+ describe(branch.node, out)
182
+ table.insert(out, ";")
183
+ end
184
+
185
+ table.insert(out, "]")
186
+ end
187
+
188
+ --[[ A fixed-length array with per-position flags lowers one node per position, and those nodes
189
+ can differ from one another — so each is written, not just the first. ]]
190
+ if node.elements then
191
+ for index, positioned in node.elements :: { Ir.Node } do
192
+ table.insert(out, `[{index}]`)
193
+ describe(positioned, out)
194
+ end
195
+ end
196
+
197
+ --[[ Fields are already in sorted name order, because that is the order they reach the wire in.
198
+ Re-sorting here would hide a lowering that stopped sorting. ]]
199
+ if node.fields then
200
+ for _, field in node.fields :: { Ir.Field } do
201
+ table.insert(out, `{field.name}:`)
202
+ describe(field.node, out)
203
+ end
204
+ end
205
+
206
+ table.insert(out, ")")
207
+ end
208
+
209
+ local function describeLayout(label: string, layout: Ir.Layout?, out: { string })
210
+ if not layout then
211
+ return
212
+ end
213
+
214
+ local resolved = layout :: Ir.Layout
215
+
216
+ table.insert(out, label)
217
+ table.insert(out, "=")
218
+ table.insert(out, `{resolved.framing}/{tostring(resolved.fixedSize)}/{resolved.maxSize}/`)
219
+ table.insert(out, `{tostring(resolved.instances)}:`)
220
+ describe(resolved.root, out)
221
+ table.insert(out, "\n")
222
+ end
223
+
224
+ --[=[
225
+ @within Protocol
226
+ @function signatureOf
227
+ @param channel Channel
228
+ @return string
229
+
230
+ One channel's contribution to the hash, as text.
231
+
232
+ Exposed because a hash that differs tells you nothing about *why*. Two peers can print their
233
+ signatures and diff them, and the line that differs is the declaration that differs.
234
+ ]=]
235
+ function Protocol.signatureOf(channel: any): string
236
+ local out: { string } = {}
237
+
238
+ table.insert(out, channel.qualified)
239
+ table.insert(out, "|")
240
+ table.insert(out, channel.class)
241
+ table.insert(out, "\n")
242
+
243
+ describeLayout("data", channel.codec and channel.codec.layout, out)
244
+ describeLayout("returns", channel.responseCodec and channel.responseCodec.layout, out)
245
+
246
+ --[[
247
+ **The subject is on the wire, so it is in the hash.**
248
+
249
+ A change packet is `id length [instances] subject flags [fields]` (`WIRE-FORMAT.md` §2): the
250
+ subject's bytes come first and the patch is read at whatever offset they end. A peer that
251
+ reads `t.u8` where the sender wrote `t.u16` is one byte short for every change on that
252
+ channel, forever — and for a subject id below 256 the byte it reads as the flags is `0x00`,
253
+ which is a **removal**: a well-formed packet, delivered to the handler, saying a subject went
254
+ away. Nothing refuses it.
255
+
256
+ Until M4 phase 8 this walked `data` and `returns` only, so two builds differing only in
257
+ `subject` hashed identically and printed byte-identical signatures. That is exactly the
258
+ failure class M3 phase 5 closed for field types (`PLAN-M3` D-7), reproduced by the class M4
259
+ added — which is the argument for describing every *layout* a channel carries rather than
260
+ listing the ones that existed when this was written.
261
+
262
+ `tests/protocol_runtime.luau` walks node attributes and could not see it: a second layout is
263
+ not an attribute of the first one's nodes.
264
+ ]]
265
+ describeLayout("subject", channel.subjectCodec and channel.subjectCodec.layout, out)
266
+
267
+ --[[ The patch layout is derived from `data` and cannot disagree with it while the derivation is
268
+ the same on both peers — so this is a cross-check on the derivation rather than a second
269
+ schema, in the same spirit as the framing and size numbers `describeLayout` already ends
270
+ each line with. ]]
271
+ describeLayout("change", channel.delta and channel.delta.layout, out)
272
+
273
+ return table.concat(out)
274
+ end
275
+
276
+ --[[
277
+ FNV-1a, 32-bit (`WIRE-FORMAT.md` §4).
278
+
279
+ Chosen for being four lines that both peers can be trusted to implement identically, which is
280
+ the only property that matters here — see the note at the top about what this is not.
281
+ ]]
282
+ local function fnv1a(text: string): number
283
+ local hash = 2166136261
284
+
285
+ for index = 1, #text do
286
+ hash = bit32.bxor(hash, string.byte(text, index))
287
+ hash = bit32.band(hash * 16777619, 0xFFFFFFFF)
288
+ end
289
+
290
+ return hash
291
+ end
292
+
293
+ --[=[
294
+ @within Protocol
295
+ @function signature
296
+ @param names { string } -- qualified names, already sorted into id order
297
+ @param byName { [string]: any } -- the channel behind each name
298
+ @return string
299
+
300
+ The whole program's signature: every channel in id order, one block each.
301
+ ]=]
302
+ function Protocol.signature(names: { string }, byName: { [string]: any }): string
303
+ local out: { string } = {}
304
+
305
+ for _, qualified in names do
306
+ table.insert(out, Protocol.signatureOf(byName[qualified]))
307
+ end
308
+
309
+ return table.concat(out)
310
+ end
311
+
312
+ --[=[
313
+ @within Protocol
314
+ @function digest
315
+ @param names { string } -- qualified names, already sorted into id order
316
+ @param byName { [string]: any }
317
+ @return Protocol
318
+ ]=]
319
+ function Protocol.digest(names: { string }, byName: { [string]: any }): Protocol
320
+ --[[
321
+ One hash per namespace beside the whole, so a disagreement can be named (`PLAN-M5` D-7).
322
+
323
+ `names` is sorted, and a namespace's channels sort together — `a.x` < `a.y` < `ab.x`, because
324
+ `.` sorts before every letter — so one pass with a running group is enough, and the per-
325
+ namespace signature is the same block per channel that the whole hash is built from.
326
+ ]]
327
+ local namespaces: { NamespaceDigest } = {}
328
+ local current: string? = nil
329
+ local parts: { string } = {}
330
+
331
+ local function close()
332
+ if current ~= nil then
333
+ --[[ The list is frozen below; the entries are not, because `table.freeze` gives them a
334
+ read-only type that is not the `NamespaceDigest` a digest packet decodes into. ]]
335
+ table.insert(namespaces, { name = current, hash = fnv1a(table.concat(parts)) })
336
+ end
337
+ end
338
+
339
+ for _, qualified in names do
340
+ local dot = string.find(qualified, ".", 1, true)
341
+ local space = if dot then string.sub(qualified, 1, dot - 1) else qualified
342
+
343
+ if space ~= current then
344
+ close()
345
+ current = space
346
+ parts = {}
347
+ end
348
+
349
+ table.insert(parts, Protocol.signatureOf(byName[qualified]))
350
+ end
351
+
352
+ close()
353
+
354
+ return table.freeze({
355
+ hash = fnv1a(Protocol.signature(names, byName)),
356
+ count = #names,
357
+ names = table.freeze(names),
358
+ namespaces = table.freeze(namespaces),
359
+ }) :: any
360
+ end
361
+
362
+ --[=[
363
+ @within Protocol
364
+ @function difference
365
+ @param mine { NamespaceDigest } -- this peer's, sorted by name
366
+ @param theirs { NamespaceDigest } -- the other peer's, as its digest packet carried them
367
+ @return string? -- the first namespace the two disagree on, said from this peer's side; nil if none
368
+
369
+ Which namespace a protocol mismatch is in. The whole hash says *that* two builds disagree; this
370
+ says *where*, which is what the person at the console needs. One difference is named, the first
371
+ in name order, because a reason is one sentence.
372
+ ]=]
373
+ function Protocol.difference(mine: { NamespaceDigest }, theirs: { NamespaceDigest }): string?
374
+ local i, j = 1, 1
375
+
376
+ while i <= #mine or j <= #theirs do
377
+ local a = mine[i]
378
+ local b = theirs[j]
379
+
380
+ if a and b and a.name == b.name then
381
+ if a.hash ~= b.hash then
382
+ return `the two disagree inside the namespace "{a.name}": a channel in it has another `
383
+ .. `name, class or schema on the peer`
384
+ end
385
+
386
+ i += 1
387
+ j += 1
388
+ elseif b and (not a or b.name < a.name) then
389
+ return `the peer declares a namespace "{b.name}" that this peer does not`
390
+ else
391
+ return `this peer declares a namespace "{(a :: NamespaceDigest).name}" that the peer does not`
392
+ end
393
+ end
394
+
395
+ return nil
396
+ end
397
+
398
+ --[=[
399
+ @within Protocol
400
+ @function hex
401
+ @param hash number
402
+ @return string
403
+
404
+ `0x1a2b3c4d`. Every message that names a hash uses this, so two consoles print the same eight
405
+ characters and a human can compare them.
406
+ ]=]
407
+ function Protocol.hex(hash: number): string
408
+ return string.format("0x%08x", hash)
409
+ end
410
+
411
+ --[[
412
+ The peer on the other end of a client's connection has no `Player` to be keyed by, and `nil` is
413
+ not a table key. This stands in for "the server" on the client's side, and it can never collide
414
+ with a `Player`.
415
+ ]]
416
+ local SERVER: any = table.freeze({})
417
+
418
+ --[=[
419
+ @interface Config
420
+ @within Protocol
421
+ .hash () -> number -- this peer's hash, read late because the protocol seals late
422
+ .announce (who: any?) -> () -- put this peer's hello on the wire, to that peer
423
+ .isServer boolean
424
+ ]=]
425
+ export type Config = {
426
+ hash: () -> number,
427
+ announce: (who: any?) -> (),
428
+ isServer: boolean,
429
+ --[[ This peer's per-namespace digest, read late for the same reason as `hash`. Optional so a
430
+ rig that only tests the whole-hash verdict keeps its shape; without it a mismatch is never
431
+ named, only detected. ]]
432
+ namespaces: (() -> { NamespaceDigest })?,
433
+ }
434
+
435
+ export type Agreement = {
436
+ greet: (who: any?, hash: number) -> string?,
437
+ verdict: (who: any?) -> string?,
438
+ agreed: (who: any?) -> boolean,
439
+ forget: (who: any) -> (),
440
+ --[[ Whether a digest from this peer would change anything: refused, and not yet named. The
441
+ transport asks before it decodes one, so a peer sending three hundred costs a table read
442
+ for every one after the first (`PLAN-M5` D-7). ]]
443
+ wants: (who: any?) -> boolean,
444
+ --[[ The peer's per-namespace digest. Rewrites a refused peer's reason to name the namespace,
445
+ once, and returns the new reason so the caller can report it; nil when nothing changed. ]]
446
+ digest: (who: any?, theirs: { NamespaceDigest }) -> string?,
447
+ }
448
+
449
+ --[=[
450
+ @within Protocol
451
+ @function new
452
+ @param config Config
453
+ @return Agreement
454
+
455
+ Tracks which peers have agreed, and refuses the ones that have not.
456
+ ]=]
457
+ function Protocol.new(config: Config): Agreement
458
+ local ours = config.hash
459
+ local announce = config.announce
460
+
461
+ --[[
462
+ nil is "has not said hello", a string is the refusal, and a peer that agreed is removed
463
+ rather than stored as `true`.
464
+
465
+ The asymmetry is the design. A peer whose hash **differs** is refused, because their bytes
466
+ would decode as a different channel than the one they sent and a wrong payload delivered
467
+ successfully is worse than no payload at all. A peer who has said **nothing** is accepted,
468
+ and that is not an oversight:
469
+
470
+ * The handshake diagnoses deploy skew. It is not an authorization boundary, and treating
471
+ it as one would be theatre — a hostile client omits the hello, and is then held to
472
+ exactly the same per-field validation as one that sent it. Nothing is gained.
473
+ * A real client's hello can be lost. Refusing them for it would turn a dropped packet into
474
+ a player who cannot play, which is a worse failure than the one being prevented.
475
+
476
+ So this table only ever holds peers that are provably wrong, which also means it stays empty
477
+ in a healthy server.
478
+ ]]
479
+ local refusals: { [any]: string } = {}
480
+
481
+ --[[ Peers whose reason already names a namespace. A digest after that is not decoded. ]]
482
+ local named: { [any]: boolean } = {}
483
+
484
+ local function keyOf(who: any?): any
485
+ return if who == nil then SERVER else who
486
+ end
487
+
488
+ return {
489
+ greet = function(who: any?, hash: number): string?
490
+ local mine = ours()
491
+ local key = keyOf(who)
492
+
493
+ if hash == mine then
494
+ refusals[key] = nil
495
+ named[key] = nil
496
+ return nil
497
+ end
498
+
499
+ --[[
500
+ A peer already known to be wrong is not re-judged, and that bound is the whole answer
501
+ to a hello flood.
502
+
503
+ Control packets are read before `sink.admit`, because resolving id 0 would fail and
504
+ that failure would be the unrecoverable one — so nothing charges a hello a rate. What
505
+ made that matter was here: every mismatched hello built a fresh reason string and
506
+ answered with a hello of this peer's own. Measured before this line, 300 hellos in one
507
+ 2,101-byte batch cost 300 replies and 76 KB of garbage. The second one now costs a
508
+ table read.
509
+
510
+ The verdict cannot change either, because the only thing that lifts a refusal is a
511
+ hash that **agrees**, and that is the branch above. So a peer that rotates its hash
512
+ keeps the reason naming the first one it claimed — which is the one a real stale
513
+ client would have sent every time.
514
+ ]]
515
+ if refusals[key] ~= nil then
516
+ return nil
517
+ end
518
+
519
+ local reason = `the peer is on protocol {Protocol.hex(hash)} and this peer is on `
520
+ .. `{Protocol.hex(mine)}. The two disagree about a channel's name, class or schema, `
521
+ .. `so every packet between them would decode as something else. Redeploy both `
522
+ .. `sides from the same declarations; nw.protocol() prints what this one computed.`
523
+
524
+ refusals[key] = reason
525
+
526
+ --[[ Answered rather than only recorded, and only on a mismatch.
527
+
528
+ The failure is symmetric and the person who can act on it is usually sitting at the
529
+ client, watching a console that would otherwise say nothing at all. One packet per
530
+ mismatched peer, never on the happy path. ]]
531
+ if config.isServer then
532
+ announce(who)
533
+ end
534
+
535
+ --[[ Returned so the caller can report the hello itself. Until M3 phase 9 a mismatched
536
+ hello was silent here, and the disagreement first surfaced on a data packet behind
537
+ it — which is to say never, for a peer that sent nothing else. ]]
538
+ return reason
539
+ end,
540
+
541
+ verdict = function(who: any?): string?
542
+ return refusals[keyOf(who)]
543
+ end,
544
+
545
+ agreed = function(who: any?): boolean
546
+ return refusals[keyOf(who)] == nil
547
+ end,
548
+
549
+ forget = function(who: any)
550
+ refusals[who] = nil
551
+ named[who] = nil
552
+ end,
553
+
554
+ wants = function(who: any?): boolean
555
+ local key = keyOf(who)
556
+ return refusals[key] ~= nil and not named[key]
557
+ end,
558
+
559
+ digest = function(who: any?, theirs: { NamespaceDigest }): string?
560
+ local key = keyOf(who)
561
+
562
+ if refusals[key] == nil or named[key] then
563
+ return nil
564
+ end
565
+
566
+ --[[ Marked before the comparison, so a digest that names nothing — two hashes that differ
567
+ with every namespace agreeing cannot happen, but a malformed one can — is still the
568
+ last one this peer gets to send us. ]]
569
+ named[key] = true
570
+
571
+ local digestOf = config.namespaces
572
+
573
+ if not digestOf then
574
+ return nil
575
+ end
576
+
577
+ local where = Protocol.difference(digestOf(), theirs)
578
+
579
+ if not where then
580
+ return nil
581
+ end
582
+
583
+ local reason = `{where}. Every packet between the two would decode as something else, so `
584
+ .. `the peer stays refused; redeploy both sides from the same declarations, and `
585
+ .. `nw.signature() prints what this one computed.`
586
+
587
+ refusals[key] = reason
588
+ return reason
589
+ end,
590
+ }
591
+ end
592
+
593
+ return Protocol