@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
@@ -7,13 +7,18 @@ export * from './game/index.ts'
7
7
  export * from './gate/index.ts'
8
8
  export * from './handler/index.ts'
9
9
  export * from './list/index.ts'
10
+ export * from './listing/index.ts'
10
11
  export * from './lobbies/index.ts'
11
12
  export * from './lobby/index.ts'
13
+ export * from './login/index.ts'
14
+ export * from './matchmaking/index.ts'
12
15
  export * from './peer/index.ts'
13
16
  export * from './players/index.ts'
17
+ export * from './query/index.ts'
14
18
  export * from './redirect/index.ts'
15
19
  export * from './rpc/index.ts'
16
20
  export * from './server/index.ts'
21
+ export * from './services/index.ts'
17
22
  export * from './settings/index.ts'
18
23
  export * from './sql/index.ts'
19
24
  export * from './stats/index.ts'
@@ -5,6 +5,7 @@ import { MasterFault } from '../../fault/index.ts'
5
5
  import type { GameState } from '../../game/index.ts'
6
6
  import type { MasterPeer } from '../../peer/index.ts'
7
7
  import type { MasterSettings } from '../../settings/index.ts'
8
+ import { FilterCost } from '../../sql/cost/index.ts'
8
9
  import { SqlError } from '../../sql/error/index.ts'
9
10
  import { SqlRemote } from '../../sql/remote/index.ts'
10
11
  import type { SqlStore } from '../../sql/store/index.ts'
@@ -154,6 +155,9 @@ export class SqlGameList extends GameList {
154
155
  )
155
156
  }
156
157
 
158
+ const refusal = this.refusal(text, parts)
159
+ if (refusal !== null) throw MasterFault.invalid(refusal)
160
+
157
161
  for (const part of parts) {
158
162
  if (part === '') continue
159
163
 
@@ -172,6 +176,9 @@ export class SqlGameList extends GameList {
172
176
  const table = PhotonHashtable.of()
173
177
  if (this.games.size === 0) return table
174
178
 
179
+ const refusal = this.refusal(query, [query])
180
+ if (refusal !== null) throw MasterFault.invalid(refusal)
181
+
175
182
  const limit = this.settings.limitSqlFilterResults
176
183
  const statement = limit <= 0 ? query : `${query} LIMIT ${String(limit)}`
177
184
 
@@ -238,9 +245,8 @@ export class SqlGameList extends GameList {
238
245
  peer: MasterPeer,
239
246
  users: readonly string[] | null,
240
247
  ): GameState | null {
241
- for (let offset = 0; ; offset += 1) {
242
- const id = this.found(`${filter} LIMIT 1 OFFSET ${String(offset)}`)[0]
243
- if (id === undefined || id === '') return null
248
+ for (const id of this.found(`${filter} LIMIT -1`)) {
249
+ if (id === '') return null
244
250
  if (typeof id !== 'string') {
245
251
  throw MasterFault.internal(
246
252
  `Unable to cast object of type '${SqlGameList.boxed(id)}' to type 'System.String'.`,
@@ -251,6 +257,34 @@ export class SqlGameList extends GameList {
251
257
  if (game === null) return null
252
258
  if (this.eligible(game, peer, users)) return game
253
259
  }
260
+
261
+ return null
262
+ }
263
+
264
+ /**
265
+ * Why the filters of one request can't run, or null
266
+ * @param text everything the client sent
267
+ * @param filters the filters in it
268
+ */
269
+ private refusal(text: string, filters: readonly string[]): string | null {
270
+ const settings = this.settings
271
+ if (text.length > settings.limitSqlFilterLength) return 'Filter is too long'
272
+
273
+ const timed = settings.limitSqlFilterTime > 0
274
+ let rows = 0
275
+ for (const filter of filters) {
276
+ const cost = FilterCost.of(filter)
277
+ if (cost.depth > settings.limitSqlFilterDepth) {
278
+ return 'Filter is nested too deeply'
279
+ }
280
+
281
+ if (!timed && cost.recursive) return 'Filter is recursive'
282
+ rows += cost.rows(this.games.size)
283
+ }
284
+
285
+ return !timed && rows > settings.limitSqlFilterScan
286
+ ? 'Filter scans too many games'
287
+ : null
254
288
  }
255
289
 
256
290
  /**
@@ -0,0 +1,133 @@
1
+ import { LobbyType } from '../../balancing/code/lobby/index.ts'
2
+ import { GetGameListRequestFormat } from '../../balancing/format/game/list/request/index.ts'
3
+ import { LobbyFormat } from '../../balancing/format/shared/lobby/index.ts'
4
+ import type { FindFriendsRequest } from '../../balancing/packet/friends/request/index.ts'
5
+ import { FindFriendsResponse } from '../../balancing/packet/friends/response/index.ts'
6
+ import type { GetGameListRequest } from '../../balancing/packet/game/list/request/index.ts'
7
+ import { GetGameListResponse } from '../../balancing/packet/game/list/response/index.ts'
8
+ import type { JoinLobbyRequest } from '../../balancing/packet/lobby/join/request/index.ts'
9
+ import { JoinLobbyResponse } from '../../balancing/packet/lobby/join/response/index.ts'
10
+ import { LeaveLobbyResponse } from '../../balancing/packet/lobby/leave/response/index.ts'
11
+ import type { GetLobbyStatsRequest } from '../../balancing/packet/lobby/stats/request/index.ts'
12
+ import type { ReplyAdapter } from '../../balancing/packet/reply/index.ts'
13
+ import type { MasterApplication } from '../application/index.ts'
14
+ import { MasterFault } from '../fault/index.ts'
15
+ import type { MasterPeer } from '../peer/index.ts'
16
+ import type { QueryScreen } from '../query/index.ts'
17
+
18
+ /**
19
+ * Lobbies, game lists, friends and lobby statistics for clients
20
+ * @class
21
+ */
22
+ export class Listing {
23
+ /**
24
+ * Lobbies, players and statistics
25
+ */
26
+ private readonly application: MasterApplication
27
+
28
+ /**
29
+ * Turns away filters with banned words
30
+ */
31
+ private readonly screen: QueryScreen
32
+
33
+ /**
34
+ * @param application lobbies, players and statistics
35
+ * @param screen turns away filters with banned words
36
+ */
37
+ public constructor(application: MasterApplication, screen: QueryScreen) {
38
+ this.application = application
39
+ this.screen = screen
40
+ }
41
+
42
+ /**
43
+ * Lets a client into a lobby
44
+ * @param peer who's asking
45
+ * @param packet lobby, game count and filter
46
+ */
47
+ public join(peer: MasterPeer, packet: JoinLobbyRequest): null {
48
+ const application = this.application
49
+ const refusal = LobbyFormat.refusal(packet.lobby)
50
+ if (refusal !== null) throw MasterFault.invalid(refusal)
51
+
52
+ application.leave(peer)
53
+
54
+ const lobby = application.lobbies.resolve(
55
+ packet.lobby?.name ?? null,
56
+ packet.lobby?.type ?? LobbyType.DEFAULT,
57
+ )
58
+ const list = lobby.join(
59
+ peer,
60
+ packet.gameListCount ?? 0,
61
+ peer.properties(packet.gameProperties),
62
+ )
63
+
64
+ peer.lobby = lobby
65
+ peer.send(JoinLobbyResponse.success().to(packet))
66
+ if (list !== null) peer.send(list)
67
+
68
+ return null
69
+ }
70
+
71
+ /**
72
+ * Lets a client out of its lobby
73
+ * @param peer who's asking
74
+ */
75
+ public leave(peer: MasterPeer): ReplyAdapter {
76
+ if (peer.lobby === null) return LeaveLobbyResponse.notJoined()
77
+
78
+ this.application.leave(peer)
79
+ return LeaveLobbyResponse.success()
80
+ }
81
+
82
+ /**
83
+ * Lists the games of a SQL lobby that pass a filter
84
+ * @param packet lobby and filter
85
+ */
86
+ public list(packet: GetGameListRequest): ReplyAdapter {
87
+ const word = this.screen.refusal(packet.sqlFilter, true)
88
+ if (word !== null) throw word
89
+
90
+ const refusal = GetGameListRequestFormat.refusal(packet)
91
+ if (refusal !== null) throw MasterFault.invalid(refusal)
92
+
93
+ const lobby = this.application.lobbies.resolve(
94
+ packet.lobby?.name ?? '',
95
+ packet.lobby?.type ?? LobbyType.DEFAULT,
96
+ )
97
+ return GetGameListResponse.success(lobby.query(packet.sqlFilter ?? ''))
98
+ }
99
+
100
+ /**
101
+ * Tells a client which friends are online and where
102
+ * @param packet user ids and option bits
103
+ */
104
+ public friends(packet: FindFriendsRequest): ReplyAdapter {
105
+ const found = this.application.players.find(
106
+ packet.userIds,
107
+ packet.options ?? 0,
108
+ )
109
+
110
+ return FindFriendsResponse.success(found.online, found.rooms)
111
+ }
112
+
113
+ /**
114
+ * Tells a client how full lobbies are
115
+ * @param packet lobbies the client asks about
116
+ */
117
+ public stats(packet: GetLobbyStatsRequest): ReplyAdapter {
118
+ return this.application.lobbyStats.answer(packet)
119
+ }
120
+
121
+ /**
122
+ * Switches lobby statistics on or off for a client
123
+ * @param peer who asked
124
+ * @param wanted whether they want them
125
+ */
126
+ public watch(peer: MasterPeer, wanted: boolean): void {
127
+ const statistics = this.application.lobbyStats
128
+
129
+ peer.lobbyStats = wanted
130
+ if (wanted) statistics.subscribe(peer)
131
+ else statistics.unsubscribe(peer)
132
+ }
133
+ }
@@ -36,6 +36,11 @@ export type LobbyHost = GameHost & {
36
36
  */
37
37
  readonly timers: Timers
38
38
 
39
+ /**
40
+ * How many games the whole application knows
41
+ */
42
+ readonly tracked: number
43
+
39
44
  /**
40
45
  * A game of any lobby by name, or null
41
46
  * @param id name of the game
@@ -410,6 +415,10 @@ export class AppLobby {
410
415
  )
411
416
  }
412
417
 
418
+ if (this.host.tracked >= this.host.settings.gamesCountLimit) {
419
+ throw MasterFault.of(ErrorCode.SERVER_FULL, 'Server is full')
420
+ }
421
+
413
422
  const game = new GameState(id, this, server, this.host)
414
423
  if (placement.properties !== null) game.configure(placement.properties)
415
424
 
@@ -0,0 +1,424 @@
1
+ import { randomUUID } from 'node:crypto'
2
+
3
+ import { AuthenticationFailure } from '../../authentication/failure/index.ts'
4
+ import type { AuthenticationAttempt } from '../../authentication/provider/index.ts'
5
+ import type { AuthenticationResult } from '../../authentication/result/index.ts'
6
+ import {
7
+ CustomAuthenticationResult,
8
+ CustomAuthenticationType,
9
+ } from '../../balancing/code/authentication/index.ts'
10
+ import { ErrorCode } from '../../balancing/code/error/index.ts'
11
+ import { ErrorMessage } from '../../balancing/code/message/index.ts'
12
+ import { OperationCode } from '../../balancing/code/operation/index.ts'
13
+ import { Grant } from '../../balancing/entity/grant/index.ts'
14
+ import { CredentialsFormat } from '../../balancing/format/shared/credentials/index.ts'
15
+ import { GrantFormat } from '../../balancing/format/shared/grant/index.ts'
16
+ import { ParameterWriter } from '../../balancing/format/writer/index.ts'
17
+ import type { AuthenticateRequest } from '../../balancing/packet/authenticate/request/index.ts'
18
+ import { AuthenticateResponse } from '../../balancing/packet/authenticate/response/index.ts'
19
+ import { UnknownResponse } from '../../balancing/packet/unknown/index.ts'
20
+ import { PhotonDictionary } from '../../binary/dictionary/index.ts'
21
+ import { OperationResponse } from '../../binary/response/index.ts'
22
+ import { Shape } from '../../binary/shape/index.ts'
23
+ import { PhotonValue } from '../../binary/value/index.ts'
24
+ import type { AuthToken } from '../../crypto/token/record/index.ts'
25
+ import { Envelope } from '../../envelope/index.ts'
26
+ import { JsonValues } from '../../message/json/values/index.ts'
27
+ import { OnceAnswer } from '../../message/once/index.ts'
28
+ import { PhotonPeer } from '../../message/peer/index.ts'
29
+ import { MasterFault } from '../fault/index.ts'
30
+ import { type MasterPeer, PeerStage } from '../peer/index.ts'
31
+ import type { MasterServices } from '../services/index.ts'
32
+
33
+ /**
34
+ * Logs clients into a Master by token or credentials
35
+ * @class
36
+ */
37
+ export class MasterLogin {
38
+ /**
39
+ * Lobbies, tokens and settings of the server
40
+ */
41
+ private readonly services: MasterServices
42
+
43
+ /**
44
+ * Writes the parameters of an authenticate response
45
+ */
46
+ private readonly grants: GrantFormat
47
+
48
+ /**
49
+ * @param services lobbies, tokens and settings of the server
50
+ */
51
+ public constructor(services: MasterServices) {
52
+ this.services = services
53
+ this.grants = new GrantFormat()
54
+ }
55
+
56
+ /**
57
+ * A user id that's never blank
58
+ * @param userId what's known, or null
59
+ */
60
+ private static named(userId: string | null): string {
61
+ return userId === null || userId.trim() === '' ? randomUUID() : userId
62
+ }
63
+
64
+ /**
65
+ * A provider's values as the dictionary a client reads, or null
66
+ * @param data values from the provider, or null
67
+ */
68
+ private static dictionary(
69
+ data: Readonly<Record<string, unknown>> | null,
70
+ ): PhotonDictionary | null {
71
+ if (data === null) return null
72
+
73
+ const dictionary = PhotonDictionary.of(Shape.string(), Shape.any())
74
+ for (const [name, value] of Object.entries<unknown>(data)) {
75
+ dictionary.set(name, JsonValues.read(value))
76
+ }
77
+
78
+ return dictionary
79
+ }
80
+
81
+ /**
82
+ * Finishes the login of a client whose init request brought a token
83
+ * @param peer who connected
84
+ * @param photon what's known about the connection
85
+ * @param token what the init request brought
86
+ */
87
+ public async admit(
88
+ peer: MasterPeer,
89
+ photon: PhotonPeer,
90
+ token: AuthToken,
91
+ ): Promise<void> {
92
+ const refusal = this.refusal(photon, token)
93
+ if (refusal !== null) {
94
+ peer.send(
95
+ Envelope.reliable<OperationResponse>(
96
+ OperationResponse.failure(
97
+ OperationCode.AUTHENTICATE_ONCE,
98
+ refusal.code,
99
+ refusal.message,
100
+ ),
101
+ ),
102
+ )
103
+ await peer.session.close()
104
+ return
105
+ }
106
+
107
+ this.enter(peer, token, false)
108
+ peer.send(OnceAnswer.master(this.services.gate.seal(token)))
109
+ }
110
+
111
+ /**
112
+ * Logs a client in, or tells it why not
113
+ * @param peer who's logging in
114
+ * @param packet token or credentials
115
+ */
116
+ public async authenticate(
117
+ peer: MasterPeer,
118
+ packet: AuthenticateRequest,
119
+ ): Promise<void> {
120
+ this.services.application.timers.cancel(peer.noAuth)
121
+ peer.noAuth = null
122
+
123
+ try {
124
+ await this.login(peer, packet)
125
+ } catch (cause) {
126
+ if (peer.stage === PeerStage.AUTHENTICATING) {
127
+ peer.stage = PeerStage.INITIAL
128
+ }
129
+
130
+ const fault = MasterFault.from(cause)
131
+ peer.send(
132
+ AuthenticateResponse.failure(fault.code, fault.message).to(packet),
133
+ )
134
+ }
135
+ }
136
+
137
+ /**
138
+ * Why a good token still doesn't get a client in, or null
139
+ * @param photon what's known about the connection
140
+ * @param token what the client brought
141
+ */
142
+ private refusal(photon: PhotonPeer, token: AuthToken): MasterFault | null {
143
+ const application = this.services.application
144
+ if (application.settings.requireSecureConnection && !photon.secure) {
145
+ return MasterFault.of(
146
+ ErrorCode.SECURE_CONNECTION_REQUIRED,
147
+ ErrorMessage.SECURE_CONNECTION_REQUIRED,
148
+ )
149
+ }
150
+
151
+ if (application.blocked(token.userId)) {
152
+ return MasterFault.of(ErrorCode.USER_BLOCKED, ErrorMessage.USER_BLOCKED)
153
+ }
154
+
155
+ return null
156
+ }
157
+
158
+ /**
159
+ * Marks a client as logged in
160
+ * @param peer who's in
161
+ * @param token what they hold from now on
162
+ * @param lobbyStats whether they asked for lobby statistics
163
+ */
164
+ private enter(peer: MasterPeer, token: AuthToken, lobbyStats: boolean): void {
165
+ peer.token = token
166
+ peer.userId = token.userId
167
+ peer.stage = PeerStage.AUTHENTICATED
168
+ peer.lobbyStats = lobbyStats
169
+ this.services.application.attach(peer)
170
+ }
171
+
172
+ /**
173
+ * Works through one authenticate request
174
+ * @param peer who's logging in
175
+ * @param packet token or credentials
176
+ */
177
+ private async login(
178
+ peer: MasterPeer,
179
+ packet: AuthenticateRequest,
180
+ ): Promise<void> {
181
+ if (this.services.gate.tokened(packet)) {
182
+ await this.byToken(peer, packet)
183
+ return
184
+ }
185
+
186
+ const credentials = packet.credentials
187
+ const refusal = CredentialsFormat.refusal(credentials)
188
+ if (refusal !== null) throw MasterFault.invalid(refusal)
189
+
190
+ const fault = this.services.applications.fault(
191
+ credentials?.applicationId ?? null,
192
+ credentials?.appVersion ?? null,
193
+ )
194
+ if (fault !== null) {
195
+ throw MasterFault.of(ErrorCode.INVALID_AUTHENTICATION, fault)
196
+ }
197
+
198
+ if (this.services.authenticator.enabled) {
199
+ await this.custom(peer, packet)
200
+ return
201
+ }
202
+
203
+ const given = credentials?.userId ?? null
204
+ const userId = MasterLogin.named(given)
205
+ const token = this.issue(packet, userId, {})
206
+
207
+ this.enter(peer, token, packet.lobbyStats)
208
+ peer.send(
209
+ AuthenticateResponse.success(
210
+ Grant.of(null, this.sealed(token), userId === given ? null : userId),
211
+ ).to(packet),
212
+ )
213
+ this.greet(peer)
214
+ }
215
+
216
+ /**
217
+ * Logs a client in by the token it brought
218
+ * @param peer who's logging in
219
+ * @param packet the token
220
+ */
221
+ private async byToken(
222
+ peer: MasterPeer,
223
+ packet: AuthenticateRequest,
224
+ ): Promise<void> {
225
+ const verdict = this.services.gate.verify(packet.token)
226
+ const token = verdict.token
227
+ if (token === null) {
228
+ throw MasterFault.of(
229
+ verdict.refusal?.code ?? ErrorCode.INVALID_AUTHENTICATION,
230
+ verdict.refusal?.message ?? ErrorMessage.AUTH_TOKEN_TYPE_NOT_SUPPORTED,
231
+ )
232
+ }
233
+
234
+ const photon = PhotonPeer.of(peer.session.channel)
235
+ const application = this.services.application
236
+ if (application.blocked(token.userId)) {
237
+ throw MasterFault.of(ErrorCode.USER_BLOCKED, ErrorMessage.USER_BLOCKED)
238
+ }
239
+
240
+ if (
241
+ application.settings.requireSecureConnection &&
242
+ photon?.secure !== true
243
+ ) {
244
+ peer.send(
245
+ AuthenticateResponse.failure(
246
+ ErrorCode.SECURE_CONNECTION_REQUIRED,
247
+ ErrorMessage.SECURE_CONNECTION_REQUIRED,
248
+ ).to(packet),
249
+ )
250
+ await peer.session.close()
251
+ return
252
+ }
253
+
254
+ const userId = token.userId
255
+ this.enter(peer, token, packet.lobbyStats)
256
+ peer.send(
257
+ AuthenticateResponse.success(
258
+ Grant.master(
259
+ PhotonValue.string(this.services.gate.seal(token)),
260
+ userId === null || userId === '' ? null : userId,
261
+ ),
262
+ ).to(packet),
263
+ )
264
+ this.greet(peer)
265
+ }
266
+
267
+ /**
268
+ * Logs a client in through custom authentication
269
+ * @param peer who's logging in
270
+ * @param packet credentials and auth values
271
+ */
272
+ private async custom(
273
+ peer: MasterPeer,
274
+ packet: AuthenticateRequest,
275
+ ): Promise<void> {
276
+ const credentials = packet.credentials
277
+ const attempt: AuthenticationAttempt = {
278
+ type:
279
+ credentials?.authentication?.type ?? CustomAuthenticationType.CUSTOM,
280
+ parameters: credentials?.authentication?.parameters ?? null,
281
+ data: credentials?.authentication?.data ?? null,
282
+ applicationId: credentials?.applicationId ?? null,
283
+ applicationVersion: credentials?.appVersion ?? null,
284
+ userId: credentials?.userId ?? null,
285
+ }
286
+
287
+ peer.stage = PeerStage.AUTHENTICATING
288
+
289
+ let result: AuthenticationResult
290
+ try {
291
+ result = await this.services.authenticator.authenticate(attempt)
292
+ } catch (cause) {
293
+ if (!(cause instanceof AuthenticationFailure)) throw cause
294
+
295
+ throw MasterFault.of(
296
+ ErrorCode.CUSTOM_AUTHENTICATION_FAILED,
297
+ cause.message,
298
+ )
299
+ }
300
+
301
+ peer.stage = PeerStage.INITIAL
302
+ if (!peer.session.channel.isActive) return
303
+
304
+ if (result.code === CustomAuthenticationResult.DATA) {
305
+ peer.send(
306
+ AuthenticateResponse.success(
307
+ Grant.of(
308
+ null,
309
+ null,
310
+ null,
311
+ null,
312
+ null,
313
+ null,
314
+ MasterLogin.dictionary(result.data),
315
+ ),
316
+ ).to(packet),
317
+ )
318
+ return
319
+ }
320
+
321
+ if (result.code !== CustomAuthenticationResult.OK) {
322
+ throw MasterFault.of(
323
+ ErrorCode.CUSTOM_AUTHENTICATION_FAILED,
324
+ result.message ?? '',
325
+ )
326
+ }
327
+
328
+ const provided = result.userId
329
+ const userId = MasterLogin.named(
330
+ provided === null || provided === ''
331
+ ? (credentials?.userId ?? null)
332
+ : provided,
333
+ )
334
+ const token = this.issue(packet, userId, result.cookie ?? {})
335
+ const writer = ParameterWriter.of(OperationCode.AUTHENTICATE)
336
+
337
+ this.grants.write(
338
+ Grant.of(
339
+ null,
340
+ this.sealed(token),
341
+ userId,
342
+ result.nickname,
343
+ null,
344
+ null,
345
+ MasterLogin.dictionary(result.data),
346
+ ),
347
+ writer,
348
+ )
349
+ this.enter(peer, token, packet.lobbyStats)
350
+ peer.send(
351
+ UnknownResponse.of(
352
+ OperationCode.AUTHENTICATE,
353
+ ErrorCode.OK,
354
+ result.message,
355
+ writer.parameters,
356
+ ).to(packet),
357
+ )
358
+ this.greet(peer)
359
+ }
360
+
361
+ /**
362
+ * Sends a fresh login its first lobby statistics, if it asked for them
363
+ * @param peer who just logged in
364
+ */
365
+ private greet(peer: MasterPeer): void {
366
+ if (peer.lobbyStats) this.services.application.lobbyStats.subscribe(peer)
367
+ }
368
+
369
+ /**
370
+ * A new token for a login that brought none
371
+ * @param packet what the client sent
372
+ * @param userId who the token is for
373
+ * @param cookie values custom authentication wants remembered
374
+ */
375
+ private issue(
376
+ packet: AuthenticateRequest,
377
+ userId: string,
378
+ cookie: Readonly<Record<string, unknown>>,
379
+ ): AuthToken {
380
+ const authority = this.services.authority
381
+ if (authority === null) {
382
+ throw new Error(ErrorMessage.AUTH_TOKEN_TYPE_NOT_SUPPORTED)
383
+ }
384
+
385
+ const credentials = packet.credentials
386
+ const application = credentials?.applicationId ?? null
387
+ const version = credentials?.appVersion ?? null
388
+
389
+ return authority.issue({
390
+ /**
391
+ * Who the token is for
392
+ */
393
+ userId,
394
+ /**
395
+ * What custom authentication wants remembered
396
+ */
397
+ authCookie: cookie,
398
+ /**
399
+ * Bit flags the servers pass along
400
+ */
401
+ flags: packet.flags ?? 0,
402
+ /**
403
+ * Custom unless the client said otherwise
404
+ */
405
+ customAuthProvider:
406
+ credentials?.authentication?.type ?? CustomAuthenticationType.CUSTOM,
407
+ ...(application === null ? {} : { applicationId: application }),
408
+ ...(version === null ? {} : { applicationVersion: version }),
409
+ })
410
+ }
411
+
412
+ /**
413
+ * A token as the value a client is sent
414
+ * @param token what to seal
415
+ */
416
+ private sealed(token: AuthToken): PhotonValue {
417
+ const authority = this.services.authority
418
+ if (authority === null) {
419
+ throw new Error(ErrorMessage.AUTH_TOKEN_TYPE_NOT_SUPPORTED)
420
+ }
421
+
422
+ return PhotonValue.string(authority.seal(token, false))
423
+ }
424
+ }