-
Notifications
You must be signed in to change notification settings - Fork 27
/
server.ts
2083 lines (1946 loc) · 88.8 KB
/
server.ts
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
/* eslint-disable prefer-const */
/* eslint-disable jsdoc/require-param */
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/ban-ts-comment */
/* eslint-disable @typescript-eslint/no-unused-vars */
// @ts-check
/* eslint-disable jsdoc/require-returns */
/* eslint-disable jsdoc/require-jsdoc */
// Legacy rplace server software, (c) BlobKat, Zekiah
// For the current server software, go to https://github.com/Zekiah-A/RplaceServer
import { promises as fs } from "fs"
import sha256 from "sha256"
import fsExists from "fs.promises.exists"
import util from "util"
import path from "path"
import * as zcaptcha from "./zcaptcha/server.ts"
import { isUser } from "ipapi-sync"
import { Worker } from "worker_threads"
import cookie from "cookie"
import repl from "basic-repl"
import { $, Server, ServerWebSocket, TLSWebSocketServeOptions } from "bun"
import { DbInternals, LiveChatMessage } from "./db-worker.ts"
import { PublicPromise, ReactionInfo } from "./server-types.ts"
import { distance } from "fastest-levenshtein"
let BOARD:Uint8Array, CHANGES:Uint8Array, PLACERS:Buffer
type ServerConfig = {
"SECURE": boolean,
"CERT_PATH": string,
"KEY_PATH": string,
"PORT": number,
"WIDTH": number,
"HEIGHT": number,
"COOLDOWN": number,
"CAPTCHA": boolean,
"PXPS_SECURITY": boolean,
"ORIGINS": string[],
"PALETTE": number[]|null,
"PALETTE_USABLE_REGION": { start: number, end: number }|null
"USE_CLOUDFLARE": boolean,
"PUSH_LOCATION": string,
"PUSH_PLACE_PATH": string,
"LOCKED": boolean,
"CHAT_WEBHOOK_URL": string,
"MOD_WEBHOOK_URL": string,
"CHAT_MAX_LENGTH": number,
"CHAT_COOLDOWN_MS": number,
"PUSH_INTERVAL_MINS": number,
"CAPTCHA_EXPIRY_SECS": number,
"PERIODIC_CAPTCHA_INTERVAL_SECS": number,
"LINK_EXPIRY_SECS": number,
"CAPTCHA_MIN_MS": number, //min solvetime
"INCLUDE_PLACER": boolean, // pixel placer
"SECURE_COOKIE": boolean,
"CORS_COOKIE": boolean,
"CHALLENGE": boolean,
"TURNSTILE": boolean,
"TURNSTILE_SITE_KEY": string,
"TURNSTILE_PRIVATE_KEY": string,
"CANVAS_ID": number
}
let configFailed = false
let configFile = await fs.readFile("./server_config.json").catch(_ => configFailed = true)
if (configFailed) {
await fs.writeFile("server_config.json", JSON.stringify({
"SECURE": true,
"CERT_PATH": "/etc/letsencrypt/live/path/to/fullchain.pem",
"KEY_PATH": "/etc/letsencrypt/live/server.rplace.live/fullchain.pem",
"PORT": 443,
"WIDTH": 2000,
"HEIGHT": 2000,
"COOLDOWN": 1000,
"CAPTCHA": false,
"PXPS_SECURITY": false,
"ORIGINS": [ "https://rplace.live", "https://rplace.tk" ],
"PALETTE": null,
"PALETTE_USABLE_REGION": null,
"USE_CLOUDFLARE": true,
"PUSH_LOCATION": "https://PUSH_USERNAME:[email protected]/MY_REPO_PATH",
"PUSH_PLACE_PATH": "/path/to/local/git/repo",
"LOCKED": false,
"CHAT_WEBHOOK_URL": "",
"MOD_WEBHOOK_URL": "",
"CHAT_MAX_LENGTH": 400,
"CHAT_COOLDOWN_MS": 2500,
"PUSH_INTERVAL_MINS": 30,
"CAPTCHA_EXPIRY_SECS": 45,
"PERIODIC_CAPTCHA_INTERVAL_SECS": -1,
"LINK_EXPIRY_SECS": 60,
"CAPTCHA_MIN_MS": 100, //min solvetime
"INCLUDE_PLACER": false, // pixel placer
"SECURE_COOKIE": true,
"CORS_COOKIE": false,
"CHALLENGE": false,
"TURNSTILE": false,
"TURNSTILE_SITE_KEY": "",
"TURNSTILE_PRIVATE_KEY": "",
"CANVAS_ID": -1
}, null, 4))
console.log("Config file created, please update it before restarting the server")
process.exit(0)
}
const DEFAULT_EMOJIS = new Map([
[ "rofl", "🤣" ],
[ "joy", "😂" ],
[ "cool", "😎" ],
[ "sunglasses", "😎" ],
[ "heart", "❤️" ],
[ "moyai", "🗿" ],
[ "bruh", "🗿" ],
[ "skull", "💀" ],
[ "sus", "ඞ" ],
[ "tr", "🇹🇷" ],
[ "turkey", "🇹🇷" ],
[ "ir", "🇮🇷" ],
[ "iran", "🇮🇷" ],
[ "uk", "🇬🇧" ],
[ "britain", "🇬🇧" ],
[ "usa", "🇺🇸" ],
[ "america", "🇺🇸" ],
[ "ru", "🇷🇺" ],
[ "russia", "🇷🇺" ],
[ "eyes", "👀" ],
[ "fire", "🔥" ],
[ "thumbsup", "👍" ],
[ "thumbsdown", "👎" ],
[ "clown", "🤡" ],
[ "facepalm", "🤦♂️" ],
[ "ok", "👌" ],
[ "poop", "💩" ],
[ "rocket", "🚀" ],
[ "tada", "🎉" ],
[ "celebration", "🎉" ],
[ "moneybag", "💰" ],
[ "crown", "👑" ],
[ "muscle", "💪" ],
[ "beer", "🍺" ],
[ "pizza", "🍕" ],
[ "cookie", "🍪" ],
[ "balloon", "🎈" ],
[ "gift", "🎁"],
[ "star", "⭐️" ],
[ "love", "😍" ],
[ "crying", "😢" ],
[ "angry", "😠" ],
[ "sleepy", "😴" ],
[ "nerd", "🤓" ],
[ "laughing", "😆" ],
[ "vomiting", "🤮" ],
[ "unicorn", "🦄" ],
[ "alien", "👽" ],
[ "ghost", "👻" ],
[ "skullcrossbones", "☠️" ],
[ "explosion", "💥" ],
[ "shush", "🤫" ],
[ "deaf", "🧏" ],
[ "mew", "🤫🧏" ],
[ "pray", "🙏" ],
[ "thinking", "🤔" ],
[ "sweat", "😅" ],
[ "wave", "👋"]
])
const DEFAULT_CUSTOM_EMOJIS = new Map([
[ "amogus", "custom_emojis/amogus.png" ],
[ "biaoqing", "custom_emojis/biaoqing.png" ],
[ "deepfriedh", "custom_emojis/deepfriedh.png" ],
[ "edp445", "custom_emojis/edp445.png" ],
[ "fan", "custom_emojis/fan.png" ],
[ "heavy", "custom_emojis/heavy.png" ],
[ "herkul", "custom_emojis/herkul.png" ],
[ "kaanozdil", "custom_emojis/kaanozdil.png" ],
[ "lowtiergod", "custom_emojis/lowtiergod.png" ],
[ "manly", "custom_emojis/manly.png" ],
[ "plsaddred", "custom_emojis/plsaddred.png" ],
[ "rplace", "custom_emojis/rplace.png" ],
[ "rplacediscord", "custom_emojis/rplacediscord.png" ],
[ "sonic", "custom_emojis/sonic.png" ],
[ "transparent", "custom_emojis/transparent.png" ],
[ "trollface", "custom_emojis/trollface.png" ]
])
const DEFAULT_PALETTE = [ 0xff1a006d, 0xff3900be, 0xff0045ff, 0xff00a8ff, 0xff35d6ff, 0xffb8f8ff, 0xff68a300, 0xff78cc00, 0xff56ed7e, 0xff6f7500, 0xffaa9e00, 0xffc0cc00, 0xffa45024, 0xffea9036, 0xfff4e951, 0xffc13a49, 0xffff5c6a, 0xffffb394, 0xff9f1e81, 0xffc04ab4, 0xffffabe4, 0xff7f10de, 0xff8138ff, 0xffaa99ff, 0xff2f486d, 0xff26699c, 0xff70b4ff, 0xff000000, 0xff525251, 0xff908d89, 0xffd9d7d4, 0xffffffff ]
let { SECURE, CERT_PATH, PORT, KEY_PATH, WIDTH, HEIGHT, ORIGINS, PALETTE, PALETTE_USABLE_REGION, COOLDOWN, CAPTCHA,
PXPS_SECURITY, USE_CLOUDFLARE, PUSH_LOCATION, PUSH_PLACE_PATH, LOCKED, CHAT_WEBHOOK_URL, MOD_WEBHOOK_URL,
CHAT_MAX_LENGTH, CHAT_COOLDOWN_MS, PUSH_INTERVAL_MINS, CAPTCHA_EXPIRY_SECS, PERIODIC_CAPTCHA_INTERVAL_SECS,
LINK_EXPIRY_SECS, CAPTCHA_MIN_MS, INCLUDE_PLACER, SECURE_COOKIE, CORS_COOKIE, CHALLENGE, TURNSTILE, TURNSTILE_SITE_KEY,
TURNSTILE_PRIVATE_KEY, CANVAS_ID } = JSON.parse(configFile.toString()) as ServerConfig
try {
BOARD = new Uint8Array(await Bun.file(path.join(PUSH_PLACE_PATH, "place")).arrayBuffer())
}
catch(e) {
console.log(e, "(regenerating)")
BOARD = new Uint8Array(WIDTH * HEIGHT)
}
try {
CHANGES = new Uint8Array(await Bun.file(path.join(PUSH_PLACE_PATH, "change")).arrayBuffer())
// Probably corrupted, try changes 2
if (CHANGES.byteLength < WIDTH * HEIGHT)
CHANGES = new Uint8Array(await Bun.file(path.join(PUSH_PLACE_PATH, "change2")).arrayBuffer())
if (CHANGES.byteLength < WIDTH * HEIGHT)
throw new Error("Changes was smaller than expected")
}
catch(e) {
console.log(e, "(regenerating)")
CHANGES = new Uint8Array(WIDTH * HEIGHT).fill(255)
}
try {
PLACERS = Buffer.from(await Bun.file(path.join(PUSH_PLACE_PATH, "placers")).arrayBuffer())
}
catch(e) {
console.log(e, "(regenerating)")
PLACERS = Buffer.alloc(WIDTH * HEIGHT * 4).fill(0xFFFFFFFF)
}
let uidTokenFailed = false
const uidTokenFile = await fs.readFile("uidtoken.txt").catch(_ => uidTokenFailed = true)
let uidToken:string
if (uidTokenFile == null || uidTokenFailed) {
uidToken = "UidToken_" + Math.random().toString(36).slice(2)
await fs.writeFile("uidtoken.txt", uidToken)
}
else {
uidToken = uidTokenFile.toString()
}
let padlock:any = null
if (CHALLENGE) {
const padlockPath = "./padlock/server.ts"
const padlockSource = Bun.file(padlockPath)
if (padlockSource.size !== 0) {
padlock = await import(padlockPath)
}
else {
throw new Error("Could not enable challenge, challenge module not found")
}
}
type PixelInfo = { index: number, colour: number, placer: ServerWebSocket<ClientData> }
const newPixels:PixelInfo[] = []
// Reports must persist between client sessions and be rate limited
let chatNameCooldownMs = 10_000
const chatNameCooldowns = new Map<string, number>()
let reportCooldownMs = 60_000
const reportCooldowns = new Map<string, number>()
let activityCooldownMs = 10_000
const activityCooldowns = new Map<string, number>()
// Cooldowns must persist between client sessions
const cooldowns = new Map<string, number>()
type LinkKeyInfo = {
intId: number,
dateCreated: number,
canvasId: number
}
const linkKeyInfos = new Map<string, LinkKeyInfo>()
/*
* Compress CHANGES with variable run length encoding
*/
function runLengthChanges() {
let changesIndex = 0
let buffers = [Buffer.alloc(256)]
let bufferIndex = 0
let bufferPointer = 0
buffers[0][bufferPointer++] = 2
buffers[0].writeUint32BE(WIDTH, 1)
buffers[0].writeUint32BE(HEIGHT, 5)
bufferPointer += 8
function addToBuffer(value:number) {
buffers[bufferIndex][bufferPointer++] = value
if (bufferPointer === 256) {
bufferPointer = 0
buffers.push(Buffer.alloc(256))
bufferIndex++
}
}
while (true) {
let blankCells = 0
while (CHANGES[changesIndex] == 255) {
blankCells++
changesIndex++
}
if (changesIndex == CHANGES.length) {
break
}
// Two bits are used to store blank cell count
// 00 = no gap
// 01 = 1-byte (Gaps up to 255)
// 10 = 2-byte (Gaps up to 65535)
// 11 = 4-byte (Likely unused)
if (blankCells < 256) {
if(!blankCells){
addToBuffer(CHANGES[changesIndex++])
}
else{
addToBuffer(CHANGES[changesIndex++] + 64)
addToBuffer(blankCells)
}
}
else if (blankCells < 65536) {
addToBuffer(CHANGES[changesIndex++] + 128)
addToBuffer(blankCells >> 8)
addToBuffer(blankCells)
}
else {
addToBuffer(CHANGES[changesIndex++] + 192)
addToBuffer(blankCells >> 24)
addToBuffer(blankCells >> 16)
addToBuffer(blankCells >> 8)
addToBuffer(blankCells)
}
}
buffers[bufferIndex] = buffers[bufferIndex].subarray(0, bufferPointer)
return Buffer.concat(buffers)
}
/** Bidirectional map */
class DoubleMap<T, K> {
foward: Map<T, K>
reverse: Map<K, T>
constructor() {
this.foward = new Map<T, K>()
this.reverse = new Map<K, T>()
}
set(key: T, value: K) {
this.foward.set(key, value)
this.reverse.set(value, key)
}
getForward(key: T) { return this.foward.get(key) }
getReverse(value: K) { return this.reverse.get(value) }
delete(key: T):boolean {
const value = this.foward.get(key)
if (value) {
this.foward.delete(key)
this.reverse.delete(value)
return true
}
return false
}
clear() { this.foward.clear(); this.reverse.clear() }
size() { return this.foward.size }
}
const criticalFiles = ["blacklist.txt", "bansheets.txt", "vip.txt", "reserved_names.txt", "censors.txt"]
for (let i = 0; i < criticalFiles.length; i++) {
const criticalFile = criticalFiles[i]
if (!await fsExists(criticalFile)) {
console.warn("Could not find critical file", criticalFile, "regenerating.")
await fs.writeFile(criticalFile, "")
}
}
/**
* @param {number} length Length of generated random string
* @returns {string} random string
*/
function randomString(length: number) {
const buf = new Uint8Array(length)
crypto.getRandomValues(buf)
let str = ""
for (let i = 0; i < buf.length; i++) {
str += (buf[i].toString(16))
}
return str.slice(0, length)
}
let playersOffset = 0
Object.defineProperty(globalThis, "realPlayers", {
get: function() {
return wss.clients.size
}
})
Object.defineProperty(globalThis, "players", {
// @ts-ignore
get: function() { return realPlayers + playersOffset },
// @ts-ignore
set: function(value) { playersOffset = value - realPlayers }
})
const RESERVED_NAMES = new DoubleMap()
// `reserved_name private_code\n`, for example "zekiah 124215253113\n"
const reservedLines = ((await fs.readFile("reserved_names.txt")).toString()).split('\n')
for (const pair of reservedLines) RESERVED_NAMES.set(pair.split(' ')[0], pair.split(' ')[1])
type BlacklistInfo = { reason: string, date: number }
async function getBansheetsIps() {
const bansheetsText = await fs.readFile("bansheets.txt")
const banListUrls = bansheetsText.toString().trim().split("\n")
const banLists = await Promise.all(
banListUrls.map(banListUrl => fetch(banListUrl)
.then(response => response.text()))
)
const blacklistedIps = banLists
.flatMap((line: string) => line.trim().split("\n")
.filter((line: string) => line.trim() && !line.trim().startsWith("#"))
.map((ip: string): [string, BlacklistInfo] => [ip.split(":")[0].trim(), { reason: "Bansheeted IP", date: 0 }]))
return new Map<string, BlacklistInfo>(blacklistedIps)
}
let BLACKLISTED:Map<string, BlacklistInfo> = await getBansheetsIps()
for (let banLine of (await fs.readFile("blacklist.txt")).toString().split("\n")) {
banLine = banLine.trim()
if (!banLine || banLine.startsWith("#")) {
continue
}
const spaceI = banLine.indexOf(" ")
const ip = banLine.slice(0, spaceI)
let info = banLine.slice(spaceI).trim()
let infoObject:BlacklistInfo|null = null
try { infoObject = JSON.parse(info) } catch(e) {/* Ignore */}
infoObject = Object.assign({ reason: "Blacklisted IP", date: 0 }, infoObject)
BLACKLISTED.set(ip, infoObject)
}
let CENSORS:Array<RegExp> = []
for (let censorPattern of (await fs.readFile("censors.txt")).toString().split("\n")) {
censorPattern = censorPattern.trim()
if (!censorPattern || censorPattern.startsWith("#")) {
continue
}
CENSORS.push(new RegExp(censorPattern, "i"))
}
const toValidate = new Map()
const captchaFailed = new Map()
const encoderUTF8 = new util.TextEncoder()
const decoderUTF8 = new util.TextDecoder()
let dbReqId = 0
let dbWorker = new Worker("./db-worker.ts")
const dbReqs = new Map()
/*
* __Always await this__, and only use in cases where you __WANT the response__, if you want something that
* you can just fire and forget then use postDbMessage instead, which does not result in a dbReq allocation
*/
//@ts-expect-error Chicanery (trust me bro)
async function makeDbRequest<T extends DbInternals>(messageCall: keyof T, args?: Parameters<T[keyof T]>[0]): Promise<Awaited<ReturnType<T[keyof T]>>> {
const handle = dbReqId++
const promise = new PublicPromise()
const postCall = { call: messageCall, data: args, handle: handle }
dbReqs.set(handle, promise)
dbWorker.postMessage(postCall)
//@ts-expect-error Chicanery (trust me bro)
return await promise.promise
}
dbWorker.on("message", (message) => {
dbReqs.get(message.handle)?.resolve(message.data)
})
dbWorker.on("error", console.warn)
//@ts-expect-error Chicanery (trust me bro)
function postDbMessage<T extends DbInternals>(messageCall: keyof T, args?: Parameters<T[keyof T]>[0]):void {
dbWorker.postMessage({ call: messageCall, data: args })
}
const playerIntIds = new Map<ServerWebSocket<ClientData>, number>() // Player ws instance<Object> : intID<Number>
const playerChatNames = new Map<number, string>() // intId<Number> : chatName<String>
let liveChatMessageId:number = (await makeDbRequest("getMaxLiveChatId")) as number || 0
let placeChatMessageId:number = (await makeDbRequest("getMaxPlaceChatId")) as number || 0
const mutes = new Map<string, number>() // IP : finishDate (unix epoch offset ms)
const bans = new Map<string, number>() // IP : finishDate (unix epoch offset ms)
const activeVips = new Map<string, ServerWebSocket<ClientData>>() // String VIP key : client
// vip key, cooldown
const vipTxt = (await fs.readFile("./vip.txt")).toString()
if (!vipTxt) {
Bun.write("./vip.txt",
"# VIP Key configuration file\n" +
"# Below is the correct format of a VIP key configuration:\n" +
"# MY_SHA256_HASHED_VIP_KEY { \"perms\": \"canvasmod\"|\"chatmod\"|\"admin\",\"vip\", \"cooldownMs\": number, \"enforceChatName\": string|null }\n\n" +
"# Example VIP key configuration:\n" +
"# 7eb65b1afd96609903c54851eb71fbdfb0e3bb2889b808ef62659ed5faf09963 { \"perms\": \"admin\", \"cooldownMs\": 30, \"enforceChatName\": \"<ADMIN> zekiah\" }\n" +
"# Make sure all VIP keys stored here are sha256 hashes of the real keys you hand out\n")
}
type VipEntry = {
perms: "admin"|"chatmod"|"vip",
cooldownMs: number,
enforceChatName: string|null
}
function readVip(vipTxt: string):Map<string, VipEntry> {
return new Map(vipTxt
.split("\n")
.filter((line: string) => line.trim() && !line.trim().startsWith("#"))
.map((pair: string) => [ pair.trim().slice(0, 64), JSON.parse(pair.slice(64).trim()) ]))
}
const VIP = readVip(vipTxt)
;(async function() {
for await (const _ of fs.watch("./vip.txt")) {
const beforeKeys = VIP.size
try {
const vipTxt = (await fs.readFile("./vip.txt")).toString()
const newVip = readVip(vipTxt)
const addedKeys = new Map([...newVip].filter(([k]) => !VIP.has(k)))
const removedKeys = new Map([...VIP].filter(([k]) => !newVip.has(k)))
const modifiedKeys = new Map([...newVip].filter(([k, v]) => VIP.has(k) && VIP.get(k) !== v))
// Update VIP map
for (const [k, v] of addedKeys) VIP.set(k, v)
for (const [k] of removedKeys) VIP.delete(k)
for (const [k, v] of modifiedKeys) VIP.set(k, v)
let removedClients = 0
for (const [k, _] of removedKeys) {
const activeClient = activeVips.get(k)
if (activeClient) {
removedClients++
activeClient.close()
}
}
console.log(`Change in VIP config detected, VIP updated: ${beforeKeys} keys -> ${VIP.size} keys detected. ${
addedKeys.size > 0 ? `${addedKeys.size} keys found to be added. `: ""} ${
removedKeys.size > 0 ? `${removedKeys.size} keys found to be removed.`: ""} ${
modifiedKeys.size > 0 ? `${modifiedKeys.size} keys found to be modified. ` : ""} ${
removedClients > 0 ? `${removedClients} active key users removed.` : ""}`)
}
catch(e) {
console.log("Error reading or updating VIP:", e)
}
}
})()
const PUNISHMENT_STATE = {
mute: 0,
ban: 1,
appealRejected: 2,
}
// Fetch all mutes, bans
const muteIdFinishes:any = await makeDbRequest("exec", {
stmt: "SELECT userIntId AS intId, finishDate FROM Mutes WHERE finishDate > ?",
params: Date.now() })
for (const idFinish of muteIdFinishes) {
const idIps:any = await makeDbRequest("exec", {
stmt: "SELECT ip FROM KnownIps WHERE userIntId = ?",
params: idFinish.intId })
for (const ipObject of idIps) {
mutes.set(ipObject.ip, idFinish.finishDate)
}
}
const banIdFinishes:any = await makeDbRequest("exec", {
stmt: "SELECT userIntId AS intId, finishDate FROM Bans WHERE finishDate > ?",
params: Date.now() })
for (const idFinish of banIdFinishes) {
const idIps:any = await makeDbRequest("exec", {
stmt: "SELECT ip FROM KnownIps WHERE userIntId = ?",
params: idFinish.intId })
for (const ipObject of idIps) {
bans.set(ipObject.ip, idFinish.finishDate)
}
}
// Server is player ID 0, all server messages have message ID 0
playerChatNames.set(0, "[email protected]✓")
const allowed = new Set(["rplace.tk", "rplace.live", "discord.gg", "twitter.com", "wikipedia.org", "pxls.space", "reddit.com"])
function censorText(text:string):string {
for (const censorPattern of CENSORS) {
text = text.replace(censorPattern, match => "*".repeat(match.length))
}
return text
.replace(/https?:\/\/(\w+\.)+\w{2,15}(\/\S*)?|(\w+\.)+\w{2,15}\/\S*|(\w+\.)+(tk|ga|gg|gq|cf|ml|fun|xxx|webcam|sexy?|tube|cam|p[o]rn|adult|com|net|org|online|ru|co|info|link)/gi,
match => allowed.has(match.replace(/^https?:\/\//, "").split("/")[0]) ? match : "")
.trim()
}
/**
* @param {number} type - (0|1) message type (0 - Live chat message, 1 - place chat message)
* @param {string} message - Message text content (maxlen(65534))
* @param {number} sendDate - Unix epoch offset __**seconds**__ of message send
* @param {number} messageId - Message integer id (u32)
* @param {number} intId - Sender integer id (u32)
* @param {string?} channel - String channel (maxlen(16))
* @param {number?} repliesTo - Integer message id replies to (u32)
* @param {number?} positionIndex - Index on canvas of place chat message (u32)
* @returns {Buffer} Message packet data prepended with packet code (15)
*/
function createChatPacket(type: number, message: string, sendDate: number, messageId: number, intId: number, channel: string|null = null, repliesTo: number|null = null, reactions: Map<string, number[]>|null = null, positionIndex: number|null = null): Buffer {
let encodedChannel:Uint8Array|null = null
if (channel) encodedChannel = encoderUTF8.encode(channel)
const encodedTxt = encoderUTF8.encode(message)
const msgPacket = Buffer.allocUnsafe(encodedTxt.byteLength +
(type == 0 ? 18 + (encodedChannel?.byteLength || 0) + (repliesTo == null ? 0 : 4) : 16))
let i = 0
msgPacket[i] = 15; i++
msgPacket[i] = type; i++
msgPacket.writeUInt32BE(messageId, i); i += 4
msgPacket.writeUInt16BE(encodedTxt.byteLength, i); i += 2
msgPacket.set(encodedTxt, i); i += encodedTxt.byteLength
msgPacket.writeUInt32BE(intId, i); i += 4
if (type == 0 && encodedChannel != null) { // Live chat message
msgPacket.writeUInt32BE(sendDate, i); i += 4
msgPacket[i] = reactions?.size || 0; i++
if (reactions != null) {
for (const [reactionKey, reactors] of reactions.entries()) {
const encodedReactionKey = encoderUTF8.encode(reactionKey)
msgPacket[i++] = encodedReactionKey.byteLength
msgPacket.set(encodedReactionKey)
msgPacket.writeUint32BE(reactors.length, i)
for (const reactor of reactors) {
msgPacket.writeUint32BE(reactor, i); i += 4
}
}
}
msgPacket[i] = encodedChannel.byteLength; i++
msgPacket.set(encodedChannel, i); i += encodedChannel.byteLength
if (repliesTo != null) {
msgPacket.writeUInt32BE(repliesTo, i); i += 4
}
}
else if (positionIndex != null) { // Place (canvas chat message)
msgPacket.writeUInt32BE(positionIndex, i); i += 4
}
return msgPacket
}
/**
*
* @param {Map<number, string>} names IntId : String names map to be encoded
* @returns {Buffer} Name packet data prepended with packet code (12)
*/
function createNamesPacket(names: Map<number, string>): Buffer {
let size = 1
const encodedNames = new Map()
for (const [intId, name] of names) {
const encName = encoderUTF8.encode(name)
encodedNames.set(intId, encName)
size += encName.length + 5
}
const infoBuffer = Buffer.allocUnsafe(size)
infoBuffer[0] = 12
let i = 1
for (const [intId, encName] of encodedNames) {
infoBuffer.writeUInt32BE(intId, i); i += 4
infoBuffer.writeUInt8(encName.length, i); i++
infoBuffer.set(encName, i); i += encName.length
}
return infoBuffer
}
function createNamePacket(name: string, intId: number): Buffer {
const encName = encoderUTF8.encode(name)
const nmInfoBuf = Buffer.alloc(6 + encName.length)
nmInfoBuf.writeUInt8(12, 0)
nmInfoBuf.writeUInt32BE(intId, 1)
nmInfoBuf.writeUInt8(encName.length, 5)
nmInfoBuf.set(encName, 6)
return nmInfoBuf
}
/**
* @param {typeof PUNISHMENT_STATE.mute|typeof PUNISHMENT_STATE.ban} type Punishment type being applied
* @param {number} startDate Punishment action creation (start) date
* @param {number} finishDate Punishment action finish date
* @param {string} reason Reason set by moderator and shared to client for why they were punished
* @param {string} userAppeal String appeal that the user provided against their own punishment
* @param {boolean} appealRejected Boolean indicating whether appeal is rejected and no logner editable
* @returns {Buffer}
*/
function createPunishPacket(type: typeof PUNISHMENT_STATE.mute | typeof PUNISHMENT_STATE.ban, startDate: number, finishDate: number, reason: string, userAppeal: string, appealRejected: boolean): Buffer {
const encReason = encoderUTF8.encode(reason)
const encAppeal = encoderUTF8.encode(userAppeal)
const buf = Buffer.allocUnsafe(12 + encReason.byteLength + encAppeal.byteLength)
let offset = 0
buf[offset++] = 14
buf[offset++] = type | (appealRejected ? PUNISHMENT_STATE.appealRejected : 0) // state
buf.writeUInt32BE(startDate / 1000, offset); offset += 4
buf.writeUInt32BE(finishDate / 1000, offset); offset += 4
buf[offset++] = encReason.byteLength
buf.set(encReason, offset); offset += encReason.byteLength
buf[offset++] = encAppeal.byteLength
buf.set(encAppeal, offset); offset += encAppeal.byteLength
return buf
}
/**
* If a user changes their intId, they will still be banned, as it applies recursively to every IP used by that intId, however
* they will not receive the detailed info on why they were banned, instead just receiving when their ban finishes. They will also
* not be able to appeal the action
* @param {import('bun').ServerWebSocket} ws - Websocket client that punishments will be applied for
* @param {number} intId - Integer ID of player to have punishments scanned for
* @param {string} ip - IP address of client to have punishments applied and scanned for
*/
async function applyPunishments(ws: ServerWebSocket<ClientData>, intId: number, ip: string) {
async function resolvePunishments(tableName: string, ipFinishMap: Map<string, number>, stateType: number) {
const punishInfo:any = await makeDbRequest("exec", {
stmt: `SELECT startDate, finishDate, reason, userAppeal, appealRejected FROM ${tableName} WHERE userIntId = ?`,
params: intId })
let ipFinish = ipFinishMap.get(ip) ?? null
if (ipFinish && ipFinish < NOW) {
ipFinishMap.delete(ip)
ipFinish = null
}
if (punishInfo && punishInfo.finishDate > NOW) {
if (!ipFinish) {
// Banned user ID on a new IP, ban this IP too
ipFinishMap.set(ip, punishInfo.finishDate)
}
const punishPacket = createPunishPacket(stateType, punishInfo.startDate,
punishInfo.finishDate, punishInfo.reason, punishInfo.userAppeal, punishInfo.appealRejected)
ws.send(punishPacket)
}
else if (ipFinish) {
const punishPacket = createPunishPacket(stateType, NOW, ipFinish, "Unknown", "N/A", true)
ws.send(punishPacket)
}
}
await resolvePunishments("Bans", bans, PUNISHMENT_STATE.ban)
await resolvePunishments("Mutes", mutes, PUNISHMENT_STATE.mute)
}
function rejectPixel(ws:ServerWebSocket<ClientData>, i:number, cd:number) {
const data = Buffer.alloc(10)
data[0] = 7
data.writeInt32BE(Math.ceil(cd / 1000) || 1, 1)
data.writeInt32BE(i, 5)
data[9] = CHANGES[i] == 255 ? BOARD[i] : CHANGES[i]
ws.send(data)
}
type ClientData = {
ip: string,
headers: Headers,
url: string,
codeHash: string,
perms: "vip"|"chatmod"|"canvasmod"|"admin",
lastChat: number,
connDate: number,
cd: number,
intId: number,
token: string,
chatName: string,
voted: number,
challenge: "pending"|"active"|undefined,
turnstile: "active"|undefined,
lastPeriodCaptcha: number,
shadowBanned: boolean,
previousLiveChats: string[],
previousPlaceChats: string[]
}
interface RplaceServer extends Server {
clients: Set<ServerWebSocket<ClientData>>
}
const serverOptions:TLSWebSocketServeOptions<ClientData> = {
async fetch(req: Request, server: Server) {
const url = new URL(req.url)
const cookies = cookie.parse(req.headers.get("Cookie") || "")
const userToken = cookies[uidToken]
// CORS BS
const corsHeaders = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Credentials": "true" }
if (req.method === "OPTIONS") {
const headers = new Headers({
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "*",
"Access-Control-Allow-Headers": "*"
})
return new Response(null, { status: 204, headers: headers })
}
// User wants to link their canvas account to the global auth server, architecture outlined in
// https://github.com/rplacetk/architecture/blob/main/account_linkage.png
if (url.pathname.startsWith("/users/")) {
const targetId = parseInt(url.pathname.slice(7))
if (Number.isNaN(targetId) || typeof targetId !== "number") {
return new Response("Invalid user ID format", {
status: 400,
headers: corsHeaders
})
}
const usersInfo = await makeDbRequest("exec", {
stmt: "SELECT intId, chatName, lastJoined, pixelsPlaced, playTimeSeconds FROM Users WHERE intId = ?1",
params: [ targetId ]
})
if (!usersInfo || !Array.isArray(usersInfo) || usersInfo.length != 1) {
return new Response("Could not find user with specified ID", {
status: 404,
headers: corsHeaders
})
}
const userInfo = usersInfo[0]
for (const p of wss.clients) {
if (p.data.intId === userInfo.intId) {
userInfo.online = true
break
}
}
return new Response(JSON.stringify(userInfo), {
status: 200,
headers: { "Content-Type": "application/json", ...corsHeaders }
})
}
else if (url.pathname.startsWith("/link/")) {
const targetLink = url.pathname.slice(6)
if (!targetLink) {
return new Response("No link key provided", {
status: 400,
headers: corsHeaders
})
}
const info = linkKeyInfos.get(targetLink)
if (info) {
linkKeyInfos.delete(targetLink)
return new Response(JSON.stringify(info), {
status: 200,
headers: { "Content-Type": "application/json", ...corsHeaders }
})
}
return new Response("Provided link key info could not be found", {
status: 404,
headers: corsHeaders
})
}
else {
let newToken:string|null = null
if (!userToken) {
newToken = randomString(32)
}
server.upgrade(req, {
data: {
url: url.pathname.slice(1).trim(),
headers: req.headers,
token: userToken || newToken
},
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": "true",
"Set-Cookie": cookie.serialize(uidToken,
newToken || userToken, {
domain: url.hostname,
expires: new Date(4e12),
httpOnly: true, // Inaccessible from JS
sameSite: CORS_COOKIE ? "lax" : "none", // Cross origin
secure: SECURE_COOKIE, // Only over HTTPS
path: "/"
}),
}
})
return undefined
}
},
websocket: {
async open(ws: ServerWebSocket<ClientData>) {
wss.clients.add(ws)
let realIp:string|undefined = ws.data.ip
if (USE_CLOUDFLARE) realIp = ws.data.headers.get("cf-connecting-ip")?.split(":", 4).join(":")
if (!realIp) realIp = ws.data.headers.get("x-forwarded-for")?.split(",")[0]?.split(":", 4).join(":")
if (!realIp) realIp = ws.remoteAddress.split(":", 4).join(":")
if (!realIp || realIp.startsWith("%")) return ws.close(4000, "No IP")
const IP = ws.data.ip = realIp
const URL = ws.data.url
if (!isUser(IP)) {
ws.close(4000, "Not user")
return
}
const USER_AGENT = ws.data.headers.get("User-Agent")
if (!USER_AGENT) {
ws.close(4000, "No agent")
return
}
let chatName:string|null = null
const ORIGIN = ws.data.headers.get("Origin")
if (ORIGIN == null || (ORIGINS && !ORIGINS.includes(ORIGIN))) {
return ws.close(4000, "No origin")
}
if (BLACKLISTED.has(IP)) return ws.close()
ws.subscribe("all") // receive all ws messages
ws.data.cd = COOLDOWN
if (URL) {
const codeHash = sha256(URL)
const vip = VIP.get(codeHash)
if (!vip) {
return ws.close(4000, "Invalid VIP code. Please do not try again")
}
const existingVip = activeVips.get(codeHash)
existingVip?.close(4000, "You have connected with this VIP code on another session")
activeVips.set(codeHash, ws)
ws.data.codeHash = codeHash
ws.data.perms = vip.perms
ws.data.cd = vip.cooldownMs
if (vip.enforceChatName) {
chatName = vip.enforceChatName
}
}
const CD = ws.data.cd
if (ws.data.perms !== "admin" && ws.data.perms !== "canvasmod") {
if (CAPTCHA) {
await forceCaptchaSolve(ws)
}
if (PERIODIC_CAPTCHA_INTERVAL_SECS > 0) {
ws.data.lastPeriodCaptcha = NOW
}
if (CHALLENGE) {
ws.data.challenge = "pending"
}
if (TURNSTILE) {
const turnstileBuffer = encoderUTF8.encode("\x18" + TURNSTILE_SITE_KEY)
ws.send(turnstileBuffer)
ws.data.turnstile = "active"
}
}
ws.data.lastChat = 0 //last chat
ws.data.connDate = NOW //connection date
ws.data.previousLiveChats = [] // previous live chat messages
ws.data.previousPlaceChats = [] // previous place chat messages
const cooldownBuffer = Buffer.alloc(9)
cooldownBuffer[0] = 1
cooldownBuffer.writeUint32BE(Math.ceil((cooldowns.get(IP)||0) / 1000) || 1, 1)
cooldownBuffer.writeUint32BE(CD + Math.min(500, 0.1 * CD), 5)
ws.send(cooldownBuffer)
ws.send(infoBuffer)
ws.send(runLengthChanges())
// Notify the client about any active canvas restrictions
if (LOCKED) {
const restrictionsBuffer = Buffer.alloc(2)
restrictionsBuffer[0] = 8
restrictionsBuffer[1] = 1
ws.send(restrictionsBuffer)
}
// If a custom palette is defined, then we send to client
// http://www.shodor.org/~efarrow/trunk/html/rgbint.html
if (Array.isArray(PALETTE) || PALETTE_USABLE_REGION) {
const usingPalette = Array.isArray(PALETTE) ? PALETTE : DEFAULT_PALETTE
let pi = 0
const paletteBuffer = Buffer.alloc(4 + usingPalette.length * 4)
paletteBuffer[pi++] = 0
paletteBuffer[pi++] = usingPalette.length
for (let i = 0; i < usingPalette.length; i++) {
paletteBuffer.writeUInt32BE(usingPalette[i], pi); pi += 4
}
const usableRegion = PALETTE_USABLE_REGION || { start: 0, end: usingPalette.length }
paletteBuffer[pi++] = usableRegion.start
paletteBuffer[pi++] = usableRegion.end
ws.send(paletteBuffer)
}
// This section is the only potentially hot DB-related code in the server, investigate optimisatiions
const intId = await makeDbRequest("authenticateUser", { token: ws.data.token, ip: IP, userAgent: USER_AGENT })
if (intId == null || typeof intId != "number") {
console.error(`Could not authenticate user ${IP}, user ID was null, even after new creation`)
return ws.close()
}
ws.data.intId = intId
playerIntIds.set(ws, intId)
const pIdBuf = Buffer.alloc(5)
pIdBuf.writeUInt8(11, 0) // TODO: Integrate into packet 1
pIdBuf.writeUInt32BE(intId, 1)
ws.send(pIdBuf)
if (ws.data.codeHash) {
postDbMessage("updateUserVip", { intId: intId, codeHash: ws.data.codeHash })
}
await applyPunishments(ws, intId, IP)
chatName ??= await makeDbRequest("getUserChatName", intId) as string
if (chatName) {
ws.data.chatName = chatName
playerChatNames.set(intId, chatName)
// Alert all other players of this player's name
const pNameInfoBuf = createNamePacket(chatName, intId)
for (const p of wss.clients) {
if (p !== ws) {
ws.send(pNameInfoBuf)
}
}
}
// Alert this player of all player's names
const nmInfoBuf = createNamesPacket(playerChatNames)
ws.send(nmInfoBuf)
},
async message(ws:ServerWebSocket<ClientData>, data:string|Buffer) {
if (typeof data === "string") return
// Redefine as message handler is now separate from open
const IP = ws.data.ip
const CD = ws.data.cd
switch (data[0]) {
case 4: { // pixel place
if (data.length < 6 || ws.data.shadowBanned === true) {
return
}
const i = data.readUInt32BE(1)
const c = data[5]