multiplayer 2.1.0__tar.gz → 2.3.0__tar.gz

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 (22) hide show
  1. {multiplayer-2.1.0 → multiplayer-2.3.0}/PKG-INFO +1 -1
  2. {multiplayer-2.1.0 → multiplayer-2.3.0}/pyproject.toml +1 -1
  3. {multiplayer-2.1.0 → multiplayer-2.3.0}/pyproject.toml.orig +1 -1
  4. {multiplayer-2.1.0 → multiplayer-2.3.0}/src/multiplayer/game.py +31 -1
  5. {multiplayer-2.1.0 → multiplayer-2.3.0}/src/multiplayer/save.py +34 -4
  6. {multiplayer-2.1.0 → multiplayer-2.3.0}/src/multiplayer/server.py +242 -16
  7. {multiplayer-2.1.0 → multiplayer-2.3.0}/README.md +0 -0
  8. {multiplayer-2.1.0 → multiplayer-2.3.0}/src/multiplayer/__init__.py +0 -0
  9. {multiplayer-2.1.0 → multiplayer-2.3.0}/src/multiplayer/client.py +0 -0
  10. {multiplayer-2.1.0 → multiplayer-2.3.0}/src/multiplayer/data/cities.csv +0 -0
  11. {multiplayer-2.1.0 → multiplayer-2.3.0}/src/multiplayer/data/countries.csv +0 -0
  12. {multiplayer-2.1.0 → multiplayer-2.3.0}/src/multiplayer/data/egyptian_gods.csv +0 -0
  13. {multiplayer-2.1.0 → multiplayer-2.3.0}/src/multiplayer/data/european_kings.csv +0 -0
  14. {multiplayer-2.1.0 → multiplayer-2.3.0}/src/multiplayer/data/european_queens.csv +0 -0
  15. {multiplayer-2.1.0 → multiplayer-2.3.0}/src/multiplayer/data/greek_gods.csv +0 -0
  16. {multiplayer-2.1.0 → multiplayer-2.3.0}/src/multiplayer/data/planets_moons.csv +0 -0
  17. {multiplayer-2.1.0 → multiplayer-2.3.0}/src/multiplayer/data/rivers.csv +0 -0
  18. {multiplayer-2.1.0 → multiplayer-2.3.0}/src/multiplayer/data/roman_gods.csv +0 -0
  19. {multiplayer-2.1.0 → multiplayer-2.3.0}/src/multiplayer/data/seas_oceans.csv +0 -0
  20. {multiplayer-2.1.0 → multiplayer-2.3.0}/src/multiplayer/exceptions.py +0 -0
  21. {multiplayer-2.1.0 → multiplayer-2.3.0}/src/multiplayer/py.typed +0 -0
  22. {multiplayer-2.1.0 → multiplayer-2.3.0}/src/multiplayer/utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: multiplayer
3
- Version: 2.1.0
3
+ Version: 2.3.0
4
4
  Summary: Library that allows you to manage multiple players, locally, on a network, or on the Internet.
5
5
  Author: devfred78
6
6
  Author-email: devfred78 <devfred78@gmail.com>
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "multiplayer"
3
- version = "2.1.0"
3
+ version = "2.3.0"
4
4
  description = "Library that allows you to manage multiple players, locally, on a network, or on the Internet."
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "multiplayer"
3
- version = "2.1.0"
3
+ version = "2.3.0"
4
4
  description = "Library that allows you to manage multiple players, locally, on a network, or on the Internet."
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -524,17 +524,22 @@ class GameGroup:
524
524
  parameters (dict): Custom parameters for the group.
525
525
  """
526
526
 
527
- def __init__(self, name: str, **kwargs: Any):
527
+ def __init__(self, name: str, password: str | None = None, **kwargs: Any):
528
528
  """Initializes a new game group.
529
529
 
530
530
  Args:
531
531
  name (str): The name of the group.
532
+ password: Optional password required to access the group.
532
533
  **kwargs: Optional custom parameters for the group.
533
534
  """
534
535
  self._id: str = str(uuid.uuid4())
535
536
  self.name: str = name
536
537
  self._games: List[Game] = []
537
538
  self.parameters: Dict[str, Any] = kwargs
539
+ self._hash: str | None = (
540
+ bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
541
+ if password else None
542
+ )
538
543
 
539
544
  @property
540
545
  def ID(self) -> str:
@@ -554,6 +559,31 @@ class GameGroup:
554
559
  """
555
560
  return tuple(self._games)
556
561
 
562
+ @property
563
+ def hash(self) -> str | None:
564
+ """The bcrypt hash of the group access password, if configured."""
565
+ return self._hash
566
+
567
+ @property
568
+ def password_required(self) -> bool:
569
+ """Whether access to the group requires a password."""
570
+ return self._hash is not None
571
+
572
+ def check_password(self, password: str | None) -> bool:
573
+ """Checks a plain-text group password."""
574
+ return bool(
575
+ self._hash
576
+ and isinstance(password, str)
577
+ and bcrypt.checkpw(password.encode(), self._hash.encode())
578
+ )
579
+
580
+ def change_password(self, new_password: str | None) -> None:
581
+ """Sets a password or removes protection when ``None`` is supplied."""
582
+ self._hash = (
583
+ bcrypt.hashpw(new_password.encode(), bcrypt.gensalt()).decode()
584
+ if new_password else None
585
+ )
586
+
557
587
  def add_game(self, game: Game | str) -> None:
558
588
  """Adds a game session to the group.
559
589
 
@@ -32,6 +32,7 @@ _SUPPORTED_CLASSES: Dict[str, type] = {
32
32
 
33
33
  # Name of the table used for the SQLite storage format.
34
34
  _SQLITE_TABLE = "objects"
35
+ _SERVER_CONFIG_CLASS = "__server_config__"
35
36
 
36
37
 
37
38
  def _player_to_dict(player: Player) -> Dict[str, Any]:
@@ -171,6 +172,7 @@ def _group_to_dict(group: GameGroup) -> Dict[str, Any]:
171
172
  return {
172
173
  "id": group.ID,
173
174
  "name": group.name,
175
+ "hash": group.hash,
174
176
  "games": [_game_to_dict(g) for g in group.games],
175
177
  "parameters": group.parameters,
176
178
  }
@@ -188,6 +190,8 @@ def _group_from_dict(data: Dict[str, Any]) -> GameGroup:
188
190
  group = GameGroup.__new__(GameGroup)
189
191
  group._id = data["id"]
190
192
  group.name = data["name"]
193
+ # ``hash`` is optional for backward compatibility with older save files.
194
+ group._hash = data.get("hash")
191
195
  group._games = [_game_from_dict(g) for g in data.get("games", [])]
192
196
  group.parameters = data.get("parameters", {})
193
197
  return group
@@ -243,6 +247,7 @@ class Save:
243
247
  self._data: Dict[str, Dict[str, Dict[str, Any]]] = {
244
248
  name: {} for name in _SUPPORTED_CLASSES
245
249
  }
250
+ self._server_config: Dict[str, Any] = {}
246
251
 
247
252
  if self.file_path.exists():
248
253
  self._load_file()
@@ -292,7 +297,8 @@ class Save:
292
297
  logger.exception("Failed to read JSON save file.")
293
298
  raise SaveError(f"Cannot read save file: {self.file_path}") from exc
294
299
 
295
- if not isinstance(content, dict) or set(content) != set(_SUPPORTED_CLASSES):
300
+ expected = set(_SUPPORTED_CLASSES)
301
+ if not isinstance(content, dict) or not expected.issubset(content) or set(content) - expected - {_SERVER_CONFIG_CLASS}:
296
302
  raise SaveError(f"Incompatible save file structure: {self.file_path}")
297
303
 
298
304
  for name in _SUPPORTED_CLASSES:
@@ -300,6 +306,10 @@ class Save:
300
306
  if not isinstance(section, dict):
301
307
  raise SaveError(f"Incompatible save file structure: {self.file_path}")
302
308
  self._data[name] = dict(section)
309
+ config = content.get(_SERVER_CONFIG_CLASS, {})
310
+ if not isinstance(config, dict):
311
+ raise SaveError(f"Incompatible save file structure: {self.file_path}")
312
+ self._server_config = dict(config)
303
313
 
304
314
  def _load_sqlite(self) -> None:
305
315
  """Loads the in-memory buffer from an SQLite save file.
@@ -321,9 +331,15 @@ class Save:
321
331
 
322
332
  cursor.execute(f"SELECT class, id, data FROM {_SQLITE_TABLE}")
323
333
  for class_name, obj_id, raw in cursor.fetchall():
324
- if class_name not in _SUPPORTED_CLASSES:
334
+ if class_name not in _SUPPORTED_CLASSES and class_name != _SERVER_CONFIG_CLASS:
325
335
  raise SaveError(f"Incompatible save file structure: {self.file_path}")
326
- self._data[class_name][obj_id] = json.loads(raw)
336
+ data = json.loads(raw)
337
+ if class_name == _SERVER_CONFIG_CLASS:
338
+ if not isinstance(data, dict):
339
+ raise SaveError(f"Incompatible save file structure: {self.file_path}")
340
+ self._server_config = data
341
+ else:
342
+ self._data[class_name][obj_id] = data
327
343
  except sqlite3.DatabaseError as exc:
328
344
  logger.exception("Failed to read SQLite save file.")
329
345
  raise SaveError(f"Cannot read save file: {self.file_path}") from exc
@@ -370,8 +386,17 @@ class Save:
370
386
  The save file is rewritten with an empty but valid structure.
371
387
  """
372
388
  self._data = {name: {} for name in _SUPPORTED_CLASSES}
389
+ self._server_config = {}
373
390
  self.flush()
374
391
 
392
+ def save_server_config(self, config: Dict[str, Any]) -> None:
393
+ """Stores the serializable server configuration in the save buffer."""
394
+ self._server_config = dict(config)
395
+
396
+ def load_server_config(self) -> Dict[str, Any]:
397
+ """Returns the stored server configuration, or an empty mapping."""
398
+ return dict(self._server_config)
399
+
375
400
  def flush(self) -> None:
376
401
  """Persists the in-memory buffer to the underlying save file.
377
402
 
@@ -390,8 +415,11 @@ class Save:
390
415
  SaveError: If the data cannot be written.
391
416
  """
392
417
  try:
418
+ content = dict(self._data)
419
+ if self._server_config:
420
+ content[_SERVER_CONFIG_CLASS] = self._server_config
393
421
  with self.file_path.open("w", encoding="utf-8") as handle:
394
- json.dump(self._data, handle, indent=2)
422
+ json.dump(content, handle, indent=2)
395
423
  except OSError as exc:
396
424
  logger.exception("Failed to write JSON save file.")
397
425
  raise SaveError(f"Cannot write save file: {self.file_path}") from exc
@@ -417,6 +445,8 @@ class Save:
417
445
  for name, section in self._data.items()
418
446
  for obj_id, data in section.items()
419
447
  ]
448
+ if self._server_config:
449
+ rows.append((_SERVER_CONFIG_CLASS, "server", json.dumps(self._server_config)))
420
450
  cursor.executemany(
421
451
  f"INSERT INTO {_SQLITE_TABLE} (class, id, data) VALUES (?, ?, ?)",
422
452
  rows,
@@ -151,6 +151,7 @@ class ClientSession:
151
151
  self._writer: "asyncio.StreamWriter" = writer
152
152
  self._guest_default_player_id: Optional[str] = None
153
153
  self.subscribed_groups: Set[str] = set()
154
+ self.authorized_groups: Set[str] = set()
154
155
  self.joined_games: Set[str] = set()
155
156
 
156
157
  @property
@@ -280,10 +281,11 @@ class GameServer:
280
281
  "GROUP_LIST": AccessLevel.BASE,
281
282
  "GROUP_SUBSCRIBE": AccessLevel.BASE,
282
283
  "GROUP_UNSUBSCRIBE": AccessLevel.BASE,
283
- "GROUP_ADD_GAME": AccessLevel.GROUP_ADMIN,
284
+ "GROUP_ADD_GAME": AccessLevel.BASE,
284
285
  "GROUP_REMOVE_GAME": AccessLevel.GROUP_ADMIN,
285
286
  "GROUP_DELETE": AccessLevel.ADMIN,
286
287
  "GROUP_GAME_LIST_ALL": AccessLevel.GROUP_ADMIN,
288
+ "GROUP_PASSWORD_SET": AccessLevel.GROUP_ADMIN,
287
289
  "SERVER_INFO_GET": AccessLevel.ADMIN,
288
290
  "SERVER_CONFIG_GET": AccessLevel.ADMIN,
289
291
  "SERVER_CONFIG_SET": AccessLevel.ADMIN,
@@ -326,6 +328,7 @@ class GameServer:
326
328
  "GROUP_REMOVE_GAME": "GROUP_REMOVE_GAME_RESPONSE",
327
329
  "GROUP_DELETE": "GROUP_DELETE_RESPONSE",
328
330
  "GROUP_GAME_LIST_ALL": "GROUP_GAME_LIST_ALL_RESPONSE",
331
+ "GROUP_PASSWORD_SET": "GROUP_PASSWORD_SET_RESPONSE",
329
332
  "SERVER_INFO_GET": "SERVER_INFO_GET_RESPONSE",
330
333
  "SERVER_CONFIG_GET": "SERVER_CONFIG_GET_RESPONSE",
331
334
  "SERVER_CONFIG_SET": "SERVER_CONFIG_SET_RESPONSE",
@@ -410,8 +413,11 @@ class GameServer:
410
413
  self._server_hash: Optional[str] = (
411
414
  bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode() if password else None
412
415
  )
413
- self._admin_hash: Optional[str] = None
414
416
  self.user_registration_enabled: bool = True
417
+ self.orphan_games_allowed: bool = True
418
+ self.unauthenticated_game_creation_allowed: bool = True
419
+ self.unauthenticated_player_join_allowed: bool = True
420
+ self.unauthenticated_observer_join_allowed: bool = True
415
421
  self.hidden: bool = False
416
422
 
417
423
  # Persistence configuration.
@@ -694,6 +700,21 @@ class GameServer:
694
700
  self.persistence_path.parent.mkdir(parents=True, exist_ok=True)
695
701
  try:
696
702
  self._save = Save(self.persistence_path, self.persistence_mode)
703
+ config = self._save.load_server_config()
704
+ if isinstance(config.get("name"), str):
705
+ self.name = config["name"]
706
+ for field in (
707
+ "user_registration_enabled",
708
+ "orphan_games_allowed",
709
+ "unauthenticated_game_creation_allowed",
710
+ "unauthenticated_player_join_allowed",
711
+ "unauthenticated_observer_join_allowed",
712
+ "hidden",
713
+ ):
714
+ if isinstance(config.get(field), bool):
715
+ setattr(self, field, config[field])
716
+ if isinstance(config.get("server_hash"), str) or config.get("server_hash") is None:
717
+ self._server_hash = config.get("server_hash")
697
718
  for game in self._save.load(Game):
698
719
  self._games[game.ID] = game
699
720
  for group in self._save.load(GameGroup):
@@ -721,6 +742,16 @@ class GameServer:
721
742
  self._save.save(player)
722
743
  for user in self._users.values():
723
744
  self._save.save(user)
745
+ self._save.save_server_config({
746
+ "name": self.name,
747
+ "user_registration_enabled": self.user_registration_enabled,
748
+ "orphan_games_allowed": self.orphan_games_allowed,
749
+ "unauthenticated_game_creation_allowed": self.unauthenticated_game_creation_allowed,
750
+ "unauthenticated_player_join_allowed": self.unauthenticated_player_join_allowed,
751
+ "unauthenticated_observer_join_allowed": self.unauthenticated_observer_join_allowed,
752
+ "hidden": self.hidden,
753
+ "server_hash": self._server_hash,
754
+ })
724
755
  self._save.flush()
725
756
  except MultiplayerError:
726
757
  logger.exception("Failed to persist data.")
@@ -1641,6 +1672,32 @@ class GameServer:
1641
1672
  "error_code": "INVALID_DATA",
1642
1673
  "message": "A game name is required.",
1643
1674
  }
1675
+ if session.user is None and not self.unauthenticated_game_creation_allowed:
1676
+ return "GAME_CREATE_RESPONSE", {
1677
+ "success": False,
1678
+ "error_code": "AUTHENTICATION_REQUIRED",
1679
+ "message": "An authenticated user is required to create a game.",
1680
+ }
1681
+ group_id = payload.get("group_id")
1682
+ group = None
1683
+ if group_id is None and not self.orphan_games_allowed:
1684
+ return "GAME_CREATE_RESPONSE", {
1685
+ "success": False,
1686
+ "error_code": "ORPHAN_GAMES_DISABLED",
1687
+ "message": "Creating a game without a group is disabled.",
1688
+ }
1689
+ if group_id is not None:
1690
+ group = self._groups.get(group_id)
1691
+ if group is None:
1692
+ return "GAME_CREATE_RESPONSE", {
1693
+ "success": False, "error_code": "GROUP_NOT_FOUND",
1694
+ "message": "Group not found.",
1695
+ }
1696
+ if not self._authorize_group(session, group, payload.get("group_password")):
1697
+ return "GAME_CREATE_RESPONSE", {
1698
+ "success": False, "error_code": "INVALID_GROUP_PASSWORD",
1699
+ "message": "Invalid group password.",
1700
+ }
1644
1701
  game = Game(
1645
1702
  name=name,
1646
1703
  max_players=payload.get("max_players"),
@@ -1655,6 +1712,8 @@ class GameServer:
1655
1712
  self._game_roles[game.ID] = {}
1656
1713
  self._game_custom_state[game.ID] = {}
1657
1714
  self._game_creator_session[game.ID] = session.session_id
1715
+ if group is not None:
1716
+ group.add_game(game)
1658
1717
  return "GAME_CREATE_RESPONSE", {
1659
1718
  "success": True,
1660
1719
  "game_id": game.ID,
@@ -1682,6 +1741,14 @@ class GameServer:
1682
1741
  "error_code": "GROUP_NOT_FOUND",
1683
1742
  "message": "Group not found.",
1684
1743
  }
1744
+ if (
1745
+ not self._can_admin_group(session, group.ID)
1746
+ and not self._authorize_group(session, group, payload.get("group_password"))
1747
+ ):
1748
+ return "GAME_LIST_RESPONSE", {
1749
+ "success": False, "error_code": "INVALID_GROUP_PASSWORD",
1750
+ "message": "Invalid group password.",
1751
+ }
1685
1752
  games = [self._game_summary(game) for game in group.games]
1686
1753
  else:
1687
1754
  games = [self._game_summary(game) for game in self._games.values()]
@@ -1706,6 +1773,15 @@ class GameServer:
1706
1773
  "error_code": "GAME_NOT_FOUND",
1707
1774
  "message": "Game not found.",
1708
1775
  }
1776
+ group_password = payload.get("group_password")
1777
+ for group in self._groups.values():
1778
+ if any(group_game.ID == game.ID for group_game in group.games):
1779
+ if not self._authorize_group(session, group, group_password):
1780
+ return "GAME_JOIN_RESPONSE", {
1781
+ "success": False,
1782
+ "error_code": "INVALID_GROUP_PASSWORD",
1783
+ "message": "Invalid group password.",
1784
+ }
1709
1785
  role = payload.get("role")
1710
1786
  if role not in ("PLAYER", "OBSERVER"):
1711
1787
  return "GAME_JOIN_RESPONSE", {
@@ -1713,6 +1789,18 @@ class GameServer:
1713
1789
  "error_code": "INVALID_ACTION",
1714
1790
  "message": "Invalid role.",
1715
1791
  }
1792
+ if role == "PLAYER" and session.user is None and not self.unauthenticated_player_join_allowed:
1793
+ return "GAME_JOIN_RESPONSE", {
1794
+ "success": False,
1795
+ "error_code": "AUTHENTICATION_REQUIRED",
1796
+ "message": "An authenticated user is required to join as a player.",
1797
+ }
1798
+ if role == "OBSERVER" and session.user is None and not self.unauthenticated_observer_join_allowed:
1799
+ return "GAME_JOIN_RESPONSE", {
1800
+ "success": False,
1801
+ "error_code": "AUTHENTICATION_REQUIRED",
1802
+ "message": "An authenticated user is required to join as an observer.",
1803
+ }
1716
1804
  player = self._resolve_player(session, payload.get("player_id"))
1717
1805
  if player is None:
1718
1806
  return "GAME_JOIN_RESPONSE", {
@@ -2217,7 +2305,20 @@ class GameServer:
2217
2305
  "message": "A group name is required.",
2218
2306
  }
2219
2307
  attributes = payload.get("attributes")
2220
- group = GameGroup(name=name, **(attributes if isinstance(attributes, dict) else {}))
2308
+ password = payload.get("password")
2309
+ if password is not None and (not isinstance(password, str) or not password):
2310
+ return "GROUP_CREATE_RESPONSE", {
2311
+ "success": False,
2312
+ "error_code": "INVALID_DATA",
2313
+ "message": "Password must be a non-empty string.",
2314
+ }
2315
+ group_attributes = dict(attributes) if isinstance(attributes, dict) else {}
2316
+ group_attributes.pop("password", None)
2317
+ group = GameGroup(
2318
+ name=name,
2319
+ password=password,
2320
+ **group_attributes,
2321
+ )
2221
2322
  self._groups[group.ID] = group
2222
2323
  self._audit("GROUP_CREATE", session, group.ID)
2223
2324
  return "GROUP_CREATE_RESPONSE", {
@@ -2239,7 +2340,12 @@ class GameServer:
2239
2340
  Tuple[str, Dict[str, Any]]: The response type and payload.
2240
2341
  """
2241
2342
  groups = [
2242
- {"group_id": group.ID, "name": group.name, "games_count": len(group.games)}
2343
+ {
2344
+ "group_id": group.ID,
2345
+ "name": group.name,
2346
+ "games_count": len(group.games),
2347
+ "requires_password": group.password_required,
2348
+ }
2243
2349
  for group in self._groups.values()
2244
2350
  ]
2245
2351
  return "GROUP_LIST_RESPONSE", {"success": True, "groups": groups}
@@ -2263,6 +2369,13 @@ class GameServer:
2263
2369
  "error_code": "GROUP_NOT_FOUND",
2264
2370
  "message": "Group not found.",
2265
2371
  }
2372
+ group = self._groups[group_id]
2373
+ if not self._authorize_group(session, group, payload.get("password")):
2374
+ return "GROUP_SUBSCRIBE_RESPONSE", {
2375
+ "success": False,
2376
+ "error_code": "INVALID_GROUP_PASSWORD",
2377
+ "message": "Invalid group password.",
2378
+ }
2266
2379
  if group_id in session.subscribed_groups:
2267
2380
  return "GROUP_SUBSCRIBE_RESPONSE", {
2268
2381
  "success": False,
@@ -2308,6 +2421,20 @@ class GameServer:
2308
2421
  "message": "Unsubscribed from group successfully",
2309
2422
  }
2310
2423
 
2424
+ def _authorize_group(
2425
+ self, session: ClientSession, group: GameGroup, password: Any
2426
+ ) -> bool:
2427
+ """Validates group access and remembers successful session authorization."""
2428
+ if not group.password_required:
2429
+ session.authorized_groups.add(group.ID)
2430
+ return True
2431
+ if group.ID in session.authorized_groups:
2432
+ return True
2433
+ if group.check_password(password):
2434
+ session.authorized_groups.add(group.ID)
2435
+ return True
2436
+ return False
2437
+
2311
2438
  def _can_admin_group(self, session: ClientSession, group_id: str) -> bool:
2312
2439
  """Checks whether a session can administer a given group.
2313
2440
 
@@ -2344,12 +2471,6 @@ class GameServer:
2344
2471
  "error_code": "GROUP_NOT_FOUND",
2345
2472
  "message": "Group not found.",
2346
2473
  }
2347
- if not self._can_admin_group(session, group.ID):
2348
- return "GROUP_ADD_GAME_RESPONSE", {
2349
- "success": False,
2350
- "error_code": "INSUFFICIENT_PERMISSIONS",
2351
- "message": "Cannot modify this group.",
2352
- }
2353
2474
  game = self._games.get(payload.get("game_id"))
2354
2475
  if game is None:
2355
2476
  return "GROUP_ADD_GAME_RESPONSE", {
@@ -2357,6 +2478,19 @@ class GameServer:
2357
2478
  "error_code": "GAME_NOT_FOUND",
2358
2479
  "message": "Game not found.",
2359
2480
  }
2481
+ is_creator = self._game_creator_session.get(game.ID) == session.session_id
2482
+ if not is_creator and not self._can_admin_group(session, group.ID):
2483
+ return "GROUP_ADD_GAME_RESPONSE", {
2484
+ "success": False,
2485
+ "error_code": "INSUFFICIENT_PERMISSIONS",
2486
+ "message": "Only the game creator or a group administrator can add this game.",
2487
+ }
2488
+ if not self._authorize_group(session, group, payload.get("group_password")):
2489
+ return "GROUP_ADD_GAME_RESPONSE", {
2490
+ "success": False,
2491
+ "error_code": "INVALID_GROUP_PASSWORD",
2492
+ "message": "Invalid group password.",
2493
+ }
2360
2494
  group.add_game(game)
2361
2495
  await self._broadcast_group(
2362
2496
  group.ID,
@@ -2424,6 +2558,44 @@ class GameServer:
2424
2558
  "message": "Game removed from group successfully",
2425
2559
  }
2426
2560
 
2561
+ def _handle_group_password_set(
2562
+ self, session: ClientSession, payload: Dict[str, Any]
2563
+ ) -> Tuple[str, Dict[str, Any]]:
2564
+ """Sets, changes, or removes a group's access password."""
2565
+ group_id = payload.get("group_id")
2566
+ group = self._groups.get(group_id)
2567
+ if group is None:
2568
+ return "GROUP_PASSWORD_SET_RESPONSE", {
2569
+ "success": False, "error_code": "GROUP_NOT_FOUND",
2570
+ "message": "Group not found.",
2571
+ }
2572
+ if not self._can_admin_group(session, group.ID):
2573
+ return "GROUP_PASSWORD_SET_RESPONSE", {
2574
+ "success": False, "error_code": "INSUFFICIENT_PERMISSIONS",
2575
+ "message": "Cannot modify this group.",
2576
+ }
2577
+ password = payload.get("password")
2578
+ if password is not None and (not isinstance(password, str) or not password):
2579
+ return "GROUP_PASSWORD_SET_RESPONSE", {
2580
+ "success": False, "error_code": "INVALID_DATA",
2581
+ "message": "Password must be a non-empty string or null.",
2582
+ }
2583
+ group.change_password(password)
2584
+ if password is None:
2585
+ for client in self._sessions.values():
2586
+ client.authorized_groups.add(group.ID)
2587
+ else:
2588
+ for client in self._sessions.values():
2589
+ client.authorized_groups.discard(group.ID)
2590
+ session.authorized_groups.add(group.ID)
2591
+ self._audit("GROUP_PASSWORD_SET", session, group.ID)
2592
+ return "GROUP_PASSWORD_SET_RESPONSE", {
2593
+ "success": True,
2594
+ "group_id": group.ID,
2595
+ "requires_password": group.password_required,
2596
+ "message": "Group password updated successfully",
2597
+ }
2598
+
2427
2599
  def _handle_group_delete(
2428
2600
  self, session: ClientSession, payload: Dict[str, Any]
2429
2601
  ) -> Tuple[str, Dict[str, Any]]:
@@ -2543,9 +2715,12 @@ class GameServer:
2543
2715
  "success": True,
2544
2716
  "config": {
2545
2717
  "user_registration_enabled": self.user_registration_enabled,
2718
+ "orphan_games_allowed": self.orphan_games_allowed,
2719
+ "unauthenticated_game_creation_allowed": self.unauthenticated_game_creation_allowed,
2720
+ "unauthenticated_player_join_allowed": self.unauthenticated_player_join_allowed,
2721
+ "unauthenticated_observer_join_allowed": self.unauthenticated_observer_join_allowed,
2546
2722
  "hidden": self.hidden,
2547
2723
  "server_password_set": self._server_hash is not None,
2548
- "admin_password_set": self._admin_hash is not None,
2549
2724
  },
2550
2725
  }
2551
2726
 
@@ -2562,6 +2737,19 @@ class GameServer:
2562
2737
  Tuple[str, Dict[str, Any]]: The response type and payload.
2563
2738
  """
2564
2739
  updated: List[str] = []
2740
+ if "name" in payload:
2741
+ value = payload["name"]
2742
+ if not isinstance(value, str):
2743
+ return "SERVER_CONFIG_SET_RESPONSE", {
2744
+ "success": False,
2745
+ "error_code": "INVALID_DATA",
2746
+ "message": "name must be a string.",
2747
+ }
2748
+ if value != self.name:
2749
+ self.name = value
2750
+ updated.append("name")
2751
+ for client in list(self._sessions.values()):
2752
+ self._close_session(client)
2565
2753
  if "user_registration_enabled" in payload:
2566
2754
  value = payload["user_registration_enabled"]
2567
2755
  if not isinstance(value, bool):
@@ -2572,6 +2760,46 @@ class GameServer:
2572
2760
  }
2573
2761
  self.user_registration_enabled = value
2574
2762
  updated.append("user_registration_enabled")
2763
+ if "orphan_games_allowed" in payload:
2764
+ value = payload["orphan_games_allowed"]
2765
+ if not isinstance(value, bool):
2766
+ return "SERVER_CONFIG_SET_RESPONSE", {
2767
+ "success": False,
2768
+ "error_code": "INVALID_DATA",
2769
+ "message": "orphan_games_allowed must be a boolean.",
2770
+ }
2771
+ self.orphan_games_allowed = value
2772
+ updated.append("orphan_games_allowed")
2773
+ if "unauthenticated_game_creation_allowed" in payload:
2774
+ value = payload["unauthenticated_game_creation_allowed"]
2775
+ if not isinstance(value, bool):
2776
+ return "SERVER_CONFIG_SET_RESPONSE", {
2777
+ "success": False,
2778
+ "error_code": "INVALID_DATA",
2779
+ "message": "unauthenticated_game_creation_allowed must be a boolean.",
2780
+ }
2781
+ self.unauthenticated_game_creation_allowed = value
2782
+ updated.append("unauthenticated_game_creation_allowed")
2783
+ if "unauthenticated_player_join_allowed" in payload:
2784
+ value = payload["unauthenticated_player_join_allowed"]
2785
+ if not isinstance(value, bool):
2786
+ return "SERVER_CONFIG_SET_RESPONSE", {
2787
+ "success": False,
2788
+ "error_code": "INVALID_DATA",
2789
+ "message": "unauthenticated_player_join_allowed must be a boolean.",
2790
+ }
2791
+ self.unauthenticated_player_join_allowed = value
2792
+ updated.append("unauthenticated_player_join_allowed")
2793
+ if "unauthenticated_observer_join_allowed" in payload:
2794
+ value = payload["unauthenticated_observer_join_allowed"]
2795
+ if not isinstance(value, bool):
2796
+ return "SERVER_CONFIG_SET_RESPONSE", {
2797
+ "success": False,
2798
+ "error_code": "INVALID_DATA",
2799
+ "message": "unauthenticated_observer_join_allowed must be a boolean.",
2800
+ }
2801
+ self.unauthenticated_observer_join_allowed = value
2802
+ updated.append("unauthenticated_observer_join_allowed")
2575
2803
  if "hidden" in payload:
2576
2804
  value = payload["hidden"]
2577
2805
  if not isinstance(value, bool):
@@ -2587,11 +2815,9 @@ class GameServer:
2587
2815
  payload["server_password"].encode(), bcrypt.gensalt()
2588
2816
  ).decode()
2589
2817
  updated.append("server_password")
2590
- if isinstance(payload.get("admin_password"), str):
2591
- self._admin_hash = bcrypt.hashpw(
2592
- payload["admin_password"].encode(), bcrypt.gensalt()
2593
- ).decode()
2594
- updated.append("admin_password")
2818
+ for client in list(self._sessions.values()):
2819
+ self._close_session(client)
2820
+ self._save_persistence()
2595
2821
  self._audit("SERVER_CONFIG_SET", session, "server")
2596
2822
  return "SERVER_CONFIG_SET_RESPONSE", {
2597
2823
  "success": True,
File without changes