-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserver.js
More file actions
3435 lines (3290 loc) ยท 127 KB
/
Copy pathserver.js
File metadata and controls
3435 lines (3290 loc) ยท 127 KB
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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const express = require('express');
const xmlparser = require('express-xml-bodyparser');
const xml2js = require('xml2js');
const os = require('os');
// Get the local LAN IP address
function getLocalIP() {
const interfaces = os.networkInterfaces();
for (const name of Object.keys(interfaces)) {
for (const interface of interfaces[name]) {
// Skip internal (i.e. 127.0.0.1) and non-IPv4 addresses
if (interface.family === 'IPv4' && !interface.internal) {
return interface.address;
}
}
}
return 'localhost'; // Fallback
}
// Check if we should run interactive configuration
async function startServer() {
// Check command line arguments
const args = process.argv.slice(2);
if (args.includes('--help') || args.includes('-h')) {
console.log('๐ฎ MMCOS Community Server');
console.log('==========================');
console.log();
console.log('Usage:');
console.log(' node server.js - Interactive configuration');
console.log(' node server.js --standard - Standard community server');
console.log(' node server.js --competitive - Competitive server (no AI)');
console.log(' node server.js --casual - Casual fun server');
console.log(' node server.js --training - AI training server');
console.log(' node server.js --battle - Battle modes server');
console.log(' node server.js --elimination - Elimination server');
console.log();
process.exit(0);
}
// Check for quick start
if (args.includes('--quick')) {
// Quick start with sensible defaults
const config = {
name: "MMCOS Community Server",
description: "Quick start with default settings",
settings: {
maxPlayers: 8,
aiEnabled: true,
allowSpectators: true,
rankedWithAI: true,
debugMode: false,
seasonSystem: true,
forceGameType: null,
competitiveMode: false
}
};
console.log('๐ฎ MMCOS Community Server');
console.log('==========================');
console.log();
console.log('๐ Quick start with default settings');
console.log();
// Set environment and continue
process.env.SERVER_CONFIG = JSON.stringify(config);
} else {
// Interactive configuration
const { runInteractiveConfig } = require('./interactive-config');
await runInteractiveConfig();
return; // Interactive config will restart the server
}
}
// Run startup logic if this is the main module
if (require.main === module) {
startServer().then(() => {
// Continue with server initialization
initializeServer();
}).catch(error => {
console.error('โ Startup error:', error.message);
process.exit(1);
});
} else {
// Being required as module, skip interactive setup
initializeServer();
}
function initializeServer() {
// Multi-Server Configuration Support
let SERVER_CONFIG;
// Check if server config was passed from interactive setup
if (process.env.SERVER_CONFIG) {
SERVER_CONFIG = JSON.parse(process.env.SERVER_CONFIG);
console.log(`๐ฏ Using interactive configuration: ${SERVER_CONFIG.name}`);
} else {
// Default configuration - Server responds to game requests
SERVER_CONFIG = {
name: "MMCOS Community Server",
description: "Community server - responds to all game modes",
settings: {
aiEnabled: true, // AI available if game requests it
rankedWithAI: true, // Allow ranked matches with AI
debugMode: false,
seasonSystem: true,
maxPlayers: 8, // Standard maximum
forceGameType: null, // Don't override game's choice
allowSpectators: true,
competitiveMode: false // Not a competitive-only server
}
};
console.log(`๐ Using default configuration - server responds to all game requests`);
}// Season and ServerStatus functions (extracted from server-configs.js)
function getCurrentSeason() {
const SEASON_CONFIG = {
schedule: [
{ season: 46, start: '2025-01-01', end: '2025-02-15' },
{ season: 47, start: '2025-03-01', end: '2025-04-15' },
{ season: 48, start: '2025-05-01', end: '2025-06-15' },
{ season: 49, start: '2025-07-01', end: '2025-08-15' },
{ season: 50, start: '2025-09-01', end: '2025-10-16' },
{ season: 51, start: '2025-11-01', end: '2025-12-16' }
]
};
const now = new Date();
for (const season of SEASON_CONFIG.schedule) {
const start = new Date(season.start);
const end = new Date(season.end);
if (now >= start && now <= end) {
return season.season;
}
}
return 46; // Default
}
function generateServerStatus(config) {
const currentSeason = config.settings.seasonSystem ? getCurrentSeason() : 45;
return `
<OnlineServiceStatus>
<Message display="false" localize="false">
${config.description}
</Message>
<ServerStatus accessible="true"/>
<Egonet enabled="${config.settings.allowSpectators}"/>
<ServerInfo>
<Name>${config.name}</Name>
<Season>${currentSeason}</Season>
<MaxPlayers>${config.settings.maxPlayers}</MaxPlayers>
<AIEnabled>${config.settings.aiEnabled}</AIEnabled>
<CompetitiveMode>${config.settings.competitiveMode}</CompetitiveMode>
</ServerInfo>
</OnlineServiceStatus>
`;
}
console.log(`๐ Starting ${SERVER_CONFIG.name}`);
console.log(`๐ Configuration:`, SERVER_CONFIG.settings);
// Global request counter for testing
let enterMatchmakingCounter = 0;
const http = require('http');
const https = require('https');
const fs = require('fs');
const { generateLoginResponse } = require('./responses');
const { GameSession } = require('./game-session');
// Initialize game session manager
const gameSession = new GameSession();
// Cleanup old games every 30 minutes
setInterval(() => {
gameSession.cleanupOldGames();
}, 30 * 60 * 1000);
const app = express();
app.use('/static', express.static('static'));
// Configure XML parser for MMCOS protocol
app.use(express.raw({
type: ['application/egonet-stream', 'application/xml', 'text/xml'],
limit: '10mb'
}));
// Convert raw buffer to string for XML processing (skip binary endpoints)
app.use((req, res, next) => {
// Skip XML parsing for services that use binary Steam ticket data
if (req.path.includes('/Login') ||
req.path.includes('AccountService') ||
req.path.includes('/MicroMachines/STEAM/') ||
req.headers['x-egonet-function'] === 'LoginService.Login') {
console.log('MMCOS Request:', req.headers['x-egonet-function'] || 'Binary Service');
console.log('๐ Binary endpoint detected - skipping XML parsing');
console.log('๐ Request path:', req.path);
next();
return;
}
if (req.headers['content-type'] &&
(req.headers['content-type'].includes('egonet-stream') ||
req.headers['content-type'].includes('application/xml') ||
req.headers['content-type'].includes('text/xml'))) {
try {
if (Buffer.isBuffer(req.body)) {
const xmlString = req.body.toString('utf8');
console.log('MMCOS Request:', req.headers['x-egonet-function'] || 'XML');
console.log('๐ XML String:', xmlString);
// Parse XML to JavaScript object
const parser = new xml2js.Parser({
explicitArray: true,
mergeAttrs: true,
ignoreAttrs: true,
explicitCharkey: false,
trim: true,
normalize: true
});
parser.parseString(xmlString, (err, result) => {
if (!err && result) {
// Convert to lowercase for easier access
req.body = {};
for (const key in result) {
req.body[key.toLowerCase()] = result[key];
}
console.log('โ
Parsed XML:', JSON.stringify(req.body, null, 2));
} else {
console.error('โ XML Parse Error:', err);
req.body = xmlString; // Fallback to original string
}
next();
});
return; // Don't call next() here, wait for parser callback
}
} catch (error) {
console.error('Error parsing XML body:', error);
}
}
next();
});
app.use(function(error, req, res, next) {
console.log('Error:', error);
next();
});
app.use((req, res, next) => {
console.log('%s %s - %s', req.method, req.url, req.ip);
next();
});
app.get('/', (req, res) => {
res.send('๐ฎ MMCOS Community Server - Micro Machines World Series Revival');
});
// ๐ง LOCALHOST COMPATIBILITY MIDDLEWARE
// Handle both localhost (without /MMCOS) and hosts-file (with /MMCOS) configurations
app.use((req, res, next) => {
// Track client configuration type for debugging
let clientType = 'unknown';
// Check if request is for a known MMCOS endpoint but without the /MMCOS prefix
const mmcosEndpoints = [
'/MMCOS-ServerStatus/ServerStatus.xml',
'/MMCOS-Account/AccountService.svc/Login',
'/MMCOS-Account/AccountService.svc/UpdateAccountTitle',
'/MMCOS-Matchmaking/MatchmakingService.svc/EnterMatchmaking2',
'/MMCOS-Matchmaking/MatchmakingService.svc/CancelMatchmaking',
'/MMCOS-Matchmaking/MatchmakingService.svc/RegisterActiveGameWithPlayers',
'/MMCOS-Matchmaking/MatchmakingService.svc/AddPoints'
];
// Check for redirect files without prefix
const redirectPattern = /^\/redirect_steam_submission[1-3]\.txt$/;
// Detect client configuration type based on request pattern
if (req.path.startsWith('/MMCOS/')) {
clientType = 'hosts-file';
} else if (mmcosEndpoints.includes(req.path) || redirectPattern.test(req.path)) {
clientType = 'localhost-config';
// Redirect internally to /MMCOS prefixed route
console.log(`๐ง Localhost client detected: ${req.method} ${req.path} โ /MMCOS${req.path}`);
req.url = '/MMCOS' + req.url;
}
// Log client type for debugging
if (clientType !== 'unknown' && !req.path.includes('admin')) {
console.log(`๏ฟฝ Client type: ${clientType} (${req.method} ${req.originalUrl || req.path})`);
}
next();
});
// Admin dashboard endpoint
app.get('/admin', (req, res) => {
const stats = gameSession.getServerStats();
const games = Array.from(gameSession.games.values());
const players = Array.from(gameSession.players.values());
res.set('Content-Type', 'text/html');
res.send(`
<html>
<head><title>MMCOS Admin Dashboard</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; background: #1a1a1a; color: #fff; }
.card { background: #2d2d2d; padding: 15px; margin: 10px 0; border-radius: 8px; }
.stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; }
.stat { background: #333; padding: 10px; border-radius: 5px; text-align: center; }
.stat-value { font-size: 24px; font-weight: bold; color: #4CAF50; }
table { width: 100%; border-collapse: collapse; margin: 10px 0; }
th, td { padding: 8px; text-align: left; border-bottom: 1px solid #444; }
th { background: #333; }
.host { color: #FFD700; font-weight: bold; }
.online { color: #4CAF50; }
.offline { color: #f44336; }
</style>
</head>
<body>
<h1>๐ฎ MMCOS Community Server Dashboard</h1>
<div class="card">
<h2>๐ Server Statistics</h2>
<div class="stats">
<div class="stat">
<div class="stat-value">${stats.totalGames}</div>
<div>Total Games</div>
</div>
<div class="stat">
<div class="stat-value">${stats.activeGames}</div>
<div>Active Games</div>
</div>
<div class="stat">
<div class="stat-value">${stats.waitingGames}</div>
<div>Waiting Games</div>
</div>
<div class="stat">
<div class="stat-value">${stats.onlinePlayers}</div>
<div>Online Players</div>
</div>
<div class="stat">
<div class="stat-value">${stats.totalPlayers}</div>
<div>Total Players</div>
</div>
<div class="stat">
<div class="stat-value">${stats.averageWaitTime.toFixed(1)}s</div>
<div>Avg Wait Time</div>
</div>
</div>
</div>
<div class="card">
<h2>๐ Active Games</h2>
<table>
<tr><th>Session ID</th><th>Host</th><th>Players</th><th>Status</th><th>Game Type</th><th>Created</th></tr>
${games.map(game => `
<tr>
<td>${game.sessionId}</td>
<td class="host">${game.hostDisplayName}</td>
<td>${game.players.length}/${game.maxPlayers}</td>
<td>${game.status}</td>
<td>${game.gameType} (${game.ranking})</td>
<td>${new Date(game.createdAt).toLocaleTimeString()}</td>
</tr>
`).join('')}
</table>
</div>
<div class="card">
<h2>๐ฅ Players</h2>
<table>
<tr><th>Display Name</th><th>Platform ID</th><th>Status</th><th>Points</th><th>Games</th><th>Wins</th><th>Current Game</th></tr>
${players.map(player => `
<tr>
<td>${player.displayName}</td>
<td>${player.platformId.substring(0, 20)}...</td>
<td class="${player.isOnline ? 'online' : 'offline'}">${player.isOnline ? 'Online' : 'Offline'}</td>
<td>${player.points}</td>
<td>${player.totalGames}</td>
<td>${player.wins}</td>
<td>${player.currentGameId || 'None'}</td>
</tr>
`).join('')}
</table>
</div>
<script>
setTimeout(() => location.reload(), 10000); // Auto-refresh every 10 seconds
</script>
</body>
</html>
`);
});
app.post('/MicroMachines/STEAM/1\.0/', (req, res) => {
console.log('๐ฎ MicroMachines STEAM 1.0 LoginService.Login request');
console.log('๐ Headers:', req.headers);
// Parse binary Steam login data
let displayName = "Player"; // Default name (will be extracted from Steam data)
let extractedSteamId = null; // Track if we found a Steam ID in the request
try {
// Convert buffer to string and extract data
const dataString = req.body.toString('utf8');
console.log('๐ Request body (first 500 chars):', dataString.substring(0, 500));
// Try to extract Steam username from the structured format: "Namedstrโ USERNAMEโ"
const namePattern = /Namedstr[^\w]*(\w+)/;
const nameMatch = dataString.match(namePattern);
if (nameMatch && nameMatch[1]) {
displayName = nameMatch[1];
console.log('โ
Found Steam username in Namedstr field:', displayName);
} else {
// Fallback: Method 1 - Look for "personaname" field (case-insensitive)
const personaMatch = dataString.match(/personaname[^\x20-\x7E]*([A-Za-z0-9_\-]{2,32})/i);
if (personaMatch && personaMatch[1]) {
displayName = personaMatch[1];
console.log('โ
Found Steam persona name:', displayName);
} else {
// Fallback: Method 2 - Look for any readable username-like string
const potentialNames = dataString.match(/[A-Za-z][A-Za-z0-9_\-]{2,31}/g);
if (potentialNames && potentialNames.length > 0) {
// Filter out common false positives
const filtered = potentialNames.filter(name =>
!['Name', 'Type', 'Data', 'Ticket', 'Steam', 'Login', 'User', 'vdic', 'dstr', 'blob', 'Namedstr', 'SteamTicketblob'].includes(name)
);
if (filtered.length > 0) {
displayName = filtered[0];
console.log('โ
Extracted display name (fallback method):', displayName);
} else {
console.warn('โ ๏ธ Could not extract display name from request, using default');
}
} else {
console.warn('โ ๏ธ Could not extract display name from request, using default');
}
}
}
// Extract Steam ID from ticket
const steamIdMatch = dataString.match(/steam_(\w+)/);
if (steamIdMatch && steamIdMatch[1]) {
extractedSteamId = "steam_" + steamIdMatch[1];
console.log('๐ Found Steam ID in request:', extractedSteamId);
}
} catch (error) {
console.error('โ Error parsing login data:', error);
}
// Generate or retrieve unique platformId based on display name
// This ensures each player with a unique name gets a unique ID
const platformId = gameSession.getOrCreatePlatformId(displayName);
console.log(`โ
MicroMachines Login: ${displayName} -> Platform ID: ${platformId}`);
const userId = Math.floor(Math.random() * 1000000);
// Generate unique session token for this player
const sessionToken = Buffer.from(`${platformId}_${Date.now()}_${Math.random()}`).toString('base64');
// Register player in game session WITH sessionToken mapping
const player = gameSession.registerPlayer(platformId, displayName, sessionToken);
// Generate authentic response with the sessionToken
const loginResponse = generateLoginResponse(platformId, displayName, userId, sessionToken);
res.set('Content-Type', 'application/xml');
res.send(loginResponse);
});
app.get('/MMCOS/redirect_steam_submission[1-3]\.txt', (req, res) => {
res.send('Live')
})
app.get('/MMCOS/MMCOS-ServerStatus/ServerStatus\.xml', (req, res) => {
const serverStatus = generateServerStatus(SERVER_CONFIG);
res.send(serverStatus);
})
app.post('/MMCOS/MMCOS-Account/AccountService\\.svc/Login', (req, res) => {
console.log('๐ MMCOS Account Login request from:', req.ip);
// Parse binary Steam login data
let displayName = "Player"; // Default name (will be extracted from Steam data)
let extractedSteamId = null; // Track if we found a Steam ID in the request
try {
// Convert buffer to string and extract data
const dataString = req.body.toString('utf8');
// Try to extract Steam username from the structured format: "Namedstrโ USERNAMEโ"
const namePattern = /Namedstr[^\w]*(\w+)/;
const nameMatch = dataString.match(namePattern);
if (nameMatch && nameMatch[1]) {
displayName = nameMatch[1];
console.log('โ
Found Steam username in Namedstr field:', displayName);
} else {
// Fallback: Method 1 - Look for readable text after "personaname" field (case-insensitive)
const personaMatch = dataString.match(/personaname[^\x20-\x7E]*([A-Za-z0-9_\-]{2,32})/i);
if (personaMatch && personaMatch[1]) {
displayName = personaMatch[1];
console.log('โ
Found Steam persona name:', displayName);
} else {
// Fallback: Method 2 - Look for any readable username-like string (3-32 chars)
const potentialNames = dataString.match(/[A-Za-z][A-Za-z0-9_\-]{2,31}/g);
if (potentialNames && potentialNames.length > 0) {
// Filter out common false positives
const filtered = potentialNames.filter(name =>
!['Name', 'Type', 'Data', 'Ticket', 'Steam', 'Login', 'User', 'vdic', 'dstr', 'blob', 'Namedstr', 'SteamTicketblob'].includes(name)
);
if (filtered.length > 0) {
displayName = filtered[0];
console.log('โ
Extracted display name (fallback method):', displayName);
} else {
console.warn('โ ๏ธ Could not extract display name from request, using default');
}
} else {
console.warn('โ ๏ธ Could not extract display name from request, using default');
}
}
}
// Extract Steam ID from ticket (optional)
const steamIdMatch = dataString.match(/steam_(\w+)/);
if (steamIdMatch && steamIdMatch[1]) {
extractedSteamId = "steam_" + steamIdMatch[1];
console.log('๐ Found Steam ID in request:', extractedSteamId);
}
} catch (error) {
console.error('โ Error parsing login data:', error);
}
// Generate or retrieve unique platformId based on display name
// This ensures each player with a unique name gets a unique ID
const platformId = gameSession.getOrCreatePlatformId(displayName);
console.log(`โ
MMCOS Account Login: ${displayName} -> Platform ID: ${platformId}`);
const userId = Math.floor(Math.random() * 1000000);
// Generate unique session token for this player
const sessionToken = Buffer.from(`${platformId}_${Date.now()}_${Math.random()}`).toString('base64');
// Register player in game session WITH sessionToken mapping
const player = gameSession.registerPlayer(platformId, displayName, sessionToken);
// Generate authentic response with the sessionToken
const loginResponse = generateLoginResponse(platformId, displayName, userId, sessionToken);
res.set('Content-Type', 'application/xml');
res.send(loginResponse);
});
app.post('/MMCOS/MMCOS-Account/AccountService\\.svc/UpdateAccountTitle', (req, res) => {
console.log('UpdateAccountTitle request:', req.body);
res.set('Content-Type', 'application/xml');
res.send('<UpdateAccountTitleResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><Error i:nil="true"/></UpdateAccountTitleResult>');
});
// Matchmaking Service Endpoints
app.post('/MMCOS/MMCOS-Matchmaking/MatchmakingService\\.svc/EnterMatchmaking2', (req, res) => {
console.log(`๐ฏ EnterMatchmaking2 request on ${SERVER_CONFIG.name}`);
console.log('๐ Raw req.body:', JSON.stringify(req.body, null, 2));
// Increment counter for testing
enterMatchmakingCounter++;
console.log(`๐ข EnterMatchmaking2 request #${enterMatchmakingCounter}`);
// Extract all important fields from request FIRST
const sessionToken = req.body.entermatchmaking2?.SessionToken?.[0];
const groupLobbyId = req.body.entermatchmaking2?.GroupLobbyId?.[0];
const gameLobbyId = req.body.entermatchmaking2?.GameLobbyId?.[0];
const gameType = req.body.entermatchmaking2?.GameType?.[0];
const ruleSet = req.body.entermatchmaking2?.RuleSet?.[0] || 'Race';
// ๐๏ธ SERVER CONFIGURATION LOGIC
const config = SERVER_CONFIG.settings;
// Force game type if configured
const actualGameType = config.forceGameType || gameType;
const actualRuleSet = config.forceGameType ? config.forceGameType.replace('Quick', '') : ruleSet;
// AI handling based on server config
const clientIgnoreMinMatch = req.body.entermatchmaking2?.IgnoreMinimumMatchRequirements?.[0] === 'true';
let ignoreMinMatch = true; // Default for community server
// Competitive server logic
if (!config.rankedWithAI && !clientIgnoreMinMatch) {
console.log(`โ๏ธ Competitive server: Rejecting ranked match without sufficient players`);
// Could implement player waiting queue here
}
console.log(`๐ฎ Server Config: AI=${config.aiEnabled}, RankedAI=${config.rankedWithAI}, MaxPlayers=${config.maxPlayers}`);
console.log(`๐ฏ Game Type: ${actualGameType}/${actualRuleSet} (${config.forceGameType ? 'FORCED' : 'CLIENT'})`);
if (actualGameType !== gameType) {
console.log(`๐ Game type overridden: ${gameType} โ ${actualGameType}`);
}
// ๐ฅ CRITICAL PATTERN DETECTION: Battle Mode triggers RegisterActiveGameWithPlayers!
const isBattleMode = gameType === 'RankedBattle' && ruleSet === 'Battle';
// DEBUG: Check why Battle Mode Detection might not trigger
console.log(`๐ Mode Check: gameType="${gameType}", ruleSet="${ruleSet}", clientIgnoreMinMatch=${clientIgnoreMinMatch}, serverIgnoreMinMatch=${ignoreMinMatch}`);
console.log(`๐ isBattleMode=${isBattleMode}, ignoreMinMatch=${ignoreMinMatch}`);
if (isBattleMode && ignoreMinMatch) {
console.log('๏ฟฝ BATTLE MODE DETECTED! RankedBattle/Battle + IgnoreMinimumMatchRequirements=true');
console.log('๐ฏ This should trigger RegisterActiveGameWithPlayers!');
// โ
BATTLE MODE RESPONSE: Critical Team=1 (not Team=0!)
const raceKey = Math.random().toString(16).substring(2, 18).toUpperCase();
const sessionId = Math.floor(Math.random() * 10000000);
const battleModeResponse = `<MatchmakingResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><AverageWaitTimeNonRanked>82.8</AverageWaitTimeNonRanked><AverageWaitTimeRanked>84.5</AverageWaitTimeRanked><Error i:nil="true"/><Groups><MatchmakingGroup><GameLobbyId>${gameLobbyId}</GameLobbyId><GroupLobbyId>${groupLobbyId}</GroupLobbyId><GroupSize>1</GroupSize><IsHost>true</IsHost><Team>1</Team><HostPlatformID>steam_AQAAAAIAAADKOgoA</HostPlatformID><GameType>${gameType}</GameType></MatchmakingGroup></Groups><InProgressGameToJoin i:nil="true"/><RaceKey>${raceKey}</RaceKey><SessionId>${sessionId}</SessionId></MatchmakingResult>`;
res.set({
'X-Powered-By': 'ASP.NET',
'Content-Type': 'text/xml; charset=utf-8',
'Content-Length': battleModeResponse.length.toString(),
'Server': 'Microsoft-IIS/8.0',
'Cache-Control': 'private'
});
console.log(`๐ค BATTLE MODE Response: Team=1, RaceKey=${raceKey}, SessionId=${sessionId}`);
res.send(battleModeResponse);
return;
}
// NEW STRATEGY: Test different response types systematically
if (enterMatchmakingCounter === 2) {
console.log(`๏ฟฝ NEW TEST: Sending "MATCH FOUND" response on request #${enterMatchmakingCounter}`);
const raceKey = gameSession.generateRaceKey();
const sessionId = Math.floor(Math.random() * 10000000);
const matchFoundXML = `<MatchmakingResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<AverageWaitTimeNonRanked>47.7</AverageWaitTimeNonRanked>
<AverageWaitTimeRanked>84.5</AverageWaitTimeRanked>
<Error i:nil="true"/>
<Groups>
<MatchmakingGroup>
<GameLobbyId>${gameLobbyId}</GameLobbyId>
<GroupLobbyId>${groupLobbyId}</GroupLobbyId>
<GroupSize>1</GroupSize>
<IsHost>true</IsHost>
<Team>1</Team>
<HostPlatformID>76561198081105540</HostPlatformID>
<GameType>${gameType}</GameType>
</MatchmakingGroup>
</Groups>
<InProgressGameToJoin i:nil="true"/>
<RaceKey>${raceKey}</RaceKey>
<SessionId>${sessionId}</SessionId>
</MatchmakingResult>`;
console.log(`๐ฎ CORRECTED MATCH FOUND XML - InProgressGameToJoin is now nil!`);
res.set('Content-Type', 'text/xml; charset=utf-8');
res.send(matchFoundXML);
return;
}
const networkVersion = req.body.entermatchmaking2?.NetworkVersion?.[0] || '1';
const requestedGroupSize = req.body.entermatchmaking2?.GroupSize?.[0] || '1';
const skillLevel = req.body.entermatchmaking2?.SkillLevel?.[0] || '1000000';
// ruleSet already defined above
const ranking = req.body.entermatchmaking2?.Ranking?.[0] || 'NotRanked';
const ignoreMinRequirements = req.body.entermatchmaking2?.IgnoreMinimumMatchRequirements?.[0] || 'false';
console.log(`๐ Field Access Test: GroupLobbyId=${groupLobbyId}, GameLobbyId=${gameLobbyId}`);
console.log(`๐ Available fields:`, Object.keys(req.body.entermatchmaking2 || {}));
// Generate MITM dump compatible IDs if not provided
if (!groupLobbyId) {
groupLobbyId = '109775241626724054'; // Fixed GroupLobbyId from MITM dump
}
if (!gameLobbyId) {
gameLobbyId = `10977524${Date.now().toString().substring(-8)}`; // Dynamic GameLobbyId in same format
}
console.log(`๐ฎ Matchmaking request: ${gameType}/${ruleSet}/${ranking}, Group: ${requestedGroupSize}, Skill: ${skillLevel}`);
console.log(`๐ Client IDs: GroupLobbyId=${groupLobbyId}, GameLobbyId=${gameLobbyId}`);
// ๐ CRITICAL FIX: Look up platformId by sessionToken to prevent duplicate players
let platformId;
if (sessionToken) {
// Try to find existing player by sessionToken
platformId = gameSession.getPlatformIdByToken(sessionToken);
if (!platformId) {
// SessionToken not found - this shouldn't happen if player logged in
console.warn(`โ ๏ธ SessionToken not found in map: ${sessionToken.substring(0, 20)}...`);
// Fallback: use IP-based ID
const clientIp = req.ip.replace(/[^a-zA-Z0-9]/g, '_');
platformId = `player_${clientIp}`;
// Register with this sessionToken
gameSession.registerPlayer(platformId, `Player_${platformId.substring(7, 15)}`, sessionToken);
} else {
// Check if player actually exists in our database
const playerExists = gameSession.getPlayer(platformId);
if (!playerExists) {
console.warn(`โ ๏ธ Session token valid but player ${platformId} not found - server was restarted`);
console.warn(`โ ๏ธ Clearing invalid session token - client must re-login`);
// Clear the invalid session token
gameSession.sessionTokenMap.delete(sessionToken);
// Return error to force re-login
return res.status(401).type('application/xml').send(`<?xml version="1.0" encoding="utf-8"?>
<MatchmakingResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Error>Session expired. Please restart game.</Error>
</MatchmakingResult>`);
}
console.log(`๐ Found existing player via sessionToken: ${platformId}`);
}
} else {
// No sessionToken - use IP address to create consistent player ID
const clientIp = req.ip.replace(/[^a-zA-Z0-9]/g, '_');
platformId = `player_${clientIp}`;
// Register player if not exists
if (!gameSession.getPlayer(platformId)) {
gameSession.registerPlayer(platformId, `Player_${platformId.substring(7, 15)}`);
console.log(`๐ฎ Player registered: Player_${platformId.substring(7, 15)} (${platformId})`);
}
}
// IMPORTANT: Using consistent platformId prevents duplicate player registration
console.log(`๐ Using consistent platformId: ${platformId}`);
let game;
let isHost = false;
// ๐ CRITICAL FIX: Check if player is already in a game (prevents loop!)
const currentPlayer = gameSession.getPlayer(platformId);
if (currentPlayer && currentPlayer.currentGameId) {
// Player already in a game - return that game instead of creating/joining another
const existingGame = gameSession.games.get(currentPlayer.currentGameId);
if (existingGame && existingGame.status === 'waiting') {
// Game is waiting - return it
game = existingGame;
const playerInGame = game.players.find(p => p.platformId === platformId);
isHost = playerInGame ? playerInGame.isHost : false;
console.log(`โป๏ธ Player already in WAITING game Session ${game.sessionId} - returning existing game`);
console.log(` ๐ฅ Players: ${game.players.length}/${game.maxPlayers}, IsHost: ${isHost}`);
} else if (existingGame && existingGame.status === 'active') {
// Game is active - check if it's old/stale (more than 5 minutes)
const gameAge = Date.now() - (existingGame.startedAt?.getTime() || existingGame.createdAt.getTime());
const fiveMinutes = 5 * 60 * 1000;
if (gameAge > fiveMinutes) {
// Game is old/stale - mark as finished and create new one
existingGame.status = 'finished';
currentPlayer.currentGameId = null;
console.log(`๐งน Game Session ${existingGame.sessionId} is stale (${Math.floor(gameAge/1000)}s old) - creating new game`);
game = null;
} else {
// Game is active and fresh - return it (client might be in-game)
game = existingGame;
const playerInGame = game.players.find(p => p.platformId === platformId);
isHost = playerInGame ? playerInGame.isHost : false;
console.log(`โป๏ธ Player in ACTIVE game Session ${game.sessionId} - returning game`);
console.log(` ๐ฅ Players: ${game.players.length}/${game.maxPlayers}, IsHost: ${isHost}`);
}
} else {
// Game is finished or doesn't exist - clear currentGameId and continue
currentPlayer.currentGameId = null;
console.log(`๐งน Cleared finished/missing game from player record`);
game = null;
}
}
// If player not in a game, do matchmaking
if (!game) {
// ๐ฏ SMART MATCHMAKING: Always try to join existing games first
// Look for any available game that matches our criteria
try {
const availableGames = gameSession.getAvailableGames(gameType, ranking);
if (availableGames.length > 0) {
// Found an existing game - join it
const existingGame = availableGames[0];
game = gameSession.joinGame(existingGame.sessionId, platformId);
isHost = false;
console.log(`๐ฎ MATCH FOUND: Joined existing game: Session ${game.sessionId} (${game.players.length}/${game.maxPlayers})`);
console.log(` ๐ฎ Game Type: ${game.gameType}/${game.ruleSet}, Ranking: ${game.ranking}`);
} else {
// No available games - create new one
game = gameSession.createGame(platformId, gameType, ruleSet, ranking, gameLobbyId, groupLobbyId);
isHost = true;
console.log(`๐ NEW GAME CREATED for GameLobbyId ${gameLobbyId}! Player is HOST: Session ${game.sessionId}`);
console.log(` ๐ฎ Game Type: ${gameType}/${ruleSet}, Ranking: ${ranking}, Skill: ${skillLevel}`);
console.log(` โณ Game stays in 'waiting' state - Client will start when ready`);
// ๐ฏ COMMUNITY SERVER AUTO-START:
// If IgnoreMinimumMatchRequirements=false (Ranked/Public mode),
// we auto-start after 3 seconds since no real players will join
if (ignoreMinMatch === false || ignoreMinMatch === 'false') {
console.log(`โฐ Community Server Mode: Auto-starting game in 3 seconds (Ranked match with solo player)`);
setTimeout(() => {
try {
const currentGame = gameSession.games.get(game.sessionId);
if (currentGame && currentGame.status === 'waiting') {
currentGame.status = 'active';
currentGame.startedAt = new Date();
console.log(`๐ AUTO-STARTED Game Session ${game.sessionId} (Community Server - Solo Ranked Match)`);
console.log(` ๏ฟฝ Player ${platformId} can now play solo!`);
}
} catch (e) {
console.error(`โ Auto-start failed: ${e.message}`);
}
}, 3000);
}
}
} catch (error) {
console.error('โ Matchmaking error:', error.message);
// Fallback: create new game
game = gameSession.createGame(platformId, gameType, ruleSet, ranking, gameLobbyId, groupLobbyId);
isHost = true;
console.log(`๐ Fallback: Created new game after error - Session ${game.sessionId}`);
}
}
// Find player info in game
const playerInGame = game.players.find(p => p.platformId === platformId);
const groupSize = game.players.length;
const stats = gameSession.getServerStats();
try {
// ๐ฏ NEW THEORY: InProgressGameToJoin with SessionId might trigger RegisterActiveGameWithPlayers!
// Tell client there's an active game ready to join
const teamValue = 0;
const inProgressGame = `<InProgressGameToJoin><SessionId>${game.sessionId}</SessionId></InProgressGameToJoin>`;
const finalResponse = `<MatchmakingResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><AverageWaitTimeNonRanked>82.8</AverageWaitTimeNonRanked><AverageWaitTimeRanked>84.5</AverageWaitTimeRanked><Error i:nil="true"/><Groups><MatchmakingGroup><GameLobbyId>${gameLobbyId}</GameLobbyId><GroupLobbyId>${groupLobbyId}</GroupLobbyId><GroupSize>${groupSize}</GroupSize><IsHost>${playerInGame.isHost}</IsHost><Team>${teamValue}</Team></MatchmakingGroup></Groups>${inProgressGame}<RaceKey>${game.raceKey}</RaceKey><SessionId>${game.sessionId}</SessionId></MatchmakingResult>`;
const response = finalResponse;
console.log(`๐ฒ Matchmaking result: SessionId ${game.sessionId}, RaceKey ${game.raceKey}`);
console.log(` ๐ฅ Players: ${groupSize}/${game.maxPlayers}, Host: ${playerInGame.isHost ? '๐ YES' : 'NO'}`);
console.log(`โ
Sending Team=${teamValue} ${ignoreMinMatch ? '(Quick Play Mode!)' : '(Ranked Mode)'} - Authentic MMCOS response format`);
console.log(`๐ค FULL Response XML:\n${response}`);
console.log(`๐ค Response length: ${response.length} bytes`);
// Set exact MMCOS-style headers
res.set('Content-Type', 'text/xml; charset=utf-8');
res.set('Content-Length', response.length.toString());
res.set('Server', 'Microsoft-IIS/8.0');
res.set('X-Powered-By', 'ASP.NET');
res.set('Cache-Control', 'private');
console.log(`๐ค Response Headers: ${JSON.stringify(res.getHeaders())}`);
res.send(response);
} catch (error) {
console.error('โ Response error:', error.message);
// Fallback response (original behavior)
const fallbackSessionId = Math.floor(Math.random() * 10000000);
const fallbackRaceKey = Math.random().toString(16).substring(2, 18).toUpperCase();
const response = `<MatchmakingResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<AverageWaitTimeNonRanked>45.0</AverageWaitTimeNonRanked>
<AverageWaitTimeRanked>55.0</AverageWaitTimeRanked>
<Error i:nil="true"/>
<Groups>
<MatchmakingGroup>
<GameLobbyId>109775241628860699</GameLobbyId>
<GroupLobbyId>109775241626724054</GroupLobbyId>
<GroupSize>1</GroupSize>
<IsHost>true</IsHost>
<Team>1</Team>
</MatchmakingGroup>
</Groups>
<InProgressGameToJoin i:nil="true"/>
<RaceKey>${fallbackRaceKey}</RaceKey>
<SessionId>${fallbackSessionId}</SessionId>
</MatchmakingResult>`;
res.set('Content-Type', 'application/xml');
res.send(response);
}
});
// Cancel Matchmaking Service Endpoint
app.post('/MMCOS/MMCOS-Matchmaking/MatchmakingService\\.svc/CancelMatchmaking', (req, res) => {
console.log('โ CancelMatchmaking request');
const sessionToken = req.body.cancelmatchmaking?.sessiontoken?.[0];
// ๐ Use SessionToken-Mapping to find existing player
let platformId;
if (sessionToken) {
platformId = gameSession.getPlatformIdByToken(sessionToken);
if (!platformId) {
console.warn(`โ ๏ธ SessionToken not found in CancelMatchmaking: ${sessionToken.substring(0, 20)}...`);
const clientIp = req.ip.replace(/[^a-zA-Z0-9]/g, '_');
platformId = `player_${clientIp}`;
}
} else {
const clientIp = req.ip.replace(/[^a-zA-Z0-9]/g, '_');
platformId = `player_${clientIp}`;
}
console.log(`๐ CancelMatchmaking for platformId: ${platformId}`);
const player = gameSession.getPlayer(platformId);
if (player && player.currentGameId) {
const game = gameSession.games.get(player.currentGameId);
if (game && game.status === 'waiting') {
// Remove player from game
game.players = game.players.filter(p => p.platformId !== platformId);
player.currentGameId = null;
console.log(`๐ช Player left matchmaking: ${player.displayName} from Session ${game.sessionId}`);
console.log(` Remaining players: ${game.players.length}/8`);
// If game is empty, remove it
if (game.players.length === 0) {
gameSession.games.delete(player.currentGameId);
console.log(`๐๏ธ Empty game removed: Session ${game.sessionId}`);
}
}
}
res.set('Content-Type', 'application/xml');
res.send('<CancelMatchmakingResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><Error i:nil="true"/></CancelMatchmakingResult>');
});
// Additional critical game endpoints
app.post('/MMCOS/MMCOS-Matchmaking/MatchmakingService\.svc/RegisterActiveGameWithPlayers', (req, res) => {
console.log('๐ฎ RegisterActiveGameWithPlayers request');
console.log('๐ Raw req.body:', JSON.stringify(req.body, null, 2));
// Try both casing variants
const data = req.body.registeractivegamewithplayers || req.body.RegisterActiveGameWithPlayers;
console.log('๐ Found data:', data ? 'YES' : 'NO');
if (data) {
const sessionToken = data.SessionToken?.[0] || data.sessiontoken?.[0];
const raceKey = data.RaceKey?.[0] || data.racekey?.[0];
const hostPlatformID = data.HostPlatformID?.[0] || data.hostplatformid?.[0];
const gameLobbyId = data.GameLobbyId?.[0] || data.gamelobbyid?.[0];
const gameType = data.GameType?.[0] || data.gametype?.[0];
const ruleSet = data.RuleSet?.[0] || data.ruleset?.[0];
const ranking = data.Ranking?.[0] || data.ranking?.[0];
const platformIDs = data.PlatformIDs?.[0] || data.platformids?.[0];
console.log(`๐ Game registration: RaceKey ${raceKey}, Host: ${hostPlatformID}`);
console.log(` Players: ${platformIDs}, Type: ${gameType}, Rules: ${ruleSet}`);
// Find and start the game
try {
// Find game by race key or create if needed
let game = null;
for (const [sessionId, gameData] of gameSession.games) {
if (gameData.raceKey === raceKey) {
game = gameData;
break;
}
}
if (game) {
gameSession.startGame(game.sessionId);
console.log(`๐ Game started via RegisterActiveGameWithPlayers: Session ${game.sessionId}`);
} else {
console.log(`โ ๏ธ No game found with RaceKey ${raceKey}`);
}
} catch (error) {
console.error('โ Error starting game:', error.message);
}
} else {
console.log('โ No valid data found in RegisterActiveGameWithPlayers request');
}
res.set('Content-Type', 'application/xml');
res.send('<RegisterActiveGameWithPlayersResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><Error i:nil="true"/></RegisterActiveGameWithPlayersResult>');
});
app.post('/MMCOS/MMCOS-Matchmaking/MatchmakingService\.svc/AddPoints', (req, res) => {
console.log('๐ AddPoints request');
const sessionToken = req.body.addpoints?.sessiontoken?.[0];
const raceKey = req.body.addpoints?.racekey?.[0];
const points = parseInt(req.body.addpoints?.points?.[0] || '0');
const level = parseInt(req.body.addpoints?.level?.[0] || '1');
const prestige = parseInt(req.body.addpoints?.prestige?.[0] || '0');
console.log(`๐ Points awarded: ${points} points, Level ${level}, Prestige ${prestige}`);
console.log(` RaceKey: ${raceKey}`);
// ๐ Find player using SessionToken-Mapping
let playerData = null;
try {
// Use SessionToken-Mapping to find correct player
let platformId;
if (sessionToken) {
platformId = gameSession.getPlatformIdByToken(sessionToken);
if (!platformId) {