@rbxts/netweave 0.0.0-stage → 0.1.0

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,457 @@
1
+ --!strict
2
+ --!optimize 2
3
+
4
+ --[=[
5
+ @class Policy
6
+
7
+ What a channel is allowed to do, written once and attached to the declaration.
8
+
9
+ ```lua
10
+ -- shared/Policies.luau
11
+ local policy = {}
12
+
13
+ policy.alive = nw.policy(function()
14
+ return function(ctx)
15
+ if not ctx.humanoid or ctx.humanoid.Health <= 0 then
16
+ return nw.deny("dead")
17
+ end
18
+ return nw.allow()
19
+ end
20
+ end)
21
+
22
+ policy.originNearCharacter = nw.policy(function(config)
23
+ local maxStuds = config.maxStuds or 8
24
+
25
+ return function(ctx, shot)
26
+ local root = ctx.character and ctx.character.PrimaryPart
27
+ if not root then
28
+ return nw.deny("no character")
29
+ end
30
+ if (shot.origin - root.Position).Magnitude > maxStuds then
31
+ return nw.deny("origin detached")
32
+ end
33
+ return nw.allow(shot)
34
+ end
35
+ end)
36
+
37
+ return policy
38
+ ```
39
+
40
+ Two stages: the outer function runs once at load, the inner runs per request. The structural
41
+ idea comes from Flamework (`RESEARCH §3.5-S3`); what differs is the attachment point. Flamework
42
+ declares the guard as middleware in `createServer({ middleware })`, so answering "what is enforced
43
+ here" means reading the server setup rather than the handler. netweave attaches it to the channel
44
+ declaration, so the answer is one line.
45
+ ]=]
46
+
47
+ --[[
48
+ R-3 is the risk this module is written against: an authorization callback per packet, plus
49
+ context setup, could erase the codec's advantage entirely and hand the argument to "just use a
50
+ RemoteEvent" — which M0 already showed is faster for small payloads.
51
+
52
+ So nothing here allocates per request. The verdict is a single shared record (see `allow`),
53
+ `all` resolves its members at declaration time into a flat array, and the context is the
54
+ reused per-player one from `Context`.
55
+ ]]
56
+
57
+ local Context = require("./Context")
58
+
59
+ local Policy = {}
60
+
61
+ --[=[
62
+ @interface Verdict
63
+ @within Policy
64
+ .ok boolean
65
+ .value any -- what the handler receives, when a policy narrowed or replaced the payload
66
+ .reason string? -- why, when refused. Reaches `nw.observe` as `Rejection.reason`
67
+
68
+ :::caution
69
+ The verdict is a **shared record**, refilled by every `allow` and `deny`. It is read
70
+ immediately by whatever called the policy and is invalid once the next policy runs. Never
71
+ retain it, and never yield inside a policy.
72
+ :::
73
+ ]=]
74
+ export type Verdict = {
75
+ ok: boolean,
76
+ value: any,
77
+ reason: string?,
78
+ }
79
+
80
+ --[=[
81
+ @type Check<T> (ctx: Ctx, payload: T) -> Verdict
82
+ @within Policy
83
+
84
+ The per-request half of a policy: the function the outer stage returns.
85
+ ]=]
86
+ export type Check<T> = (ctx: Context.Ctx, payload: T) -> Verdict
87
+
88
+ --[=[
89
+ @type Stage () -> ()
90
+ @within Policy
91
+
92
+ The server-only half a factory may return second. Runs once, on the server, when the protocol
93
+ is sealed — before any packet decodes, and never on a client — so it is where a policy reaches
94
+ the module that exists on one side only (`PLAN-M5` D-5).
95
+ ]=]
96
+ export type Stage = () -> ()
97
+
98
+ --[=[
99
+ @type Factory<T> (config: any) -> (Check<T>, Stage?)
100
+ @within Policy
101
+
102
+ The load-time half. Receives whatever the policy was configured with, or an empty table when
103
+ it was used bare, and returns the per-request check — and, optionally, the server stage.
104
+ ]=]
105
+ --[[ A variadic tail rather than `(Check<T>, Stage?)`: a return pack of one value is not a subtype
106
+ of a pack of two, so the fixed spelling refused every factory that returns the check alone —
107
+ measured as 35 diagnostics across `api_ok` and `api_reject` the moment it was written. ]]
108
+ export type Factory<T> = (config: any) -> (Check<T>, ...Stage?)
109
+
110
+ --[=[
111
+ @type Policy<T> Check<T>
112
+ @within Policy
113
+
114
+ A policy is usable in two forms, and both appear in real declarations:
115
+
116
+ ```lua
117
+ authorize = policy.alive, -- bare, default configuration
118
+ authorize = policy.originNearCharacter({ maxStuds = 12 }), -- reconfigured
119
+ ```
120
+
121
+ Bare, it already is the per-request check. Called, it produces a differently configured one.
122
+ ]=]
123
+ --[[
124
+ Two aliases rather than one recursive intersection.
125
+
126
+ `Policy<T>` used to be a `typeof(setmetatable(…))` alias, which enforces the argument *count* of a
127
+ reconfiguration and nothing about variance — so `nw.all(alive, ownsSlot)`, one payload-agnostic
128
+ policy composed with one that names its request, was refused in every spelling (M4 report finding
129
+ 43; `PLAN-M5` phase 3). An intersection fixes that, because a function type is contravariant in
130
+ its parameters and `Check<any>` is then usable where `Check<Equip>` is wanted.
131
+
132
+ Written recursively — `Record<T> & ((config: any) -> Policy<T>)` — it takes `Channel`'s type
133
+ functions down with `type functions do not currently support types of the form '*error-type*'`,
134
+ measured. So the call returns the record: a *reconfigured* policy is a `Configured<T>`, which is
135
+ what everything here accepts, and `Policy<T>` is that record plus the one call that produces one.
136
+ Calling a configured policy again was never a shape anyone wrote.
137
+ ]]
138
+ export type Configured<T> = {
139
+ __nwCheck: (ctx: Context.Ctx, payload: T) -> Verdict,
140
+ __nwStages: { Stage },
141
+ }
142
+
143
+ export type Policy<T> = Configured<T> & ((config: any) -> Configured<T>)
144
+
145
+ --[[
146
+ One record for every verdict in the process. A policy returns it, the caller reads `ok`,
147
+ `value` and `reason` into locals before doing anything else, and the next policy overwrites it.
148
+
149
+ The alternative — a fresh table per verdict — is one allocation per policy per packet, which on
150
+ a `command` at 20 Hz across 50 players is a thousand tables a second doing nothing.
151
+ ]]
152
+ local VERDICT: Verdict = {
153
+ ok = true,
154
+ value = nil,
155
+ reason = nil,
156
+ }
157
+
158
+ --[=[
159
+ @within Policy
160
+ @function allow
161
+ @param value any? -- the payload to hand onward, if this policy narrowed it
162
+ @return Verdict
163
+
164
+ Approves the request.
165
+
166
+ ```lua
167
+ return nw.allow() -- unchanged
168
+ return nw.allow(clamped) -- the handler receives `clamped`
169
+ ```
170
+
171
+ Passing a value is how a policy becomes a *narrowing* step rather than only a gate: clamp a
172
+ number, resolve an id to the object it names, drop a field the caller must not set.
173
+ ]=]
174
+ function Policy.allow(value: any?): Verdict
175
+ VERDICT.ok = true
176
+ VERDICT.value = value
177
+ VERDICT.reason = nil
178
+ return VERDICT
179
+ end
180
+
181
+ --[=[
182
+ @within Policy
183
+ @function deny
184
+ @param reason string -- reaches `nw.observe` verbatim, so make it greppable
185
+ @return Verdict
186
+
187
+ Refuses the request. The handler does not run, and a rejection is emitted at stage
188
+ `"authorize"`.
189
+
190
+ ```lua
191
+ return nw.deny("origin detached")
192
+ ```
193
+
194
+ :::note
195
+ The reason is developer-facing telemetry, not a message for the player. It is never sent back
196
+ over the wire — telling a client *why* it was refused is how an attacker maps your checks.
197
+ :::
198
+ ]=]
199
+ function Policy.deny(reason: string): Verdict
200
+ VERDICT.ok = false
201
+ VERDICT.value = nil
202
+ VERDICT.reason = reason
203
+ return VERDICT
204
+ end
205
+
206
+ --[[
207
+ Runs a factory and checks the shape of what came back. Shared by the bare form and the
208
+ configured one, so the two cannot drift on what a second return means.
209
+ ]]
210
+ local function build<T>(factory: Factory<T>, config: any): (Check<T>, { Stage })
211
+ local check, stage = factory(config)
212
+
213
+ if type(check) ~= "function" then
214
+ error(
215
+ `a policy factory returns the per-request function, and this one returned {typeof(check)}. `
216
+ .. `The two stages are the point: nw.policy(function(config) --[[ once ]] return `
217
+ .. `function(ctx, value) --[[ per request ]] return nw.allow() end end).`,
218
+ 3
219
+ )
220
+ end
221
+
222
+ if stage ~= nil and type(stage) ~= "function" then
223
+ error(
224
+ `a policy factory's second return is its server stage, a function run once on the server `
225
+ .. `when the protocol is sealed, and this one returned {typeof(stage)}. Write it as `
226
+ .. `return check, function() --[[ server only, once ]] end — or return the check alone.`,
227
+ 3
228
+ )
229
+ end
230
+
231
+ return check, if stage then { stage } else {}
232
+ end
233
+
234
+ local function callable<T>(check: Check<T>, factory: Factory<T>?, stages: { Stage }): Policy<T>
235
+ local self = { __nwCheck = check, __nwStages = stages }
236
+
237
+ return (
238
+ setmetatable(self, {
239
+ __call = function(_, config: any): Configured<T>
240
+ if not factory then
241
+ error(
242
+ "this policy takes no configuration, so calling it with a table does nothing "
243
+ .. "but build another one. Attach it directly — authorize = policy.alive — "
244
+ .. "without the parentheses. A policy that should take options declares "
245
+ .. "them in its factory: nw.policy(function(config) ... end).",
246
+ 2
247
+ )
248
+ end
249
+
250
+ if config ~= nil and type(config) ~= "table" then
251
+ error(
252
+ "a policy is configured with a table of options, got "
253
+ .. type(config)
254
+ .. ". Write it as policy.originNearCharacter({ maxStuds = 12 }) — the "
255
+ .. "table reaches the factory's `config` parameter.",
256
+ 2
257
+ )
258
+ end
259
+
260
+ local configured, built = build(factory, config or {})
261
+ return callable(configured, factory, built)
262
+ end,
263
+
264
+ __metatable = "netweave.Policy",
265
+ }) :: any
266
+ ) :: Policy<T>
267
+ end
268
+
269
+ --[=[
270
+ @within Policy
271
+ @function policy
272
+ @param factory (config: any) -> (ctx: Ctx, payload: T) -> Verdict
273
+ @return Policy<T>
274
+
275
+ Declares a policy. The outer function runs once, now; the one it returns runs per request.
276
+
277
+ ```lua
278
+ policy.ownsSlot = nw.policy(function(config)
279
+ local slots = config.slots or 3 -- once
280
+ return function(ctx, slot) -- per request
281
+ return slot < slots and nw.allow() or nw.deny("no such slot")
282
+ end
283
+ end)
284
+ ```
285
+
286
+ Do the expensive part in the outer function: read configuration, build lookup tables. Whatever
287
+ the inner function closes over is paid for once.
288
+
289
+ **The outer function runs on both sides**, because the declaration file is required by both, so
290
+ it is not where a server-only module is reached. That is the third piece, the **server stage**:
291
+ a second function the factory may return, run once on the server when the protocol is sealed,
292
+ before any packet decodes, and discarded on the client.
293
+
294
+ ```lua
295
+ policy.canAfford = nw.policy(function()
296
+ local wallet: Wallet? = nil -- filled by the stage, server only
297
+
298
+ return function(ctx, offer) -- per request, server only
299
+ local held = (wallet :: Wallet).goldOf(ctx.player)
300
+ return held >= offer.gold and nw.allow() or nw.deny(`holds {held}`)
301
+ end, function() -- once, at seal, server only
302
+ wallet = require(game:GetService("ServerStorage").Wallet)
303
+ end
304
+ end)
305
+ ```
306
+
307
+ A policy attached to two channels runs its stage once. A stage that raises or yields fails the
308
+ seal with the policy's channel in the message — a startup error, loud — because a check that runs
309
+ before its stage did would be a policy deciding on nothing.
310
+
311
+ :::caution
312
+ The inner function must not yield. It runs inside the receive loop, holding a `ctx` that is
313
+ recycled the moment it returns; since `PLAN-M5` a yield across another packet of the same player
314
+ is reported at `authorize`.
315
+ :::
316
+ ]=]
317
+ function Policy.policy<T>(factory: Factory<T>): Policy<T>
318
+ if type(factory) ~= "function" then
319
+ error(
320
+ `nw.policy takes a factory that returns the per-request check, got {typeof(factory)}. `
321
+ .. `Write it as: nw.policy(function(config) return function(ctx, value) return `
322
+ .. `nw.allow() end end). The outer function runs once at load; the inner one runs per `
323
+ .. `request.`,
324
+ 2
325
+ )
326
+ end
327
+
328
+ local check, stages = build(factory, {})
329
+
330
+ return callable(check, factory, stages)
331
+ end
332
+
333
+ --[=[
334
+ @within Policy
335
+ @function all
336
+ @param ... Configured<T> -- a policy, bare or reconfigured; evaluated left to right
337
+ @return Policy<T>
338
+
339
+ Every policy must allow. The first denial wins and the rest do not run.
340
+
341
+ ```lua
342
+ authorize = nw.all(policy.alive, policy.originNearCharacter({ maxStuds = 12 })),
343
+ ```
344
+
345
+ A value passed to [Policy.allow] is threaded onward, so policies compose as a narrowing
346
+ pipeline: the second sees what the first approved, not what arrived.
347
+
348
+ :::note
349
+ Order is the cheap check first. `policy.alive` reads one property; a distance check reads a
350
+ character, then a part, then subtracts two vectors. Under a flood that difference is the whole
351
+ cost of the channel.
352
+ :::
353
+ ]=]
354
+ function Policy.all<T>(...: Configured<T>): Policy<T>
355
+ local count = select("#", ...)
356
+
357
+ if count == 0 then
358
+ error(
359
+ "nw.all composes policies and was given none. Pass the ones this channel needs — "
360
+ .. "nw.all(policy.alive, policy.ownsSlot) — or attach the single policy directly "
361
+ .. "rather than wrapping it.",
362
+ 2
363
+ )
364
+ end
365
+
366
+ --[[ Flattened once, at declaration time: the per-request path walks an array, never a varargs
367
+ pack and never a nested composition. ]]
368
+ --[[ `table.create` yields `{unknown}` and Luau arrays are invariant, so the cast is the only
369
+ way to pre-size this rather than growing it element by element. ]]
370
+ local checks: { Check<T> } = (table.create(count) :: any) :: { Check<T> }
371
+
372
+ --[[ Every member's stages, in member order, so a composed policy's stages are the members'
373
+ and `Namespace.runStages` sees the same function for a member attached elsewhere too. ]]
374
+ local stages: { Stage } = {}
375
+
376
+ for index = 1, count do
377
+ local member = select(index, ...) :: any
378
+
379
+ if type(member) ~= "table" or type(member.__nwCheck) ~= "function" then
380
+ error(
381
+ `nw.all takes policies; argument {index} is a {type(member)}. Every argument has to come `
382
+ .. `from nw.policy — a bare function is not one, because a policy carries the check `
383
+ .. `netweave calls and the shape nw.all composes.`,
384
+ 2
385
+ )
386
+ end
387
+
388
+ checks[index] = member.__nwCheck
389
+
390
+ for _, stage in member.__nwStages do
391
+ table.insert(stages, stage)
392
+ end
393
+ end
394
+
395
+ local function composed(ctx: Context.Ctx, payload: T): Verdict
396
+ local current: any = payload
397
+
398
+ for index = 1, count do
399
+ local verdict = checks[index](ctx, current)
400
+
401
+ --[[ Read out of the shared record before the next policy overwrites it. ]]
402
+ if not verdict.ok then
403
+ return Policy.deny(verdict.reason or "denied")
404
+ end
405
+
406
+ if verdict.value ~= nil then
407
+ current = verdict.value
408
+ end
409
+ end
410
+
411
+ return Policy.allow(current)
412
+ end
413
+
414
+ return callable(composed, nil, stages)
415
+ end
416
+
417
+ --[=[
418
+ @within Policy
419
+ @function stagesOf
420
+ @param policy Configured<T>
421
+ @return { Stage }
422
+ @private
423
+
424
+ The server stages a policy carries — its own, or for a composed one its members'. Read by the
425
+ channel at declaration and run by `Namespace.runStages`, once per distinct function.
426
+ ]=]
427
+ function Policy.stagesOf<T>(policy: Configured<T>): { Stage }
428
+ return (policy :: any).__nwStages
429
+ end
430
+
431
+ --[=[
432
+ @within Policy
433
+ @function checkOf
434
+ @param policy Configured<T>
435
+ @return Check<T>
436
+ @private
437
+
438
+ Unwraps a policy to the function the transport calls. Deliberately not public: a game that
439
+ reaches for this is running authorization somewhere other than the declaration, which is the
440
+ thing this design exists to prevent.
441
+ ]=]
442
+ function Policy.checkOf<T>(policy: Configured<T>): Check<T>
443
+ return (policy :: any).__nwCheck
444
+ end
445
+
446
+ --[=[
447
+ @within Policy
448
+ @function isPolicy
449
+ @param value any
450
+ @return boolean
451
+ @private
452
+ ]=]
453
+ function Policy.isPolicy(value: any): boolean
454
+ return type(value) == "table" and type((value :: any).__nwCheck) == "function"
455
+ end
456
+
457
+ return Policy