Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
1944 lines (1713 loc) · 63.6 KB
/
Copy pathserver.js
File metadata and controls
1944 lines (1713 loc) · 63.6 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
require("dotenv").config();
const express = require("express");
const { createServer } = require("http");
const { Server } = require("socket.io");
const fs = require("fs");
const path = require("path");
const cookieSession = require("cookie-session");
const crypto = require("crypto");
const pokemonData = require("./public/data/pokemon.json");
const itemData = require("./public/data/items.json");
const moveData = require("./public/data/moves.json");
const areaData = require("./public/data/area.json");
const { BagItemEffects } = require("./public/js/itemEffects.js");
const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer);
const knex = require("knex")(
require("./knexfile")[process.env.NODE_ENV || "development"]
);
// Run migrations on startup
knex.migrate.latest().then(() => {
console.log("Database migrations complete");
});
const SESSION_SECRET = process.env.SESSION_SECRET || "pokecode-dev-secret-change-me";
const HC_CLIENT_ID = process.env.HC_CLIENT_ID;
const HC_CLIENT_SECRET = process.env.HC_CLIENT_SECRET;
const HACKATIME_CLIENT_ID = process.env.HACKATIME_CLIENT_ID;
const HACKATIME_CLIENT_SECRET = process.env.HACKATIME_CLIENT_SECRET;
const HACKATIME_URL = "https://hackatime.hackclub.com";
const HACKATIME_SCOPE = "profile read";
const configuredBaseUrl = process.env.BASE_URL || "http://localhost:3000";
const BASE_URL = new URL(
/^https?:\/\//i.test(configuredBaseUrl)
? configuredBaseUrl
: `https://${configuredBaseUrl}`
).toString().replace(/\/+$/, "");
const BASE_PATH = `${new URL(BASE_URL).pathname.replace(/\/+$/, "")}/`;
const publicDir = path.join(__dirname, "public");
const indexHtml = fs
.readFileSync(path.join(publicDir, "index.html"), "utf8")
.replace("__BASE_PATH__", BASE_PATH);
app.use(express.json());
app.use(
cookieSession({
name: "session",
keys: [SESSION_SECRET],
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
})
);
app.get(["/", "/index.html"], (req, res) => {
res.type("html").send(indexHtml);
});
app.use(express.static(publicDir, { index: false }));
// Auth middleware
function requireAuth(req, res, next) {
if (!req.session.userId) {
return res.status(401).json({ error: "Not authenticated" });
}
next();
}
async function requireAdmin(req, res, next) {
const user = await knex("users").where({ id: req.session.userId }).first();
if (!user?.admin) {
return res.status(403).json({ error: "Admin access required" });
}
next();
}
// Get current user
app.get("/api/me", async (req, res) => {
if (!req.session.userId) {
return res.json({ user: null });
}
const user = await knex("users").where({ id: req.session.userId }).first();
if (!user) {
req.session = null;
return res.json({ user: null });
}
res.json({
user: {
id: user.id,
email: user.email,
slackId: user.slackId,
username: user.username,
gender: user.gender,
x: user.x,
y: user.y,
direction: user.direction,
admin: user.admin,
lastPokemartId: user.lastPokemartId,
needsStarter: !user.starterReceived,
impersonating: Boolean(req.session.impersonatorId),
hackatimeConnected: Boolean(user.hackatimeId),
},
});
});
// Start OAuth flow
app.get("/auth/login", (req, res) => {
const params = new URLSearchParams({
client_id: HC_CLIENT_ID,
redirect_uri: `${BASE_URL}/auth/callback`,
response_type: "code",
scope: "email slack_id",
});
res.redirect(`https://auth.hackclub.com/oauth/authorize?${params}`);
});
// OAuth callback
app.get("/auth/callback", async (req, res) => {
const { code } = req.query;
if (!code) {
return res.redirect(`${BASE_URL}/?error=no_code`);
}
try {
// Exchange code for tokens
const tokenRes = await fetch("https://auth.hackclub.com/oauth/token", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
client_id: HC_CLIENT_ID,
client_secret: HC_CLIENT_SECRET,
redirect_uri: `${BASE_URL}/auth/callback`,
code,
grant_type: "authorization_code",
}),
});
if (!tokenRes.ok) {
console.error("Token exchange failed:", await tokenRes.text());
return res.redirect(`${BASE_URL}/?error=token_failed`);
}
const tokenData = await tokenRes.json();
// Get user info
const meRes = await fetch("https://auth.hackclub.com/api/v1/me", {
headers: { Authorization: `Bearer ${tokenData.access_token}` },
});
if (!meRes.ok) {
console.error("User info fetch failed:", await meRes.text());
return res.redirect(`${BASE_URL}/?error=user_fetch_failed`);
}
const meData = await meRes.json();
const identity = meData.identity;
// Upsert user
let user = await knex("users").where({ hackclubId: identity.id }).first();
if (user) {
await knex("users").where({ id: user.id }).update({
email: identity.primary_email || user.email,
slackId: identity.slack_id || user.slackId,
accessToken: tokenData.access_token,
refreshToken: tokenData.refresh_token,
updated_at: knex.fn.now(),
});
user = await knex("users").where({ id: user.id }).first();
} else {
const [newUser] = await knex("users")
.insert({
hackclubId: identity.id,
email: identity.primary_email,
slackId: identity.slack_id,
accessToken: tokenData.access_token,
refreshToken: tokenData.refresh_token,
})
.returning("*");
user = newUser;
}
req.session.userId = user.id;
res.redirect(`${BASE_URL}/`);
} catch (err) {
console.error("OAuth error:", err);
res.redirect(`${BASE_URL}/?error=oauth_error`);
}
});
// Start Hackatime OAuth flow (links Hackatime to the logged-in account)
app.get("/auth/hackatime", (req, res) => {
if (!req.session.userId) {
return res.redirect(`${BASE_URL}/?error=not_logged_in`);
}
if (!HACKATIME_CLIENT_ID) {
return res.redirect(`${BASE_URL}/?error=hackatime_not_configured`);
}
const state = crypto.randomBytes(16).toString("hex");
const codeVerifier = crypto.randomBytes(32).toString("base64url");
const codeChallenge = crypto
.createHash("sha256")
.update(codeVerifier)
.digest("base64url");
req.session.hackatimeState = state;
req.session.hackatimeVerifier = codeVerifier;
const params = new URLSearchParams({
client_id: HACKATIME_CLIENT_ID,
redirect_uri: `${BASE_URL}/auth/hackatime/callback`,
response_type: "code",
scope: HACKATIME_SCOPE,
state,
code_challenge: codeChallenge,
code_challenge_method: "S256",
});
res.redirect(`${HACKATIME_URL}/oauth/authorize?${params}`);
});
// Hackatime OAuth callback
app.get("/auth/hackatime/callback", async (req, res) => {
const { code, state, error } = req.query;
const expectedState = req.session.hackatimeState;
const codeVerifier = req.session.hackatimeVerifier;
req.session.hackatimeState = null;
req.session.hackatimeVerifier = null;
if (!req.session.userId) {
return res.redirect(`${BASE_URL}/?error=not_logged_in`);
}
if (error) {
return res.redirect(`${BASE_URL}/?error=hackatime_denied`);
}
if (!code || !state || state !== expectedState) {
return res.redirect(`${BASE_URL}/?error=hackatime_invalid_state`);
}
try {
const tokenBody = new URLSearchParams({
client_id: HACKATIME_CLIENT_ID,
code,
redirect_uri: `${BASE_URL}/auth/hackatime/callback`,
grant_type: "authorization_code",
code_verifier: codeVerifier,
});
if (HACKATIME_CLIENT_SECRET) {
tokenBody.set("client_secret", HACKATIME_CLIENT_SECRET);
}
const tokenRes = await fetch(`${HACKATIME_URL}/oauth/token`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: tokenBody,
});
if (!tokenRes.ok) {
console.error("Hackatime token exchange failed:", await tokenRes.text());
return res.redirect(`${BASE_URL}/?error=hackatime_token_failed`);
}
const tokenData = await tokenRes.json();
const meRes = await fetch(`${HACKATIME_URL}/api/v1/authenticated/me`, {
headers: { Authorization: `Bearer ${tokenData.access_token}` },
});
if (!meRes.ok) {
console.error("Hackatime user fetch failed:", await meRes.text());
return res.redirect(`${BASE_URL}/?error=hackatime_user_fetch_failed`);
}
const meData = await meRes.json();
const hackatimeId = String(meData.id);
const linkedUser = await knex("users")
.where({ hackatimeId })
.whereNot({ id: req.session.userId })
.first();
if (linkedUser) {
return res.redirect(`${BASE_URL}/?error=hackatime_already_linked`);
}
await knex("users").where({ id: req.session.userId }).update({
hackatimeId,
hackatimeAccessToken: tokenData.access_token,
hackatimeScope: tokenData.scope || HACKATIME_SCOPE,
hackatimeConnectedAt: knex.fn.now(),
updated_at: knex.fn.now(),
});
res.redirect(`${BASE_URL}/?hackatime=connected`);
} catch (err) {
console.error("Hackatime OAuth error:", err);
res.redirect(`${BASE_URL}/?error=hackatime_oauth_error`);
}
});
// Logout
app.post("/auth/logout", (req, res) => {
req.session = null;
res.json({ ok: true });
});
// Set username and gender (after first login)
app.post("/api/setup", requireAuth, async (req, res) => {
const { username, gender } = req.body;
if (!username || username.trim().length === 0 || username.trim().length > 12) {
return res.status(400).json({ error: "Username must be 1-12 characters" });
}
if (!["male", "female"].includes(gender)) {
return res.status(400).json({ error: "Invalid gender" });
}
const trimmed = username.trim();
// Check uniqueness
const existing = await knex("users")
.where({ username: trimmed })
.whereNot({ id: req.session.userId })
.first();
if (existing) {
return res.status(409).json({ error: "Username already taken" });
}
await knex("users").where({ id: req.session.userId }).update({
username: trimmed,
gender,
updated_at: knex.fn.now(),
});
const user = await knex("users").where({ id: req.session.userId }).first();
res.json({
user: {
id: user.id,
email: user.email,
slackId: user.slackId,
username: user.username,
gender: user.gender,
x: user.x,
y: user.y,
direction: user.direction,
admin: user.admin,
lastPokemartId: user.lastPokemartId,
needsStarter: !user.starterReceived,
impersonating: Boolean(req.session.impersonatorId),
hackatimeConnected: Boolean(user.hackatimeId),
},
});
});
function learnableMovesForLevel(speciesId, level) {
return (pokemonData[speciesId]?.moves || [])
.filter((learnedMove) => learnedMove.level <= level)
.map((learnedMove) => learnedMove.move);
}
function knownMovesForLevel(speciesId, level) {
return learnableMovesForLevel(speciesId, level).slice(-4);
}
function maxHealthForLevel(speciesId, level) {
const baseHp = pokemonData[speciesId].stats.HP;
return Math.floor((baseHp * 2 * level) / 100) + level + 10;
}
// EXP needed to go from `level` to `level + 1`.
function expToLevelUp(speciesId, level) {
return Math.max(1, Math.ceil(level * 0.2 * pokemonData[speciesId].stats.EXPRATE));
}
// EXP dropped by a defeated wild Pokémon found in `area`.
function wildExpReward(area, level) {
return Math.max(1, Math.floor(level * area.encounterChance * 0.25));
}
function formatOwnedPokemon(row) {
return {
id: row.id,
speciesId: row.speciesId,
nickname: row.nickname,
level: row.level,
health: row.health,
friendship: row.friendship,
location: row.location,
exp: row.exp,
expToNextLevel: row.level < 100 ? expToLevelUp(row.speciesId, row.level) : null,
slot: row.slot,
moves: Array.isArray(row.moves) ? row.moves : [],
status: row.status || null,
};
}
// Status conditions a Pokémon can keep between battles (see status() in moveEffects.js).
const STATUS_NAMES = new Set(["burned", "frozen", "paralyzed", "poisoned", "asleep"]);
// Returns a clean { name, turns } status, null for no status, or undefined if invalid.
function parseStatus(value) {
if (value === null || value === undefined) return null;
if (typeof value !== "object" || !STATUS_NAMES.has(value.name)) return undefined;
const turns = value.turns ?? null;
if (turns !== null && (!Number.isInteger(turns) || turns < 1 || turns > 10)) return undefined;
return { name: value.name, turns };
}
// Value to write to the user_pokemon.status jsonb column.
function statusColumn(status) {
return status ? JSON.stringify(status) : null;
}
const STARTER_SPECIES = new Set([
"charmander",
"bulbasaur",
"squirtle",
"eevee",
"pikachu",
]);
// Give an eligible user their one-time level 5 starter.
app.post("/api/starter", requireAuth, async (req, res) => {
const { speciesId } = req.body;
if (!STARTER_SPECIES.has(speciesId)) {
return res.status(400).json({ error: "Invalid starter Pokémon" });
}
try {
const pokemon = await knex.transaction(async (trx) => {
const user = await trx("users")
.where({ id: req.session.userId })
.forUpdate()
.first();
if (user.starterReceived) {
const err = new Error("Starter already received");
err.status = 409;
throw err;
}
// Users sent back through onboarding may already own Pokémon; a full party sends it to the box.
const partyCount = await trx("user_pokemon")
.where({ userId: user.id, location: "party" })
.count("id as count")
.first();
const location = Number(partyCount.count) < 6 ? "party" : "box";
const level = 5;
const [row] = await trx("user_pokemon")
.insert({
userId: user.id,
speciesId,
location,
slot: await nextFreeSlot(trx, user.id, location),
level,
health: maxHealthForLevel(speciesId, level),
moves: JSON.stringify(knownMovesForLevel(speciesId, level)),
})
.returning("*");
await trx("users").where({ id: user.id }).update({
starterReceived: true,
updated_at: trx.fn.now(),
});
return row;
});
res.status(201).json({ pokemon: formatOwnedPokemon(pokemon) });
} catch (err) {
if (err.status) {
return res.status(err.status).json({ error: err.message });
}
throw err;
}
});
// Get the current user's Pokémon, split into party (max 6) and box
app.get("/api/my-pokemon", requireAuth, async (req, res) => {
const rows = await knex("user_pokemon")
.where({ userId: req.session.userId })
.orderBy("slot", "asc");
res.json({
party: rows.filter((r) => r.location === "party").map(formatOwnedPokemon),
box: rows.filter((r) => r.location === "box").map(formatOwnedPokemon),
});
});
// Restore every Pokémon in the current user's party to full health and remember
// the Pokémart they healed at (where they return to after blacking out).
app.post("/api/my-pokemon/heal-party", requireAuth, async (req, res) => {
const pokemartId = req.body?.pokemartId;
if (typeof pokemartId !== "string" || !pokemartId || pokemartId.length > 255) {
return res.status(400).json({ error: "Invalid Pokémart" });
}
const party = await knex.transaction(async (trx) => {
await trx("users")
.where({ id: req.session.userId })
.update({ lastPokemartId: pokemartId, updated_at: trx.fn.now() });
const rows = await trx("user_pokemon")
.where({ userId: req.session.userId, location: "party" })
.orderBy("slot", "asc")
.forUpdate();
for (const pokemon of rows) {
pokemon.health = maxHealthForLevel(pokemon.speciesId, pokemon.level);
pokemon.status = null;
await trx("user_pokemon")
.where({ id: pokemon.id, userId: req.session.userId })
.update({ health: pokemon.health, status: null, updated_at: trx.fn.now() });
}
return rows;
});
res.json({ party: party.map(formatOwnedPokemon) });
});
// Update the four moves known by one of the current user's Pokémon.
app.patch("/api/my-pokemon/:id/moves", requireAuth, async (req, res) => {
const pokemonId = Number(req.params.id);
const selectedMoves = req.body?.moves;
if (!Number.isInteger(pokemonId) || pokemonId <= 0 || !Array.isArray(selectedMoves)) {
return res.status(400).json({ error: "Invalid move selection" });
}
const pokemon = await knex("user_pokemon")
.where({ id: pokemonId, userId: req.session.userId })
.first();
if (!pokemon) {
return res.status(404).json({ error: "Pokémon not found" });
}
const learnableMoves = learnableMovesForLevel(pokemon.speciesId, pokemon.level);
const uniqueMoves = new Set(selectedMoves);
// Fewer than four is allowed so players can decline moves offered on level up.
const isValidSelection =
selectedMoves.length >= 1 &&
selectedMoves.length <= 4 &&
uniqueMoves.size === selectedMoves.length &&
selectedMoves.every(
(moveId) => typeof moveId === "string" && learnableMoves.includes(moveId)
);
if (!isValidSelection) {
return res.status(400).json({
error: "Choose 1 to 4 moves this Pokémon can learn",
});
}
const [updatedPokemon] = await knex("user_pokemon")
.where({ id: pokemonId, userId: req.session.userId })
.update({ moves: JSON.stringify(selectedMoves), updated_at: knex.fn.now() })
.returning("*");
res.json({ pokemon: formatOwnedPokemon(updatedPokemon) });
});
// Admins can update the level of one of their Pokémon.
app.patch("/api/my-pokemon/:id/level", requireAuth, requireAdmin, async (req, res) => {
const pokemonId = Number(req.params.id);
const level = Number(req.body?.level);
if (
!Number.isInteger(pokemonId) ||
pokemonId <= 0 ||
!Number.isInteger(level) ||
level < 1 ||
level > 100
) {
return res.status(400).json({ error: "Level must be a whole number from 1 to 100" });
}
const [updatedPokemon] = await knex("user_pokemon")
.where({ id: pokemonId, userId: req.session.userId })
.update({ level, exp: 0, updated_at: knex.fn.now() })
.returning("*");
if (!updatedPokemon) {
return res.status(404).json({ error: "Pokémon not found" });
}
res.json({ pokemon: formatOwnedPokemon(updatedPokemon) });
});
// Admins can update the health of one of their Pokémon.
app.patch("/api/my-pokemon/:id/health", requireAuth, requireAdmin, async (req, res) => {
const pokemonId = Number(req.params.id);
const health = Number(req.body?.health);
if (!Number.isInteger(pokemonId) || pokemonId <= 0 || !Number.isInteger(health)) {
return res.status(400).json({ error: "Health must be a whole number" });
}
const pokemon = await knex("user_pokemon")
.where({ id: pokemonId, userId: req.session.userId })
.first();
if (!pokemon) {
return res.status(404).json({ error: "Pokémon not found" });
}
const maxHealth = maxHealthForLevel(pokemon.speciesId, pokemon.level);
if (health < 0 || health > maxHealth) {
return res.status(400).json({
error: `Health must be a whole number from 0 to ${maxHealth}`,
});
}
const [updatedPokemon] = await knex("user_pokemon")
.where({ id: pokemonId, userId: req.session.userId })
.update({ health, updated_at: knex.fn.now() })
.returning("*");
res.json({ pokemon: formatOwnedPokemon(updatedPokemon) });
});
// Admins can add a Pokémon directly to their own party
app.post("/api/my-pokemon", requireAuth, requireAdmin, async (req, res) => {
const { speciesId } = req.body;
if (typeof speciesId !== "string" || !pokemonData[speciesId]) {
return res.status(400).json({ error: "Invalid Pokémon species" });
}
try {
const pokemon = await knex.transaction(async (trx) => {
// Lock the user row so simultaneous requests cannot overfill the party.
await trx("users").where({ id: req.session.userId }).forUpdate().first();
const party = await trx("user_pokemon")
.where({ userId: req.session.userId, location: "party" })
.orderBy("slot", "asc");
if (party.length >= 6) {
const err = new Error("Your party is full");
err.status = 409;
throw err;
}
const usedSlots = new Set(party.map((row) => row.slot));
let slot = 0;
while (usedSlots.has(slot)) slot++;
const [row] = await trx("user_pokemon")
.insert({
userId: req.session.userId,
speciesId,
location: "party",
slot,
health: maxHealthForLevel(speciesId, 1),
moves: JSON.stringify(knownMovesForLevel(speciesId, 1)),
})
.returning("*");
return row;
});
res.status(201).json({
pokemon: formatOwnedPokemon(pokemon),
});
} catch (err) {
if (err.status) {
return res.status(err.status).json({ error: err.message });
}
throw err;
}
});
// Admins can delete one of their Pokémon.
app.delete("/api/my-pokemon/:id", requireAuth, requireAdmin, async (req, res) => {
const pokemonId = Number(req.params.id);
if (!Number.isInteger(pokemonId) || pokemonId <= 0) {
return res.status(400).json({ error: "Invalid Pokémon" });
}
const deleted = await knex("user_pokemon")
.where({ id: pokemonId, userId: req.session.userId })
.del();
if (!deleted) {
return res.status(404).json({ error: "Pokémon not found" });
}
res.json({ ok: true });
});
// Get the current user's item quantities. Item details live in items.json.
app.get("/api/my-items", requireAuth, async (req, res) => {
const rows = await knex("user_items")
.where({ userId: req.session.userId })
.orderBy("itemId", "asc");
res.json({
items: rows.map((row) => ({
itemId: row.itemId,
quantity: row.quantity,
})),
});
});
// Get the current user's currency balances.
app.get("/api/my-currency", requireAuth, async (req, res) => {
const user = await knex("users")
.where({ id: req.session.userId })
.select("pokedollars", "watts")
.first();
res.json({ pokedollars: user.pokedollars, watts: user.watts });
});
// Buy items listed in items.json with a shopPrice, paid in their shopType currency.
app.post("/api/shop/buy", requireAuth, async (req, res) => {
const { itemId } = req.body;
const quantity = Number(req.body?.quantity ?? 1);
const item = itemData[itemId];
if (
typeof itemId !== "string" ||
!Number.isInteger(item?.shopPrice) ||
!["pokedollars", "watts"].includes(item.shopType)
) {
return res.status(400).json({ error: "That item is not for sale" });
}
if (!Number.isInteger(quantity) || quantity < 1 || quantity > 99) {
return res.status(400).json({ error: "Quantity must be a whole number from 1 to 99" });
}
const cost = item.shopPrice * quantity;
try {
const result = await knex.transaction(async (trx) => {
const user = await trx("users")
.where({ id: req.session.userId })
.forUpdate()
.first();
if (user[item.shopType] < cost) {
const error = new Error(
`Not enough ${item.shopType === "watts" ? "Watts" : "Pokédollars"}`
);
error.status = 409;
throw error;
}
const [balances] = await trx("users")
.where({ id: user.id })
.update({
[item.shopType]: user[item.shopType] - cost,
updated_at: trx.fn.now(),
})
.returning(["pokedollars", "watts"]);
const [ownedItem] = await trx("user_items")
.insert({ userId: user.id, itemId, quantity })
.onConflict(["userId", "itemId"])
.merge({
quantity: trx.raw("user_items.quantity + ?", [quantity]),
updated_at: trx.fn.now(),
})
.returning(["itemId", "quantity"]);
return { item: ownedItem, currency: balances };
});
res.json(result);
} catch (error) {
if (error.status) {
return res.status(error.status).json({ error: error.message });
}
throw error;
}
});
// Admins can add one or more items to their own bag.
app.post("/api/my-items", requireAuth, requireAdmin, async (req, res) => {
const { itemId } = req.body;
const quantity = Number(req.body?.quantity ?? 1);
if (typeof itemId !== "string" || !itemData[itemId]) {
return res.status(400).json({ error: "Invalid item" });
}
if (!Number.isInteger(quantity) || quantity < 1 || quantity > 999) {
return res.status(400).json({ error: "Quantity must be a whole number from 1 to 999" });
}
const [item] = await knex("user_items")
.insert({ userId: req.session.userId, itemId, quantity })
.onConflict(["userId", "itemId"])
.merge({
quantity: knex.raw("user_items.quantity + ?", [quantity]),
updated_at: knex.fn.now(),
})
.returning(["itemId", "quantity"]);
res.status(201).json({ item });
});
// Use a bagUsable item from the bag on one of the current user's Pokémon. The
// effect itself lives in BagItemEffects (public/js/itemEffects.js).
app.post("/api/my-items/use", requireAuth, async (req, res) => {
const { itemId } = req.body;
const pokemonId = Number(req.body?.pokemonId);
if (
typeof itemId !== "string" ||
!itemData[itemId]?.bagUsable ||
!Object.hasOwn(BagItemEffects, itemId)
) {
return res.status(400).json({ error: "That item can't be used here" });
}
if (!Number.isInteger(pokemonId) || pokemonId <= 0) {
return res.status(400).json({ error: "Invalid Pokémon" });
}
try {
const result = await knex.transaction(async (trx) => {
const item = await trx("user_items")
.where({ userId: req.session.userId, itemId })
.forUpdate()
.first();
if (!item || item.quantity < 1) {
const error = new Error(`You don't have any ${itemData[itemId].name}`);
error.status = 409;
throw error;
}
const pokemon = await trx("user_pokemon")
.where({ id: pokemonId, userId: req.session.userId })
.forUpdate()
.first();
if (!pokemon) {
const error = new Error("Pokémon not found");
error.status = 404;
throw error;
}
const target = {
name: pokemon.nickname || pokemonData[pokemon.speciesId]?.name || pokemon.speciesId,
level: pokemon.level,
exp: pokemon.exp,
health: pokemon.health,
maxHealth: maxHealthForLevel(pokemon.speciesId, pokemon.level),
status: pokemon.status || null,
maxHealthForLevel: (level) => maxHealthForLevel(pokemon.speciesId, level),
};
const effect = BagItemEffects[itemId]({ target });
if (!effect.used) {
const error = new Error(effect.message);
error.status = 400;
throw error;
}
const [updatedPokemon] = await trx("user_pokemon")
.where({ id: pokemon.id, userId: req.session.userId })
.update({
level: target.level,
exp: target.exp,
health: target.health,
status: statusColumn(target.status),
updated_at: trx.fn.now(),
})
.returning("*");
if (item.quantity === 1) {
await trx("user_items").where({ id: item.id }).del();
} else {
await trx("user_items")
.where({ id: item.id })
.update({ quantity: item.quantity - 1, updated_at: trx.fn.now() });
}
return {
message: effect.message,
pokemon: formatOwnedPokemon(updatedPokemon),
item: { itemId, quantity: item.quantity - 1 },
};
});
res.json(result);
} catch (error) {
if (error.status) {
return res.status(error.status).json({ error: error.message });
}
throw error;
}
});
// ─── Profile ───
// Text profile columns on users, with their max lengths.
const PROFILE_TEXT_FIELDS = {
firstName: { label: "First name", max: 100 },
lastName: { label: "Last name", max: 100 },
addressLine1: { label: "Address (line 1)", max: 200 },
addressLine2: { label: "Address (line 2)", max: 200 },
city: { label: "City", max: 100 },
state: { label: "State / Province", max: 100 },
country: { label: "Country", max: 100 },
postalCode: { label: "ZIP / Postal code", max: 20 },
};
// pg returns DATE columns as local-midnight Dates; turn them back into YYYY-MM-DD.
function formatDateOnly(value) {
if (!value) return null;
if (typeof value === "string") return value.slice(0, 10);
const pad = (n) => String(n).padStart(2, "0");
return `${value.getFullYear()}-${pad(value.getMonth() + 1)}-${pad(value.getDate())}`;
}
function profileJson(user) {
const profile = { gender: user.gender, birthday: formatDateOnly(user.birthday) };
for (const field of Object.keys(PROFILE_TEXT_FIELDS)) profile[field] = user[field] || "";
return profile;
}
// Validate profile fields from a request body. Fields that are missing from the body are
// left out; blank ones become null.
function parseProfileBody(body) {
const fields = {};
for (const [field, { label, max }] of Object.entries(PROFILE_TEXT_FIELDS)) {
const value = body?.[field];
if (value === undefined || value === null) continue;
if (typeof value !== "string") throw httpError(400, `${label} must be text`);
const trimmed = value.trim();
if (trimmed.length > max) throw httpError(400, `${label} must be at most ${max} characters`);
fields[field] = trimmed || null;
}
if (body?.birthday !== undefined && body?.birthday !== null) {
const birthday = typeof body.birthday === "string" ? body.birthday.trim() : null;
if (birthday) {
const date = new Date(`${birthday}T00:00:00Z`);
if (
!/^\d{4}-\d{2}-\d{2}$/.test(birthday) ||
Number.isNaN(date.getTime()) ||
date.toISOString().slice(0, 10) !== birthday ||
birthday < "1900-01-01" ||
date > new Date()
) {
throw httpError(400, "Birthday must be a valid past date");
}
}
fields.birthday = birthday || null;
}
if (body?.gender !== undefined) {
if (!["male", "female"].includes(body.gender)) throw httpError(400, "Invalid character");
fields.gender = body.gender;
}
return fields;
}
// Show a character change to everyone, including the user's other open tabs.
function broadcastCharacterChange(userId, gender) {
for (const [socketId, socketUserId] of Object.entries(activeSockets)) {
if (Number(socketUserId) !== userId || !players[socketId]) continue;
players[socketId].gender = gender;
io.emit("playerCharacterChanged", { id: socketId, gender });
}
}
app.get("/api/profile", requireAuth, async (req, res) => {
const user = await knex("users").where({ id: req.session.userId }).first();
res.json({ profile: profileJson(user) });
});
// Update any of the profile fields and the character (gender).
app.patch("/api/profile", requireAuth, async (req, res) => {
let fields;
try {
fields = parseProfileBody(req.body);
} catch (error) {
return res.status(error.status || 500).json({ error: error.message });
}
const before = await knex("users").where({ id: req.session.userId }).first();
const [user] = await knex("users")
.where({ id: req.session.userId })
.update({ ...fields, updated_at: knex.fn.now() })
.returning("*");
if (user.gender !== before.gender) broadcastCharacterChange(user.id, user.gender);
res.json({ profile: profileJson(user) });
});
// ─── Projects ───
// Fetch the user's Hackatime projects with their stored token (needs the read scope).
async function fetchHackatimeProjects(accessToken) {
const response = await fetch(`${HACKATIME_URL}/api/v1/authenticated/projects`, {
headers: { Authorization: `Bearer ${accessToken}`, Accept: "application/json" },
});
if (!response.ok) {
console.error("Hackatime projects fetch failed:", await response.text());
throw httpError(502, "Could not load your Hackatime projects");
}
const data = await response.json();
return (data.projects || []).map((project) => ({
name: project.name,
totalSeconds: project.total_seconds || 0,
}));
}
const PROJECT_COLUMNS = [
"id",
"name",
"description",
"iconType",
"hackatimeProjects",
"codeUrl",
"playableUrl",
"updated_at",
];
const MAX_PROJECT_ICON_BYTES = 256 * 1024;