signal-fish-server 0.2.0

A lightweight, in-memory WebSocket signaling server for peer-to-peer game networking
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
// Protocol module: Message types, validation, and room state management

pub mod error_codes;
pub mod messages;
pub mod room_codes;
pub mod room_state;
pub mod types;
pub mod validation;

// Re-export everything for backward compatibility
// This allows external code to use `use crate::protocol::*`

// From error_codes
pub use error_codes::ErrorCode;

// From types
pub use types::{
    ConnectionInfo, GameDataEncoding, PeerConnectionInfo, PlayerId, PlayerInfo,
    PlayerNameRulesPayload, ProtocolInfoPayload, RateLimitInfo, RelayTransport, RoomId,
    SpectatorInfo, SpectatorStateChangeReason, DEFAULT_MAX_GAME_NAME_LENGTH,
    DEFAULT_MAX_PLAYERS_LIMIT, DEFAULT_MAX_PLAYER_NAME_LENGTH, DEFAULT_REGION_ID,
    DEFAULT_ROOM_CODE_LENGTH,
};

// From messages
pub use messages::{
    ClientMessage, ReconnectedPayload, RoomJoinedPayload, ServerMessage, SpectatorJoinedPayload,
};

// From room_state
pub use room_state::{LobbyState, Room};

#[cfg(test)]
mod tests {
    use super::room_codes;
    use super::validation::{
        validate_game_name_with_config, validate_player_name_with_config,
        validate_room_code_with_config,
    };
    use super::*;
    use crate::config::ProtocolConfig;
    use proptest::prelude::*;
    use uuid::Uuid;

    #[test]
    #[cfg_attr(miri, ignore)] // Room::new calls Utc::now() (clock_gettime), which Miri isolation blocks
    fn test_room_creation() {
        let room = Room::new(
            "test_game".to_string(),
            "ABC123".to_string(),
            4,
            true,
            "matchbox".to_string(),
        );
        assert_eq!(room.game_name, "test_game");
        assert_eq!(room.code, "ABC123");
        assert_eq!(room.max_players, 4);
        assert!(room.supports_authority);
        assert_eq!(room.relay_type, "matchbox");
        assert!(room.can_join());
    }

    #[test]
    #[cfg_attr(miri, ignore)] // Uses Utc::now() in test data; blocked by Miri isolation
    fn test_player_management() {
        let mut room = Room::new(
            "test_game".to_string(),
            "ABC123".to_string(),
            2,
            true,
            "matchbox".to_string(),
        );

        let player1 = PlayerInfo {
            id: Uuid::new_v4(),
            name: "Player1".to_string(),
            is_authority: false,
            is_ready: false,
            connected_at: chrono::Utc::now(),
            connection_info: None,
            region_id: types::DEFAULT_REGION_ID.to_string(),
        };

        let player2 = PlayerInfo {
            id: Uuid::new_v4(),
            name: "Player2".to_string(),
            is_authority: false,
            is_ready: false,
            connected_at: chrono::Utc::now(),
            connection_info: None,
            region_id: types::DEFAULT_REGION_ID.to_string(),
        };

        assert!(room.add_player(player1));
        assert!(room.add_player(player2));
        assert!(!room.can_join());

        let player3 = PlayerInfo {
            id: Uuid::new_v4(),
            name: "Player3".to_string(),
            is_authority: false,
            is_ready: false,
            connected_at: chrono::Utc::now(),
            connection_info: None,
            region_id: types::DEFAULT_REGION_ID.to_string(),
        };

        assert!(!room.add_player(player3));
    }

    #[test]
    #[cfg_attr(miri, ignore)] // Uses Room::new/Utc::now(); clock_gettime is blocked under Miri isolation
    fn test_authority_management() {
        let mut room = Room::new(
            "test_game".to_string(),
            "ABC123".to_string(),
            4,
            true,
            "matchbox".to_string(),
        );

        let player_id = Uuid::new_v4();
        let player = PlayerInfo {
            id: player_id,
            name: "Authority Player".to_string(),
            is_authority: false,
            is_ready: false,
            connected_at: chrono::Utc::now(),
            connection_info: None,
            region_id: types::DEFAULT_REGION_ID.to_string(),
        };

        room.add_player(player);
        assert!(room.set_authority(Some(player_id)));
        assert_eq!(room.authority_player, Some(player_id));
        assert!(room.players[&player_id].is_authority);
    }

    #[test]
    #[cfg_attr(miri, ignore)] // Uses Room::new/Utc::now(); clock_gettime is blocked under Miri isolation
    fn test_authority_management_disabled() {
        let mut room = Room::new(
            "test_game".to_string(),
            "ABC123".to_string(),
            4,
            false,
            "matchbox".to_string(),
        );

        let player_id = Uuid::new_v4();
        let player = PlayerInfo {
            id: player_id,
            name: "Authority Player".to_string(),
            is_authority: false,
            is_ready: false,
            connected_at: chrono::Utc::now(),
            connection_info: None,
            region_id: types::DEFAULT_REGION_ID.to_string(),
        };

        room.add_player(player);

        // Authority operations should fail when not supported
        assert!(!room.set_authority(Some(player_id)));
        assert_eq!(room.authority_player, None);
        assert!(!room.players[&player_id].is_authority);
    }

    #[test]
    fn test_validation() {
        use validation::*;

        assert!(validate_game_name("valid_game").is_ok());
        assert!(validate_game_name("").is_err());
        assert!(validate_game_name("a".repeat(100).as_str()).is_err());

        assert!(validate_room_code("ABC123").is_ok());
        assert!(validate_room_code("").is_err());
        assert!(validate_room_code("abc!@#").is_err());

        assert!(validate_player_name("ValidPlayer").is_ok());
        assert!(validate_player_name("Player One").is_ok());
        assert!(validate_player_name("Player-One").is_ok());
        assert!(validate_player_name("玩家One").is_ok());
        assert!(validate_player_name("").is_err());
        assert!(validate_player_name("  ").is_err());
        assert!(validate_player_name(" spaced ").is_err());
        assert!(validate_player_name("Player\tOne").is_err()); // Contains tab
        assert!(validate_player_name("User@123").is_err()); // Contains disallowed symbol

        assert!(validate_max_players(4).is_ok());
        assert!(validate_max_players(0).is_err());
        assert!(validate_max_players(101).is_err());
    }

    #[test]
    fn player_name_validation_obeys_config_overrides() {
        use validation::validate_player_name_with_config;

        let mut config = ProtocolConfig::default();
        config.player_name_validation.allow_spaces = false;
        config.player_name_validation.allow_unicode_alphanumeric = false;

        assert!(validate_player_name_with_config("AsciiName", &config).is_ok());
        assert!(validate_player_name_with_config("Player Two", &config).is_err());
        assert!(validate_player_name_with_config("玩家", &config).is_err());

        config.player_name_validation.allowed_symbols.push('!');
        assert!(validate_player_name_with_config("Alert!", &config).is_ok());
    }

    #[test]
    #[cfg_attr(miri, ignore)] // Uses Utc::now() in PlayerInfo test fixtures
    fn test_player_name_uniqueness() {
        use std::collections::HashMap;
        use validation::*;

        let mut players = HashMap::new();

        // Add first player
        players.insert(
            Uuid::new_v4(),
            PlayerInfo {
                id: Uuid::new_v4(),
                name: "Player1".to_string(),
                is_authority: false,
                is_ready: false,
                connected_at: chrono::Utc::now(),
                connection_info: None,
                region_id: types::DEFAULT_REGION_ID.to_string(),
            },
        );

        // Different name should be OK
        assert!(validate_player_name_uniqueness("Player2", &players).is_ok());

        // Exact same name should fail
        assert!(validate_player_name_uniqueness("Player1", &players).is_err());

        // Case insensitive check should fail
        assert!(validate_player_name_uniqueness("player1", &players).is_err());
        assert!(validate_player_name_uniqueness("PLAYER1", &players).is_err());
    }

    #[test]
    fn test_room_code_generation() {
        use room_codes::*;

        let code = generate_room_code();
        assert_eq!(code.len(), 6);
        assert!(code.chars().all(|c| c.is_ascii_alphanumeric()));
        assert!(code
            .chars()
            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit()));

        let clean_code = generate_clean_room_code();
        assert_eq!(clean_code.len(), 6);
        // Should not contain confusing characters
        assert!(!clean_code.contains('0'));
        assert!(!clean_code.contains('O'));
        assert!(!clean_code.contains('I'));
        assert!(!clean_code.contains('1'));

        // Generate multiple codes to test uniqueness probability
        let mut codes = std::collections::HashSet::new();
        for _ in 0..100 {
            codes.insert(generate_clean_room_code());
        }
        // Should generate many unique codes (high probability)
        assert!(codes.len() > 90);
    }

    #[test]
    #[cfg_attr(miri, ignore)] // Uses Room::new/Utc::now(); clock_gettime is blocked under Miri isolation
    fn test_authority_protocol_basic_rules() {
        // Test first player gets authority rule
        let mut room = Room::new(
            "test_game".to_string(),
            "AUTH01".to_string(),
            4,
            true,
            "matchbox".to_string(),
        );

        let player1_id = Uuid::new_v4();
        let player1 = PlayerInfo {
            id: player1_id,
            name: "Player1".to_string(),
            is_authority: true, // First player should get authority
            is_ready: false,
            connected_at: chrono::Utc::now(),
            connection_info: None,
            region_id: types::DEFAULT_REGION_ID.to_string(),
        };

        room.add_player(player1);
        room.authority_player = Some(player1_id);

        assert_eq!(room.authority_player, Some(player1_id));
        assert!(room.players[&player1_id].is_authority);

        // Add second player - should NOT get authority
        let player2_id = Uuid::new_v4();
        let player2 = PlayerInfo {
            id: player2_id,
            name: "Player2".to_string(),
            is_authority: false,
            is_ready: false,
            connected_at: chrono::Utc::now(),
            connection_info: None,
            region_id: types::DEFAULT_REGION_ID.to_string(),
        };

        room.add_player(player2);

        // Only first player should have authority
        assert_eq!(room.authority_player, Some(player1_id));
        assert!(room.players[&player1_id].is_authority);
        assert!(!room.players[&player2_id].is_authority);
    }

    #[test]
    #[cfg_attr(miri, ignore)] // Uses Room::new/Utc::now(); clock_gettime is blocked under Miri isolation
    fn test_authority_protocol_single_authority_rule() {
        let mut room = Room::new(
            "test_game".to_string(),
            "SINGLE".to_string(),
            4,
            true,
            "matchbox".to_string(),
        );

        let player1_id = Uuid::new_v4();
        let player2_id = Uuid::new_v4();

        let player1 = PlayerInfo {
            id: player1_id,
            name: "Player1".to_string(),
            is_authority: true,
            is_ready: false,
            connected_at: chrono::Utc::now(),
            connection_info: None,
            region_id: types::DEFAULT_REGION_ID.to_string(),
        };
        let player2 = PlayerInfo {
            id: player2_id,
            name: "Player2".to_string(),
            is_authority: false,
            is_ready: false,
            connected_at: chrono::Utc::now(),
            connection_info: None,
            region_id: types::DEFAULT_REGION_ID.to_string(),
        };

        room.add_player(player1);
        room.add_player(player2);
        room.authority_player = Some(player1_id);

        // Test: Can only have 0 or 1 players with authority
        let authority_count = room.players.values().filter(|p| p.is_authority).count();
        assert_eq!(authority_count, 1);

        // Test authority transfer (clear old, set new)
        room.clear_authority();
        let authority_count_after_clear = room.players.values().filter(|p| p.is_authority).count();
        assert_eq!(authority_count_after_clear, 0);
        assert_eq!(room.authority_player, None);

        // Set new authority
        room.set_authority(Some(player2_id));
        let authority_count_after_set = room.players.values().filter(|p| p.is_authority).count();
        assert_eq!(authority_count_after_set, 1);
        assert_eq!(room.authority_player, Some(player2_id));
        assert!(!room.players[&player1_id].is_authority);
        assert!(room.players[&player2_id].is_authority);
    }

    #[test]
    #[cfg_attr(miri, ignore)] // Uses Room::new/Utc::now(); clock_gettime is blocked under Miri isolation
    fn test_authority_protocol_no_auto_reassignment() {
        let mut room = Room::new(
            "test_game".to_string(),
            "NOAUTO".to_string(),
            4,
            true,
            "matchbox".to_string(),
        );

        let player1_id = Uuid::new_v4();
        let player2_id = Uuid::new_v4();

        let player1 = PlayerInfo {
            id: player1_id,
            name: "AuthorityPlayer".to_string(),
            is_authority: true,
            is_ready: false,
            connected_at: chrono::Utc::now(),
            connection_info: None,
            region_id: types::DEFAULT_REGION_ID.to_string(),
        };
        let player2 = PlayerInfo {
            id: player2_id,
            name: "RegularPlayer".to_string(),
            is_authority: false,
            is_ready: false,
            connected_at: chrono::Utc::now(),
            connection_info: None,
            region_id: types::DEFAULT_REGION_ID.to_string(),
        };

        room.add_player(player1);
        room.add_player(player2);
        room.authority_player = Some(player1_id);

        // Authority player leaves
        room.remove_player(&player1_id);

        // Per protocol: Authority should be cleared, NOT auto-assigned to remaining player
        assert_eq!(room.authority_player, None);
        if let Some(remaining_player) = room.players.get(&player2_id) {
            assert!(!remaining_player.is_authority);
        }
    }

    #[test]
    #[cfg_attr(miri, ignore)] // Uses Room::new/Utc::now(); clock_gettime is blocked under Miri isolation
    fn test_authority_protocol_room_support_validation() {
        // Room WITH authority support
        let mut auth_room = Room::new(
            "auth_game".to_string(),
            "WITHAUTH".to_string(),
            4,
            true,
            "matchbox".to_string(),
        );
        assert!(auth_room.supports_authority);

        let player_id = Uuid::new_v4();
        let player = PlayerInfo {
            id: player_id,
            name: "Player".to_string(),
            is_authority: false,
            is_ready: false,
            connected_at: chrono::Utc::now(),
            connection_info: None,
            region_id: types::DEFAULT_REGION_ID.to_string(),
        };

        auth_room.add_player(player);

        // Should be able to set authority
        assert!(auth_room.set_authority(Some(player_id)));
        assert_eq!(auth_room.authority_player, Some(player_id));

        // Room WITHOUT authority support
        let mut no_auth_room = Room::new(
            "noauth_game".to_string(),
            "NOAUTH".to_string(),
            4,
            false,
            "matchbox".to_string(),
        );
        assert!(!no_auth_room.supports_authority);

        let player2_id = Uuid::new_v4();
        let player2 = PlayerInfo {
            id: player2_id,
            name: "Player2".to_string(),
            is_authority: false,
            is_ready: false,
            connected_at: chrono::Utc::now(),
            connection_info: None,
            region_id: types::DEFAULT_REGION_ID.to_string(),
        };

        no_auth_room.add_player(player2);

        // Should NOT be able to set authority
        assert!(!no_auth_room.set_authority(Some(player2_id)));
        assert_eq!(no_auth_room.authority_player, None);
        assert!(!no_auth_room.players[&player2_id].is_authority);
    }

    #[test]
    #[cfg_attr(miri, ignore)] // Uses Room::new/Utc::now(); clock_gettime is blocked under Miri isolation
    fn test_lobby_state_transitions() {
        let mut room = Room::new(
            "lobby_game".to_string(),
            "LOBBY1".to_string(),
            2,
            true,
            "matchbox".to_string(),
        );

        // Initially in waiting state
        assert_eq!(room.lobby_state, LobbyState::Waiting);
        assert!(!room.should_enter_lobby());
        assert!(!room.all_players_ready());

        // Add first player
        let player1_id = Uuid::new_v4();
        let player1 = PlayerInfo {
            id: player1_id,
            name: "Player1".to_string(),
            is_authority: true,
            is_ready: false,
            connected_at: chrono::Utc::now(),
            connection_info: None,
            region_id: types::DEFAULT_REGION_ID.to_string(),
        };
        room.add_player(player1);

        // Still shouldn't enter lobby with only one player
        assert!(!room.should_enter_lobby());
        assert!(!room.enter_lobby());
        assert_eq!(room.lobby_state, LobbyState::Waiting);

        // Add second player (room is now full)
        let player2_id = Uuid::new_v4();
        let player2 = PlayerInfo {
            id: player2_id,
            name: "Player2".to_string(),
            is_authority: false,
            is_ready: false,
            connected_at: chrono::Utc::now(),
            connection_info: None,
            region_id: types::DEFAULT_REGION_ID.to_string(),
        };
        room.add_player(player2);

        // Now should transition to lobby
        assert!(room.should_enter_lobby());
        assert!(room.enter_lobby());
        assert_eq!(room.lobby_state, LobbyState::Lobby);
        assert!(room.lobby_started_at.is_some());

        // Players should be able to mark themselves ready
        assert!(room.set_player_ready(&player1_id, true));
        assert_eq!(room.ready_players.len(), 1);
        assert!(room.players[&player1_id].is_ready);
        assert!(!room.all_players_ready());

        // Mark second player ready
        assert!(room.set_player_ready(&player2_id, true));
        assert_eq!(room.ready_players.len(), 2);
        assert!(room.all_players_ready());

        // Should be able to finalize game
        assert!(room.finalize_game());
        assert_eq!(room.lobby_state, LobbyState::Finalized);
        assert!(room.game_finalized_at.is_some());
        assert!(room.is_finalized());
    }

    #[test]
    #[cfg_attr(miri, ignore)] // Uses Room::new/Utc::now(); clock_gettime is blocked under Miri isolation
    fn test_lobby_ready_state_changes() {
        let mut room = Room::new(
            "ready_game".to_string(),
            "READY1".to_string(),
            3,
            true,
            "matchbox".to_string(),
        );

        // Add three players
        let player1_id = Uuid::new_v4();
        let player2_id = Uuid::new_v4();
        let player3_id = Uuid::new_v4();

        for (id, name) in [(player1_id, "P1"), (player2_id, "P2"), (player3_id, "P3")] {
            room.add_player(PlayerInfo {
                id,
                name: name.to_string(),
                is_authority: id == player1_id,
                is_ready: false,
                connected_at: chrono::Utc::now(),
                connection_info: None,
                region_id: types::DEFAULT_REGION_ID.to_string(),
            });
        }

        // Enter lobby
        room.enter_lobby();

        // Mark players ready one by one
        room.set_player_ready(&player1_id, true);
        assert!(!room.all_players_ready());

        room.set_player_ready(&player2_id, true);
        assert!(!room.all_players_ready());

        room.set_player_ready(&player3_id, true);
        assert!(room.all_players_ready());

        // Unready one player
        room.set_player_ready(&player2_id, false);
        assert!(!room.all_players_ready());
        assert!(!room.players[&player2_id].is_ready);
        assert_eq!(room.ready_players.len(), 2);
    }

    #[test]
    #[cfg_attr(miri, ignore)] // Uses Room::new/Utc::now(); clock_gettime is blocked under Miri isolation
    fn test_peer_connections() {
        let mut room = Room::new(
            "peer_game".to_string(),
            "PEER01".to_string(),
            2,
            true,
            "matchbox".to_string(),
        );

        let player1_id = Uuid::new_v4();
        let player2_id = Uuid::new_v4();

        room.add_player(PlayerInfo {
            id: player1_id,
            name: "Authority".to_string(),
            is_authority: true,
            is_ready: false,
            connected_at: chrono::Utc::now(),
            connection_info: None,
            region_id: types::DEFAULT_REGION_ID.to_string(),
        });

        room.add_player(PlayerInfo {
            id: player2_id,
            name: "Player".to_string(),
            is_authority: false,
            is_ready: false,
            connected_at: chrono::Utc::now(),
            connection_info: None,
            region_id: types::DEFAULT_REGION_ID.to_string(),
        });

        let peer_connections = room.get_peer_connections();
        assert_eq!(peer_connections.len(), 2);

        // Verify authority and player info is correct
        let auth_peer = peer_connections.iter().find(|p| p.is_authority).unwrap();
        let player_peer = peer_connections.iter().find(|p| !p.is_authority).unwrap();

        assert_eq!(auth_peer.player_id, player1_id);
        assert_eq!(auth_peer.player_name, "Authority");
        assert_eq!(player_peer.player_id, player2_id);
        assert_eq!(player_peer.player_name, "Player");
    }

    #[test]
    #[cfg_attr(miri, ignore)] // Uses Room::new/Utc::now(); clock_gettime is blocked under Miri isolation
    fn test_lobby_edge_cases() {
        let mut room = Room::new(
            "edge_game".to_string(),
            "EDGE01".to_string(),
            2,
            false,
            "matchbox".to_string(),
        );

        // Add players
        let player1_id = Uuid::new_v4();
        let player2_id = Uuid::new_v4();

        for id in [player1_id, player2_id] {
            room.add_player(PlayerInfo {
                id,
                name: format!("Player{id}"),
                is_authority: false,
                is_ready: false,
                connected_at: chrono::Utc::now(),
                connection_info: None,
                region_id: types::DEFAULT_REGION_ID.to_string(),
            });
        }

        // Enter lobby
        room.enter_lobby();

        // Can't set ready for non-existent player
        let fake_id = Uuid::new_v4();
        assert!(!room.set_player_ready(&fake_id, true));

        // Can't finalize without all players ready
        room.set_player_ready(&player1_id, true);
        assert!(!room.finalize_game());

        // Can't set ready when not in lobby state
        room.lobby_state = LobbyState::Waiting;
        assert!(!room.set_player_ready(&player1_id, false));
    }

    fn expected_game_name_ok(name: &str, config: &ProtocolConfig) -> bool {
        !name.is_empty()
            && name.len() <= config.max_game_name_length
            && name
                .chars()
                .all(|c| c.is_alphanumeric() || c == '-' || c == '_' || c == ' ')
    }

    fn expected_room_code_ok(code: &str, config: &ProtocolConfig) -> bool {
        code.len() == config.room_code_length && code.chars().all(|c| c.is_ascii_alphanumeric())
    }

    fn expected_player_name_ok(name: &str, config: &ProtocolConfig) -> bool {
        if name.is_empty() || name.len() > config.max_player_name_length {
            return false;
        }

        let trimmed = name.trim();
        if trimmed.is_empty() {
            return false;
        }

        let rules = &config.player_name_validation;
        if !rules.allow_leading_trailing_whitespace && trimmed.len() != name.len() {
            return false;
        }

        for ch in name.chars() {
            if ch == ' ' {
                if rules.allow_spaces {
                    continue;
                }
                return false;
            }
            if ch.is_whitespace() {
                return false;
            }

            let is_alphanumeric = if rules.allow_unicode_alphanumeric {
                ch.is_alphanumeric()
            } else {
                ch.is_ascii_alphanumeric()
            };

            if is_alphanumeric || rules.is_allowed_symbol(ch) {
                continue;
            }

            return false;
        }

        true
    }

    // NOTE: All proptest tests are excluded from Miri runs via
    // `#[cfg_attr(miri, ignore)]`. Proptest's failure-persistence layer calls
    // `std::env::current_dir()` (getcwd), which is blocked by Miri isolation
    // and aborts the entire test binary.
    proptest! {
        #[test]
        #[cfg_attr(miri, ignore)]
        fn game_name_validation_matches_predicate(raw in proptest::collection::vec(any::<char>(), 0..=64)) {
            let candidate: String = raw.into_iter().collect();
            let config = ProtocolConfig::default();
            prop_assert_eq!(
                validate_game_name_with_config(&candidate, &config).is_ok(),
                expected_game_name_ok(&candidate, &config)
            );
        }

        #[test]
        #[cfg_attr(miri, ignore)]
        fn room_code_validation_matches_predicate(raw in proptest::collection::vec(any::<char>(), 0..=10)) {
            let candidate: String = raw.into_iter().collect();
            let config = ProtocolConfig::default();
            prop_assert_eq!(
                validate_room_code_with_config(&candidate, &config).is_ok(),
                expected_room_code_ok(&candidate, &config)
            );
        }

        #[test]
        #[cfg_attr(miri, ignore)]
        fn player_name_validation_matches_predicate(raw in proptest::collection::vec(any::<char>(), 0..=32)) {
            let candidate: String = raw.into_iter().collect();
            let config = ProtocolConfig::default();
            prop_assert_eq!(
                validate_player_name_with_config(&candidate, &config).is_ok(),
                expected_player_name_ok(&candidate, &config)
            );
        }

    }

    #[test]
    fn player_name_rules_payload_reflects_protocol_config() {
        let mut config = ProtocolConfig {
            max_player_name_length: 40,
            ..ProtocolConfig::default()
        };
        config.player_name_validation.allow_spaces = false;
        config.player_name_validation.allowed_symbols = vec!['*'];
        config.player_name_validation.additional_allowed_characters = Some("!?".to_string());

        let hint = PlayerNameRulesPayload::from_protocol_config(&config);
        assert_eq!(hint.max_length, 40);
        assert_eq!(hint.min_length, 1);
        assert!(!hint.allow_spaces);
        assert!(hint.allow_unicode_alphanumeric);
        assert!(hint.allowed_symbols.contains(&'*'));
        assert_eq!(hint.additional_allowed_characters.as_deref(), Some("!?"));
    }

    #[test]
    fn region_room_code_applies_prefix() {
        let config = ProtocolConfig {
            room_code_length: 6,
            ..ProtocolConfig::default()
        };
        let code = room_codes::generate_region_room_code(&config, Some("na"));
        assert!(code.starts_with("NA"));
        assert_eq!(code.len(), 6);
    }

    #[test]
    fn region_room_code_falls_back_when_prefix_too_long() {
        let config = ProtocolConfig {
            room_code_length: 4,
            ..ProtocolConfig::default()
        };
        let code = room_codes::generate_region_room_code(&config, Some("LONGPREFIX"));
        assert_eq!(code.len(), 4);
    }
}