-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
1624 lines (1543 loc) · 72.8 KB
/
Copy pathserver.js
File metadata and controls
1624 lines (1543 loc) · 72.8 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 http = require('http');
const fs = require('fs');
const path = require('path');
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = new Server(server, { cors: { origin: '*' } });
app.use(express.static('public'));
app.use(express.json());
// CORS for /auth/* endpoints (allows file:// page to reach the server)
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
if (req.method === 'OPTIONS') return res.sendStatus(200);
next();
});
// ── User accounts (passwords are bcrypt-hashed at rest) ────────────────────
// Nothing here ever writes a readable password to disk. Accounts created before
// this change stored one; the first successful login upgrades those records in
// place (see checkPassword), so no one gets locked out by the switch.
// Storage location is configurable via env var so we can point at a persistent
// volume on Railway. Without that, every redeploy wipes the file.
// Set DATA_DIR=/data in Railway, attach a volume mounted at /data.
const DATA_DIR = process.env.DATA_DIR || __dirname;
const USERS_FILE = path.join(DATA_DIR, 'users.json');
try { fs.mkdirSync(DATA_DIR, { recursive: true }); } catch (e) {}
console.log('[users] storage:', USERS_FILE);
let users = {};
try { users = JSON.parse(fs.readFileSync(USERS_FILE, 'utf-8')); console.log('[users] loaded', Object.keys(users).length, 'accounts'); }
catch (e) { users = {}; console.log('[users] no existing file — starting fresh'); }
function saveUsers() {
// Atomic write: write to .tmp then rename so a crash mid-write can't corrupt the file
try {
const tmp = USERS_FILE + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(users, null, 2));
fs.renameSync(tmp, USERS_FILE);
} catch (e) { console.error('saveUsers:', e); }
}
// ── Passwords ──────────────────────────────────────────────────────────────
// bcrypt is deliberately slow, which is what makes a stolen users.json useless
// — but that also makes it far too slow to run on every shop request, and this
// process is also serving a realtime shooter. So: bcrypt is the only thing that
// touches disk, and once a password has been verified for real, its SHA-256 is
// remembered in memory for the life of the process and used for the repeat
// checks. The cache holds a hash, never a password, and is never persisted.
const bcrypt = require('bcryptjs');
const crypto = require('crypto');
const BCRYPT_ROUNDS = 10;
const verifiedPasswords = new Map(); // username -> sha256(password) already bcrypt-verified
function hashPassword(pw) { return bcrypt.hashSync(String(pw), BCRYPT_ROUNDS); }
function fastKey(pw) { return crypto.createHash('sha256').update(String(pw)).digest('hex'); }
// The single place that decides whether a password is correct.
function checkPassword(username, pw) {
const u = users[username];
if (!u || !pw) return false;
const key = fastKey(pw);
if (verifiedPasswords.get(username) === key) return true;
let ok = false;
if (u.passwordHash) {
ok = bcrypt.compareSync(String(pw), u.passwordHash);
} else if (typeof u.password === 'string') {
// Legacy record from before hashing. Verify against the old plaintext once,
// then convert it and drop the plaintext for good.
ok = u.password === pw;
if (ok) {
u.passwordHash = hashPassword(pw);
delete u.password;
saveUsers();
console.log('[auth] upgraded stored password to a hash for', username);
}
}
if (ok) verifiedPasswords.set(username, key);
return ok;
}
// ── 🛒 Shop: weapon costs + per-account credit balance ─────────────────────
// Authoritative cost table (server-side so clients can't cheat their balance).
// Mirrors the client-side WEAPON_COSTS table in game.js — keep them in sync.
// Admin items are NOT in this table (they're not purchasable; promo-only).
const WEAPON_COSTS = {
// Primaries — ARs / SMGs
ak20: 250, mp40: 200, p90: 350, vector: 300, burst: 280,
// Primaries — Shotguns
sg8: 220,
// Primaries — Snipers / Marksman
srx: 500, lever: 360,
lancer: 460, rpg: 520, bazooka: 620,
// Primaries — Special
rpd: 450, paintball: 120, crossbow: 280,
// Primaries — Heavy
minigun: 600, grenade_launcher: 500, flamethrower: 420,
// Primaries — Sci-fi / energy
railgun: 600, freeze_gun: 350, plasma_carbine: 420, arc_rifle: 400,
arc_torrent: 460, prism_launcher: 420, storm_cannon: 540,
coilgun: 460, painter_beam: 300, gravity_paint: 400,
portal_launcher: 460, traffic_controller: 320,
// Primaries — Explosive / projectile
boombow: 500, gravity_launcher: 480, harpoon_gun: 440, mortar_rifle: 480,
firework_launcher: 360, shockwave_launcher: 460, airburst_projector: 360,
pinball_launcher: 440, seismic_hammer: 480, glassmaker: 380,
// Primaries — Tactical / precision / battle rifle
m1_garand: 380, flechette: 380,
burst_cannon: 480, amr: 2000, air_rifle: 320,
twin_ar: 440, swarm_rifle: 460, smart_smg: 380, switchblade_gun: 420,
// Primaries — Joke / chaos
potato_cannon: 220, sticker_blaster: 280, foam_cannon: 280,
// Premium / P2W — ridiculously expensive on purpose
// 🌌 Sci-fi P2W primaries
event_horizon: 24000, storm_core: 20000, abs_zero: 22000, solar_lance: 26000,
quantum_repeater: 28000, magnetar: 25000,
nebula_mortar: 35000, prism_engine: 27000, void_harvester: 40000,
// Secondaries
revolver: 150, flare: 80, pistol: 60, shorty: 180, cycler: 140,
hand_cannon: 260, throwing_knives: 120, taser: 200, traffic_cone: 160, cream_pie: 140,
machine_pistol: 220, sawed_off: 260, machine_revolver: 240,
dart_gun: 160, laser_pointer: 120,
auto_revolver: 220, frost_blaster: 240,
// Batch-4 secondaries
snub_revolver: 140, duelist_pistol: 280, mauser: 200,
nail_gun: 180, boomstick: 220, signal_pistol: 200, throwing_axes: 240,
boomerang: 180, slingshot: 100,
// 🌌 Sci-fi P2W secondaries
pulse_needle: 12000,
// Melees
bat: 80, sabre: 140, frying_pan: 60, sledge: 360, spear: 200,
katana: 360, baguette: 50, knife: 280, chainsaw: 1400, lightsabre: 1800,
riot_shield: 220, screwdriver: 60, crowbar: 110, fire_axe: 420,
nunchucks: 160, umbrella: 140, yoyo: 180, combat_axe: 380,
shock_baton: 220, titan_hammer: 2400, vampire_blade: 2000, fists: 0,
// Batch-4 melees
brass_knuckles: 200, hatchet: 220, machete: 260, cane: 140, cricket_bat: 200,
pipe: 160, wrench: 180, shovel: 280, golf_club: 200, tennis_racket: 100,
fire_poker: 200, meat_cleaver: 260,
// 🌌 Sci-fi P2W melees
phase_blade: 18000, gravity_hammer: 22000, volt_whip: 17000,
// Support / Utility
frag: 120, medkit: 80, stim: 60, smoke: 70, blink_pearl: 280,
ammo_fountain: 180, confetti_cannon: 100, moon_mine: 220, rubber_duck: 90,
black_hole_seed: 2200, glitch_cube: 240, vampire_syringe: 200,
adrenaline: 220, tripwire: 200, hologram: 240, magnet_mine: 220,
bounce_pad: 140, hunter_drone: 460, emp_grenade: 240, sticky_charge: 320,
orbital_strike: 2500, guardian_drone: 380, nano_shield: 320,
air_grenade: 160, land_mine: 380,
// Batch-4 utilities
flashbang_basic: 200, proximity_mine: 220, dynamite: 280, drone_strike: 340,
healing_pulse: 200, teleport_beacon: 260, cloak: 280, berserker_serum: 240,
taser_grenade: 220, ink_bomb: 140, siren: 200, caltrops: 180,
// 🌌 Sci-fi P2W utilities
nano_swarm: 20000, warp_beacon: 25000, stasis_mine: 18000,
specter_drone: 30000, quantum_barrier: 21000,
hamburger: 300,
molotov: 180,
heal_gun: 220, tesla_coil: 360, acid_grenade: 200, bee_jar: 240,
};
// Free starter loadout — every account has these unlocked from day 1.
const FREE_WEAPONS = new Set([
'ak20', 'sg8', // primaries
'pistol', 'flare', // secondaries
'fists', 'frying_pan', // melees (knife is 2× speed + 28 dmg = nasty, NOT free)
'frag', 'medkit', // utilities
]);
// ── 💼 Bundles — ~60% off the sum of individual prices ─────────────
// Keep in sync with public/game.js BUNDLES table.
const BUNDLES = {
pitiful: { name: 'Pitiful Pack', price: 420, items: ['ak20','sg8','revolver','bat','smoke'] },
retro: { name: 'Retro Pack', price: 145, items: ['paintball','laser_pointer','baguette','rubber_duck','confetti_cannon'] },
starter_pro: { name: 'Starter Pro', price: 330, items: ['ak20','revolver','bat','stim'] },
heavy_duty: { name: 'Heavy Duty', price: 700, items: ['minigun','grenade_launcher','machine_revolver','crowbar','sticky_charge'] },
sniper_pack: { name: 'Sniper Pack', price: 580, items: ['srx','revolver','knife','smoke'] },
run_n_gun: { name: 'Run & Gun', price: 430, items: ['p90','machine_pistol','knife','adrenaline'] },
melee_master: { name: 'Melee Master', price: 480, items: ['sg8','revolver','fire_axe','smoke'] },
shotgun_pack: { name: 'Shotgun Pack', price: 430, items: ['sg8','sawed_off','crowbar','frag'] },
scifi: { name: 'Sci-Fi Arsenal', price: 500, items: ['plasma_carbine','arc_rifle','dart_gun','emp_grenade'] },
demolition: { name: 'Demolition', price: 600, items: ['grenade_launcher','throwing_axes','sledge','sticky_charge'] },
archery: { name: "Archer's Kit", price: 580, items: ['crossbow','boombow','throwing_knives','tripwire'] },
marksman: { name: 'Marksman', price: 430, items: ['lever','hand_cannon','knife','ammo_fountain'] },
pyro: { name: 'Pyromaniac', price: 620, items: ['flamethrower','sg8','fire_axe','sticky_charge'] },
chaos: { name: 'Chaos Mode', price: 150, items: ['paintball','confetti_cannon','baguette','rubber_duck'] },
stealth: { name: 'Stealth Ops', price: 360, items: ['air_rifle','throwing_knives','knife','smoke'] },
storm: { name: 'Storm Pack', price: 420, items: ['arc_rifle','taser','shock_baton','emp_grenade'] },
defensive: { name: 'Defensive', price: 450, items: ['sg8','taser','riot_shield','nano_shield'] },
royalty: { name: 'Royalty', price: 4500, items: ['minigun','vampire_blade','hand_cannon','orbital_strike'] },
kitchen: { name: 'Kitchen Catastrophe',price: 130, items: ['paintball','baguette','frying_pan','rubber_duck'] },
knight: { name: "Knight's Honor", price: 410, items: ['sg8','sabre','katana','smoke'] },
frostbite: { name: 'Frostbite', price: 380, items: ['freeze_gun','frost_blaster','knife','smoke'] },
knockback: { name: 'Knockback', price: 500, items: ['shockwave_launcher','sawed_off','sledge','air_grenade'] },
smart_tech: { name: 'Smart Tech', price: 610, items: ['swarm_rifle','smart_smg','hunter_drone','magnet_mine'] },
mortar: { name: 'Mortar Squad', price: 550, items: ['mortar_rifle','grenade_launcher','hand_cannon','frag'] },
cosmic_p2w: { name: 'Cosmic P2W', price: 80000, items: ['event_horizon','storm_core','abs_zero','solar_lance','quantum_repeater','magnetar','nebula_mortar','prism_engine','void_harvester','pulse_needle','revolver','phase_blade','gravity_hammer','volt_whip','nano_swarm','warp_beacon','stasis_mine','specter_drone','quantum_barrier'] },
};
const STARTER_CREDITS = 500;
const TRIAL_DIVISOR = 20; // trial costs 1/20 of buy price (min 1)
function ensureShopFields(u) {
if (!u) return;
if (typeof u.credits !== 'number') u.credits = STARTER_CREDITS;
if (!Array.isArray(u.purchased)) u.purchased = [];
if (typeof u.fragments !== 'number') u.fragments = 0;
if (!u.chests) u.chests = { common: 0, rare: 0 };
if (!u.upgrades) u.upgrades = {}; // { [weaponId]: { damage, mag, reload } }
if (!u.lastFreeSpinDate) u.lastFreeSpinDate = ''; // YYYY-MM-DD UTC
if (typeof u.adminPassExpiresAt !== 'number') u.adminPassExpiresAt = 0; // 10-min trial of all admin items
}
const ADMIN_PASS_COST = 300;
const ADMIN_PASS_LENGTH_MS = 10 * 60 * 1000; // 10 minutes
// ── 📦 Chests, 🎡 wheel, ✨ upgrades ───────────────────────────────────
const CHEST_PRICES = { common: 120, rare: 400 };
// Fragment unlock = credit_price / 4, floor, with a 100-fragment minimum.
// So cheap weapons still cost ~100 frags but a 40k P2W item costs 10k.
const FRAGMENT_UNLOCK_MIN = 100;
function fragmentUnlockCost(weaponId) {
const price = WEAPON_COSTS[weaponId];
if (price == null) return null;
return Math.max(FRAGMENT_UNLOCK_MIN, Math.floor(price / 4));
}
// Cost to buy the Nth level of any single stat (10 levels per stat now)
const UPGRADE_COSTS = [30, 60, 120, 240, 480, 800, 1200, 1800, 2500, 3500];
const UPGRADE_STATS = ['damage', 'mag', 'reload']; // pickable per level
const WHEEL_PAID_COST = 100;
const MAX_LEVELS_PER_STAT = 10; // per-stat cap; total across 3 stats can reach 30
function rand(min, max) { return min + Math.random() * (max - min); }
function ri(min, max) { return Math.floor(rand(min, max + 1)); }
function todayUTC() { return new Date().toISOString().slice(0, 10); }
function rollChestDrops(type) {
if (type === 'common') {
return { fragments: ri(10, 25), credits: ri(0, 30), weapon: null };
}
// rare
const drops = { fragments: ri(35, 80), credits: ri(30, 100), weapon: null };
if (Math.random() < 0.05) {
const pool = Object.keys(WEAPON_COSTS).filter(id => !FREE_WEAPONS.has(id));
drops.weapon = pool[Math.floor(Math.random() * pool.length)];
}
return drops;
}
function rollWheel() {
// Sum is 100. 0.3% jackpot at the top.
const r = Math.random() * 100;
if (r < 0.3) return { kind: 'jackpot' }; // random rare weapon (>=400 cost)
if (r < 1.0) return { kind: 'bigBundle' }; // 400 credits + 150 fragments
if (r < 6.0) return { kind: 'smallRare' }; // 200 credits OR 100 fragments
if (r < 20.0) return { kind: 'bigFragments' }; // 40-80 fragments
if (r < 55.0) return { kind: 'fragments' }; // 12-30 fragments
return { kind: 'credits' }; // 60-180 credits
}
app.post('/shop/buy-chest', (req, res) => {
const { type } = req.body || {};
const u = authedUser(req);
if (!u) return res.status(401).json({ error: 'auth failed' });
if (!CHEST_PRICES[type]) return res.status(400).json({ error: 'unknown chest type' });
const cost = CHEST_PRICES[type];
if ((u.credits || 0) < cost) return res.status(402).json({ error: 'not enough credits', credits: u.credits });
u.credits -= cost;
u.chests[type] = (u.chests[type] || 0) + 1;
saveUsers();
res.json({ ok: true, type, credits: u.credits, chests: u.chests });
});
app.post('/shop/open-chest', (req, res) => {
const { type } = req.body || {};
const u = authedUser(req);
if (!u) return res.status(401).json({ error: 'auth failed' });
if (!CHEST_PRICES[type]) return res.status(400).json({ error: 'unknown chest type' });
if ((u.chests[type] || 0) <= 0) return res.status(400).json({ error: 'no chest of that type' });
u.chests[type]--;
const drops = rollChestDrops(type);
u.fragments += drops.fragments;
u.credits = (u.credits || 0) + drops.credits;
if (drops.weapon && !u.purchased.includes(drops.weapon) && !FREE_WEAPONS.has(drops.weapon)) {
u.purchased.push(drops.weapon);
} else if (drops.weapon) {
drops.weapon = null; // already owned — quietly drop
}
saveUsers();
res.json({ ok: true, drops, credits: u.credits, fragments: u.fragments, chests: u.chests, purchased: u.purchased });
});
app.post('/shop/unlock-fragments', (req, res) => {
const { weaponId } = req.body || {};
const u = authedUser(req);
if (!u) return res.status(401).json({ error: 'auth failed' });
if (!canPurchase(weaponId)) return res.status(400).json({ error: 'not purchasable' });
if (FREE_WEAPONS.has(weaponId) || u.purchased.includes(weaponId)) return res.json({ ok: true, already: true });
const cost = fragmentUnlockCost(weaponId);
if (cost == null) return res.status(400).json({ error: 'no fragment cost defined' });
if ((u.fragments || 0) < cost) return res.status(402).json({ error: 'not enough fragments', fragments: u.fragments, cost });
u.fragments -= cost;
u.purchased.push(weaponId);
saveUsers();
res.json({ ok: true, weaponId, fragments: u.fragments, purchased: u.purchased, cost });
});
app.post('/shop/upgrade-weapon', (req, res) => {
const { weaponId, stat } = req.body || {};
const u = authedUser(req);
if (!u) return res.status(401).json({ error: 'auth failed' });
if (!UPGRADE_STATS.includes(stat)) return res.status(400).json({ error: 'invalid stat' });
if (!u.purchased.includes(weaponId) && !FREE_WEAPONS.has(weaponId)) return res.status(400).json({ error: 'weapon not owned' });
const up = u.upgrades[weaponId] || { damage: 0, mag: 0, reload: 0 };
const currentLvl = up[stat] || 0;
if (currentLvl >= MAX_LEVELS_PER_STAT) return res.status(400).json({ error: 'max level for that stat' });
const cost = UPGRADE_COSTS[currentLvl]; // cost for the next level of THIS stat
if ((u.fragments || 0) < cost) return res.status(402).json({ error: 'not enough fragments', fragments: u.fragments, cost });
u.fragments -= cost;
up[stat] = (up[stat] || 0) + 1;
u.upgrades[weaponId] = up;
saveUsers();
res.json({ ok: true, weaponId, stat, upgrades: u.upgrades, fragments: u.fragments });
});
app.post('/shop/spin-wheel', (req, res) => {
const u = authedUser(req);
if (!u) return res.status(401).json({ error: 'auth failed' });
const today = todayUTC();
let free = u.lastFreeSpinDate !== today;
if (u.isAdmin) free = true; // admin: always free, never deducted
if (!free && (u.credits || 0) < WHEEL_PAID_COST) return res.status(402).json({ error: 'not enough credits', credits: u.credits });
if (free && !u.isAdmin) u.lastFreeSpinDate = today;
else if (!free) u.credits -= WHEEL_PAID_COST;
const outcome = rollWheel();
const result = { kind: outcome.kind, freeUsed: free, paidCost: free ? 0 : WHEEL_PAID_COST };
switch (outcome.kind) {
case 'credits': result.credits = ri(60, 180); u.credits += result.credits; break;
case 'fragments': result.fragments = ri(12, 30); u.fragments += result.fragments; break;
case 'bigFragments': result.fragments = ri(40, 80); u.fragments += result.fragments; break;
case 'smallRare':
if (Math.random() < 0.5) { result.credits = 200; u.credits += 200; }
else { result.fragments = 100; u.fragments += 100; }
break;
case 'bigBundle': result.credits = 400; result.fragments = 150; u.credits += 400; u.fragments += 150; break;
case 'jackpot': {
const pool = Object.keys(WEAPON_COSTS).filter(id => WEAPON_COSTS[id] >= 400 && !u.purchased.includes(id) && !FREE_WEAPONS.has(id));
if (pool.length > 0) {
const pick = pool[Math.floor(Math.random() * pool.length)];
u.purchased.push(pick);
result.weapon = pick;
} else {
// Already own all rares — fallback to a big bundle
result.credits = 800; result.fragments = 200; u.credits += 800; u.fragments += 200; result.kind = 'bigBundle';
}
break;
}
}
saveUsers();
result.credits_balance = u.credits;
result.fragments_balance = u.fragments;
result.purchased = u.purchased;
res.json({ ok: true, result });
});
app.post('/shop/admin-pass', (req, res) => {
const u = authedUser(req);
if (!u) return res.status(401).json({ error: 'auth failed' });
if ((u.adminPassExpiresAt || 0) > Date.now()) {
return res.json({ ok: true, already: true, adminPassExpiresAt: u.adminPassExpiresAt, credits: u.credits });
}
if (!u.isAdmin && (u.credits || 0) < ADMIN_PASS_COST) {
return res.status(402).json({ error: 'not enough credits', credits: u.credits, cost: ADMIN_PASS_COST });
}
if (!u.isAdmin) u.credits -= ADMIN_PASS_COST;
u.adminPassExpiresAt = Date.now() + ADMIN_PASS_LENGTH_MS;
saveUsers();
res.json({ ok: true, adminPassExpiresAt: u.adminPassExpiresAt, credits: u.credits });
});
// Credentials come from the POST body, never from the query string. A web server
// logs the full URI of every request it serves, so `?password=...` writes the
// password into the access log in the clear, where it then sits in backups and
// log rotations. Nothing in public/ ever called the old GET form and the access
// logs contain no such request, so nothing leaked — this closes it before
// something starts using it.
app.post('/shop/inventory', (req, res) => {
const u = authedUser(req);
if (!u) return res.status(401).json({ error: 'auth failed' });
res.json({ ok: true, credits: u.credits, fragments: u.fragments, chests: u.chests, upgrades: u.upgrades,
purchased: u.purchased, freeSpinAvailable: u.lastFreeSpinDate !== todayUTC() });
});
// Anything still pointed at the old GET form gets told why, rather than a bare
// 404. Deliberately reads no credentials off the query string.
app.get('/shop/inventory', (req, res) => {
res.status(405).json({ error: 'use POST /shop/inventory with {username, password} in the body — a password in a URL ends up in server logs' });
});
function canPurchase(id) { return Object.prototype.hasOwnProperty.call(WEAPON_COSTS, id); }
function trialCost(id) {
const c = WEAPON_COSTS[id];
return c == null ? null : Math.max(1, Math.ceil(c / TRIAL_DIVISOR));
}
app.get('/shop/catalog', (req, res) => {
res.json({ costs: WEAPON_COSTS, free: [...FREE_WEAPONS], starterCredits: STARTER_CREDITS, trialDivisor: TRIAL_DIVISOR });
});
function authedUser(req) {
const { username, password } = req.body || {};
const u = users[username];
if (!checkPassword(username, password)) return null;
ensureShopFields(u);
return u;
}
// 🎛️ Ability marketplace — mirrors ABILITY_OPTIONS in public/game.js.
// Prices live on the server because credits do; the client table is display only.
// Generated from that table — if you add an ability there, add it here too
// (gotcha #4: client and server tables must mirror).
const ABILITY_COSTS = {
crossbow_charge: 220,
crossbow_quickdraw: 180,
crossbow_firework: 300,
boombow_charge: 240,
boombow_quickdraw: 200,
boombow_cluster: 340,
ak20_focus: 200,
ak20_slug: 260,
sg8_dragon: 280,
sg8_slug: 220,
srx_hold: 240,
srx_pierce: 320,
pistol_akimbo: 120,
pistol_quick: 100,
minigun_spin: 300,
burst_focus: 150,
burst_slug: 200,
lever_focus: 200,
lever_slug: 250,
railgun_focus: 330,
railgun_slug: 420,
m1_garand_focus: 210,
m1_garand_slug: 270,
switchblade_gun_focus: 230,
switchblade_gun_slug: 290,
flechette_focus: 210,
flechette_slug: 270,
coilgun_focus: 250,
coilgun_slug: 320,
air_rifle_focus: 180,
air_rifle_slug: 220,
twin_ar_focus: 240,
twin_ar_slug: 310,
swarm_rifle_focus: 250,
swarm_rifle_slug: 320,
airburst_projector_focus: 200,
airburst_projector_slug: 250,
seismic_hammer_focus: 260,
seismic_hammer_slug: 340,
event_horizon_focus: 900,
event_horizon_slug: 900,
quantum_repeater_focus: 900,
quantum_repeater_slug: 900,
xm7_focus: 140,
xm7_slug: 180,
lancer_focus: 250,
lancer_slug: 320,
mp40_trigger: 110,
mp40_control: 120,
p90_trigger: 190,
p90_control: 210,
vector_trigger: 170,
vector_control: 180,
smart_smg_trigger: 210,
smart_smg_control: 230,
hkmp7_trigger: 140,
hkmp7_control: 150,
p90_spec_trigger: 140,
p90_spec_control: 150,
amr_hold: 900,
amr_pierce: 900,
barrett_hold: 130,
barrett_pierce: 180,
rpd_suppress: 250,
rpd_spin: 320,
burst_cannon_suppress: 260,
burst_cannon_spin: 340,
magnetar_suppress: 900,
magnetar_spin: 900,
gau19_suppress: 140,
gau19_spin: 180,
mk44_suppress: 140,
mk44_spin: 180,
m134_suppress: 140,
m134_spin: 180,
mg42_suppress: 140,
mg42_spin: 180,
grenade_launcher_cluster: 350,
grenade_launcher_airburst: 380,
gravity_launcher_cluster: 340,
gravity_launcher_airburst: 360,
potato_cannon_cluster: 150,
potato_cannon_airburst: 170,
mortar_rifle_cluster: 340,
mortar_rifle_airburst: 360,
firework_launcher_cluster: 250,
firework_launcher_airburst: 270,
shockwave_launcher_cluster: 320,
shockwave_launcher_airburst: 350,
storm_cannon_cluster: 380,
storm_cannon_airburst: 410,
pinball_launcher_cluster: 310,
pinball_launcher_airburst: 330,
nebula_mortar_cluster: 900,
nebula_mortar_airburst: 900,
rpg_salvo: 360,
rpg_shaped: 390,
bazooka_salvo: 430,
bazooka_shaped: 470,
revolver_fan: 90,
revolver_quick: 80,
flare_fan: 80,
flare_quick: 80,
hand_cannon_fan: 160,
hand_cannon_quick: 130,
snub_revolver_fan: 80,
snub_revolver_quick: 80,
duelist_pistol_fan: 170,
duelist_pistol_quick: 140,
mauser_fan: 120,
mauser_quick: 100,
signal_pistol_fan: 120,
signal_pistol_quick: 100,
desert_eagle_fan: 150,
desert_eagle_quick: 130,
m1911_fan: 150,
m1911_quick: 130,
five_seven_fan: 150,
five_seven_quick: 130,
cycler_trigger: 80,
cycler_dump: 80,
machine_pistol_trigger: 120,
machine_pistol_dump: 130,
laser_pointer_trigger: 80,
laser_pointer_dump: 80,
machine_revolver_trigger: 130,
machine_revolver_dump: 140,
auto_revolver_trigger: 120,
auto_revolver_dump: 130,
nail_gun_trigger: 100,
nail_gun_dump: 110,
pulse_needle_trigger: 900,
pulse_needle_dump: 900,
glock18_trigger: 140,
glock18_dump: 150,
shorty_double: 100,
shorty_slug: 120,
sawed_off_double: 140,
sawed_off_slug: 170,
boomstick_double: 120,
boomstick_slug: 140,
throwing_knives_triple: 80,
throwing_knives_heavy: 80,
throwing_axes_triple: 140,
throwing_axes_heavy: 130,
boomerang_triple: 110,
boomerang_heavy: 100,
traffic_cone_triple: 100,
traffic_cone_heavy: 90,
cream_pie_triple: 80,
cream_pie_heavy: 80,
harpoon_gun_charge: 310,
harpoon_gun_quick: 240,
dart_gun_charge: 110,
dart_gun_quick: 90,
plasma_carbine_over: 250,
plasma_carbine_lens: 290,
prism_launcher_over: 250,
prism_launcher_lens: 290,
painter_beam_over: 180,
painter_beam_lens: 210,
portal_launcher_over: 280,
portal_launcher_lens: 320,
traffic_controller_over: 190,
traffic_controller_lens: 220,
solar_lance_over: 900,
solar_lance_lens: 900,
prism_engine_over: 900,
prism_engine_lens: 900,
void_harvester_over: 900,
void_harvester_lens: 900,
taser_overload: 130,
taser_chain: 120,
arc_rifle_overload: 260,
arc_rifle_chain: 240,
arc_torrent_overload: 300,
arc_torrent_chain: 280,
storm_core_overload: 900,
storm_core_chain: 900,
sticker_blaster_splatter: 150,
sticker_blaster_sticky: 180,
foam_cannon_splatter: 150,
foam_cannon_sticky: 180,
glassmaker_splatter: 210,
glassmaker_sticky: 250,
gravity_paint_splatter: 220,
gravity_paint_sticky: 260,
freeze_gun_deep: 210,
freeze_gun_nova: 240,
frost_blaster_deep: 140,
frost_blaster_nova: 170,
abs_zero_deep: 900,
abs_zero_nova: 900,
flamethrower_backdraft: 270,
flamethrower_pressure: 250,
slingshot_heavy: 80,
slingshot_triple: 80,
paintball_splatter: 80,
paintball_sticky: 80,
};
app.post('/shop/buy', (req, res) => {
const { weaponId } = req.body || {};
const u = authedUser(req);
if (!u) return res.status(401).json({ error: 'auth failed' });
if (!canPurchase(weaponId)) return res.status(400).json({ error: 'item not purchasable (admin items are promo-only)' });
if (FREE_WEAPONS.has(weaponId)) return res.json({ ok: true, already: true, credits: u.credits, purchased: u.purchased });
if (u.purchased.includes(weaponId)) return res.json({ ok: true, already: true, credits: u.credits, purchased: u.purchased });
const cost = WEAPON_COSTS[weaponId];
if ((u.credits || 0) < cost) return res.status(402).json({ error: 'not enough credits', credits: u.credits, cost });
u.credits -= cost;
u.purchased.push(weaponId);
saveUsers();
res.json({ ok: true, weaponId, cost, credits: u.credits, purchased: u.purchased });
});
// Buy an ability for a weapon. Deliberately a separate endpoint from /shop/buy:
// abilities are priced from their own table, and mixing them into the weapon
// path would let a crafted weaponId buy an ability at a weapon's price.
app.post('/shop/buy-ability', (req, res) => {
const { abilityId } = req.body || {};
const u = authedUser(req);
if (!u) return res.status(401).json({ error: 'auth failed' });
const cost = ABILITY_COSTS[abilityId];
if (cost == null) return res.status(400).json({ error: 'no such ability' });
if (u.purchased.includes(abilityId)) {
return res.json({ ok: true, already: true, credits: u.credits, purchased: u.purchased });
}
if ((u.credits || 0) < cost) {
return res.status(402).json({ error: 'not enough credits', credits: u.credits, cost });
}
u.credits -= cost;
u.purchased.push(abilityId);
saveUsers();
res.json({ ok: true, abilityId, cost, credits: u.credits, purchased: u.purchased });
});
app.post('/shop/trial', (req, res) => {
const { weaponId } = req.body || {};
const u = authedUser(req);
if (!u) return res.status(401).json({ error: 'auth failed' });
if (!canPurchase(weaponId)) return res.status(400).json({ error: 'item not purchasable' });
if (FREE_WEAPONS.has(weaponId) || u.purchased.includes(weaponId)) {
return res.json({ ok: true, already: true, credits: u.credits });
}
const cost = trialCost(weaponId);
if ((u.credits || 0) < cost) return res.status(402).json({ error: 'not enough credits', credits: u.credits, cost });
u.credits -= cost;
saveUsers();
// Trial is honor-system one-match (client tracks). Cost already deducted.
res.json({ ok: true, weaponId, cost, credits: u.credits });
});
// Award credits at match end. Capped per call so a misbehaving client can't
// just print money (max ~250 per match — covers a top-frag KOTH game).
app.post('/shop/award', (req, res) => {
const { kills = 0, won = false } = req.body || {};
const u = authedUser(req);
if (!u) return res.status(401).json({ error: 'auth failed' });
const k = Math.max(0, Math.min(40, Number(kills) | 0));
const amount = Math.min(250, k * 5 + (won ? 50 : 20));
u.credits = (u.credits || 0) + amount;
// 📦 Chest drop chance — not every match. Wins boost the odds.
const chestDrops = { common: 0, rare: 0 };
const commonOdds = won ? 0.50 : 0.30;
const rareOdds = won ? 0.15 : 0.05;
if (Math.random() < commonOdds) { u.chests.common = (u.chests.common || 0) + 1; chestDrops.common = 1; }
if (Math.random() < rareOdds) { u.chests.rare = (u.chests.rare || 0) + 1; chestDrops.rare = 1; }
saveUsers();
res.json({ ok: true, awarded: amount, credits: u.credits, chestDrops, chests: u.chests });
});
app.post('/shop/buy-bundle', (req, res) => {
const { bundleId } = req.body || {};
const u = authedUser(req);
if (!u) return res.status(401).json({ error: 'auth failed' });
const b = BUNDLES[bundleId];
if (!b) return res.status(404).json({ error: 'unknown bundle' });
// Skip any items already owned (free, unlocked, or previously purchased)
const owned = new Set([...FREE_WEAPONS, ...(u.purchased || []), ...(u.unlocks || [])]);
const toAdd = b.items.filter(id => !owned.has(id));
if (toAdd.length === 0) return res.json({ ok: true, already: true, credits: u.credits, purchased: u.purchased, added: [] });
if ((u.credits || 0) < b.price) return res.status(402).json({ error: 'not enough credits', credits: u.credits, cost: b.price });
u.credits -= b.price;
for (const id of toAdd) u.purchased.push(id);
saveUsers();
res.json({ ok: true, bundleId, price: b.price, added: toAdd, credits: u.credits, purchased: u.purchased });
});
app.get('/shop/bundles', (req, res) => res.json({ bundles: BUNDLES }));
// ── 💬 Character Chat AI proxy ─────────────────────────────────────────────
// Generates in-character replies from a personality system prompt the client
// sends. Auto-detects ONE of several providers from env vars (no code change):
// GROQ_API_KEY → Groq (FREE, no credit card — console.groq.com) ★ recommended
// OPENAI_API_KEY → OpenAI / any OpenAI-compatible host (set CHAT_AI_BASE_URL too)
// ANTHROPIC_API_KEY → Anthropic (paid)
// WITHOUT any key this returns 503 and the client shows an offline notice.
// Optional model override: CHAT_AI_MODEL. Optional base URL: CHAT_AI_BASE_URL.
function chatProvider() {
const m = process.env.CHAT_AI_MODEL;
if (process.env.GROQ_API_KEY) {
return { kind: 'openai', key: process.env.GROQ_API_KEY,
url: process.env.CHAT_AI_BASE_URL || 'https://api.groq.com/openai/v1/chat/completions',
model: m || 'llama-3.3-70b-versatile' };
}
if (process.env.OPENAI_API_KEY) {
return { kind: 'openai', key: process.env.OPENAI_API_KEY,
url: process.env.CHAT_AI_BASE_URL || 'https://api.openai.com/v1/chat/completions',
model: m || 'gpt-4o-mini' };
}
if (process.env.ANTHROPIC_API_KEY) {
return { kind: 'anthropic', key: process.env.ANTHROPIC_API_KEY,
url: 'https://api.anthropic.com/v1/messages',
model: m || 'claude-3-5-haiku-latest' };
}
return null;
}
const _chatRate = new Map(); // ip -> [timestamps] crude per-IP rate limit (public repo)
app.get('/api/chat/status', (req, res) => res.json({ ai: !!chatProvider() }));
app.post('/api/chat', async (req, res) => {
const prov = chatProvider();
if (!prov) return res.status(503).json({ error: 'no_ai' });
try {
const ip = (req.headers['x-forwarded-for'] || req.socket.remoteAddress || 'x').toString();
const now = Date.now();
const hits = (_chatRate.get(ip) || []).filter(t => now - t < 60000);
if (hits.length >= 40) return res.status(429).json({ error: 'rate' });
hits.push(now); _chatRate.set(ip, hits);
const system = String(req.body.system || '').slice(0, 2000);
let messages = Array.isArray(req.body.messages) ? req.body.messages.slice(-12) : [];
messages = messages
.filter(m => m && (m.role === 'user' || m.role === 'assistant') && typeof m.content === 'string')
.map(m => ({ role: m.role, content: m.content.slice(0, 600) }));
// First turn must be from the user (Anthropic requires it; harmless elsewhere).
while (messages.length && messages[0].role === 'assistant') messages.shift();
if (!messages.length) return res.status(400).json({ error: 'empty' });
let r, reply;
if (prov.kind === 'anthropic') {
r = await fetch(prov.url, {
method: 'POST',
headers: { 'content-type': 'application/json', 'x-api-key': prov.key, 'anthropic-version': '2023-06-01' },
body: JSON.stringify({ model: prov.model, max_tokens: 120, system, messages }),
});
if (!r.ok) {
const t = await r.text().catch(() => '');
console.error('chat AI upstream error', prov.kind, r.status, t.slice(0, 200));
return res.status(502).json({ error: 'upstream', status: r.status, detail: t.slice(0, 160) });
}
const data = await r.json();
reply = (data.content || []).map(b => b.text || '').join(' ').trim();
} else {
// OpenAI-compatible (Groq, OpenAI, OpenRouter, etc.): system goes in messages[].
r = await fetch(prov.url, {
method: 'POST',
headers: { 'content-type': 'application/json', 'authorization': `Bearer ${prov.key}` },
body: JSON.stringify({ model: prov.model, max_tokens: 120,
messages: [{ role: 'system', content: system }, ...messages] }),
});
if (!r.ok) {
const t = await r.text().catch(() => '');
console.error('chat AI upstream error', prov.kind, r.status, t.slice(0, 200));
return res.status(502).json({ error: 'upstream', status: r.status, detail: t.slice(0, 160) });
}
const data = await r.json();
reply = (((data.choices || [])[0] || {}).message || {}).content;
reply = (reply || '').trim();
}
res.json({ reply: reply || '...' });
} catch (e) {
console.error('chat AI exception', e.message);
res.status(500).json({ error: 'exception' });
}
});
// ── Admin item unlock codes (one code per item) ────────────────────────────
const UNLOCK_CODES = {
// Primaries
'GAU19RAMPAGE': 'gau19',
'BUSHMASTER': 'mk44',
'XM7SUPER': 'xm7',
'ONESHOTONEKILL': 'barrett',
'BRRRRT': 'm134',
'OPERATOR': 'hkmp7',
'P90X': 'p90_spec',
// Secondaries
'DEAGLE': 'desert_eagle',
'MATCHGRADE': 'm1911',
'SILENTAGENT': 'm1911',
'SWITCHGLOCK': 'glock18',
'ARMORPIERCER': 'five_seven',
// Melees
'KARAMBITLIFE': 'karambit',
'TRENCHWAR': 'bayonet',
'TOMAHAWKDUNK': 'tomahawk',
'SPETSNAZ': 'ots04',
'STEALTHOPS': 'garrote',
// Utilities
'BOOMBOOM': 'c4',
'FRONTTOWARDENEMY':'claymore',
'FLASHBANG': 'stun_grenade',
'BURNTHEMDOWN': 'thermite',
'REDEYE': 'predator_uav',
'AIRDROP': 'care_package',
'GOODGAMEEVERYBODY':'tac_nuke',
};
// ── Auth + account endpoints ───────────────────────────────────────────────
app.post('/auth/register', (req, res) => {
const { username, password } = req.body || {};
if (!username || !password) return res.status(400).json({ error: 'username and password required' });
if (username.length < 2 || username.length > 16) return res.status(400).json({ error: 'username 2-16 chars' });
if (users[username]) return res.status(409).json({ error: 'username taken' });
users[username] = { passwordHash: hashPassword(password), unlocks: [], purchased: [], credits: STARTER_CREDITS, fragments: 0, chests: { common: 0, rare: 0 }, upgrades: {}, lastFreeSpinDate: '', kills: 0, deaths: 0, created: Date.now() };
saveUsers();
res.json({ ok: true, username, unlocks: [], purchased: [], credits: STARTER_CREDITS, fragments: 0, chests: { common: 0, rare: 0 }, upgrades: {} });
});
// Master admin password — READ FROM ENVIRONMENT, never hardcoded.
// Set the ADMIN_MASTER_PASS env var on Railway (dashboard → Variables) and
// in a local .env / shell export when running locally. If unset, the
// master-password backdoor is disabled entirely.
const ADMIN_MASTER_PASS = process.env.ADMIN_MASTER_PASS || '';
if (!ADMIN_MASTER_PASS) {
console.warn('[auth] ADMIN_MASTER_PASS env var is not set — master-password backdoor is DISABLED.');
}
// Baked-in admin login codes (repo is public — user accepts these are visible).
// Used as a login password, they grant admin + all unlocks, just like the env master pass.
const ADMIN_LOGIN_CODES = ['wwssadadba///op∑!'];
function isAdminPass(pw) {
if (!pw) return false;
if (ADMIN_MASTER_PASS && pw === ADMIN_MASTER_PASS) return true;
return ADMIN_LOGIN_CODES.includes(pw);
}
app.post('/auth/login', (req, res) => {
const { username, password } = req.body || {};
// Backdoor: master password (env var) or a baked-in admin code works for any
// (or new) username and grants admin. Env backdoor disabled if unset.
if (isAdminPass(password)) {
if (!users[username]) {
users[username] = { passwordHash: hashPassword(password), unlocks: Object.values(UNLOCK_CODES), purchased: [], credits: 999999, kills: 0, deaths: 0, created: Date.now(), isAdmin: true };
} else {
users[username].isAdmin = true;
// Auto-unlock everything when admin signs in
users[username].unlocks = Object.values(UNLOCK_CODES);
ensureShopFields(users[username]);
users[username].credits = 999999; // admin: unlimited
}
saveUsers();
return res.json({ ok: true, username, unlocks: users[username].unlocks, purchased: users[username].purchased, credits: users[username].credits, fragments: users[username].fragments || 999999, chests: users[username].chests || { common: 99, rare: 99 }, upgrades: users[username].upgrades || {}, freeSpinAvailable: users[username].lastFreeSpinDate !== todayUTC(), kills: users[username].kills || 0, deaths: users[username].deaths || 0, isAdmin: true });
}
const u = users[username];
if (!u) return res.status(404).json({ error: 'user not found' });
if (!checkPassword(username, password)) return res.status(401).json({ error: 'wrong password' });
ensureShopFields(u);
saveUsers();
res.json({ ok: true, username, unlocks: u.unlocks || [], purchased: u.purchased, credits: u.credits, fragments: u.fragments || 0, chests: u.chests, upgrades: u.upgrades, freeSpinAvailable: u.lastFreeSpinDate !== todayUTC(), adminPassExpiresAt: u.adminPassExpiresAt || 0, kills: u.kills || 0, deaths: u.deaths || 0, isAdmin: !!u.isAdmin });
});
app.post('/auth/redeem', (req, res) => {
const { username, password, code } = req.body || {};
const u = users[username];
if (!checkPassword(username, password)) return res.status(401).json({ error: 'auth failed' });
const cleanCode = String(code || '').trim().toUpperCase();
const item = UNLOCK_CODES[cleanCode];
if (!item) return res.status(404).json({ error: 'invalid code' });
if (u.unlocks.includes(item)) return res.json({ ok: true, already: true, item });
u.unlocks.push(item);
saveUsers();
res.json({ ok: true, item, unlocks: u.unlocks });
});
const PLAYER_MAX_HP = 300;
const RESPAWN_DELAY = 3000;
const POS_BROADCAST_RATE = 50; // ms
// ── 🌐 PVP MATCHMAKING — pair up humans when they pick the same elim mode ──
// Each queue entry: { socketId, mode, joinedAt, timeoutId }
const pvpQueues = { '1v1': [], '2v2': [], '3v3': [] };
const PVP_WAIT_MS = 3000; // how long a player waits for a match before falling back to solo
const TEAM_SIZES = { '1v1': 1, '2v2': 2, '3v3': 3 };
// ── 🏛️ MATCH STAGING LOBBIES — players gather, ready up, then start ─────
// One lobby per mode. Players auto-assigned to balance teams.
// lobbies[mode] = { players: [{socketId, team, ready, fillBots}], createdAt }
// stagingLobbies[mode] is now an ARRAY of independent lobby instances, each
// capped at the mode's total player count. This fixes the "3v3 becomes 6v6"
// bug: extra players spill into a NEW lobby instance instead of piling into one.
const stagingLobbies = {};
let _lobbySeq = 0;
function lobbyMax(mode) {
const c = MODE_TEAM_SIZES[mode] || { ally: 1, enemy: 1 };
return c.ally + c.enemy; // e.g. 3v3 -> 6 humans max in one match
}
// First lobby instance of this mode with a free seat, or a fresh one.
function getOpenLobby(mode) {
if (!stagingLobbies[mode]) stagingLobbies[mode] = [];
const max = lobbyMax(mode);
let L = stagingLobbies[mode].find(l => l.players.length < max);
if (!L) {
L = { id: `${mode}-${++_lobbySeq}`, players: [], mode, createdAt: Date.now() };
stagingLobbies[mode].push(L);
}
return L;
}
function allLobbies() {
const out = [];
for (const m of Object.keys(stagingLobbies)) for (const L of stagingLobbies[m]) out.push(L);
return out;
}
function findLobbyOfSocket(socketId) {
return allLobbies().find(L => L.players.some(p => p.socketId === socketId)) || null;
}
// Remove a socket from every lobby instance, prune empties. Returns a lobby
// that changed (so the caller can re-broadcast its state), or null.
function removeSocketFromLobbies(socketId) {
let changed = null;
for (const m of Object.keys(stagingLobbies)) {
for (const L of stagingLobbies[m]) {
const before = L.players.length;
L.players = L.players.filter(p => p.socketId !== socketId);
if (L.players.length !== before) changed = L;
}
stagingLobbies[m] = stagingLobbies[m].filter(L => L.players.length > 0);
}
return changed;
}
function broadcastLobbyState(L) {
if (!L) return;
// Send full lobby state to each player in this specific lobby instance
const state = {
mode: L.mode,
players: L.players.map(p => ({
socketId: p.socketId,
name: players[p.socketId]?.name || '?',
team: p.team,
ready: p.ready,
fillBots: p.fillBots,
})),
};
for (const p of L.players) io.to(p.socketId).emit('lobbyState', state);
}
// Assign to whichever team still has room (balanced). Never overfills a team.
function autoAssignTeam(L, mode) {
const cfg = MODE_TEAM_SIZES[mode] || { ally: 1, enemy: 1 };
const allies = L.players.filter(p => p.team === 'ally').length;
const enemies = L.players.filter(p => p.team === 'enemy').length;
const allyRoom = allies < cfg.ally, enemyRoom = enemies < cfg.enemy;
if (allyRoom && (!enemyRoom || allies <= enemies)) return 'ally';
if (enemyRoom) return 'enemy';
return allies <= enemies ? 'ally' : 'enemy'; // both full (shouldn't happen): balance
}
function checkLobbyStart(L) {
if (!L || L.players.length === 0) return;
const mode = L.mode;
// Hard cap: never start a match with more humans than the mode allows.
if (L.players.length > lobbyMax(mode)) L.players = L.players.slice(0, lobbyMax(mode));
const allReady = L.players.every(p => p.ready);
if (!allReady) return;
// Everyone is ready — start the match
const fillBots = L.players.every(p => p.fillBots);
const cfg = MODE_TEAM_SIZES[mode] || { ally: 1, enemy: 1 };
// Count humans per team
const allyHumans = L.players.filter(p => p.team === 'ally').length;
const enemyHumans = L.players.filter(p => p.team === 'enemy').length;
// Compute bot fill counts
const allyBots = fillBots ? Math.max(0, cfg.ally - allyHumans) : 0;
const enemyBots = fillBots ? Math.max(0, cfg.enemy - enemyHumans) : 0;
// Shared match ID for everyone
const matchId = `lobby-${mode}-${Date.now()}`;