Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
3460 lines (3052 loc) · 116 KB
/
Copy pathserver.js
File metadata and controls
3460 lines (3052 loc) · 116 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 http = require("http");
const crypto = require("crypto");
const fs = require("fs");
const path = require("path");
const { WebSocketServer } = require("ws");
const { ensurePluginData, getPluginData, setPluginData } = require("./server/plugin-data");
const { plugins } = require("./server/plugins");
const { atomicWriteJson } = require("./server/atomic-write");
const { createVisitorStats } = require("./server/visitor-stats");
const { registerPublicPlugins } = require("./plugins");
const { createToken, hashAdminToken, tokensMatch, adminTokenMatches } = require("./server/auth-tokens");
const { createAdminSessionStore, parseCookies } = require("./server/admin-sessions");
const { createPlausibleProxy } = require("./server/plausible");
const { createStaticFiles } = require("./server/static-files");
const { makeBucketStore } = require("./server/rate-limit");
const { createSitesWriter } = require("./server/sites-store");
const {
clampPosition,
sanitizeBrowserId,
sanitizeBrowserSecret,
sanitizeBlockedWords,
parseOptionalEmail,
} = require("./server/sanitize");
// Browser admin sessions: a valid token login mints one of these and the id is
// returned in an HttpOnly cookie, so the raw token is not persisted in JS.
const adminSessions = createAdminSessionStore();
loadEnvFile();
// Defense-in-depth: registration is already isolated per-plugin, but never let
// a registration failure prevent the server process from starting.
try {
registerPublicPlugins();
} catch (error) {
console.error("Plugin registration failed; continuing without plugins", error);
}
// Optional plugin injection: TOWNSQUARE_EXTRA_PLUGINS is a comma/space-separated
// list of module paths that self-register via registerPlugin on require. Used by
// the plugin smoke test and by private plugin bundles loaded at deploy time.
for (const entry of String(process.env.TOWNSQUARE_EXTRA_PLUGINS || "").split(/[,\s]+/).filter(Boolean)) {
try {
require(path.resolve(entry));
} catch (error) {
console.error(`Failed to load extra plugin '${entry}'`, error);
}
}
/**
* Tiny demo server for the first playable TownSquare slice.
*
* Responsibilities:
* - serve widget, hosted admin, map, and development assets from ./public
* - keep a short-lived in-memory list of connected visitors
* - treat multiple tabs from the same browser as one visitor identity
* - arbitrate interactive props so seat ownership stays consistent
* - broadcast movement/chat/presence events over WebSocket
*
* Non-goals for this first slice:
* - persistence
* - auth/accounts
* - durable history
* - multi-room routing
*/
const HOST = process.env.HOST || "127.0.0.1";
const PORT = Number(process.env.PORT || 8787);
const SERVICE_ADMIN_PASSWORD = process.env.SERVICE_ADMIN_PASSWORD || "";
const LANDING_ORIGIN = parseHttpOrigin(process.env.LANDING_ORIGIN);
const PLAUSIBLE_DOMAIN = String(process.env.PLAUSIBLE_DOMAIN || "").trim();
const PLAUSIBLE_UPSTREAM = String(process.env.PLAUSIBLE_UPSTREAM || "https://plausible.io").replace(/\/$/, "");
const PLAUSIBLE_SCRIPT_SRC = String(process.env.PLAUSIBLE_SCRIPT_SRC || "/js/script.js").trim();
const PLAUSIBLE_API_PATH = process.env.PLAUSIBLE_API_PATH === undefined
? "/api/event"
: String(process.env.PLAUSIBLE_API_PATH).trim();
const PUBLIC_DIR = path.join(__dirname, "public");
// Optional overlay of extra static assets (e.g. private plugin browser modules)
// served as a fallback after the core public dir. Replaces the dev symlink.
const PLUGIN_ASSETS_DIR = process.env.TOWNSQUARE_PLUGIN_ASSETS_DIR
? path.resolve(process.env.TOWNSQUARE_PLUGIN_ASSETS_DIR)
: null;
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, ".data");
const DEV_TOOLS_ENABLED = envFlag("ENABLE_DEV_TOOLS");
const STAGING_PAGE_ENABLED = envFlag("ENABLE_STAGING_PAGE");
const SITES_FILE = path.join(DATA_DIR, "sites.json");
const MAP_WORLD_FILE = path.join(DATA_DIR, "map-world.json");
const VISITOR_STATS_FILE = path.join(DATA_DIR, "visitor-stats.json");
const DEFAULT_MAP_WORLD_FILE = path.join(PUBLIC_DIR, "default-map-world.json");
let ALLOWED_ORIGINS = new Set();
const DEFAULT_DEV_ORIGINS = new Set([
`http://${HOST}:${PORT}`,
`http://127.0.0.1:${PORT}`,
`http://localhost:${PORT}`,
`https://${HOST}:${PORT}`,
`https://127.0.0.1:${PORT}`,
`https://localhost:${PORT}`,
]);
const MAX_SITE_CONNECTION_LIMIT = 1000;
const DEFAULT_CONNECTION_LIMIT = Math.min(MAX_SITE_CONNECTION_LIMIT, Math.max(1, readLimit("MAX_CONNECTIONS", 100)));
const MAX_WS_PAYLOAD_BYTES = Number(process.env.MAX_WS_PAYLOAD_BYTES || 512);
const MAX_READING_URL_LEN = 240;
const MAX_SITE_NAME_LEN = 80;
const MAX_ORIGIN_LEN = 240;
const MAX_PAGE_URL_LEN = 512;
const REGISTRATIONS_PER_HOUR = Number(process.env.REGISTRATIONS_PER_HOUR || 20);
const AUTH_FAILURES_PER_HOUR = Number(process.env.AUTH_FAILURES_PER_HOUR || 30);
const IP_MAX_IDENTITIES = readLimit("IP_MAX_IDENTITIES", 2);
const IP_JOIN_LIMIT = readLimit("IP_JOIN_LIMIT", 30);
const IP_STATE_EVENT_LIMIT = readLimit("IP_STATE_EVENT_LIMIT", 600);
const IP_CHAT_EVENT_LIMIT = readLimit("IP_CHAT_EVENT_LIMIT", 20);
// Behavioral flood ban: count rename + chat actions per IP over a rolling
// window. Crossing FLOOD_BAN_LIMIT is non-human (the abuse bot renames several
// times a second), so the IP is persistently blocked — but only when
// FLOOD_BAN_ENFORCE is set. Unset (default) is dry-run: it logs `flood_detect`
// with the rate it *would* ban and changes nothing, so the threshold can be
// validated against real traffic before it can act. Owners are exempt.
const FLOOD_BAN_LIMIT = readLimit("FLOOD_BAN_LIMIT", 30);
const FLOOD_BAN_WINDOW_MS = readLimit("FLOOD_BAN_WINDOW_MS", 10000);
const FLOOD_BAN_ENFORCE = process.env.FLOOD_BAN_ENFORCE === "1";
const IP_SYNC_ACTION_ROUNDS = readLimit("IP_SYNC_ACTION_ROUNDS", 3);
const IP_SYNC_ACTION_WINDOW_MS = readLimit("IP_SYNC_ACTION_WINDOW_MS", 10000);
const IP_SYNC_ACTION_TOLERANCE_MS = readLimit("IP_SYNC_ACTION_TOLERANCE_MS", 250);
const IP_QUARANTINE_MS = readLimit("IP_QUARANTINE_MS", 10 * 60 * 1000);
// Hard cap on the per-(scene, IP) activity map so a flood of distinct keys
// (including spoofed x-real-ip behind a proxy) can't grow it without bound.
const MAX_IP_ACTIVITY_ENTRIES = readLimit("MAX_IP_ACTIVITY_ENTRIES", 50000);
const IP_JOIN_WINDOW_MS = 60 * 1000;
const IP_EVENT_WINDOW_MS = 10 * 1000;
const LAST_SEEN_SAVE_INTERVAL_MS = 60000;
const MOVE_THROTTLE_MS = 40;
const ACTION_THROTTLE_MS = 560;
const DEFAULT_CHAT_THROTTLE_MS = 500;
const MAX_CHAT_THROTTLE_MS = 30000;
const MAX_MODERATION_LOG = 50;
const RECONNECT_GRACE_MS = 1500;
const INACTIVE_DISCONNECT_MS = Number(process.env.INACTIVE_DISCONNECT_MS || 30 * 60 * 1000);
const INACTIVE_CHECK_INTERVAL_MS = Number(process.env.INACTIVE_CHECK_INTERVAL_MS || 60000);
const HEARTBEAT_INTERVAL_MS = 30000;
const BIRD_TICK_INTERVAL_MS = 1000;
// Minimum delay between a visitor joining and their first chat message. A human
// cannot read the widget and type within this window, so faster messages are the
// scripted enter-say-leave pattern and are dropped. 0 disables the check.
const MIN_HUMAN_SAY_MS = readLimit("MIN_HUMAN_SAY_MS", 1500);
// Proof-of-work difficulty (leading zero bits) for the per-site bot-protection
// gate. Sent to the widget in the challenge, so it is tunable without shipping a
// new widget. Higher costs the client more CPU per join.
const POW_DIFFICULTY_BITS = readLimit("POW_DIFFICULTY_BITS", 15);
// Emit one structured JSON line per new visitor join (name, IP, a stable
// per-site browser fingerprint, origin, PoW status) so abuse can be diagnosed
// from server logs. On by default; set LOG_JOINS=0 to silence.
const LOG_JOINS = process.env.LOG_JOINS !== "0";
const BIRD_FLEE_RADIUS = 0.07;
const VALID_ACTIONS = new Set(["jump", "raise-hand", "high-five"]);
const BIRD_SPAWN_MIN_MS = Number(process.env.BIRD_SPAWN_MIN_MS || 12000);
const BIRD_SPAWN_MAX_MS = Number(process.env.BIRD_SPAWN_MAX_MS || 22000);
const BIRD_FIRST_SPAWN_MS = Number(process.env.BIRD_FIRST_SPAWN_MS || 500);
// Wire-protocol limits and the character palette, shared with the widget.
// Populated from public/shared/shared-constants.mjs in startServer (the server is
// CommonJS, so the shared ES module is loaded via dynamic import).
let MAX_MESSAGE_LEN;
let MAX_DISPLAY_NAME_LEN;
let MAX_READING_LABEL_LEN;
let MAX_RECENT_MESSAGES;
let HIGH_FIVE_DISTANCE;
let DEFAULT_CHARACTER_COLOR;
let DEFAULT_OWNER_BADGE_COLOR;
/** @type {Set<string>} */
let CHARACTER_COLORS = new Set();
/** @type {Set<string>} */
let OWNER_BADGE_COLORS = new Set();
/** @type {() => number} */
let randomSpawnX;
function envFlag(name) {
const value = String(process.env[name] || "").trim().toLowerCase();
return value === "1" || value === "true" || value === "yes";
}
function readLimit(name, fallback) {
const value = Number(process.env[name]);
return Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;
}
function loadEnvFile(filePath = path.join(__dirname, ".env")) {
try {
const raw = fs.readFileSync(filePath, "utf8");
for (const line of raw.split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) continue;
const separator = trimmed.indexOf("=");
if (separator === -1) continue;
const key = trimmed.slice(0, separator).trim();
let value = trimmed.slice(separator + 1).trim();
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) || Object.hasOwn(process.env, key)) continue;
if (
(value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))
) {
value = value.slice(1, -1);
}
process.env[key] = value;
}
} catch (error) {
if (error.code !== "ENOENT") {
console.warn(`Could not load .env: ${error.message}`);
}
}
}
function parseHttpOrigin(value) {
if (!value) return "";
try {
const url = new URL(String(value));
return ["http:", "https:"].includes(url.protocol) ? url.origin : "";
} catch {
return "";
}
}
/** @type {Map<string, import("./public/shared/scene-props.mjs").SceneProp>} */
let PROPS_BY_ID = new Map();
/** @type {Array<import("./public/shared/bird-perches.mjs").BirdPerch>} */
let BIRD_PERCHES = [];
// Shared realtime protocol vocabulary, assigned from protocol.mjs in
// loadSharedModules() before the server starts listening.
let MSG;
let GESTURE;
let BIRD_ACTION;
// Assigned synchronously from site-config-core.mjs once loadSharedModules()
// resolves — before server.listen(), so requests never see them unset. (No
// stub re-implementations: those were a second, divergent source of truth.)
let DEFAULT_SITE_SCENE_CONFIG;
let DEFAULT_SITE_STYLE;
let sanitizeSceneConfig;
let sanitizeConnections;
let sanitizeMessageBoard;
let sanitizeSiteStyle;
let buildSceneProps;
let buildBirdPerches;
let buildSiteCss;
/** @type {(prop: import("./public/shared/site-config-core.mjs").SceneProp, x: number) => boolean} */
let isWithinPropSettleZone = () => false;
let validateMapWorld;
/** @type {(storedWorld: object, siteCount: number) => object} */
let resolveMapWorld = (storedWorld) => storedWorld;
let mapWorld;
let normalizeOrigin;
let buildAllowedOrigins = (origin) => (origin ? [origin] : []);
let getMatchingWwwOrigin = () => null;
function parseAllowedOrigins(value) {
return new Set(
String(value)
.split(",")
.map((origin) => origin.trim())
.filter(Boolean)
.map((origin) => normalizeOrigin(origin))
.filter(Boolean),
);
}
function isAllowedOrigin(origin, hostHeader) {
if (!origin) {
return true;
}
const normalized = normalizeOrigin(origin);
if (!normalized) return false;
if (DEFAULT_DEV_ORIGINS.has(normalized)) return true;
try {
const originUrl = new URL(normalized);
const requestHost = String(hostHeader || "").trim().toLowerCase();
if (requestHost && originUrl.host.toLowerCase() === requestHost) {
return true;
}
} catch {
return false;
}
if (ALLOWED_ORIGINS.size === 0) return false;
return ALLOWED_ORIGINS.has(normalized);
}
function isPlainObject(value) {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
const MESSAGE_HANDLERS = {
action: handleAction,
init: handleInit,
move: handleMove,
profile: handleProfile,
reading: handleReading,
sceneConfig: handleSceneConfig,
settle: handleSettle,
say: handleSay,
solve: handleSolve,
typing: handleTyping,
};
/** @returns {{connectionId:number,ws:any,scene:any,site:any,origin:string,ip:string,propsById:Map<string, any>,identity:any,joined:boolean,readingActive:boolean,typing:boolean,lastMoveAt:number,lastActionAt:number,lastChatAt:number}} */
function createClient(connectionId, ws, scene, site, origin = "", ip = "unknown") {
return {
connectionId,
ws,
scene,
site,
origin,
ip,
propsById: scene.propsById,
identity: null,
joined: false,
readingActive: false,
lastMoveAt: 0,
lastActionAt: 0,
lastChatAt: 0,
typing: false,
challenge: null,
powVerified: false,
pendingInit: null,
};
}
// Count the leading zero bits of a hash buffer, used to grade proof-of-work.
function leadingZeroBits(buffer) {
let bits = 0;
for (const byte of buffer) {
if (byte === 0) {
bits += 8;
continue;
}
bits += Math.clz32(byte) - 24;
break;
}
return bits;
}
// Issue a fresh per-connection proof-of-work challenge. The salt is random so a
// solution cannot be precomputed or replayed across connections.
function issuePowChallenge(client) {
const salt = crypto.randomBytes(16).toString("hex");
client.challenge = { salt, difficulty: POW_DIFFICULTY_BITS };
send(client.ws, { type: MSG.CHALLENGE, salt, difficulty: POW_DIFFICULTY_BITS });
}
function verifyPow(challenge, nonce) {
if (!challenge || typeof nonce !== "string" || nonce.length === 0 || nonce.length > 64) return false;
const hash = crypto.createHash("sha256").update(`${challenge.salt}:${nonce}`).digest();
return leadingZeroBits(hash) >= challenge.difficulty;
}
function handleSolve(client, message) {
if (client.powVerified || !client.challenge) return;
if (!verifyPow(client.challenge, message.nonce)) {
client.ws.close(1008, "challenge failed");
return;
}
client.powVerified = true;
client.challenge = null;
const pending = client.pendingInit;
client.pendingInit = null;
if (pending) handleInit(client, pending);
}
function syncClientSceneProps(client, message) {
if (client.site) {
client.propsById = client.scene.propsById;
return;
}
const config = isPlainObject(message.sceneConfig) ? message.sceneConfig : DEFAULT_SITE_SCENE_CONFIG;
const props = buildSceneProps(sanitizeSceneConfig(config));
client.propsById = new Map(props.map((prop) => [prop.id, prop]));
}
/** @returns {{id:number,browserId:string,browserSecret:string,x:number,pose:string|null,propId:string|null,displayName:string,color:string,readingLabel:string,readingUrl:string,readingActive:boolean,isOwner:boolean,clients:Set<any>,joined:boolean,leaveTimer:any,inactiveKick:boolean,lastActivityAt:number,awaySince:number|null,messages:Array<{text:string,at:number}>}} */
function createIdentity(id, browserId, x) {
return {
id,
browserId,
browserSecret: crypto.randomBytes(32).toString("hex"),
x,
pose: null,
propId: null,
displayName: "",
color: DEFAULT_CHARACTER_COLOR,
readingLabel: "",
readingUrl: "",
readingActive: false,
isOwner: false,
clients: new Set(),
joined: false,
leaveTimer: null,
inactiveKick: false,
lastActivityAt: 0,
joinedAt: 0,
awaySince: null,
messages: [],
};
}
function sanitizeMessage(text) {
if (typeof text !== "string") return "";
return text.trim().slice(0, MAX_MESSAGE_LEN);
}
/** Per-site slow-mode cooldown, clamped to a sane range; falls back to default. */
function sanitizeChatThrottle(input) {
const ms = Number(input);
if (!Number.isFinite(ms) || ms < 0) return DEFAULT_CHAT_THROTTLE_MS;
return Math.min(Math.round(ms), MAX_CHAT_THROTTLE_MS);
}
/** Per-site concurrent WebSocket cap, persisted on each site record. */
function sanitizeConnectionLimit(input) {
const limit = Number(input);
if (!Number.isFinite(limit) || limit < 1) return DEFAULT_CONNECTION_LIMIT;
return Math.min(Math.round(limit), MAX_SITE_CONNECTION_LIMIT);
}
function escapeRegExp(text) {
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
/**
* Mask any forbidden word in `text` with asterisks. Whole-word and
* case-insensitive so innocent substrings (the Scunthorpe problem) survive.
* Returns the text unchanged when the site has no word list.
*/
function applyWordFilter(text, words) {
if (!text || !Array.isArray(words) || words.length === 0) return text;
let filtered = text;
for (const word of words) {
const pattern = new RegExp(`\\b${escapeRegExp(word)}\\b`, "gi");
filtered = filtered.replace(pattern, (match) => "*".repeat(match.length));
}
return filtered;
}
/** Names are visible to everyone, so they run through the same word filter. */
function filterDisplayName(site, name) {
return site ? applyWordFilter(name, site.blockedWords) : name;
}
/**
* The verified owner badge is a 👑 the server renders next to a name only when
* it has stamped `isOwner` on that identity. A visitor could otherwise fake the
* badge by simply typing a crown (or a crown-like confusable) into their own
* name. Strip those glyphs from every display name so the crown stays a signal
* the server alone can grant. Covers the crown emoji plus the obvious royalty /
* chess-king/queen lookalikes; ordinary letters are untouched.
*/
const OWNER_BADGE_LOOKALIKES = /[\u{1F451}\u{1F934}\u{1F478}\u{1FAC5}♔♕♚♛]/gu;
function stripOwnerBadgeLookalikes(text) {
return text.replace(OWNER_BADGE_LOOKALIKES, "");
}
function sanitizeDisplayName(displayName) {
if (typeof displayName !== "string") return "";
return stripOwnerBadgeLookalikes(displayName)
.trim()
.replace(/\s+/g, " ")
.slice(0, MAX_DISPLAY_NAME_LEN);
}
function sanitizeReadingLabel(readingLabel) {
if (typeof readingLabel !== "string") return "";
return readingLabel.trim().replace(/\s+/g, " ").slice(0, MAX_READING_LABEL_LEN);
}
function sanitizeReadingUrl(readingUrl) {
if (typeof readingUrl !== "string") return "";
try {
const url = new URL(readingUrl.slice(0, MAX_READING_URL_LEN));
return url.protocol === "http:" || url.protocol === "https:" ? url.href : "";
} catch {
return "";
}
}
function parseReadingUrl(readingUrl) {
const sanitized = sanitizeReadingUrl(readingUrl);
if (!sanitized) return null;
try {
return new URL(sanitized);
} catch {
return null;
}
}
function labelFromReadingUrl(url) {
const segment = url.pathname.split("/").filter(Boolean).pop() || "";
if (!segment) return sanitizeReadingLabel(url.hostname.replace(/^www\./, ""));
try {
return sanitizeReadingLabel(decodeURIComponent(segment)
.replace(/\.[a-z0-9]+$/i, "")
.replace(/[-_]+/g, " "));
} catch {
return sanitizeReadingLabel(segment.replace(/[-_]+/g, " "));
}
}
function readingUrlAllowedForClient(client, url) {
const urlOrigin = normalizeOrigin(url.origin);
if (!urlOrigin) return false;
if (client.site) return isOriginAllowedForSite(urlOrigin, client.site);
return !client.origin || urlOrigin === client.origin;
}
function sanitizeReadingState(client, message, fallback = {}) {
const hasReadingUrl = Object.hasOwn(message, "readingUrl");
const readingUrl = hasReadingUrl ? parseReadingUrl(message.readingUrl) : parseReadingUrl(fallback.readingUrl || "");
if (!readingUrl || !readingUrlAllowedForClient(client, readingUrl)) {
return { readingLabel: "", readingUrl: "" };
}
return {
readingLabel: labelFromReadingUrl(readingUrl),
readingUrl: readingUrl.href,
};
}
function sanitizeCharacterColor(color) {
return CHARACTER_COLORS.has(color) ? color : DEFAULT_CHARACTER_COLOR;
}
function sanitizeOwnerBadgeColor(color) {
return OWNER_BADGE_COLORS.has(color) ? color : DEFAULT_OWNER_BADGE_COLOR;
}
/**
* A site owner's name/color is "claimed" alongside their ownership so it
* survives client-side profile resets and server restarts. Profiles are keyed
* by browserId and live on the site record next to `ownerBrowserIds`.
*/
function getOwnerProfile(site, browserId) {
if (!site || !isPlainObject(site.ownerProfiles)) return null;
const profile = site.ownerProfiles[browserId];
return isPlainObject(profile) ? profile : null;
}
/** Persist the current name/color for an owner so it re-applies on rejoin. */
function rememberOwnerProfile(site, identity) {
if (!site || !identity || !identity.isOwner) return;
if (!isPlainObject(site.ownerProfiles)) site.ownerProfiles = {};
const current = getOwnerProfile(site, identity.browserId) || {};
site.ownerProfiles[identity.browserId] = {
displayName: identity.displayName,
color: identity.color,
badgeColor: sanitizeOwnerBadgeColor(current.badgeColor || identity.badgeColor),
};
touchSite(site);
}
/** Re-apply a stored owner profile onto an identity, if one exists. */
function applyOwnerProfile(site, identity) {
const profile = getOwnerProfile(site, identity.browserId);
if (!profile) return;
identity.displayName = sanitizeDisplayName(profile.displayName);
identity.color = sanitizeCharacterColor(profile.color);
identity.badgeColor = sanitizeOwnerBadgeColor(profile.badgeColor);
}
/**
* Opaque, stable reference for an owner used by the admin "Site owner" editor.
* Lets the admin manage owners without the raw browserId ever leaving the
* server (kept consistent with the visitor payload, which omits browserId too).
*/
function ownerHandle(siteKey, browserId) {
return crypto.createHash("sha256").update(`${siteKey}:${browserId}`).digest("hex").slice(0, 16);
}
// One structured line per genuine new join, for diagnosing bot/abuse patterns
// from server logs. The browser fingerprint is the same per-site hash the admin
// editor uses (ownerHandle), so a bot reusing its browserId shows a stable `fp`
// across joins; a rotating one shows a fresh `fp` each time. Raw browserId never
// leaves the server.
function logJoin(client, identity) {
if (!LOG_JOINS) return;
const site = client.site;
console.log(JSON.stringify({
event: "join",
at: new Date().toISOString(),
site: site ? site.siteKey : null,
scene: client.scene.key,
name: identity.displayName,
ip: client.ip,
fp: site ? ownerHandle(site.siteKey, identity.browserId) : null,
origin: client.origin || null,
powVerified: Boolean(client.powVerified),
botProtection: Boolean(site && site.botProtection),
}));
}
/** The site's owners with their persisted look, for the dedicated admin section. */
function getOwners(site, scene) {
if (!site || !Array.isArray(site.ownerBrowserIds)) return [];
return site.ownerBrowserIds.map((browserId) => {
const profile = getOwnerProfile(site, browserId) || {};
const identity = scene ? scene.identityByBrowser.get(browserId) : null;
return {
handle: ownerHandle(site.siteKey, browserId),
displayName: typeof profile.displayName === "string" ? profile.displayName : "",
color: sanitizeCharacterColor(profile.color),
badgeColor: sanitizeOwnerBadgeColor(profile.badgeColor),
online: Boolean(identity && identity.clients && identity.clients.size > 0),
};
});
}
function sanitizeSiteName(name, origin) {
const cleanName = typeof name === "string" ? name.trim().slice(0, MAX_SITE_NAME_LEN) : "";
if (cleanName) return cleanName;
try {
return new URL(origin).hostname;
} catch {
return "Untitled site";
}
}
function readJsonBody(req, res, callback, maxBytes = 4096) {
let raw = "";
req.on("data", (chunk) => {
raw += chunk;
if (raw.length > maxBytes) {
res.writeHead(413, { "content-type": "application/json; charset=utf-8" });
res.end(JSON.stringify({ error: "request too large" }));
req.destroy();
}
});
req.on("end", () => {
if (!raw) {
callback({});
return;
}
try {
const parsed = JSON.parse(raw);
callback(isPlainObject(parsed) ? parsed : {});
} catch {
res.writeHead(400, { "content-type": "application/json; charset=utf-8" });
res.end(JSON.stringify({ error: "invalid json" }));
}
});
}
function sendJson(res, status, body, extraHeaders = null) {
res.writeHead(status, {
"content-type": "application/json; charset=utf-8",
...(extraHeaders || {}),
});
res.end(JSON.stringify(body));
}
function sendPublicJson(res, status, body) {
res.writeHead(status, {
"content-type": "application/json; charset=utf-8",
"cache-control": "no-store",
"access-control-allow-origin": "*",
});
res.end(JSON.stringify(body));
}
function getAdminSiteByCredentials(siteKey, adminToken) {
const site = sitesByKey.get(siteKey);
if (!adminTokenMatches(site, adminToken)) return null;
return site;
}
function findSiteByAdminToken(adminToken) {
const token = typeof adminToken === "string" ? adminToken.trim() : "";
if (!token) return null;
for (const site of sitesByKey.values()) {
if (adminTokenMatches(site, token)) return site;
}
return null;
}
function getPublicOrigin(req) {
if (process.env.PUBLIC_ORIGIN) {
return normalizeOrigin(process.env.PUBLIC_ORIGIN);
}
const forwardedProto = String(req.headers["x-forwarded-proto"] || "").split(",")[0].trim();
const proto = forwardedProto === "https" ? "https" : "http";
return normalizeOrigin(`${proto}://${req.headers.host || `${HOST}:${PORT}`}`);
}
function getSceneConfig(site) {
return sanitizeSceneConfig(site?.sceneConfig || DEFAULT_SITE_SCENE_CONFIG);
}
function getStyleConfig(site) {
return sanitizeSiteStyle(site?.styleConfig || DEFAULT_SITE_STYLE);
}
function getConnections(site) {
return sanitizeConnections(site?.connections || []);
}
function getMessageBoard(site) {
return sanitizeMessageBoard(site?.messageBoard || {});
}
function getSceneProps(site) {
return site ? buildSceneProps(getSceneConfig(site)) : Array.from(PROPS_BY_ID.values());
}
function getSceneBirdPerches(site) {
return site ? buildBirdPerches(getSceneProps(site)) : BIRD_PERCHES;
}
function buildStyleSnippet(site) {
return buildSiteCss(getStyleConfig(site));
}
function getAllowedOrigins(site) {
if (!site) return [];
const origins = [];
const seen = new Set();
const add = (value) => {
const normalized = normalizeOrigin(value || "");
if (!normalized || seen.has(normalized)) return;
seen.add(normalized);
origins.push(normalized);
};
add(site.origin);
if (Array.isArray(site.allowedOrigins)) {
site.allowedOrigins.forEach(add);
}
return origins;
}
function siteUsesMatchingWwwOrigin(site) {
if (!site) return false;
const matching = getMatchingWwwOrigin(site.origin);
return Boolean(matching && getAllowedOrigins(site).includes(matching));
}
function parseSiteOriginSettings(body, { defaultIncludeMatchingWww = true } = {}) {
const origin = normalizeOrigin(String(body.origin || "").slice(0, MAX_ORIGIN_LEN));
if (!origin) {
return { error: "Enter a valid website origin, like https://example.com." };
}
const includeMatchingWww = body.includeMatchingWww === undefined
? defaultIncludeMatchingWww
: Boolean(body.includeMatchingWww);
return {
origin,
allowedOrigins: buildAllowedOrigins(origin, { includeMatchingWww }),
includeMatchingWww,
};
}
function buildEmbedSnippet(req, site) {
const serverOrigin = getPublicOrigin(req);
const pluginModules = plugins.browserModules("widget", pluginContext(site));
// Scene, connections, and the message board are delivered live over the socket
// (see the `hello` payload), not baked here, so this snippet is install-once:
// owners paste it a single time and manage everything else from the dashboard.
// Power users can still pin any of those fields inline to take them off live
// management (see README → Customization).
const coreConfig = {
serverOrigin,
siteKey: site.siteKey,
...(pluginModules.length > 0 ? { pluginModules } : {}),
theme: "host",
};
const extendedConfig = plugins.extend("extendWidgetConfig", coreConfig, pluginContext(site));
const widgetConfig = isPlainObject(extendedConfig) ? extendedConfig : coreConfig;
const configLines = Object.entries(widgetConfig)
.filter(([key]) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key))
.map(([key, value]) => ` ${key}: ${JSON.stringify(value)}`)
.join(",\n");
// `preconnect` warms the DNS/TLS handshake to the widget origin before the
// module import fires, shaving a round trip off a cross-origin embed. `async`
// on the module lets it run the moment it arrives instead of waiting in the
// defer queue, so the widget never delays the host page's own work.
return `<link rel="preconnect" href="${serverOrigin}" crossorigin />
<link rel="stylesheet" href="${serverOrigin}/widget.css" />
<div id="townsquare-root"></div>
<script type="module" async>
import { mountTownSquare } from "${serverOrigin}/townsquare.mjs";
mountTownSquare(document.getElementById("townsquare-root"), {
${configLines}
});
</script>`;
}
function buildAdminUrl(req, adminToken) {
const serverOrigin = getPublicOrigin(req);
const url = new URL("/admin", `${serverOrigin}/`);
url.hash = new URLSearchParams({ adminToken }).toString();
return url.toString();
}
// Cookies are only marked Secure over https, otherwise the browser would drop
// them on plain-http local dev.
function requestIsSecure(req) {
return getPublicOrigin(req).startsWith("https://");
}
function buildSessionCookie(id, maxAgeMs, secure) {
const attrs = [
`${adminSessions.cookieName}=${id}`,
"HttpOnly",
"SameSite=Strict",
"Path=/api/admin",
`Max-Age=${Math.floor(maxAgeMs / 1000)}`,
];
if (secure) attrs.push("Secure");
return attrs.join("; ");
}
function clearSessionCookie(secure) {
const attrs = [
`${adminSessions.cookieName}=`,
"HttpOnly",
"SameSite=Strict",
"Path=/api/admin",
"Max-Age=0",
];
if (secure) attrs.push("Secure");
return attrs.join("; ");
}
function readSessionFromCookie(req) {
const cookies = parseCookies(req.headers.cookie);
return adminSessions.get(cookies[adminSessions.cookieName]);
}
/**
* Authenticate an admin request, preferring an HttpOnly session cookie over the
* bootstrap token in the body. On a successful token bootstrap a fresh session
* is minted and a Set-Cookie header is returned so the raw token is not needed
* (nor resent) again.
*
* @returns {{ site: any, tokenPresented: boolean, setCookie: string|null }|null}
*/
function resolveAdminRequest(req, body) {
const requestedKey = String(body.siteKey || "");
const token = String(body.adminToken || "").trim();
// 1) Existing session cookie. The cookie's site must match an explicitly
// requested siteKey so a session can't be aimed at another site.
const session = readSessionFromCookie(req);
if (session) {
const site = sitesByKey.get(session.siteKey);
if (site && (!requestedKey || requestedKey === session.siteKey)) {
return { site, tokenPresented: token.length > 0, setCookie: null };
}
}
// 2) Bootstrap token in the body. Mint a session cookie on success.
if (token) {
const site = getAdminSiteByCredentials(requestedKey, token);
if (site) {
const created = adminSessions.create(site.siteKey, { remember: Boolean(body.rememberMe) });
return {
site,
tokenPresented: true,
setCookie: buildSessionCookie(created.id, created.maxAgeMs, requestIsSecure(req)),
};
}
}
return null;
}
const registrationsByIp = makeBucketStore();
const adminAuthFailuresByIp = makeBucketStore();
const serviceAdminAuthFailuresByIp = makeBucketStore();
const activityByIpAndScene = new Map();
function getRequestIp(req) {
const remote = req.socket.remoteAddress || "unknown";
const fromLoopback = remote === "127.0.0.1" || remote === "::1" || remote === "::ffff:127.0.0.1";
const proxyIp = fromLoopback ? String(req.headers["x-real-ip"] || "").trim() : "";
return proxyIp && !/[\s,]/.test(proxyIp) ? proxyIp.slice(0, 64) : remote;
}
function getIpActivity(scene, ip, now = Date.now()) {
const key = `${scene.key}\0${ip}`;
let activity = activityByIpAndScene.get(key);
if (!activity) {
if (activityByIpAndScene.size >= MAX_IP_ACTIVITY_ENTRIES) {
enforceIpActivityCap(now);
}
activity = { lastSeenAt: now, budgets: new Map() };
activityByIpAndScene.set(key, activity);
}
activity.lastSeenAt = now;
return activity;
}
// Bound activityByIpAndScene so a flood of distinct (scene, spoofed-IP) keys —
// including quarantined ones, which pruneIpActivity deliberately keeps — can't
// grow it without limit. Drop stale entries first, then, if still at the cap,
// evict the least-recently-seen entries (preferring un-quarantined ones) down
// to 90% in a single batch so this stays amortized cheap per insert.
function enforceIpActivityCap(now = Date.now()) {
pruneIpActivity(now);
const target = Math.floor(MAX_IP_ACTIVITY_ENTRIES * 0.9);
if (activityByIpAndScene.size <= target) return;
const byAge = Array.from(activityByIpAndScene.entries())
.sort((a, b) => a[1].lastSeenAt - b[1].lastSeenAt);
for (const [key, activity] of byAge) {
if (activityByIpAndScene.size <= target) break;
if ((activity.quarantinedUntil || 0) > now) continue;
activityByIpAndScene.delete(key);
}
for (const [key] of byAge) {
if (activityByIpAndScene.size <= target) break;
activityByIpAndScene.delete(key);
}
}
function consumeIpBudget(client, type, limit, windowMs, now = Date.now()) {
if (limit <= 0) return true;
const activity = getIpActivity(client.scene, client.ip, now);
let budget = activity.budgets.get(type);
if (!budget || now - budget.startedAt >= windowMs) {
budget = { startedAt: now, count: 0 };
activity.budgets.set(type, budget);
}
if (budget.count >= limit) return false;
budget.count += 1;
return true;
}
function pruneIpActivity(now = Date.now()) {
const cutoff = now - Math.max(IP_JOIN_WINDOW_MS, IP_EVENT_WINDOW_MS) * 2;
for (const [key, activity] of activityByIpAndScene) {
if (activity.lastSeenAt < cutoff && (activity.quarantinedUntil || 0) <= now) {
activityByIpAndScene.delete(key);
}
}
}
function closeRateLimited(client) {
client.ws.close(1008, "rate limited");
}
function allowIpEvent(client, type, limit) {
if (consumeIpBudget(client, type, limit, IP_EVENT_WINDOW_MS)) return true;
closeRateLimited(client);
return false;
}
// Behavioral flood detector: tally rename/chat actions per IP in a rolling
// window. A human cannot rename or message dozens of times in 10s; the abuse bot
// does. On crossing the threshold we persistently block the IP (reusing
// blockedIps enforcement) and kick every connection on it. In dry-run
// (FLOOD_BAN_ENFORCE unset) it only logs what it *would* ban. Returns true when
// the caller's action should be dropped (i.e. the IP was just banned).
function registerFloodAction(client, now = Date.now()) {
if (FLOOD_BAN_LIMIT <= 0 || !client.site) return false;
if (client.identity?.isOwner) return false; // never auto-ban a verified owner
const activity = getIpActivity(client.scene, client.ip, now);
let flood = activity.flood;
if (!flood || now - flood.startedAt >= FLOOD_BAN_WINDOW_MS) {
flood = { startedAt: now, count: 0, flagged: false };
activity.flood = flood;
}
flood.count += 1;
if (flood.count < FLOOD_BAN_LIMIT || flood.flagged) return false;
// Threshold crossed: log once per window either way (audit + dry-run signal).
flood.flagged = true;
console.log(JSON.stringify({
event: "flood_detect",
at: new Date(now).toISOString(),
enforce: FLOOD_BAN_ENFORCE,
site: client.site.siteKey,
ip: client.ip,
count: flood.count,
windowMs: FLOOD_BAN_WINDOW_MS,
name: client.identity?.displayName || "",
}));