@netifyjs/protocol 1.0.0-alpha.3 → 1.0.0-beta.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.
Files changed (175) hide show
  1. package/package.json +2 -2
  2. package/src/codec/index.ts +51 -221
  3. package/src/dispatch/dispatcher/index.ts +89 -47
  4. package/src/dispatch/session/index.ts +6 -24
  5. package/src/index.ts +2 -4
  6. package/src/photon/balancing/codec/index.ts +27 -53
  7. package/src/photon/balancing/format/authenticate/request/index.ts +52 -6
  8. package/src/photon/balancing/format/friends/request/index.ts +21 -5
  9. package/src/photon/balancing/format/game/create/request/index.ts +45 -8
  10. package/src/photon/balancing/format/game/debug/request/index.ts +19 -4
  11. package/src/photon/balancing/format/game/join/request/index.ts +65 -13
  12. package/src/photon/balancing/format/game/list/request/index.ts +29 -3
  13. package/src/photon/balancing/format/game/random/request/index.ts +58 -10
  14. package/src/photon/balancing/format/groups/request/index.ts +19 -3
  15. package/src/photon/balancing/format/index.ts +7 -0
  16. package/src/photon/balancing/format/leave/request/index.ts +19 -3
  17. package/src/photon/balancing/format/lobby/join/request/index.ts +23 -3
  18. package/src/photon/balancing/format/lobby/stats/request/index.ts +19 -3
  19. package/src/photon/balancing/format/once/request/index.ts +31 -8
  20. package/src/photon/balancing/format/properties/get/request/index.ts +31 -4
  21. package/src/photon/balancing/format/properties/set/request/index.ts +36 -7
  22. package/src/photon/balancing/format/raise/request/index.ts +76 -10
  23. package/src/photon/balancing/format/reader/index.ts +75 -6
  24. package/src/photon/balancing/format/regions/request/index.ts +16 -1
  25. package/src/photon/balancing/format/rpc/request/index.ts +26 -3
  26. package/src/photon/balancing/format/settings/request/index.ts +15 -2
  27. package/src/photon/balancing/format/shared/credentials/index.ts +77 -33
  28. package/src/photon/balancing/format/shared/lobby/index.ts +41 -5
  29. package/src/photon/balancing/format/shared/options/index.ts +56 -24
  30. package/src/photon/balancing/format/table/index.ts +399 -0
  31. package/src/photon/balancing/index.ts +11 -1
  32. package/src/photon/balancing/travel/index.ts +15 -12
  33. package/src/photon/client/connection/index.ts +6 -6
  34. package/src/photon/cluster/back/index.ts +32 -45
  35. package/src/photon/cluster/dresser/index.ts +7 -8
  36. package/src/photon/cluster/front/index.ts +25 -49
  37. package/src/photon/cluster/grid/index.ts +1 -1
  38. package/src/photon/cluster/mover/index.ts +12 -12
  39. package/src/photon/cluster/press/index.ts +2 -18
  40. package/src/photon/cluster/route/game/index.ts +9 -11
  41. package/src/photon/cluster/route/master/index.ts +15 -34
  42. package/src/photon/cluster/route/name/index.ts +4 -21
  43. package/src/photon/cluster/seat/game/index.ts +6 -26
  44. package/src/photon/cluster/seat/master/index.ts +1 -1
  45. package/src/photon/cluster/sessions/index.ts +5 -6
  46. package/src/photon/cluster/spread/index.ts +8 -147
  47. package/src/photon/enet/client/index.ts +1 -8
  48. package/src/photon/enet/gateway/index.ts +5 -15
  49. package/src/photon/enet/index.ts +1 -1
  50. package/src/photon/enet/link/index.ts +34 -15
  51. package/src/photon/enet/outbound/index.ts +279 -0
  52. package/src/photon/enet/peer/index.ts +59 -0
  53. package/src/photon/enet/transport/index.ts +8 -24
  54. package/src/photon/game/admission/index.ts +353 -0
  55. package/src/photon/game/bag/index.ts +13 -0
  56. package/src/photon/game/broadcast/index.ts +79 -0
  57. package/src/photon/game/editor/index.ts +446 -0
  58. package/src/photon/game/gate/index.ts +9 -8
  59. package/src/photon/game/handler/index.ts +30 -3
  60. package/src/photon/game/history/index.ts +234 -0
  61. package/src/photon/game/hooked/index.ts +16 -15
  62. package/src/photon/game/index.ts +12 -1
  63. package/src/photon/game/lifecycle/index.ts +193 -0
  64. package/src/photon/game/peer/index.ts +1 -10
  65. package/src/photon/game/properties/index.ts +342 -0
  66. package/src/photon/game/room/index.ts +435 -1793
  67. package/src/photon/game/rooms/index.ts +2 -1
  68. package/src/photon/game/seats/index.ts +237 -0
  69. package/src/photon/game/server/index.ts +12 -2
  70. package/src/photon/game/services/index.ts +41 -0
  71. package/src/photon/game/settings/index.ts +22 -0
  72. package/src/photon/game/snapshot/index.ts +133 -0
  73. package/src/photon/game/throttle/index.ts +60 -0
  74. package/src/photon/game/touch/index.ts +2 -5
  75. package/src/photon/game/venue/index.ts +31 -0
  76. package/src/photon/master/application/index.ts +7 -0
  77. package/src/photon/master/gate/index.ts +12 -8
  78. package/src/photon/master/handler/index.ts +36 -748
  79. package/src/photon/master/index.ts +5 -0
  80. package/src/photon/master/list/sql/index.ts +37 -3
  81. package/src/photon/master/listing/index.ts +133 -0
  82. package/src/photon/master/lobby/index.ts +9 -0
  83. package/src/photon/master/login/index.ts +424 -0
  84. package/src/photon/master/matchmaking/index.ts +282 -0
  85. package/src/photon/master/query/index.ts +45 -0
  86. package/src/photon/master/redirect/index.ts +8 -7
  87. package/src/photon/master/services/index.ts +35 -0
  88. package/src/photon/master/settings/index.ts +44 -0
  89. package/src/photon/master/sql/cost/index.ts +263 -0
  90. package/src/photon/master/sql/index.ts +1 -0
  91. package/src/photon/message/client/index.ts +14 -11
  92. package/src/photon/message/handler/index.ts +22 -64
  93. package/src/photon/message/pipeline/index.ts +12 -12
  94. package/src/photon/message/server/index.ts +87 -43
  95. package/src/photon/message/watch/index.ts +14 -37
  96. package/src/photon/server/deferral/index.ts +57 -0
  97. package/src/photon/server/host/index.ts +32 -10
  98. package/src/photon/server/index.ts +1 -0
  99. package/src/photon/tcp/client/index.ts +1 -1
  100. package/src/photon/tcp/codec/index.ts +13 -42
  101. package/src/photon/tcp/server/index.ts +4 -4
  102. package/src/photon/websocket/bridge/index.ts +16 -20
  103. package/src/photon/websocket/message/index.ts +27 -39
  104. package/src/photon/websocket/path/index.ts +2 -5
  105. package/src/scale/fanout/index.ts +6 -6
  106. package/src/scale/index.ts +2 -4
  107. package/src/scale/outbound/index.ts +192 -0
  108. package/src/scale/relay/index.ts +20 -31
  109. package/src/scale/sink/index.ts +6 -11
  110. package/src/scale/transport/index.ts +27 -44
  111. package/src/scale/tunnel/index.ts +37 -91
  112. package/src/smartfox/common/bluebox/gateway/index.ts +401 -0
  113. package/src/smartfox/common/bluebox/index.ts +4 -0
  114. package/src/smartfox/{x2 → common}/bluebox/transport/index.ts +36 -23
  115. package/src/smartfox/common/index.ts +5 -0
  116. package/src/smartfox/common/strikes/index.ts +74 -0
  117. package/src/smartfox/pro/bluebox/index.ts +176 -4
  118. package/src/smartfox/pro/codec/index.ts +8 -7
  119. package/src/smartfox/pro/escalation/index.ts +28 -20
  120. package/src/smartfox/pro/flood/index.ts +2 -2
  121. package/src/smartfox/pro/format/extension/raw/index.ts +12 -2
  122. package/src/smartfox/pro/handler/chat/index.ts +11 -8
  123. package/src/smartfox/pro/handler/login/index.ts +2 -25
  124. package/src/smartfox/pro/handler/shared/index.ts +4 -3
  125. package/src/smartfox/pro/index.ts +11 -5
  126. package/src/smartfox/pro/login/gate/index.ts +166 -0
  127. package/src/smartfox/pro/login/index.ts +1 -0
  128. package/src/smartfox/pro/moderation/index.ts +220 -0
  129. package/src/smartfox/pro/options/index.ts +5 -5
  130. package/src/smartfox/pro/protocol/index.ts +62 -8
  131. package/src/smartfox/pro/web/index.ts +33 -26
  132. package/src/smartfox/pro/zone/index.ts +59 -282
  133. package/src/smartfox/pro/zones/index.ts +3 -3
  134. package/src/smartfox/x2/bluebox/index.ts +149 -4
  135. package/src/smartfox/x2/chat/index.ts +9 -19
  136. package/src/smartfox/x2/codec/index.ts +31 -39
  137. package/src/smartfox/x2/config/index.ts +6 -1
  138. package/src/smartfox/x2/data/array/index.ts +96 -60
  139. package/src/smartfox/x2/data/object/index.ts +144 -82
  140. package/src/smartfox/x2/data/serializer/index.ts +41 -23
  141. package/src/smartfox/x2/flood/gate/index.ts +19 -13
  142. package/src/smartfox/x2/format/buddy/init/response/index.ts +4 -3
  143. package/src/smartfox/x2/format/find/rooms/response/index.ts +4 -3
  144. package/src/smartfox/x2/format/find/users/response/index.ts +4 -3
  145. package/src/smartfox/x2/format/group/subscribe/response/index.ts +4 -3
  146. package/src/smartfox/x2/format/login/response/index.ts +4 -3
  147. package/src/smartfox/x2/format/mmo/position/response/index.ts +8 -6
  148. package/src/smartfox/x2/format/room/join/response/index.ts +4 -3
  149. package/src/smartfox/x2/games/index.ts +35 -8
  150. package/src/smartfox/x2/hall/index.ts +0 -6
  151. package/src/smartfox/x2/handler/session/index.ts +1 -1
  152. package/src/smartfox/x2/index.ts +8 -3
  153. package/src/smartfox/x2/member/index.ts +10 -3
  154. package/src/smartfox/x2/packet/login/response/index.ts +12 -0
  155. package/src/smartfox/x2/protocol/index.ts +11 -1
  156. package/src/smartfox/x2/rooms/index.ts +1 -2
  157. package/src/smartfox/x2/sessions/index.ts +6 -0
  158. package/src/smartfox/x2/udp/index.ts +61 -24
  159. package/src/smartfox/x2/web/index.ts +35 -17
  160. package/src/smartfox/x2/websocket/index.ts +18 -36
  161. package/src/smartfox/x2/zone/index.ts +77 -28
  162. package/src/smartfox/x2/zones/index.ts +17 -5
  163. package/src/photon/enet/handler/index.ts +0 -65
  164. package/src/scale/hosted/index.ts +0 -68
  165. package/src/scale/outlet/index.ts +0 -121
  166. package/src/smartfox/pro/bluebox/gateway/index.ts +0 -310
  167. package/src/smartfox/pro/bluebox/session/index.ts +0 -63
  168. package/src/smartfox/pro/bluebox/transport/index.ts +0 -104
  169. package/src/smartfox/x2/bluebox/gateway/index.ts +0 -315
  170. /package/src/smartfox/{x2 → common}/bluebox/session/index.ts +0 -0
  171. /package/src/smartfox/{pro → common}/counters/index.ts +0 -0
  172. /package/src/smartfox/{pro → common}/counters/memory/index.ts +0 -0
  173. /package/src/smartfox/{pro → common}/counters/offender/index.ts +0 -0
  174. /package/src/smartfox/{pro → common}/counters/store/index.ts +0 -0
  175. /package/src/smartfox/{pro → common}/sequence/index.ts +0 -0
@@ -50,9 +50,10 @@ export class FindUsersResponseFormat implements X2Format<FindUsersResponse> {
50
50
  const users: User[] = []
51
51
  if (list === null) return users
52
52
 
53
- for (const entry of list.entries()) {
54
- if (entry.value instanceof SfsArray) {
55
- users.push(User.fromArray(entry.value))
53
+ for (let at = 0; at < list.size; at++) {
54
+ const value = list.valueAt(at)
55
+ if (value instanceof SfsArray) {
56
+ users.push(User.fromArray(value))
56
57
  }
57
58
  }
58
59
 
@@ -65,9 +65,10 @@ export class SubscribeRoomGroupResponseFormat implements X2Format<SubscribeRoomG
65
65
  const rooms: Room[] = []
66
66
  if (list === null) return rooms
67
67
 
68
- for (const entry of list.entries()) {
69
- if (entry.value instanceof SfsArray) {
70
- rooms.push(Room.fromArray(entry.value))
68
+ for (let at = 0; at < list.size; at++) {
69
+ const value = list.valueAt(at)
70
+ if (value instanceof SfsArray) {
71
+ rooms.push(Room.fromArray(value))
71
72
  }
72
73
  }
73
74
 
@@ -75,9 +75,10 @@ export class LoginResponseFormat implements X2Format<LoginResponse> {
75
75
  const rooms: Room[] = []
76
76
  if (list === null) return rooms
77
77
 
78
- for (const entry of list.entries()) {
79
- if (entry.value instanceof SfsArray) {
80
- rooms.push(Room.fromArray(entry.value))
78
+ for (let at = 0; at < list.size; at++) {
79
+ const value = list.valueAt(at)
80
+ if (value instanceof SfsArray) {
81
+ rooms.push(Room.fromArray(value))
81
82
  }
82
83
  }
83
84
 
@@ -77,10 +77,11 @@ export class SetUserPositionResponseFormat implements X2Format<SetUserPositionRe
77
77
  const users: ProximityUser[] = []
78
78
  if (list === null) return users
79
79
 
80
- for (const entry of list.entries()) {
81
- if (!(entry.value instanceof SfsArray)) continue
80
+ for (let at = 0; at < list.size; at++) {
81
+ const value = list.valueAt(at)
82
+ if (!(value instanceof SfsArray)) continue
82
83
 
83
- const user = User.fromArray(entry.value)
84
+ const user = User.fromArray(value)
84
85
  users.push({ user, playerId: user.playerId, entry: user.entry })
85
86
  }
86
87
 
@@ -95,10 +96,11 @@ export class SetUserPositionResponseFormat implements X2Format<SetUserPositionRe
95
96
  const items: ProximityItem[] = []
96
97
  if (list === null) return items
97
98
 
98
- for (const entry of list.entries()) {
99
- if (!(entry.value instanceof SfsArray)) continue
99
+ for (let at = 0; at < list.size; at++) {
100
+ const value = list.valueAt(at)
101
+ if (!(value instanceof SfsArray)) continue
100
102
 
101
- const item = MMOItem.fromArray(entry.value)
103
+ const item = MMOItem.fromArray(value)
102
104
  items.push({ item, entry: item.entry })
103
105
  }
104
106
 
@@ -72,10 +72,11 @@ export class JoinRoomResponseFormat implements X2Format<JoinRoomResponse> {
72
72
  const occupants: Occupant[] = []
73
73
  if (list === null) return occupants
74
74
 
75
- for (const entry of list.entries()) {
76
- if (!(entry.value instanceof SfsArray)) continue
75
+ for (let at = 0; at < list.size; at++) {
76
+ const value = list.valueAt(at)
77
+ if (!(value instanceof SfsArray)) continue
77
78
 
78
- const user = User.fromArray(entry.value)
79
+ const user = User.fromArray(value)
79
80
  occupants.push({ user, playerId: user.playerId })
80
81
  }
81
82
 
@@ -63,6 +63,11 @@ export class Games {
63
63
  */
64
64
  private static readonly maxInvited: number = 8
65
65
 
66
+ /**
67
+ * Longest an invitation waits for its answer, in seconds
68
+ */
69
+ private static readonly maxSeconds: number = 300
70
+
66
71
  /**
67
72
  * The zone the users are in
68
73
  */
@@ -104,27 +109,49 @@ export class Games {
104
109
  accepted: Accepted | null = null,
105
110
  hall: Hall | null = null,
106
111
  ): void {
112
+ const wait = Math.min(Math.max(1, seconds), Games.maxSeconds)
113
+ let waiting = this.waitingOn(inviter)
114
+
107
115
  for (const invitee of new Set<Member>(invitees)) {
108
116
  if (invitee === inviter) continue
117
+ if (waiting >= this.zone.maxInvitations) {
118
+ inviter.send(
119
+ InvitationReplyResponse.failure(
120
+ this.zone.error(ErrorCode.INVITATION_NOT_VALID),
121
+ ),
122
+ )
123
+ return
124
+ }
109
125
 
110
126
  const id = this.nextId++
111
- const timer = setTimeout(
112
- (): void => {
113
- this.expire(id)
114
- },
115
- Math.max(1, seconds) * 1000,
116
- )
127
+ const timer = setTimeout((): void => {
128
+ this.expire(id)
129
+ }, wait * 1000)
117
130
  timer.unref()
118
131
 
132
+ waiting += 1
119
133
  this.pending.set(id, { id, inviter, invitee, hall, accepted, timer })
120
134
  invitee.send(
121
135
  this.shares(inviter, invitee)
122
- ? InvitationEvent.known(id, inviter.id, seconds, params)
123
- : InvitationEvent.of(id, inviter.view(), seconds, params),
136
+ ? InvitationEvent.known(id, inviter.id, wait, params)
137
+ : InvitationEvent.of(id, inviter.view(), wait, params),
124
138
  )
125
139
  }
126
140
  }
127
141
 
142
+ /**
143
+ * How many invitations a user has waiting for an answer
144
+ * @param inviter who sent them
145
+ */
146
+ private waitingOn(inviter: Member): number {
147
+ let count = 0
148
+ for (const pending of this.pending.values()) {
149
+ if (pending.inviter === inviter) count += 1
150
+ }
151
+
152
+ return count
153
+ }
154
+
128
155
  /**
129
156
  * Passes an answer to whoever sent the invitation
130
157
  * @param member who's answering
@@ -55,11 +55,6 @@ export class Hall {
55
55
  */
56
56
  public readonly secret: Set<string>
57
57
 
58
- /**
59
- * Ids of users an invitation lets in without the password
60
- */
61
- public readonly invited: Set<number>
62
-
63
58
  /**
64
59
  * Items placed in an MMO room, by id
65
60
  */
@@ -94,7 +89,6 @@ export class Hall {
94
89
  this.owners = new Map<string, number>()
95
90
  this.globals = new Set<string>()
96
91
  this.secret = new Set<string>()
97
- this.invited = new Set<number>()
98
92
  this.items = new Map<number, PlacedItem>()
99
93
  this.autoRemove = AutoRemove.DEFAULT
100
94
  this.creator = null
@@ -3,7 +3,7 @@ import { IdleStateEvent } from '@netifyjs/netify'
3
3
  import { Closed } from '../../../../dispatch/event/index.ts'
4
4
  import { on, when } from '../../../../dispatch/route/index.ts'
5
5
  import type { Session } from '../../../../dispatch/session/index.ts'
6
- import { BlueBox } from '../../bluebox/gateway/index.ts'
6
+ import { BlueBox } from '../../bluebox/index.ts'
7
7
  import type { Member } from '../../member/index.ts'
8
8
  import { ManualDisconnectionRequest } from '../../packet/disconnect/request/index.ts'
9
9
  import { ErrorCode } from '../../packet/error/codes/index.ts'
@@ -2,12 +2,17 @@ export { ShardBalancer } from './balancer/index.ts'
2
2
  export type { ShardBalancerOptions } from './balancer/index.ts'
3
3
  export { Bans, MemoryBanStore } from './ban/index.ts'
4
4
  export type { BanModeId, BanRecord, BanStore } from './ban/index.ts'
5
- export { BlueBox, BlueBoxSession, BlueBoxTransport } from './bluebox/index.ts'
5
+ export { BlueBox } from './bluebox/index.ts'
6
6
  export type { BlueBoxOptions } from './bluebox/index.ts'
7
7
  export { Buddies } from './buddies/index.ts'
8
8
  export { Catalogue } from './catalogue/index.ts'
9
- export { MemoryCounterStore, Offender } from '../pro/counters/index.ts'
10
- export type { CounterStore } from '../pro/counters/index.ts'
9
+ export {
10
+ BlueBoxSession,
11
+ BlueBoxTransport,
12
+ MemoryCounterStore,
13
+ Offender,
14
+ } from '../common/index.ts'
15
+ export type { CounterStore } from '../common/index.ts'
11
16
  export { Chat } from './chat/index.ts'
12
17
  export { PacketCipher } from './cipher/index.ts'
13
18
  export { SmartFox2XCodec } from './codec/index.ts'
@@ -46,6 +46,11 @@ export class Member {
46
46
  */
47
47
  public token: string
48
48
 
49
+ /**
50
+ * Secret their client echoes to bind UDP
51
+ */
52
+ public readonly udpKey: bigint
53
+
49
54
  /**
50
55
  * Their connection, null while they're reconnecting
51
56
  */
@@ -163,6 +168,8 @@ export class Member {
163
168
  this.address = channel.remoteAddress
164
169
  this.privilege = privilege
165
170
  this.token = token
171
+ this.udpKey =
172
+ crypto.getRandomValues(new BigInt64Array(1))[0] ?? BigInt(Date.now())
166
173
  this.channel = channel
167
174
  this.variables = new Map<string, UserVariable>()
168
175
  this.rooms = new Map<number, number>()
@@ -217,7 +224,7 @@ export class Member {
217
224
  */
218
225
  public send(packet: object): void {
219
226
  if (this.channel !== null) {
220
- this.channel.writeAndFlushSync(packet)
227
+ this.channel.writeAndFlush(packet)
221
228
  return
222
229
  }
223
230
 
@@ -234,10 +241,10 @@ export class Member {
234
241
  this.token = token
235
242
 
236
243
  for (const packet of this.backlog.splice(0)) {
237
- channel.writeSync(packet)
244
+ channel.write(packet)
238
245
  }
239
246
 
240
- void channel.flush()
247
+ channel.flush()
241
248
  }
242
249
 
243
250
  /**
@@ -122,6 +122,18 @@ export class LoginResponse {
122
122
  */
123
123
  public static readonly nodeKey: string = '_sid'
124
124
 
125
+ /**
126
+ * Key in the extra data that carries the secret for UDP
127
+ */
128
+ public static readonly udpKey: string = '_udp'
129
+
130
+ /**
131
+ * Secret the client echoes to bind UDP, or null
132
+ */
133
+ public get udpKey(): bigint | null {
134
+ return this.params?.getLong(LoginResponse.udpKey) ?? null
135
+ }
136
+
125
137
  /**
126
138
  * Cluster node the user landed on, or null
127
139
  */
@@ -32,6 +32,11 @@ export type SmartFox2XOptions = {
32
32
  * Largest message taken once unpacked in bytes
33
33
  */
34
34
  readonly maxInflatedSize?: number
35
+
36
+ /**
37
+ * Most objects and arrays read inside each other, 32 by default
38
+ */
39
+ readonly maxDepth?: number
35
40
  }
36
41
 
37
42
  /**
@@ -159,7 +164,9 @@ export class SmartFox2X extends Protocol {
159
164
  this.maxInflatedSize =
160
165
  options.maxInflatedSize ??
161
166
  Math.max(this.maxMessageSize, SmartFox2X.defaultMaxInflatedSize)
162
- this.serializer = new SfsSerializer()
167
+ this.serializer = new SfsSerializer(
168
+ options.maxDepth ?? SfsSerializer.defaultMaxDepth,
169
+ )
163
170
  this.inbound = new FormatRegistry<number, X2Format>()
164
171
  this.outbound = new FormatRegistry<number, X2Format>()
165
172
 
@@ -212,6 +219,9 @@ export class SmartFox2X extends Protocol {
212
219
  return 'Unpacked message limit is invalid'
213
220
  }
214
221
 
222
+ const depth = options.maxDepth ?? SfsSerializer.defaultMaxDepth
223
+ if (!Number.isInteger(depth) || depth < 3) return 'Depth limit is invalid'
224
+
215
225
  return null
216
226
  }
217
227
 
@@ -218,7 +218,7 @@ export class Rooms {
218
218
  options: JoinOptions = {},
219
219
  ): SfsError | null {
220
220
  const spectator = options.spectator ?? false
221
- const forced = options.forced ?? hall.invited.has(member.id)
221
+ const forced = options.forced ?? false
222
222
 
223
223
  const error = this.joinRefusal(member, hall, options, spectator, forced)
224
224
  if (error !== null) return error
@@ -226,7 +226,6 @@ export class Rooms {
226
226
  const previous = member.lastJoined
227
227
  const playerId = hall.enter(member, spectator)
228
228
  this.zone.hear(member, hall)
229
- hall.invited.delete(member.id)
230
229
  member.lastJoined = hall.id
231
230
 
232
231
  const mmo = hall.room.mmo !== null
@@ -15,4 +15,10 @@ export type SessionLookup = {
15
15
  * @param id their user id
16
16
  */
17
17
  byUser(id: number): Channel | null
18
+
19
+ /**
20
+ * The key a logged in user binds UDP with, or null
21
+ * @param id their user id
22
+ */
23
+ udpKey(id: number): bigint | null
18
24
  }
@@ -34,6 +34,11 @@ export type UdpOptions = {
34
34
  * Goes in front of the link topics the gateway uses
35
35
  */
36
36
  readonly topic?: string
37
+
38
+ /**
39
+ * Refuses clients that don't send their key, false by default so stock clients can bind
40
+ */
41
+ readonly requireKey?: boolean
37
42
  }
38
43
 
39
44
  /**
@@ -71,6 +76,11 @@ export class UdpGateway extends InboundHandlerAdapter {
71
76
  */
72
77
  public static readonly topic: string = 'netify:protocol:smartfox2x:udp'
73
78
 
79
+ /**
80
+ * Key of the init message that carries the user's UDP key
81
+ */
82
+ public static readonly keyField: string = 'k'
83
+
74
84
  /**
75
85
  * Largest payload the 2 byte size field can describe
76
86
  */
@@ -101,6 +111,11 @@ export class UdpGateway extends InboundHandlerAdapter {
101
111
  */
102
112
  private readonly shards: DatagramSwitch | null
103
113
 
114
+ /**
115
+ * Whether clients must send their key
116
+ */
117
+ private readonly requireKey: boolean
118
+
104
119
  /**
105
120
  * The socket datagrams leave on, or null
106
121
  */
@@ -125,6 +140,7 @@ export class UdpGateway extends InboundHandlerAdapter {
125
140
  this.byAddress = new Map<string, UdpPeer>()
126
141
  this.byChannel = new Map<Channel, UdpPeer>()
127
142
  this.socket = null
143
+ this.requireKey = options.requireKey ?? false
128
144
  this.shards =
129
145
  link === null || link.count < 2
130
146
  ? null
@@ -134,7 +150,7 @@ export class UdpGateway extends InboundHandlerAdapter {
134
150
  bytes: Uint8Array,
135
151
  sender: PacketAddress,
136
152
  via: number,
137
- ): Promise<DatagramVerdict> =>
153
+ ): DatagramVerdict =>
138
154
  this.receive(ByteBuf.wrap(bytes), sender, via),
139
155
  )
140
156
  }
@@ -183,7 +199,7 @@ export class UdpGateway extends InboundHandlerAdapter {
183
199
  frame === null ||
184
200
  frame.length - 3 > UdpGateway.largest
185
201
  ) {
186
- channel.writeAndFlushSync(packet)
202
+ channel.writeAndFlush(packet)
187
203
  return false
188
204
  }
189
205
 
@@ -197,15 +213,15 @@ export class UdpGateway extends InboundHandlerAdapter {
197
213
  * Remembers the socket datagrams leave on
198
214
  * @param context the datagram socket
199
215
  */
200
- public override channelActive(context: HandlerContext): Promise<void> {
216
+ public override channelActive(context: HandlerContext): void {
201
217
  const socket = context.channel
202
218
 
203
219
  this.socket = socket
204
220
  this.shards?.bind((bytes: Uint8Array, recipient: PacketAddress): void => {
205
- socket.writeAndFlushSync(new DatagramPacket(bytes, recipient))
221
+ socket.writeAndFlush(new DatagramPacket(bytes, recipient))
206
222
  })
207
223
 
208
- return context.fireChannelActive()
224
+ context.fireChannelActive()
209
225
  }
210
226
 
211
227
  /**
@@ -213,18 +229,15 @@ export class UdpGateway extends InboundHandlerAdapter {
213
229
  * @param context the datagram socket
214
230
  * @param message a datagram, or anything else
215
231
  */
216
- public override async channelRead(
217
- context: HandlerContext,
218
- message: unknown,
219
- ): Promise<void> {
232
+ public override channelRead(context: HandlerContext, message: unknown): void {
220
233
  if (!(message instanceof DatagramPacket) || message.sender === null) {
221
- await context.fireChannelRead(message)
234
+ context.fireChannelRead(message)
222
235
  return
223
236
  }
224
237
 
225
238
  const content = message.content
226
239
  const start = content.readerIndex
227
- const verdict = await this.receive(content, message.sender, null)
240
+ const verdict = this.receive(content, message.sender, null)
228
241
  if (verdict === 'taken' || this.shards === null) return
229
242
 
230
243
  content.readerIndex = start
@@ -240,11 +253,11 @@ export class UdpGateway extends InboundHandlerAdapter {
240
253
  * @param sender where it came from
241
254
  * @param via shard whose socket it arrived on, null for this one
242
255
  */
243
- private async receive(
256
+ private receive(
244
257
  content: ByteBuf,
245
258
  sender: PacketAddress,
246
259
  via: number | null,
247
- ): Promise<DatagramVerdict> {
260
+ ): DatagramVerdict {
248
261
  if (content.readableBytes < 4) return 'taken'
249
262
 
250
263
  const header = content.readUint8()
@@ -272,7 +285,7 @@ export class UdpGateway extends InboundHandlerAdapter {
272
285
 
273
286
  if (peer === undefined) return 'missed'
274
287
 
275
- await this.deliver(peer, envelope)
288
+ this.deliver(peer, envelope, size)
276
289
  return 'taken'
277
290
  }
278
291
 
@@ -292,7 +305,7 @@ export class UdpGateway extends InboundHandlerAdapter {
292
305
  return
293
306
  }
294
307
 
295
- this.socket?.writeAndFlushSync(new DatagramPacket(frame, recipient))
308
+ this.socket?.writeAndFlush(new DatagramPacket(frame, recipient))
296
309
  }
297
310
 
298
311
  /**
@@ -308,13 +321,8 @@ export class UdpGateway extends InboundHandlerAdapter {
308
321
  ): boolean {
309
322
  const user = envelope.getNumber('u')
310
323
  const channel = user === null ? null : this.sessions.byUser(user)
311
- if (channel === null) return false
312
- if (
313
- UdpGateway.plain(channel.remoteAddress) !==
314
- UdpGateway.plain(sender.hostname)
315
- ) {
316
- return true
317
- }
324
+ if (user === null || channel === null) return false
325
+ if (!this.proves(envelope, user, channel, sender)) return true
318
326
 
319
327
  this.bind(channel, sender, via)
320
328
 
@@ -330,6 +338,33 @@ export class UdpGateway extends InboundHandlerAdapter {
330
338
  return true
331
339
  }
332
340
 
341
+ /**
342
+ * Whether an init message shows it comes from the user it names
343
+ * @param envelope the init message
344
+ * @param user the user id it names
345
+ * @param channel the connection that user logged in on
346
+ * @param sender where it came from
347
+ */
348
+ private proves(
349
+ envelope: SfsObject,
350
+ user: number,
351
+ channel: Channel,
352
+ sender: PacketAddress,
353
+ ): boolean {
354
+ const key = envelope.getLong(UdpGateway.keyField)
355
+ if (key !== null) return key === this.sessions.udpKey(user)
356
+ if (this.requireKey) return false
357
+
358
+ const host = UdpGateway.plain(sender.hostname)
359
+ if (UdpGateway.plain(channel.remoteAddress) !== host) return false
360
+
361
+ const known = this.byChannel.get(channel)
362
+ return (
363
+ known === undefined ||
364
+ UdpGateway.key(known.address) === UdpGateway.key(sender)
365
+ )
366
+ }
367
+
333
368
  /**
334
369
  * Remembers where a user's datagrams come from
335
370
  * @param channel the connection they logged in on
@@ -372,21 +407,23 @@ export class UdpGateway extends InboundHandlerAdapter {
372
407
  * Passes an extension message to the sender's own connection
373
408
  * @param peer who sent it
374
409
  * @param envelope the message
410
+ * @param size bytes it took on the wire
375
411
  */
376
- private async deliver(peer: UdpPeer, envelope: SfsObject): Promise<void> {
412
+ private deliver(peer: UdpPeer, envelope: SfsObject, size: number): void {
377
413
  const user = envelope.getNumber('u')
378
414
  if (user === null || this.sessions.byUser(user) !== peer.channel) return
379
415
 
380
416
  const request = this.protocol.decode(envelope)
381
417
  if (!(request instanceof ExtensionRequest)) return
382
418
 
383
- await peer.channel.handleMessage(
419
+ peer.channel.receive(
384
420
  ExtensionRequest.of(
385
421
  request.command,
386
422
  request.params,
387
423
  request.room,
388
424
  envelope.getLong('i') ?? 0n,
389
425
  ),
426
+ size,
390
427
  )
391
428
  }
392
429
  }
@@ -5,9 +5,10 @@ import {
5
5
  HttpResponseStatus,
6
6
  InboundHandlerAdapter,
7
7
  type HandlerContext,
8
+ type Outcome,
8
9
  } from '@netifyjs/netify'
9
10
 
10
- import { BlueBox } from '../bluebox/gateway/index.ts'
11
+ import { BlueBox } from '../bluebox/index.ts'
11
12
  import type { SessionLookup } from '../sessions/index.ts'
12
13
 
13
14
  /**
@@ -73,31 +74,48 @@ export class WebHandler extends InboundHandlerAdapter {
73
74
  * @param context the HTTP connection
74
75
  * @param message an aggregated request
75
76
  */
76
- public override async channelRead(
77
+ public override channelRead(
77
78
  context: HandlerContext,
78
79
  message: unknown,
79
- ): Promise<void> {
80
+ ): Outcome {
80
81
  if (
81
82
  !(message instanceof FullHttpRequest) ||
82
83
  message.method !== HttpMethod.POST
83
84
  ) {
84
- await context.fireChannelRead(message)
85
+ context.fireChannelRead(message)
85
86
  return
86
87
  }
87
88
 
88
89
  const path = WebHandler.pathOf(message.uri)
89
90
 
90
91
  if (path === BlueBox.path && this.bluebox !== null) {
91
- await this.tunnel(context, message, this.bluebox)
92
- return
92
+ return this.held(context, this.tunnel(context, message, this.bluebox))
93
93
  }
94
94
 
95
95
  if (path === WebHandler.cryptoPath && this.sessions !== null) {
96
- await this.key(context, message, this.sessions)
97
- return
96
+ return this.held(context, this.key(context, message, this.sessions))
98
97
  }
99
98
 
100
- await context.fireChannelRead(message)
99
+ context.fireChannelRead(message)
100
+ }
101
+
102
+ /**
103
+ * Holds later requests back while one is being answered
104
+ * @param context the HTTP connection
105
+ * @param work the answer on its way
106
+ */
107
+ private async held(
108
+ context: HandlerContext,
109
+ work: Promise<void>,
110
+ ): Promise<void> {
111
+ const channel = context.channel
112
+ channel.pauseReads()
113
+
114
+ try {
115
+ await work
116
+ } finally {
117
+ channel.resumeReads()
118
+ }
101
119
  }
102
120
 
103
121
  /**
@@ -113,7 +131,7 @@ export class WebHandler extends InboundHandlerAdapter {
113
131
  ): Promise<void> {
114
132
  const value = this.field(request, BlueBox.field)
115
133
  if (value === null) {
116
- await this.reply(context, request, HttpResponseStatus.BAD_REQUEST, '')
134
+ this.reply(context, request, HttpResponseStatus.BAD_REQUEST, '')
117
135
  return
118
136
  }
119
137
 
@@ -122,7 +140,7 @@ export class WebHandler extends InboundHandlerAdapter {
122
140
  context.channel.remoteAddress,
123
141
  context.channel.remotePort,
124
142
  )
125
- await this.reply(context, request, HttpResponseStatus.OK, answer)
143
+ this.reply(context, request, HttpResponseStatus.OK, answer)
126
144
  }
127
145
 
128
146
  /**
@@ -139,11 +157,11 @@ export class WebHandler extends InboundHandlerAdapter {
139
157
  const token = this.field(request, WebHandler.tokenField)
140
158
  const secret = token === null ? null : await sessions.secure(token)
141
159
  if (secret === null) {
142
- await this.reply(context, request, HttpResponseStatus.BAD_REQUEST, '')
160
+ this.reply(context, request, HttpResponseStatus.BAD_REQUEST, '')
143
161
  return
144
162
  }
145
163
 
146
- await this.reply(context, request, HttpResponseStatus.OK, secret)
164
+ this.reply(context, request, HttpResponseStatus.OK, secret)
147
165
  }
148
166
 
149
167
  /**
@@ -166,18 +184,18 @@ export class WebHandler extends InboundHandlerAdapter {
166
184
  * @param status how it went
167
185
  * @param text the response body
168
186
  */
169
- private async reply(
187
+ private reply(
170
188
  context: HandlerContext,
171
189
  request: FullHttpRequest,
172
190
  status: HttpResponseStatus,
173
191
  text: string,
174
- ): Promise<void> {
192
+ ): void {
175
193
  const response = new FullHttpResponse(status, text)
176
194
  response.headers.set('content-type', 'text/plain; charset=utf-8')
177
195
  response.setContentLength(response.content.readableBytes)
178
196
  response.setKeepAlive(request.isKeepAlive())
179
197
 
180
- await context.writeAndFlush(response)
181
- if (!request.isKeepAlive()) await context.close()
198
+ context.writeAndFlush(response)
199
+ if (!request.isKeepAlive()) void context.close()
182
200
  }
183
201
  }