Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
1386 lines (1283 loc) · 74.1 KB
/
Copy pathserver.js
File metadata and controls
1386 lines (1283 loc) · 74.1 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 app = express();
const fs = require('fs');
const crypto = require('crypto');
const TechFeeds = require('./feeds');
// Optional .env file (KEY=VALUE lines) for the Web3 settings, without extra dependencies
try {
require('fs').readFileSync(require('path').join(__dirname, '.env'), 'utf8').split(/\r?\n/).forEach((line) => {
const match = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);
if (match && !(match[1] in process.env)) process.env[match[1]] = match[2].replace(/^(['"])(.*)\1$/, '$2');
});
} catch (error) { /* no .env file */ }
const Web3 = require('./web3/server'); // optional MVC token on a testnet (see web3/server.js)
const path = require('path'); // Core module to handle absolute system directory paths smoothly
const http = require('http').createServer(app);
const io = require('socket.io')(http, {
cors: { origin: "*" }
});
const PUBLIC_DIR = path.join(__dirname, 'public');
// Serves all static layout assets (index.html, scripts, maps JSON directories) nested inside public folder
app.use(express.static(PUBLIC_DIR));
app.use(express.json({ limit: '10kb' }));
// Lists the images the owner dropped in public/assets (ads, store, logos), so
// the client loads exactly the files that exist, whatever their format
// (.png, .jpg, .jpeg, .webp, .svg), instead of guessing and causing 404s
const OWNER_ASSET_FOLDERS = ['ads', 'ads/brands', 'store', 'logos'];
// Public Web3 settings for the browser (enabled only when configured)
app.get('/api/web3/config', (req, res) => {
const config = Web3.publicConfig();
if (config.enabled) config.landPrice = LAND_PRICE;
res.set('Cache-Control', 'no-cache');
res.json(config);
});
app.get('/api/owner-assets', (req, res) => {
const listing = {};
OWNER_ASSET_FOLDERS.forEach((folder) => {
try {
listing[folder] = fs.readdirSync(path.join(PUBLIC_DIR, 'assets', folder), { withFileTypes: true })
.filter((entry) => entry.isFile() && /\.(png|jpe?g|webp|svg)$/i.test(entry.name))
.map((entry) => entry.name);
} catch (error) {
listing[folder] = [];
}
});
res.set('Cache-Control', 'no-cache');
res.json(listing);
});
// ----------------------------------------------------------------------------
// Accounts: usernames + scrypt-hashed passwords, persisted in data/users.json
// ----------------------------------------------------------------------------
const DATA_DIR = path.join(__dirname, 'data');
const USERS_FILE = path.join(DATA_DIR, 'users.json');
const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000;
let accounts = { users: {}, sessions: {} };
try {
accounts = JSON.parse(fs.readFileSync(USERS_FILE, 'utf8'));
} catch (error) {
if (error.code !== 'ENOENT') console.error('[ACCOUNTS] Could not read users file:', error.message);
}
accounts.lands = accounts.lands || {}; // parcel "x,z" -> { owner, boughtAt }
// In-game economy (like Decentraland's MANA and LAND, but NOT real money):
// Multiverse Coins (MVC) are earned by playing and spent on land parcels.
const STARTING_COINS = 100;
const LAND_PRICE = 250;
// The Underground Tech Hub: the hall under The Glass Cube district (worlds.json)
const glassCube = JSON.parse(fs.readFileSync(path.join(PUBLIC_DIR, 'maps', 'worlds.json'), 'utf8')).find((world) => world.key === 'glasscube');
function inTechHub(position) {
if (!glassCube || !position) return false;
const [cx, cz] = glassCube.region.center;
return Math.abs(position.x - cx) < 20 && Math.abs(position.z - cz) < 17 && position.y < -6 && position.y > -14;
}
const pendingParcels = new Set(); // parcels being paid on-chain right now
const claimsInProgress = new Set(); // usernames with a mint in flight (memory only)
const MAX_PARCEL = 60; // Genesis City spans parcels -60..59 (16 m each, up to 960 m)
// Around the central districts the land is a grid of parcels split by roads
// (one parcel wide, every 8 parcels): road parcels cannot be bought
// Same rules as the client (public/city.js): roads from maps/land.json and
// community scenes picked by the same parcel hash cannot be bought
const CORE_PARCELS = 25; // the center commons spans parcels -25..24
const landLayout = JSON.parse(fs.readFileSync(path.join(PUBLIC_DIR, 'maps', 'land.json'), 'utf8'));
function parcelHash(px, pz) {
let h = Math.imul((px * 374761393 + pz * 668265263) | 0, 1274126177);
h ^= h >>> 13;
return ((h >>> 0) % 1000) / 1000;
}
const isRoadParcel = (px, pz) => landLayout.roadsX.includes(px) || landLayout.roadsZ.includes(pz);
const isSceneParcel = (px, pz) => parcelHash(px, pz) < landLayout.sceneChance;
// Seas (open water is not for sale; island parcels are)
function inSea(px, pz) {
const x = px * 16 + 8;
const z = -(pz * 16 + 8);
const blob = (cx, cz, r, seed) => {
const angle = Math.atan2(z - cz, x - cx);
return Math.hypot(x - cx, z - cz) < r * (1 + 0.16 * Math.sin(3 * angle + seed) + 0.08 * Math.sin(5 * angle + seed * 2));
};
return (landLayout.seas || []).some((sea, i) => blob(sea.x, sea.z, sea.r, i + 1) && !(sea.islands || []).some((island, k) => blob(island.x, island.z, island.r, i * 7 + k + 3)));
}
function walletOf(account) {
if (typeof account.coins !== 'number') account.coins = STARTING_COINS;
return account.coins;
}
let saveTimer = null;
function saveAccounts() {
clearTimeout(saveTimer);
saveTimer = setTimeout(() => {
fs.mkdirSync(DATA_DIR, { recursive: true });
fs.writeFile(USERS_FILE, JSON.stringify(accounts), (error) => {
if (error) console.error('[ACCOUNTS] Could not save users file:', error.message);
});
}, 300);
}
Web3.init();
Web3.loadUsedTransactions(accounts.web3UsedTransactions);
// ----------------------------------------------------------------------------
// Scenes (Decentraland-style): the content devs build on their own parcels and
// estates, persisted in data/scenes.json like users.json. The validation rules
// (ownership, bounds, per-parcel limits) are shared with the browser Builder.
// ----------------------------------------------------------------------------
const SceneRules = require('./public/scenes-builder.js');
const SCENES_FILE = path.join(DATA_DIR, 'scenes.json');
let sceneStore = { published: {}, drafts: {} }; // base parcel "x,y" -> scene manifest
try {
sceneStore = JSON.parse(fs.readFileSync(SCENES_FILE, 'utf8'));
} catch (error) {
if (error.code !== 'ENOENT') console.error('[SCENES] Could not read scenes file:', error.message);
}
sceneStore.published = sceneStore.published || {};
sceneStore.drafts = sceneStore.drafts || {};
let sceneSaveTimer = null;
function saveScenes() {
clearTimeout(sceneSaveTimer);
sceneSaveTimer = setTimeout(() => {
fs.mkdirSync(DATA_DIR, { recursive: true });
fs.writeFile(SCENES_FILE, JSON.stringify(sceneStore), (error) => {
if (error) console.error('[SCENES] Could not save scenes file:', error.message);
});
}, 300);
}
const landOwnerOf = (parcel) => (accounts.lands[parcel] ? accounts.lands[parcel].owner : null);
// Published scenes whose parcels still belong to the scene owner
const publishedScenes = () => Object.values(sceneStore.published).filter((scene) => scene.scene.parcels.every((parcel) => SceneRules.sameName(landOwnerOf(parcel), scene.owner)));
app.get('/api/scenes', (req, res) => {
res.set('Cache-Control', 'no-cache');
res.json(publishedScenes());
});
function hashPassword(password, salt) {
return crypto.scryptSync(password, salt, 64).toString('hex');
}
function createSession(userKey) {
const token = crypto.randomBytes(32).toString('hex');
accounts.sessions[token] = { user: userKey, expiresAt: Date.now() + SESSION_TTL_MS };
saveAccounts();
return token;
}
function userFromToken(token) {
const session = typeof token === 'string' ? accounts.sessions[token] : null;
if (!session || session.expiresAt < Date.now()) return null;
return accounts.users[session.user] || null;
}
// Simple per-IP rate limit for login and sign-up attempts
const authAttempts = new Map();
function rateLimited(ip) {
const now = Date.now();
const entry = authAttempts.get(ip) || { count: 0, resetAt: now + 5 * 60 * 1000 };
if (entry.resetAt < now) { entry.count = 0; entry.resetAt = now + 5 * 60 * 1000; }
entry.count++;
authAttempts.set(ip, entry);
return entry.count > 10;
}
const USERNAME_PATTERN = /^[A-Za-z0-9_]{3,16}$/;
const DEVICE_KEY_PATTERN = /^[a-f0-9]{64}$/;
// Remembered devices: the browser keeps a random device key and the server
// keeps only its SHA-256, so a returning player reconnects without a password
// even after the session token expired or the server lost its sessions.
function deviceHash(deviceKey) {
return crypto.createHash('sha256').update(deviceKey).digest('hex');
}
function rememberDevice(user, deviceKey) {
if (typeof deviceKey !== 'string' || !DEVICE_KEY_PATTERN.test(deviceKey)) return;
const hash = deviceHash(deviceKey);
user.devices = (user.devices || []).filter((known) => known !== hash);
user.devices.push(hash);
if (user.devices.length > 10) user.devices.shift();
saveAccounts();
}
app.post('/api/signup', (req, res) => {
if (rateLimited(req.ip)) return res.status(429).json({ error: 'Too many attempts. Try again in a few minutes.' });
const { username, password } = req.body || {};
if (!USERNAME_PATTERN.test(username || '')) return res.status(400).json({ error: 'Usernames have 3-16 letters, numbers or _.' });
if (typeof password !== 'string' || password.length < 8 || password.length > 128) return res.status(400).json({ error: 'Passwords need at least 8 characters.' });
const key = username.toLowerCase();
if (accounts.users[key]) return res.status(409).json({ error: 'That username is taken. Log in instead?' });
const salt = crypto.randomBytes(16).toString('hex');
accounts.users[key] = { username, salt, hash: hashPassword(password, salt), createdAt: Date.now(), inventory: [] };
rememberDevice(accounts.users[key], req.body.deviceKey);
res.json({ token: createSession(key), username });
});
app.post('/api/login', (req, res) => {
if (rateLimited(req.ip)) return res.status(429).json({ error: 'Too many attempts. Try again in a few minutes.' });
const { username, password } = req.body || {};
const user = typeof username === 'string' ? accounts.users[username.toLowerCase()] : null;
const candidate = user && typeof password === 'string' ? Buffer.from(hashPassword(password, user.salt), 'hex') : null;
if (!user || !crypto.timingSafeEqual(candidate, Buffer.from(user.hash, 'hex'))) {
return res.status(401).json({ error: 'Wrong username or password.' });
}
rememberDevice(user, req.body.deviceKey);
res.json({ token: createSession(username.toLowerCase()), username: user.username });
});
// Daily bonus: +50 MVC every 20 hours (socket "daily_bonus" in the game and
// POST /api/daily from the launcher share the same rule)
const DAILY_BONUS = 50;
const DAILY_EVERY_MS = 20 * 60 * 60 * 1000;
function claimDaily(account) {
const waitMs = DAILY_EVERY_MS - (Date.now() - (account.lastDaily || 0));
if (waitMs > 0) return { ok: false, waitMs };
account.lastDaily = Date.now();
account.coins = walletOf(account) + DAILY_BONUS;
saveAccounts();
return { ok: true };
}
// Launcher (the screen after login): balance and the daily bonus before the world opens
app.get('/api/wallet', (req, res) => {
const user = userFromToken(req.get('x-session-token'));
if (!user) return res.status(401).json({ error: 'Session expired.' });
res.json({ username: user.username, coins: walletOf(user), nextDailyInMs: Math.max(0, DAILY_EVERY_MS - (Date.now() - (user.lastDaily || 0))) });
});
app.post('/api/daily', (req, res) => {
const user = userFromToken(req.get('x-session-token'));
if (!user) return res.status(401).json({ error: 'Session expired.' });
const result = claimDaily(user);
if (!result.ok) return res.status(429).json({ error: `Daily bonus already claimed. Come back in ${Math.ceil(result.waitMs / 3600000)} h.`, nextDailyInMs: result.waitMs, coins: walletOf(user) });
res.json({ coins: user.coins, earned: DAILY_BONUS, nextDailyInMs: DAILY_EVERY_MS });
});
// Reconnect a remembered device. If the account no longer exists (a server
// with a fresh database, e.g. after a redeploy on a host without a persistent
// disk), it is recreated for this device so the player is never stuck.
app.post('/api/resume', (req, res) => {
const { username, deviceKey } = req.body || {};
if (!USERNAME_PATTERN.test(username || '') || typeof deviceKey !== 'string' || !DEVICE_KEY_PATTERN.test(deviceKey)) return res.status(400).json({ error: 'Invalid device.' });
const key = username.toLowerCase();
const user = accounts.users[key];
if (user) {
if (!(user.devices || []).includes(deviceHash(deviceKey))) return res.status(401).json({ error: 'Please log in on this device.' });
return res.json({ token: createSession(key), username: user.username });
}
if (rateLimited(req.ip)) return res.status(429).json({ error: 'Too many attempts. Try again in a few minutes.' });
const salt = crypto.randomBytes(16).toString('hex');
accounts.users[key] = { username, salt, hash: hashPassword(crypto.randomBytes(24).toString('hex'), salt), createdAt: Date.now(), inventory: [], restored: true };
rememberDevice(accounts.users[key], deviceKey);
res.json({ token: createSession(key), username, restored: true });
});
// Attach this browser's device key to an already signed-in account
app.post('/api/device', (req, res) => {
const user = userFromToken(req.get('x-session-token'));
if (!user) return res.status(401).json({ error: 'Session expired.' });
rememberDevice(user, (req.body || {}).deviceKey);
res.json({ ok: true });
});
app.get('/api/session', (req, res) => {
const user = userFromToken(req.get('x-session-token'));
if (!user) return res.status(401).json({ error: 'Session expired.' });
// Sliding session: every visit keeps you signed in for another 30 days
const session = accounts.sessions[req.get('x-session-token')];
if (session && session.expiresAt - Date.now() < SESSION_TTL_MS - 24 * 60 * 60 * 1000) { session.expiresAt = Date.now() + SESSION_TTL_MS; saveAccounts(); }
res.json({ username: user.username });
});
app.post('/api/logout', (req, res) => {
delete accounts.sessions[req.get('x-session-token')];
saveAccounts();
res.json({ ok: true });
});
// ----------------------------------------------------------------------------
// Genius Bar AI (The Orchard Nexus, public/orchard.js): answers questions about
// 3D optimization, spatial audio and SDK scripting. With ANTHROPIC_API_KEY set
// it asks Claude (the key never leaves the server); without it, it answers
// offline with a curated tip picked by keyword.
// ----------------------------------------------------------------------------
const GENIUS_MAX_QUESTION = 500;
const GENIUS_SYSTEM_PROMPT = 'You are the Genius Bar AI in GitHub Multiverse, a developer metaverse. Answer concisely about 3D optimization, spatial audio and metaverse SDK scripting.';
const GENIUS_TIPS = [
{ keywords: ['gltf', 'glb', 'model', 'export', 'blender', 'file size'], answer: 'glTF optimization: export .glb (binary), apply transforms, remove unused nodes, materials and animations, merge meshes that share a material, and run gltf-transform (dedup, prune, weld, quantize) before shipping. Keep each scene file small so it streams fast.' },
{ keywords: ['draco', 'compress', 'meshopt', 'geometry size'], answer: 'Draco (or meshoptimizer) compresses glTF geometry 5-10x. Use gltf-transform draco (or meshopt) and load it with DRACOLoader/MeshoptDecoder in three.js. Decoding costs a little CPU on load, so keep it for heavy meshes, not tiny props.' },
{ keywords: ['texture', 'atlas', 'ktx2', 'basis', 'mipmap', 'png', 'jpg'], answer: 'Texture atlases pack many small textures into one image so many meshes can share one material (fewer draw calls). Use power-of-two sizes (512-2048), KTX2/Basis Universal for GPU-compressed textures, and keep mipmaps on to avoid shimmering.' },
{ keywords: ['lod', 'level of detail', 'distance', 'far away', 'polygon', 'poly'], answer: 'Levels of detail (LODs): ship 2-3 versions of heavy models (100%, ~40%, ~10% triangles) and switch by camera distance (THREE.LOD in three.js). Past a certain distance, replace the model with an impostor billboard or hide it completely.' },
{ keywords: ['instanc', 'draw call', 'repeated', 'many objects', 'trees', 'grass'], answer: 'Instancing: anything repeated more than ~30 times (trees, chairs, lamps) should be one THREE.InstancedMesh with a matrix per copy. That turns hundreds of draw calls into one. Update instanceMatrix only when copies move and set needsUpdate = true.' },
{ keywords: ['spatial audio', 'rolloff', 'panner', 'hrtf', 'positional', 'distance model'], answer: 'Spatial audio rolloff: use a PannerNode (THREE.PositionalAudio) with panningModel "HRTF", distanceModel "inverse", refDistance about 1-2 m, rolloffFactor about 1 and a maxDistance where the sound should fade out. Linear rolloff sounds unnatural; exponential suits small loud sources.' },
{ keywords: ['audio', 'sound', 'music', 'reverb', 'occlusion', 'listener'], answer: 'Spatial audio basics: attach the AudioListener to the camera, give every sound source a position, add a ConvolverNode reverb per room type, and lower the volume with a low-pass filter when a wall blocks the line of sight (cheap occlusion). Stream long music, preload short effects.' },
{ keywords: ['sdk7', 'decentraland', 'component', 'system', 'ecs', 'entity'], answer: 'Decentraland SDK7 is ECS: entities are ids, components hold data (Transform, MeshRenderer, custom components via engine.defineComponent) and systems are functions run every frame (engine.addSystem((dt) => {...})). Query entities with engine.getEntitiesWith(Component) and keep systems small and data-driven.' },
{ keywords: ['collider', 'collision', 'physics', 'raycast', 'walk'], answer: 'Colliders: never collide against the render mesh of a detailed model. Use simple invisible boxes (MeshCollider box/plane in SDK7, or a low-poly proxy) on the collision layer, and disable collisions on decorative and transparent objects so raycasts stay cheap.' },
{ keywords: ['pointer', 'click', 'interact', 'input', 'button', 'event'], answer: 'SDK interactions: in SDK7 use pointerEventsSystem.onPointerDown({ entity, opts: { button: InputAction.IA_PRIMARY, hoverText: "Open" } }, callback). Keep the hover text short, give feedback (sound, animation) immediately and validate anything important on the server.' },
{ keywords: ['performance', 'fps', 'slow', 'lag', 'optimi', 'frame'], answer: 'Performance checklist: count draw calls (renderer.info), merge static meshes by material, instance repeated props, limit real-time lights and shadow casters, cap pixel ratio at 1.5-2, and run per-frame logic only for objects near the player.' },
{ keywords: ['light', 'shadow', 'bake', 'emissive', 'lightmap'], answer: 'Lighting: bake static lighting into lightmaps or vertex colors, fake lamps with emissive materials and additive light cones, and keep one directional light with a tight shadow camera. Point and spot lights are expensive in forward renderers.' }
];
const geniusRequests = new Map();
function geniusRateLimited(ip) {
const now = Date.now();
const entry = geniusRequests.get(ip) || { count: 0, resetAt: now + 60 * 1000 };
if (entry.resetAt < now) { entry.count = 0; entry.resetAt = now + 60 * 1000; }
entry.count++;
geniusRequests.set(ip, entry);
return entry.count > 10;
}
function geniusOfflineAnswer(question) {
const text = question.toLowerCase();
let best = null;
let bestScore = 0;
GENIUS_TIPS.forEach((tip) => {
const score = tip.keywords.filter((keyword) => text.includes(keyword)).length;
if (score > bestScore) { best = tip; bestScore = score; }
});
if (best) return best.answer;
return 'I can help with 3D optimization (glTF, Draco, texture atlases, LODs, instancing), spatial audio (rolloff, HRTF, occlusion) and SDK scripting (SDK7 components and systems, colliders, pointer events). Try asking about one of those.';
}
app.post('/api/genius', async (req, res) => {
if (geniusRateLimited(req.ip)) return res.status(429).json({ error: 'The Genius Bar is busy. Try again in a minute.' });
const raw = req.body && typeof req.body.question === 'string' ? req.body.question.trim() : '';
if (!raw) return res.status(400).json({ error: 'Ask a question first.' });
const question = raw.slice(0, GENIUS_MAX_QUESTION);
const apiKey = process.env.ANTHROPIC_API_KEY;
if (!apiKey) return res.json({ answer: geniusOfflineAnswer(question), offline: true });
try {
const response = await fetch('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: { 'x-api-key': apiKey, 'anthropic-version': '2023-06-01', 'content-type': 'application/json' },
body: JSON.stringify({
model: 'claude-haiku-4-5',
max_tokens: 600,
system: GENIUS_SYSTEM_PROMPT,
messages: [{ role: 'user', content: question }]
}),
signal: AbortSignal.timeout(30000)
});
if (!response.ok) throw new Error(`Anthropic API status ${response.status}`);
const data = await response.json();
const answer = (data.content || []).filter((block) => block.type === 'text').map((block) => block.text).join('\n').trim();
if (!answer || data.stop_reason === 'refusal') return res.json({ answer: geniusOfflineAnswer(question), offline: true });
res.json({ answer });
} catch (error) {
console.error('[GENIUS] AI request failed:', error.message);
res.json({ answer: geniusOfflineAnswer(question), offline: true });
}
});
const MAX_CHAT_LENGTH = 200;
const MAX_COORDINATE = 3000;
const TICKS_PER_SECOND = 20; // Minecraft pace: a full day lasts 20 minutes
const MONSTER_RESPAWN_MS = 30000;
const ALLOWED_DAMAGE = new Set([10, 15, 40]);
const CHEST_RESPAWN_MS = 2 * 60 * 1000;
const SUPPLY_DROP_EVERY_MS = Number(process.env.SUPPLY_DROP_EVERY_MS) || 3 * 60 * 1000;
const SUPPLY_DROP_FALL_MS = 20000;
const LOOT_REACH = 7;
const DECOR_ITEMS = new Set(['tree', 'lamp', 'banner', 'fountain', 'duck', 'flag', 'neon', 'bench']);
const WEARABLES = new Set(['hoodie', 'mug', 'cap', 'headphones', 'hammer']); // the crown only comes from Legendary loot
// Active tracking memory for connected developers network clients
const activeDevelopers = {};
// ----------------------------------------------------------------------------
// Shared world state: time of day, weather and the interactive districts
// ----------------------------------------------------------------------------
const worldState = { ticks: 1000, cycle: true, weather: 'clear', changedAt: Date.now() };
function currentTicks() {
const elapsed = worldState.cycle ? ((Date.now() - worldState.changedAt) / 1000) * TICKS_PER_SECOND : 0;
return (worldState.ticks + elapsed) % 24000;
}
function worldStatePayload(extra = {}) {
return { ticks: currentTicks(), cycle: worldState.cycle, weather: worldState.weather, elapsedMs: 0, ...extra };
}
// Debug Dungeon monsters are read from the map file so the server owns their health
// District maps live in public/maps/districts.json (a separate file wins if it exists)
function readMap(file) {
const separate = path.join(PUBLIC_DIR, 'maps', file);
if (fs.existsSync(separate)) return JSON.parse(fs.readFileSync(separate, 'utf8'));
return JSON.parse(fs.readFileSync(path.join(PUBLIC_DIR, 'maps', 'districts.json'), 'utf8')).maps[file];
}
const dungeonMap = readMap('map_debug_dungeon.json');
const monsters = {};
dungeonMap.blocks.filter((block) => block.id && block.hp).forEach((block) => {
monsters[block.id] = { name: block.label, maxHp: block.hp, hp: block.hp, alive: true };
});
const gameState = {
scores: {},
murals: {},
decorations: { slot1: { item: 'tree' }, slot2: { item: 'lamp' }, slot3: { item: 'banner', color: '#8250df' }, slot4: { item: 'duck' }, slot5: { item: 'tree' }, slot6: { item: 'lamp' }, slot7: { item: 'flag', color: '#2da44e' }, slot8: { item: 'bench' } },
pullRequests: [],
stream: null,
trees: []
};
// ----------------------------------------------------------------------------
// Fortnite-style loot: chests on the streets and supply drops from the sky
// ----------------------------------------------------------------------------
const lootTable = JSON.parse(fs.readFileSync(path.join(PUBLIC_DIR, 'maps', 'loot.json'), 'utf8'));
const lootSpawns = {};
lootTable.spawns.forEach((spawn, index) => {
lootSpawns[`chest${index}`] = { id: `chest${index}`, kind: 'chest', x: spawn.x, z: spawn.z, area: spawn.area, openUntil: 0 };
});
let supplyDropCounter = 0;
function publicLoot() {
return Object.values(lootSpawns).map(({ id, kind, x, z, area, openUntil, landsAt }) => ({ id, kind, x, z, area, open: openUntil > Date.now(), landsAt }));
}
function rollItem(kind) {
const weightKey = kind === 'drop' ? 'dropWeight' : 'chestWeight';
const rarities = Object.entries(lootTable.rarities).filter(([, rarity]) => rarity[weightKey] > 0);
let roll = Math.random() * rarities.reduce((sum, [, rarity]) => sum + rarity[weightKey], 0);
const [rarityKey] = rarities.find(([, rarity]) => (roll -= rarity[weightKey]) < 0) || rarities[0];
const options = lootTable.items.filter((item) => item.rarity === rarityKey);
return options[Math.floor(Math.random() * options.length)];
}
function spawnSupplyDrop() {
if (!Object.keys(activeDevelopers).length) return;
const spot = lootTable.spawns[Math.floor(Math.random() * lootTable.spawns.length)];
const id = `drop${++supplyDropCounter}`;
lootSpawns[id] = { id, kind: 'drop', x: spot.x + (Math.random() - 0.5) * 6, z: spot.z + (Math.random() - 0.5) * 6, area: spot.area, openUntil: 0, landsAt: Date.now() + SUPPLY_DROP_FALL_MS };
io.emit('loot_spawned', publicLoot().find((loot) => loot.id === id));
io.emit('system_message', `A SUPPLY DROP is falling over ${spot.area}! First dev to reach it gets Rare-to-Legendary loot.`);
// Unopened drops disappear after five minutes
setTimeout(() => {
if (lootSpawns[id] && !lootSpawns[id].openUntil) { delete lootSpawns[id]; io.emit('loot_removed', id); }
}, 5 * 60 * 1000);
}
setInterval(spawnSupplyDrop, SUPPLY_DROP_EVERY_MS);
// ----------------------------------------------------------------------------
// Community events (public/maps/events.json): the board lists them, stages
// stream them, and a background validator rewards presence. Every 15 s the
// server checks where each developer is (the position the game reports); a
// player who stays inside the stage radius of a LIVE event for N continuous
// minutes gets the reward once per event (stored in the account).
// ----------------------------------------------------------------------------
const EVENTS_FILE = path.join(PUBLIC_DIR, 'maps', 'events.json');
let eventsCache = { mtime: -1, data: { attendance: { radius: 28, minutes: 5, reward: 100 }, events: [] } };
function loadEvents() {
try {
const mtime = fs.statSync(EVENTS_FILE).mtimeMs;
if (mtime !== eventsCache.mtime) {
const data = JSON.parse(fs.readFileSync(EVENTS_FILE, 'utf8'));
const events = (Array.isArray(data.events) ? data.events : []).filter((event) => event && typeof event.id === 'string'
&& !Number.isNaN(Date.parse(event.dataHoraInicio)) && !Number.isNaN(Date.parse(event.dataHoraFim))
&& event.coordenadasDestino && Number.isFinite(event.coordenadasDestino.x) && Number.isFinite(event.coordenadasDestino.y));
eventsCache = { mtime, data: { attendance: { radius: 28, minutes: 5, reward: 100, ...(data.attendance || {}) }, events } };
}
} catch (error) {
console.error('[EVENTS] Could not read events.json:', error.message);
}
return eventsCache.data;
}
app.get('/api/events', (req, res) => {
const { attendance, events } = loadEvents();
res.set('Cache-Control', 'no-cache');
// serverTime lets every browser correct its own clock for the countdowns
res.json({ serverTime: Date.now(), attendance, events });
});
const attendanceTimers = new Map(); // "username|eventId" -> { since, lastSeen }
setInterval(() => {
const { attendance, events } = loadEvents();
const now = Date.now();
const live = events.filter((event) => Date.parse(event.dataHoraInicio) <= now && now < Date.parse(event.dataHoraFim));
if (!live.length) return;
for (const [socketId, dev] of Object.entries(activeDevelopers)) {
const socket = io.sockets.sockets.get(socketId);
const account = socket && accounts.users[socket.data.userKey];
if (!account) continue;
account.eventRewards = account.eventRewards || {};
for (const event of live) {
if (account.eventRewards[event.id]) continue;
const key = `${account.username}|${event.id}`;
const target = event.coordenadasDestino;
const inside = Math.hypot(dev.position.x - target.x, dev.position.z - target.y) < attendance.radius && dev.position.y > -20;
if (!inside) { attendanceTimers.delete(key); continue; }
const entry = attendanceTimers.get(key);
if (!entry || now - entry.lastSeen > 40000) {
attendanceTimers.set(key, { since: now, lastSeen: now });
socket.emit('event_presence', { eventId: event.id, title: event.titulo, minutes: attendance.minutes });
continue;
}
entry.lastSeen = now;
if (now - entry.since < attendance.minutes * 60000) continue;
attendanceTimers.delete(key);
account.eventRewards[event.id] = now;
account.coins = walletOf(account) + attendance.reward;
saveAccounts();
socket.emit('wallet', { coins: account.coins, earned: attendance.reward, reason: `attendance at ${event.titulo}` });
socket.emit('event_reward', { eventId: event.id, title: event.titulo, reward: attendance.reward });
}
}
}, 15000);
// Underground Cafe menu (prices are read here so the client cannot change them)
const cafeMenu = JSON.parse(fs.readFileSync(path.join(PUBLIC_DIR, 'maps', 'cafe_menu.json'), 'utf8'));
const cafeItems = new Map(cafeMenu.sections.flatMap((section) => section.items).map((item) => [item.id, item]));
const AVATAR_OPTIONS = {
color: ['#c7ceea', '#b5ead7', '#ffdac1', '#ff9aa2', '#e2f0cb', '#a0c4ff', '#ffd166', '#f1f3f5', '#2b2d42', '#ff70a6'],
eyes: ['none', 'pixel', 'round', 'visor', 'heart'],
body: ['none', 'leather', 'puffer', 'varsity', 'hoodie', 'tuxedo'],
head: ['none', 'cap', 'beanie', 'tophat', 'crown', 'headphones', 'halo'],
bodyColor: ['#212529', '#c92a2a', '#1864ab', '#2b8a3e', '#f08c00', '#862e9c', '#f8f9fa']
};
const sharedCodeBlocks = new Map(); // Codify blocks their owners chose to share
const VEHICLES = new Set(['rosso', 'wedge', 'volt', 'cyberwedge', 'cycle', 'cycleRed']);
const EMOTES = new Set(['wave', 'dance', 'cheer', 'clap', 'sit', 'think', 'ship', 'coffee']);
function commitLeaderboard() {
return Object.values(accounts.users).filter((user) => user.commits).map((user) => [user.username, user.commits]).sort((a, b) => b[1] - a[1]).slice(0, 10);
}
function publicGameState() {
const monsterState = {};
Object.entries(monsters).forEach(([id, monster]) => { monsterState[id] = { hp: monster.hp, alive: monster.alive }; });
return { ...gameState, monsters: monsterState };
}
function sanitizePosition(position) {
if (!position || typeof position !== 'object') return null;
const axes = ['x', 'y', 'z'].map((axis) => Number(position[axis]));
if (axes.some((value) => !Number.isFinite(value))) return null;
const [x, y, z] = axes.map((value) => Math.max(-MAX_COORDINATE, Math.min(MAX_COORDINATE, value)));
return { x, y, z };
}
function cleanText(value, maxLength) {
return typeof value === 'string' ? value.replace(/[\u0000-\u001f]/g, ' ').trim().slice(0, maxLength) : '';
}
function pullRequestsPayload(message) {
return { pullRequests: gameState.pullRequests.slice(-40), decorations: gameState.decorations, message };
}
// Only YouTube and Twitch embeds are accepted for the Keynote screen
function toEmbedUrl(rawUrl, hostForTwitch) {
let url;
try { url = new URL(rawUrl); } catch (error) { return null; }
const host = url.hostname.replace(/^www\./, '');
if (host === 'youtube.com' || host === 'm.youtube.com') {
const videoId = url.searchParams.get('v') || (url.pathname.startsWith('/live/') ? url.pathname.split('/')[2] : null);
return videoId && /^[\w-]{6,20}$/.test(videoId) ? `https://www.youtube.com/embed/${videoId}?autoplay=1` : null;
}
if (host === 'youtu.be') {
const videoId = url.pathname.slice(1);
return /^[\w-]{6,20}$/.test(videoId) ? `https://www.youtube.com/embed/${videoId}?autoplay=1` : null;
}
if (host === 'twitch.tv') {
const channel = url.pathname.split('/')[1];
return /^\w{3,25}$/.test(channel || '') ? `https://player.twitch.tv/?channel=${channel}&parent=${hostForTwitch}` : null;
}
return null;
}
// Only logged-in developers can join the multiverse
io.use((socket, next) => {
const user = userFromToken(socket.handshake.auth && socket.handshake.auth.token);
if (!user) return next(new Error('unauthorized'));
socket.data.userKey = user.username.toLowerCase();
// Private lobbies: devs only see and hear others in the same lobby (default: public)
const lobby = typeof socket.handshake.auth.lobby === 'string' ? socket.handshake.auth.lobby.replace(/[^a-z0-9]/gi, '').slice(0, 12) : '';
socket.data.room = lobby ? `lobby:${lobby}` : 'lobby:public';
next();
});
// This manages every developer that connects to your multiverse environment cluster
// ----------------------------------------------------------------------------
// Community Portals: six totems behind the Genesis Plaza spawn that any dev can
// rent for 24 hours (100 MVC) to show a project: title, short description,
// author and an https link. Slots live in memory and in data/community-portals.json
// and every change is broadcast to all players.
// ----------------------------------------------------------------------------
const PORTAL_SLOTS = 6;
const PORTAL_PRICE = 100;
const PORTAL_DURATION_MS = 24 * 60 * 60 * 1000;
const PORTALS_FILE = path.join(DATA_DIR, 'community-portals.json');
let communityPortals = Array.from({ length: PORTAL_SLOTS }, () => null);
try {
const saved = JSON.parse(fs.readFileSync(PORTALS_FILE, 'utf8'));
if (Array.isArray(saved)) communityPortals = Array.from({ length: PORTAL_SLOTS }, (unused, i) => saved[i] || null);
} catch (error) { /* no portals yet */ }
function savePortals() {
fs.mkdirSync(DATA_DIR, { recursive: true });
fs.writeFile(PORTALS_FILE, JSON.stringify(communityPortals), (error) => { if (error) console.error('[PORTALS] Could not save:', error.message); });
}
// Frees the slots whose 24 hours are over; returns true when something changed
function expirePortals() {
let changed = false;
communityPortals = communityPortals.map((slot) => {
if (slot && slot.expiresAt <= Date.now()) { changed = true; return null; }
return slot;
});
if (changed) savePortals();
return changed;
}
function publicPortals() {
expirePortals();
return communityPortals.map((slot) => slot && { title: slot.title, description: slot.description, url: slot.url, host: slot.host, author: slot.author, expiresAt: slot.expiresAt });
}
// Only plain https links to public hosts: no credentials, no local or private
// addresses, no raw IPs and no known IP-logger or link-hiding services
const PORTAL_BLOCKED_HOSTS = /(^|\.)(grabify\.link|iplogger\.(org|com|ru|co)|2no\.co|yip\.su|blasze\.com|ps3cfw\.com|bit\.ly|tinyurl\.com|t\.co|is\.gd|cutt\.ly|shorturl\.at|rb\.gy)$/i;
function validatePortalUrl(raw) {
if (typeof raw !== 'string' || raw.length > 200) return { error: 'The URL must have at most 200 characters.' };
let url;
try { url = new URL(raw.trim()); } catch (error) { return { error: 'That is not a valid URL.' }; }
if (url.protocol !== 'https:') return { error: 'Only https:// links are accepted.' };
if (url.username || url.password) return { error: 'Links with a username or password are not accepted.' };
const host = url.hostname.toLowerCase();
if (!host.includes('.') || /^[\d.]+$/.test(host) || host.includes(':') || /(^|\.)(localhost|local|internal|lan|home|test|example|invalid)$/.test(host)) return { error: 'Use the public address of the site (no local or IP addresses).' };
if (PORTAL_BLOCKED_HOSTS.test(host)) return { error: 'Link shorteners and IP loggers are not accepted: use the real address of the site.' };
if (url.port && url.port !== '443') return { error: 'Use the standard https port.' };
return { url: url.href, host };
}
setInterval(() => { if (expirePortals()) io.emit('portals_state', publicPortals()); }, 60 * 1000);
// Lands for the clients, with the GitHub handle each owner linked (/github)
function landsPayload() {
const out = {};
Object.entries(accounts.lands).forEach(([parcel, land]) => {
const owner = accounts.users[String(land.owner || '').toLowerCase()];
out[parcel] = owner && owner.github ? { ...land, github: owner.github } : land;
});
return out;
}
// ----------------------------------------------------------------------------
// Coworking Hub: four private tables in Genesis Plaza. Players inside a table's
// area share a private chat, a code board, a collective Pomodoro (25 min,
// +15 MVC each) and can "commit code" from the table laptops (+3 MVC).
// ----------------------------------------------------------------------------
const COWORK_TABLES = 4;
const COMMIT_REWARD = 3;
const COMMIT_COOLDOWN_MS = 60 * 1000;
const POMODORO_MS = 25 * 60 * 1000;
const POMODORO_REWARD = 15;
const coworkBoards = {}; // "room|table" -> { text, by, at }
const coworkPomodoros = {}; // "room|table" -> { endsAt, startedBy, members: Set(userKey), timer }
const tableRoom = (room, table) => `cowork:${room}:${table}`;
function pomodoroPayload(key, table) {
const pomodoro = coworkPomodoros[key];
return { table, running: Boolean(pomodoro), endsAt: pomodoro ? pomodoro.endsAt : 0, startedBy: pomodoro ? pomodoro.startedBy : null };
}
// Collabs & jobs board: 20 MVC for a card looking for partners (14 days)
const COLLAB_PRICE = 20;
const COLLAB_DAYS = 14;
const COLLABS_FILE = path.join(DATA_DIR, 'collabs.json');
let collabCards = [];
try { collabCards = JSON.parse(fs.readFileSync(COLLABS_FILE, 'utf8')) || []; } catch (error) { collabCards = []; }
function publicCollabs() {
const now = Date.now();
const before = collabCards.length;
collabCards = collabCards.filter((card) => card.expiresAt > now).slice(0, 40);
if (collabCards.length !== before) saveCollabs();
return collabCards.map(({ id, title, roles, description, repo, author, createdAt, expiresAt }) => ({ id, title, roles, description, repo, author, createdAt, expiresAt }));
}
function saveCollabs() {
fs.mkdirSync(DATA_DIR, { recursive: true });
fs.writeFile(COLLABS_FILE, JSON.stringify(collabCards), (error) => { if (error) console.error('[COLLABS] Could not save:', error.message); });
}
const STATUSES = ['available', 'focus', 'afk'];
io.on('connection', (socket) => {
const account = accounts.users[socket.data.userKey];
const developerTag = account.username;
// Assigns initial state parameters to the joining tridimensional cursor mesh pointer
activeDevelopers[socket.id] = {
id: socket.id,
devTag: developerTag,
position: { x: 0, y: 1, z: 0 },
color: (account.avatar && account.avatar.color) || getRandomPastelColor(),
avatar: account.avatar || null,
wearable: null
};
console.log(`[NETWORK] Developer registered: ${developerTag} (${socket.id})`);
socket.emit('local_registration_success', activeDevelopers[socket.id]);
const room = socket.data.room;
socket.join(room);
activeDevelopers[socket.id].room = room;
socket.emit('sync_entire_developer_pool', Object.values(activeDevelopers).filter((peer) => peer.room === room));
socket.emit('commit_leaderboard', commitLeaderboard());
socket.emit('world_state', worldStatePayload());
socket.emit('game_state', publicGameState());
socket.emit('loot_spawns', publicLoot());
socket.emit('tech_feeds', TechFeeds.snapshot());
socket.emit('portals_state', publicPortals());
socket.emit('collabs_state', publicCollabs());
// ---- Coworking tables ----
socket.on('cowork_zone', (rawTable, ack) => {
const reply = typeof ack === 'function' ? ack : () => {};
if (!developer()) return reply({ error: 'Not connected.' });
const table = Number.isInteger(rawTable) && rawTable >= 1 && rawTable <= COWORK_TABLES ? rawTable : null;
const previous = developer().table;
if (previous === table) return reply({ ok: true, table });
if (previous) socket.leave(tableRoom(room, previous));
developer().table = table;
if (!table) return reply({ ok: true, table: null });
socket.join(tableRoom(room, table));
const key = `${room}|${table}`;
reply({ ok: true, table, board: coworkBoards[key] || { text: '', by: null, at: 0 }, pomodoro: pomodoroPayload(key, table) });
});
socket.on('cowork_commit', (ack) => {
const reply = typeof ack === 'function' ? ack : () => {};
const me = accounts.users[socket.data.userKey];
if (!me || !developer() || !developer().table) return reply({ error: 'Sit at a coworking table to commit.' });
const wait = COMMIT_COOLDOWN_MS - (Date.now() - (me.lastCoworkCommit || 0));
if (wait > 0) return reply({ error: `Next commit in ${Math.ceil(wait / 1000)} s.` });
me.lastCoworkCommit = Date.now();
me.coins = walletOf(me) + COMMIT_REWARD;
saveAccounts();
socket.emit('wallet', { coins: me.coins, earned: COMMIT_REWARD, reason: 'commit at a coworking table' });
socket.to(tableRoom(room, developer().table)).emit('cowork_event', { table: developer().table, text: `${developer().devTag} committed code.` });
reply({ ok: true, coins: me.coins });
});
socket.on('cowork_board', ({ text } = {}) => {
if (!developer() || !developer().table || typeof text !== 'string') return;
const table = developer().table;
const board = { text: text.slice(0, 8000), by: developer().devTag, at: Date.now() };
coworkBoards[`${room}|${table}`] = board;
socket.to(tableRoom(room, table)).emit('cowork_board', { table, ...board });
});
socket.on('cowork_pomodoro_start', (ack) => {
const reply = typeof ack === 'function' ? ack : () => {};
if (!developer() || !developer().table) return reply({ error: 'Sit at a coworking table first.' });
const table = developer().table;
const key = `${room}|${table}`;
if (coworkPomodoros[key]) return reply({ error: 'A Pomodoro is already running at this table.' });
const members = new Set();
const sockets = io.sockets.adapter.rooms.get(tableRoom(room, table)) || new Set();
sockets.forEach((id) => { const peer = io.sockets.sockets.get(id); if (peer && peer.data.userKey) members.add(peer.data.userKey); });
const pomodoro = { endsAt: Date.now() + POMODORO_MS, startedBy: developer().devTag, members };
pomodoro.timer = setTimeout(() => {
delete coworkPomodoros[key];
// Everyone who started it and is still at the table earns the reward
const now = io.sockets.adapter.rooms.get(tableRoom(room, table)) || new Set();
const paid = new Set();
now.forEach((id) => {
const peer = io.sockets.sockets.get(id);
const user = peer && accounts.users[peer.data.userKey];
if (!user || !members.has(peer.data.userKey) || paid.has(peer.data.userKey)) return;
paid.add(peer.data.userKey);
user.coins = walletOf(user) + POMODORO_REWARD;
peer.emit('wallet', { coins: user.coins, earned: POMODORO_REWARD, reason: 'collective Pomodoro' });
});
saveAccounts();
io.to(tableRoom(room, table)).emit('cowork_pomodoro', { table, running: false, endsAt: 0, done: true, paid: paid.size });
}, POMODORO_MS);
coworkPomodoros[key] = pomodoro;
io.to(tableRoom(room, table)).emit('cowork_pomodoro', pomodoroPayload(key, table));
reply({ ok: true });
});
// ---- Status next to the name (available, focus, afk) ----
socket.on('set_status', (status) => {
if (!developer() || !STATUSES.includes(status)) return;
developer().status = status;
io.to(room).emit('peer_status', { id: socket.id, status });
});
// ---- Collabs & jobs board ----
socket.on('collabs_list', (ack) => { if (typeof ack === 'function') ack(publicCollabs()); });
socket.on('collab_post', (payload = {}, ack) => {
const reply = typeof ack === 'function' ? ack : () => {};
const me = accounts.users[socket.data.userKey];
if (!me) return reply({ error: 'Sign in again to post.' });
const title = cleanText(payload.title, 40);
const roles = cleanText(payload.roles, 60);
const description = cleanText(payload.description, 140);
if (!title || !description) return reply({ error: 'Add a title and a short description.' });
let repo = '';
if (payload.repo) {
const link = validatePortalUrl(payload.repo);
if (link.error) return reply({ error: link.error });
repo = link.url;
}
if (walletOf(me) < COLLAB_PRICE) return reply({ error: `You need ${COLLAB_PRICE} MVC (you have ${walletOf(me)}).` });
me.coins = walletOf(me) - COLLAB_PRICE;
saveAccounts();
collabCards.unshift({ id: Date.now().toString(36) + Math.random().toString(36).slice(2, 6), title, roles, description, repo, author: me.username, createdAt: Date.now(), expiresAt: Date.now() + COLLAB_DAYS * 86400000 });
saveCollabs();
socket.emit('wallet', { coins: me.coins, spent: COLLAB_PRICE, reason: 'Collabs board card' });
io.emit('collabs_state', publicCollabs());
reply({ ok: true });
});
// ---- GitHub handle shown on the owner's parcels (/github <handle>) ----
socket.on('set_github', (handle, ack) => {
const reply = typeof ack === 'function' ? ack : () => {};
const me = accounts.users[socket.data.userKey];
if (!me) return reply({ error: 'Sign in again.' });
const clean = String(handle || '').replace(/^@/, '').trim();
if (clean && !/^[a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38}$/i.test(clean)) return reply({ error: 'That is not a valid GitHub username.' });
me.github = clean || undefined;
saveAccounts();
io.emit('lands', landsPayload());
reply({ ok: true, github: me.github || null });
});
socket.on('portals_list', (ack) => { if (typeof ack === 'function') ack(publicPortals()); });
// Rent a free portal for 24 h: validated text and link, 100 MVC from the balance
socket.on('portal_rent', (payload = {}, ack) => {
const reply = typeof ack === 'function' ? ack : () => {};
const renter = accounts.users[socket.data.userKey];
if (!renter) return reply({ error: 'Sign in again to rent a portal.' });
const slot = Number(payload && payload.slot);
if (!Number.isInteger(slot) || slot < 0 || slot >= PORTAL_SLOTS) return reply({ error: 'Unknown portal.' });
expirePortals();
if (communityPortals[slot]) return reply({ error: 'This portal was just rented by someone else.' });
const title = cleanText(payload.title, 30);
const description = cleanText(payload.description, 80);
if (!title) return reply({ error: 'Give your project a title.' });
if (!description) return reply({ error: 'Add a short description.' });
const link = validatePortalUrl(payload.url);
if (link.error) return reply({ error: link.error });
if (walletOf(renter) < PORTAL_PRICE) return reply({ error: `You need ${PORTAL_PRICE} MVC (you have ${walletOf(renter)}).` });
renter.coins = walletOf(renter) - PORTAL_PRICE;
saveAccounts();
communityPortals[slot] = { title, description, url: link.url, host: link.host, author: renter.username, ownerKey: socket.data.userKey, rentedAt: Date.now(), expiresAt: Date.now() + PORTAL_DURATION_MS };
savePortals();
socket.emit('wallet', { coins: renter.coins, spent: PORTAL_PRICE, reason: 'Community Portal (24 h)' });
io.emit('portals_state', publicPortals());
reply({ ok: true, coins: renter.coins });
});
socket.to(room).emit('new_developer_joined', activeDevelopers[socket.id]);
const developer = () => activeDevelopers[socket.id];
// Synchronizes real-time coordinates transform movements across the whole city
socket.on('update_cursor_transform', (transformData) => {
const position = sanitizePosition(transformData && transformData.position);
if (!developer() || !position) return;
developer().position = position;
socket.to(room).emit('peer_cursor_transformed', { id: socket.id, position });
});
socket.on('chat_message', (rawText) => {
const text = cleanText(rawText, MAX_CHAT_LENGTH);
if (!developer() || !text) return;
// At a coworking table the chat stays among the people at that table
const table = developer().table;
if (table) { io.to(tableRoom(room, table)).emit('chat_message', { id: socket.id, devTag: developer().devTag, color: developer().color, text, table, timestamp: Date.now() }); return; }
io.to(room).emit('chat_message', { id: socket.id, devTag: developer().devTag, color: developer().color, text, timestamp: Date.now() });
});
socket.on('private_message', ({ targetId, text } = {}) => {
const target = activeDevelopers[targetId];
const cleanMessage = cleanText(text, MAX_CHAT_LENGTH);
if (!developer() || !target || !cleanMessage) return;
const message = { fromId: socket.id, devTag: developer().devTag, toTag: target.devTag, color: developer().color, text: cleanMessage };
io.to(targetId).emit('private_message', message);
socket.emit('private_message', message);
});
socket.on('set_nick', () => {
socket.emit('system_message', 'Your name is your account username. Create a new account to use another name.');
});
// Avatar customization (cursor color, eyewear, jacket, hat), saved on the account
socket.on('set_avatar', (look = {}) => {
const dev = developer();
if (!dev || typeof look !== 'object') return;
const clean = {};
Object.entries(AVATAR_OPTIONS).forEach(([key, allowed]) => { clean[key] = allowed.includes(look[key]) ? look[key] : allowed[0]; });
account.avatar = clean;
dev.avatar = clean;
dev.color = clean.color;
saveAccounts();
io.to(room).emit('peer_updated', { id: socket.id, devTag: dev.devTag, avatar: clean, color: clean.color });
});
socket.on('set_wearable', (item) => {
if (!developer()) return;
developer().wearable = WEARABLES.has(item) ? item : null;
io.to(room).emit('peer_updated', { id: socket.id, devTag: developer().devTag, wearable: developer().wearable });
});
// Minecraft-style /time, /gamerule doDaylightCycle and /weather (shared by everyone)
socket.on('world_state_change', (change = {}) => {
if (!developer()) return;
let kind = null;
if (typeof change.ticks === 'number' && Number.isFinite(change.ticks)) {
worldState.ticks = ((change.ticks % 24000) + 24000) % 24000;
worldState.changedAt = Date.now();
kind = 'time';
}
if (typeof change.cycle === 'boolean') {
worldState.ticks = currentTicks();
worldState.changedAt = Date.now();
worldState.cycle = change.cycle;
kind = 'cycle';
}
if (['clear', 'rain', 'snow', 'thunder'].includes(change.weather)) {
worldState.weather = change.weather;
kind = 'weather';
}
if (kind) io.emit('world_state', worldStatePayload({ by: developer().devTag, kind }));
});
// Teleport requests always need the other player's consent (/tpa, /tpahere, /tpaccept)
socket.on('teleport_request', ({ targetId, mode } = {}) => {
if (!developer() || !activeDevelopers[targetId] || targetId === socket.id) return;
io.to(targetId).emit('teleport_request', { fromId: socket.id, fromTag: developer().devTag, mode: mode === 'here' ? 'here' : 'to' });
});
socket.on('teleport_accept', ({ requesterId, mode } = {}) => {
if (!developer() || !activeDevelopers[requesterId]) return;
io.to(requesterId).emit('teleport_accepted', { byId: socket.id, byTag: developer().devTag, mode: mode === 'here' ? 'here' : 'to' });
});
socket.on('teleport_deny', ({ requesterId } = {}) => {
if (!developer() || !activeDevelopers[requesterId]) return;
io.to(requesterId).emit('teleport_denied', { byTag: developer().devTag });
});
// Debug Dungeon: co-op bug squashing with server-owned health
socket.on('monster_hit', ({ id, damage } = {}) => {
const monster = monsters[id];
if (!developer() || !monster || !monster.alive || !ALLOWED_DAMAGE.has(damage)) return;
if (developer().lensUntil > Date.now()) damage *= 2; // Debugger Lens buff
monster.hp = Math.max(0, monster.hp - damage);
monster.alive = monster.hp > 0;
io.emit('monster_update', { id, hp: monster.hp, alive: monster.alive, by: developer().devTag, damage });
if (!monster.alive) {
gameState.scores[developer().devTag] = (gameState.scores[developer().devTag] || 0) + 1;
io.emit('scores', gameState.scores);
setTimeout(() => {
monster.hp = monster.maxHp;
monster.alive = true;
io.emit('monster_update', { id, hp: monster.hp, alive: true });
}, MONSTER_RESPAWN_MS);
}
});
// Open Source HQ: code murals and visual pull requests
socket.on('mural_post', ({ muralId, text } = {}) => {
const cleanCode = cleanText(text, 80);
if (!developer() || !/^mural[1-4]$/.test(muralId || '') || !cleanCode) return;
gameState.murals[muralId] = [...(gameState.murals[muralId] || []), { devTag: developer().devTag, text: cleanCode }].slice(-30);
io.emit('murals', gameState.murals);
});
socket.on('pr_open', ({ slot, item, color } = {}) => {
if (!developer() || !(slot >= 1 && slot <= 8) || !DECOR_ITEMS.has(item)) return;
const pr = {
id: gameState.pullRequests.length + 1,
slot: Math.floor(slot),
item,
color: /^#[0-9a-f]{6}$/i.test(color || '') ? color : null,
author: developer().devTag,
authorId: socket.id,
approvals: [],
status: 'open'
};
gameState.pullRequests.push(pr);
io.emit('pull_requests', pullRequestsPayload(`${pr.author} opened PR #${pr.id}: slot ${pr.slot} -> ${pr.item}. Another dev must /approve ${pr.id} before /merge.`));
});
socket.on('pr_review', ({ id, action } = {}) => {
const pr = gameState.pullRequests.find((candidate) => candidate.id === id);
if (!developer() || !pr) return;
if (pr.status !== 'open') { socket.emit('system_message', `PR #${id} is already ${pr.status}.`); return; }
const reviewer = developer().devTag;
if (action === 'approve') {
if (pr.authorId === socket.id) { socket.emit('system_message', 'You cannot approve your own pull request.'); return; }
if (!pr.approvals.includes(reviewer)) pr.approvals.push(reviewer);