Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
executable file
·3667 lines (3448 loc) · 154 KB
/
Copy pathserver.js
File metadata and controls
executable file
·3667 lines (3448 loc) · 154 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 fs = require("node:fs");
const http = require("node:http");
const https = require("node:https");
const path = require("node:path");
const crypto = require("node:crypto");
const vm = require("node:vm");
const { spawnSync } = require("node:child_process");
const os = require("node:os");
const store = require("./data-store");
const ot = require("./public/ot-text.js");
loadServerEnvFiles();
store.init();
seedAdminAccount();
// 서버 버전. 클라이언트(앱) 버전은 package.json 의 version 이며 따로 관리한다.
// 규칙: 클라 코드가 바뀌면 서버가 그 코드를 배포하므로 서버·클라 둘 다 올리고,
// 서버만 바뀌면 서버 버전만 올린다.
const VERSION = "3.4.0";
const PORT = Number(process.env.PORT || 25565);
const HOST = process.env.HOST || "0.0.0.0";
const PUBLIC_HOST = cleanHost(process.env.PUBLIC_HOST || "");
const PUBLIC_URL = cleanPublicUrl(process.env.PUBLIC_URL || "", PUBLIC_HOST, PORT);
const REQUIRE_HTTPS = process.env.VOICE_CHAT_REQUIRE_HTTPS === "1" || process.env.HTTPS === "1";
// nginx 같은 리버스 프록시 뒤에서만 1 로 둔다: 루프백 연결의 X-Real-IP 를 실제 접속 IP로 쓴다(IP별 제한용).
const TRUST_PROXY = process.env.TRUST_PROXY === "1";
const MAX_ROOM_LIMIT = 8;
const PUBLIC_DIR = path.join(__dirname, "public");
// ─── 보안/남용 방지 상한 ─────────────────────────────────
// 외부 공격(메모리 고갈·연결/메시지 폭주·브루트포스)에 대한 서버측 방어값.
const MAX_MESSAGE_BYTES = 12 * 1024 * 1024; // WebSocket 단일 메시지 최대 크기(그림판 문서 8MB 여유 포함)
const MAX_PRE_AUTH_MESSAGE_BYTES = 512 * 1024; // 로그인 전 메시지 최대 크기(가입 시 프로필 이미지 400KB 포함)
const MAX_SEND_BUFFER_BYTES = 64 * 1024 * 1024; // 안 읽고 쌓아두는 클라이언트의 송신 대기 상한(메모리 고갈 방어, 멤버 프로필 이미지가 큰 채널 목록 여유 포함)
const MAX_UPLOADS_PER_USER = 3; // 사용자당 동시 업로드 수(업로드는 메모리에 모았다 저장한다)
const MAX_CONN_PER_IP = 24; // 같은 IP 동시 연결 상한(여러 탭/기기 허용, 폭주는 차단)
const MAX_TOTAL_CLIENTS = 500; // 전체 동시 연결 상한(백스톱)
const MSG_BUCKET_CAP = 600; // 메시지 토큰버킷 용량(순간 폭주 허용치)
const MSG_REFILL_PER_MS = 0.3; // 초당 300개 리필(정상 실시간 사용은 최대 ~80/s)
const MSG_FLOOD_CLOSE = 1500; // 이 수치를 넘게 초과 전송하면 연결을 끊는다
const AUTH_ATTEMPT_MAX = 20; // IP당 창(window) 내 로그인/회원가입 시도 상한
const AUTH_WINDOW_MS = 60 * 1000; // 인증 시도 집계 창
// 채팅에 gif 사이트 페이지 링크(확장자 없음, 예: klipy.com/gifs/...)를 붙였을 때 썸네일을 보여주기 위해
// og:image 메타를 대신 가져와주는 프록시. 임의 URL을 서버가 fetch하면 SSRF(내부망 접근)로 악용될 수 있어
// 알려진 gif 사이트 호스트만 https로 허용한다.
const LINK_PREVIEW_HOSTS = new Set(["klipy.com", "www.klipy.com", "tenor.com", "www.tenor.com", "giphy.com", "www.giphy.com"]);
const LINK_PREVIEW_MAX_BYTES = 512 * 1024;
const LINK_PREVIEW_TIMEOUT_MS = 4000;
// 로그인 전(pre-auth)에 허용하는 메시지 타입. 그 외는 로그인해야 처리한다.
const PRE_AUTH_TYPES = new Set(["register", "login", "auth-token", "logout", "client-log"]);
// 로그인 브라우저 연결의 Origin 검증에 추가로 허용할 오리진(쉼표 구분, 예: 리버스 프록시 도메인).
const EXTRA_WS_ORIGINS = new Set(
String(process.env.ALLOW_WS_ORIGINS || "")
.split(",")
.map((s) => s.trim().toLowerCase())
.filter(Boolean)
);
const ipConnCounts = new Map(); // ip -> 동시 연결 수
const authAttempts = new Map(); // ip -> { count, resetAt }
const activeUploads = new Map(); // userId -> 진행 중인 업로드 수
const CERT_FILE = path.resolve(process.env.SSL_CERT_FILE || path.join(__dirname, ".cert", "cert.pem"));
const KEY_FILE = path.resolve(process.env.SSL_KEY_FILE || path.join(__dirname, ".cert", "key.pem"));
const CERT_DIR = path.dirname(CERT_FILE);
const clients = new Map();
const rooms = new Map();
// ===== 방 통계 =====
// memoDocs/drawDocs와 같은 패턴: roomId -> { totalMs, users, saveTimer } 메모리 캐시 + 디바운스 저장.
const statsCache = new Map();
const STATS_PERSIST_DEBOUNCE = 2000;
function getRoomStatsMut(roomId) {
let s = statsCache.get(roomId);
if (!s) {
const saved = store.getRoomStats(roomId);
s = { totalMs: saved.totalMs, users: saved.users, saveTimer: 0 };
statsCache.set(roomId, s);
}
return s;
}
function scheduleStatsPersist(roomId) {
const s = statsCache.get(roomId);
if (!s) return;
if (s.saveTimer) clearTimeout(s.saveTimer);
s.saveTimer = setTimeout(() => {
s.saveTimer = 0;
store.saveRoomStats(roomId, { totalMs: s.totalMs, users: s.users });
}, STATS_PERSIST_DEBOUNCE);
}
// 유저 하나의 누적 카운터(key)에 amount를 더한다. 표시 이름은 매번 최신으로 갱신.
function addStat(roomId, userId, name, key, amount) {
if (!roomId || !userId || !amount) return;
const s = getRoomStatsMut(roomId);
if (!s.users[userId]) s.users[userId] = { name };
else s.users[userId].name = name;
s.users[userId][key] = (s.users[userId][key] || 0) + amount;
scheduleStatsPersist(roomId);
}
// 마이크/화면/소리공유 on 구간을 열고 닫는다. kind: "mic" | "screen" | "sound".
function setMediaOn(client, kind, on) {
if (!client.userId || !client.roomId) return;
const since = client.mediaOn[kind] || 0;
if (on) {
if (!since) client.mediaOn[kind] = Date.now();
return;
}
if (since) {
addStat(client.roomId, client.userId, client.name, `${kind}OnMs`, Date.now() - since);
client.mediaOn[kind] = 0;
}
}
// OT 연산(문자열=삽입, 음수=삭제, 양수=유지)에서 입력한 글자수·지운 글자수·입력한 줄수를 셈한다.
function memoOpDelta(o) {
let charsTyped = 0, charsDeleted = 0, linesTyped = 0;
for (const comp of o) {
if (typeof comp === "string") { charsTyped += comp.length; linesTyped += (comp.match(/\n/g) || []).length; }
else if (comp < 0) charsDeleted += -comp;
}
return { charsTyped, charsDeleted, linesTyped };
}
// 방 종류별로 "지금 이 방을 보고 있는지" 판정할 client 필드와, 그 시작 시각 필드.
const STATS_LIVE_FIELDS = {
voice: { roomField: "roomId", sinceField: "roomJoinedAt", key: "joinMs" },
chat: { roomField: "chatRoomId", sinceField: "chatJoinedAt", key: "viewMs" },
memo: { roomField: "memoRoomId", sinceField: "memoJoinedAt", key: "viewMs" },
draw: { roomField: "drawRoomId", sinceField: "drawJoinedAt", key: "viewMs" },
};
// 조회 시점 기준 스냅샷. 아직 안 닫힌 구간(접속 중인 시간, 켜져 있는 마이크·화면·소리공유 시간,
// 진행 중인 통화의 전체 시간)을 더해 돌려준다 — 통계 창을 열어둔 채로 숫자가 실시간으로 올라가게.
// statsCache 는 절대 건드리지 않는다. 폴링할 때마다 누적되면 값이 몇 배로 부풀기 때문.
function roomStatsSnapshot(roomId, roomType) {
const s = getRoomStatsMut(roomId);
const now = Date.now();
const users = new Map(Object.entries(s.users).map(([userId, u]) => [userId, { userId, ...u }]));
const bump = (client, key, amount) => {
if (!amount) return;
let u = users.get(client.userId);
if (!u) { u = { userId: client.userId }; users.set(client.userId, u); }
u.name = client.name;
u[key] = (u[key] || 0) + amount;
};
const live = STATS_LIVE_FIELDS[roomType];
if (live) {
for (const c of clients.values()) {
if (!c.userId || c[live.roomField] !== roomId) continue;
if (c[live.sinceField]) bump(c, live.key, now - c[live.sinceField]);
if (roomType !== "voice") continue;
for (const [kind, since] of Object.entries(c.mediaOn)) {
if (since) bump(c, `${kind}OnMs`, now - since);
}
}
}
const room = rooms.get(roomId);
const totalMs = s.totalMs + (room ? now - (room.startedAt || now) : 0);
return { totalMs, users: [...users.values()] };
}
// 통화방을 나갈 때 열려 있던 마이크/화면/소리공유 구간을 전부 마감한다.
function finalizeMediaStats(client, roomId) {
for (const kind of Object.keys(client.mediaOn)) {
const since = client.mediaOn[kind];
if (!since) continue;
addStat(roomId, client.userId, client.name, `${kind}OnMs`, Date.now() - since);
client.mediaOn[kind] = 0;
}
}
const tlsOptions = loadTlsOptions();
if (!tlsOptions && REQUIRE_HTTPS) {
console.error("HTTPS certificate was not created. Install openssl or set SSL_CERT_FILE and SSL_KEY_FILE.");
process.exit(1);
}
const server = tlsOptions
? https.createServer(tlsOptions, safeHandleRequest)
: http.createServer(safeHandleRequest);
server.on("upgrade", safeHandleUpgrade);
server.on("clientError", handleClientError);
server.listen(PORT, HOST, () => {
const protocol = tlsOptions ? "https" : "http";
const localUrl = `${protocol}://localhost:${PORT}`;
const lanUrl = getLanUrl(protocol, PORT);
console.log("");
console.log(`Accord v${VERSION}`);
console.log(`Local: ${localUrl}`);
if (lanUrl) console.log(`LAN: ${lanUrl}`);
console.log(`Friend: ${PUBLIC_URL || `${protocol}://YOUR_PUBLIC_IP:${PORT}`}`);
if (!tlsOptions) {
console.log("Warning: HTTPS certificate was not created. Remote browsers may block microphone and AudioWorklet.");
console.log("Run `npm run server:https` after installing openssl, or set SSL_CERT_FILE and SSL_KEY_FILE.");
}
printTurnStatus();
console.log("");
});
// 잘못된 URL 인코딩(%C0)·Host 헤더·널 바이트 경로 등은 URL/decodeURIComponent/fs 에서 동기 예외를 던진다.
// 여기서 잡지 않으면 요청 하나로 서버 프로세스 전체가 죽는다.
function safeHandleRequest(req, res) {
try {
handleRequest(req, res);
} catch {
if (!res.headersSent) sendText(res, 400, "Bad request");
else res.destroy();
}
}
function safeHandleUpgrade(req, socket) {
try {
handleUpgrade(req, socket);
} catch {
socket.destroy();
}
}
function handleRequest(req, res) {
if (req.method === "OPTIONS") {
sendCors(res, 204);
res.end();
return;
}
const base = `${tlsOptions ? "https" : "http"}://${req.headers.host || "localhost"}`;
const url = new URL(req.url, base);
if (req.method === "POST") {
if (url.pathname === "/upload") {
handleUpload(req, res, url);
return;
}
sendText(res, 404, "Not found");
return;
}
if (req.method !== "GET") {
sendText(res, 405, "Method not allowed");
return;
}
if (url.pathname.startsWith("/uploads/")) {
serveUpload(res, url.pathname);
return;
}
if (url.pathname === "/health") {
sendJson(res, 200, { ok: true, version: VERSION, secure: Boolean(tlsOptions) });
return;
}
if (url.pathname === "/version") {
sendJson(res, 200, { version: VERSION, secure: Boolean(tlsOptions), updatedAt: new Date().toISOString() });
return;
}
if (url.pathname === "/config") {
sendJson(res, 200, {
version: VERSION,
secure: Boolean(tlsOptions),
protocol: tlsOptions ? "https" : "http",
maxRoomLimit: MAX_ROOM_LIMIT,
publicUrl: PUBLIC_URL,
iceServers: getIceServers(),
turnConfigured: hasTurnServer(),
stunConfigured: hasStunServer(),
});
return;
}
if (url.pathname === "/api/link-image") {
fetchLinkPreviewImage(res, url.searchParams.get("url") || "");
return;
}
const fileName = url.pathname === "/" ? "index.html" : decodeURIComponent(url.pathname.slice(1));
const filePath = path.normalize(path.join(PUBLIC_DIR, fileName));
const relativePath = path.relative(PUBLIC_DIR, filePath);
if (relativePath.startsWith("..") || path.isAbsolute(relativePath)) {
sendText(res, 403, "Forbidden");
return;
}
fs.readFile(filePath, (error, data) => {
if (error) {
sendText(res, 404, "Not found");
return;
}
sendCors(res, 200, {
"content-type": getContentType(filePath),
"cache-control": "no-store, max-age=0",
});
res.end(data);
});
}
// 채팅 파일/이미지 업로드. 바이너리 본문 + 헤더(x-file-name)로 받는다.
function handleUpload(req, res, url) {
const token = url.searchParams.get("token") || req.headers["x-auth-token"] || "";
const user = store.getUserByToken(token);
if (!user) {
sendJson(res, 401, { error: "인증이 필요합니다." });
return;
}
// 업로드는 본문 전체를 메모리에 모으므로 한 사용자가 동시에 여러 개(50MB씩)를 밀어 넣지 못하게 한다.
const active = activeUploads.get(user.id) || 0;
if (active >= MAX_UPLOADS_PER_USER) {
sendJson(res, 429, { error: "이전 업로드가 끝난 뒤 다시 시도해 주세요." });
return;
}
activeUploads.set(user.id, active + 1);
res.once("close", () => {
const left = (activeUploads.get(user.id) || 1) - 1;
if (left > 0) activeUploads.set(user.id, left);
else activeUploads.delete(user.id);
});
const mime = String(req.headers["content-type"] || "application/octet-stream").split(";")[0].trim();
let rawName = "file";
try {
rawName = decodeURIComponent(String(req.headers["x-file-name"] || "file"));
} catch {
rawName = String(req.headers["x-file-name"] || "file");
}
const chunks = [];
let size = 0;
let aborted = false;
req.on("data", (chunk) => {
if (aborted) return;
size += chunk.length;
if (size > store.UPLOAD_MAX_BYTES) {
aborted = true;
sendJson(res, 413, { error: "파일이 너무 큽니다. 50MB 이하만 올릴 수 있습니다." });
req.destroy();
return;
}
chunks.push(chunk);
});
req.on("end", () => {
if (aborted) return;
if (!size) {
sendJson(res, 400, { error: "빈 파일입니다." });
return;
}
try {
const saved = store.saveUpload({ buffer: Buffer.concat(chunks), name: rawName, mime, ownerId: user.id });
logServer(`upload file=${saved.fileName} size=${saved.size} by=${user.username}`);
sendJson(res, 200, { url: `/uploads/${saved.fileName}`, name: saved.name, size: saved.size, mime: saved.mime });
} catch (error) {
logServer(`upload failed: ${error.message || error}`);
sendJson(res, 500, { error: "업로드에 실패했습니다." });
}
});
req.on("error", () => {
if (!aborted) sendJson(res, 500, { error: "업로드 중 오류가 발생했습니다." });
});
}
function serveUpload(res, pathname) {
let fileName = "";
try {
fileName = decodeURIComponent(pathname.slice("/uploads/".length));
} catch {
sendText(res, 400, "Bad request");
return;
}
const filePath = store.getUploadPath(fileName);
if (!filePath) {
sendText(res, 403, "Forbidden");
return;
}
fs.readFile(filePath, (error, data) => {
if (error) {
sendText(res, 404, "Not found");
return;
}
// 저장형 XSS 방어: 이미지/영상/오디오 등 안전한 매체만 인라인으로 제공하고,
// HTML/SVG/스크립트 등은 원래 콘텐츠타입으로 렌더되지 않도록 첨부(다운로드)로 강제한다.
// (업로드한 HTML/SVG 를 직접 열어 앱 오리진에서 스크립트를 실행 → 토큰 탈취하는 공격 차단)
const inlineSafe = isInlineSafeUpload(filePath);
sendCors(res, 200, {
"content-type": inlineSafe ? getContentType(filePath) : "application/octet-stream",
"content-disposition": inlineSafe ? "inline" : "attachment",
"cache-control": "public, max-age=31536000, immutable",
});
res.end(data);
});
}
// 브라우저가 인라인 렌더해도 안전한(스크립트 실행 불가) 업로드 확장자만 허용한다.
// SVG 는 스크립트를 품을 수 있어 제외한다.
const INLINE_SAFE_UPLOAD_EXT = new Set([
".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".ico",
".mp4", ".webm", ".mov", ".mp3", ".wav", ".ogg", ".m4a",
]);
function isInlineSafeUpload(filePath) {
return INLINE_SAFE_UPLOAD_EXT.has(path.extname(filePath).toLowerCase());
}
// WebSocket 연결의 Origin 을 검증한다(브라우저발 교차 사이트 연결 차단).
// - Origin 이 없거나 null(네이티브/파일 로드 클라이언트)은 허용한다.
// - http(s) Origin 은 요청 Host 와 호스트가 같을 때만 허용한다(정상 클라는 항상 same-origin).
// - 환경변수 ALLOW_WS_ORIGINS 로 추가 오리진을 허용할 수 있다.
function isAllowedWsOrigin(req) {
const origin = String(req.headers.origin || "").trim();
if (!origin || origin === "null") return true; // 네이티브/Electron 파일 로드 등
let originHost = "";
try {
originHost = new URL(origin).host.toLowerCase();
} catch {
return false; // 파싱 불가한 Origin 은 거부
}
if (EXTRA_WS_ORIGINS.has(origin.toLowerCase())) return true;
const hostHeader = String(req.headers.host || "").toLowerCase();
if (originHost && originHost === hostHeader) return true;
if (PUBLIC_HOST && originHost === PUBLIC_HOST.toLowerCase()) return true;
const bareOriginHost = originHost.split(":")[0];
if (bareOriginHost === "localhost" || bareOriginHost === "127.0.0.1") return true;
return false;
}
function handleUpgrade(req, socket) {
const base = `${tlsOptions ? "https" : "http"}://${req.headers.host || "localhost"}`;
const url = new URL(req.url, base);
if (url.pathname !== "/signal") {
socket.destroy();
return;
}
const key = req.headers["sec-websocket-key"];
if (!key) {
socket.destroy();
return;
}
if (!isAllowedWsOrigin(req)) {
logServer(`ws upgrade blocked: origin=${String(req.headers.origin || "").slice(0, 120)}`);
socket.destroy();
return;
}
// 연결 폭주 방어: IP당 · 전체 동시 연결 상한.
const ip = clientIpOf(req);
if (clients.size >= MAX_TOTAL_CLIENTS) {
logServer(`ws upgrade rejected: server full (${clients.size})`);
socket.destroy();
return;
}
const ipCount = ipConnCounts.get(ip) || 0;
if (ipCount >= MAX_CONN_PER_IP) {
logServer(`ws upgrade rejected: too many connections ip=${ip} count=${ipCount}`);
socket.destroy();
return;
}
const accept = crypto
.createHash("sha1")
.update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`)
.digest("base64");
socket.write([
"HTTP/1.1 101 Switching Protocols",
"Upgrade: websocket",
"Connection: Upgrade",
`Sec-WebSocket-Accept: ${accept}`,
"",
"",
].join("\r\n"));
// 유휴 상태에서 연결이 끊기지 않도록: 소켓 타임아웃 해제 + TCP keepalive.
// (아무 것도 안 하고 가만히 있으면 WebSocket이 닫히는 문제 방지)
socket.setTimeout(0);
socket.setKeepAlive(true, 30000);
socket.setNoDelay(true);
const client = {
id: crypto.randomBytes(8).toString("hex"),
name: "Guest",
roomId: "",
socket,
buffer: Buffer.alloc(0),
closed: false,
fragments: null,
fragmentBytes: 0, // 조립 중인 메시지의 누적 바이트(과도 누적 시 연결 차단)
fragmentOpcode: 0,
ip,
msgTokens: MSG_BUCKET_CAP, // 메시지 토큰버킷(플러드 방어)
msgTokenTs: Date.now(),
floodStrikes: 0,
userId: "",
authToken: "", // 이 연결이 쓰는 세션 토큰(비밀번호 변경 시 이 세션만 남기려고 보관)
isAdmin: false,
chatRoomId: "", // 현재 보고 있는 채팅방(입력중 표시 대상 판별용)
aiRoomId: "", // 현재 보고 있는 AI방(브로드캐스트 대상 판별용)
memoRoomId: "", // 현재 보고 있는 메모장(실시간 동기화 대상 판별용)
drawRoomId: "", // 현재 보고 있는 그림판(실시간 동기화 대상 판별용)
logRoomId: "", // 현재 보고 있는 로그방(실시간 로그 대상 판별용)
logChannelId: "", // 그 로그방이 속한 채널(채널 단위 피드라 따로 보관)
dmUserId: "", // 현재 보고 있는 DM 상대(읽음 판별용)
roomJoinedAt: 0, // 통화방 접속 시각(통계용 접속시간 누적)
chatJoinedAt: 0, // 채팅방 보기 시작 시각(통계용)
memoJoinedAt: 0, // 메모장 보기 시작 시각(통계용)
drawJoinedAt: 0, // 그림판 보기 시작 시각(통계용)
mediaOn: {}, // 통계용 마이크/화면/소리공유 on 시작 시각. { mic, screen, sound } -> Date.now() 또는 0
};
clients.set(client.id, client);
ipConnCounts.set(ip, ipCount + 1);
logServer("client connected", client);
socket.on("data", (chunk) => readFrames(client, chunk));
socket.on("close", () => removeClient(client));
socket.on("error", () => removeClient(client));
send(client, { type: "hello", id: client.id, version: VERSION });
}
function handleClientError(error, socket) {
if (!socket.writable) return;
socket.end("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n");
}
// 메시지 폭주 방어: 토큰버킷. 정상 실시간 사용(최대 ~80/s)엔 걸리지 않고
// 초당 수백~수천 개를 쏟아붓는 플러드만 차단한다. 남는 토큰이 없으면 false.
function allowClientMessage(client) {
const now = Date.now();
client.msgTokens = Math.min(
MSG_BUCKET_CAP,
client.msgTokens + (now - client.msgTokenTs) * MSG_REFILL_PER_MS
);
client.msgTokenTs = now;
if (client.msgTokens < 1) return false;
client.msgTokens -= 1;
return true;
}
function readFrames(client, chunk) {
client.buffer = Buffer.concat([client.buffer, chunk]);
while (client.buffer.length >= 2) {
const first = client.buffer[0];
const second = client.buffer[1];
const opcode = first & 0x0f;
const masked = (second & 0x80) === 0x80;
let length = second & 0x7f;
let offset = 2;
// RFC 6455: 클라이언트→서버 프레임은 반드시 마스킹되어야 한다.
// 마스킹되지 않은 프레임은 비정상(비브라우저/공격) 클라이언트로 보고 연결을 끊는다.
if (!masked) {
closeClient(client);
return;
}
if (length === 126) {
if (client.buffer.length < 4) return;
length = client.buffer.readUInt16BE(2);
offset = 4;
} else if (length === 127) {
if (client.buffer.length < 10) return;
const big = client.buffer.readBigUInt64BE(2);
if (big > BigInt(Number.MAX_SAFE_INTEGER)) {
closeClient(client);
return;
}
length = Number(big);
offset = 10;
}
// 메모리 고갈 방어: 상한을 넘는 프레임을 선언하면 버퍼링하지 않고 즉시 끊는다.
// 로그인 전에는 작은 상한만 허용한다(인증 없이 연결마다 12MB씩 쌓는 공격 차단).
const maxBytes = client.userId ? MAX_MESSAGE_BYTES : MAX_PRE_AUTH_MESSAGE_BYTES;
if (length > maxBytes) {
logServer(`frame too large: ${length} bytes`, client);
closeClient(client);
return;
}
const frameLength = offset + 4 + length; // 마스킹 키 4바이트(마스킹 안 된 프레임은 위에서 끊었다)
if (client.buffer.length < frameLength) return;
const payload = Buffer.from(client.buffer.subarray(offset + 4, frameLength));
const mask = client.buffer.subarray(offset, offset + 4);
for (let i = 0; i < payload.length; i += 1) payload[i] ^= mask[i & 3];
client.buffer = client.buffer.slice(frameLength);
const fin = (first & 0x80) === 0x80;
if (opcode === 8) {
closeClient(client);
return;
}
if (opcode === 9 || opcode === 10) continue; // ping/pong 무시
// 큰 메시지(예: 이미지 data URL)는 브라우저가 여러 프레임으로 쪼개 보낸다.
// 연속(continuation) 프레임을 이어붙여 완성된 뒤에 처리한다.
if (opcode === 0) {
if (!Array.isArray(client.fragments)) continue; // 시작 없는 연속 프레임은 버린다.
client.fragments.push(payload);
client.fragmentBytes += payload.length;
} else if (opcode === 1 || opcode === 2) {
client.fragments = [payload];
client.fragmentOpcode = opcode;
client.fragmentBytes = payload.length;
} else {
continue;
}
// 연속 프레임 누적이 상한을 넘으면(조각내어 우회하는 메모리 고갈 시도) 끊는다.
if (client.fragmentBytes > maxBytes) {
logServer(`message too large: ${client.fragmentBytes} bytes`, client);
client.fragments = null;
client.fragmentBytes = 0;
closeClient(client);
return;
}
if (!fin) continue;
const full = client.fragments.length === 1 ? client.fragments[0] : Buffer.concat(client.fragments);
const op = client.fragmentOpcode;
client.fragments = null;
client.fragmentBytes = 0;
// 메시지 폭주 방어: 완성된 데이터 메시지마다 속도를 검사한다(텍스트·바이너리 모두).
// 초과 시 파싱/처리 없이 버리고, 지속되면 연결을 끊는다.
if (!allowClientMessage(client)) {
client.floodStrikes += 1;
if (client.floodStrikes > MSG_FLOOD_CLOSE) {
logServer("message flood: closing connection", client);
closeClient(client);
return;
}
continue;
}
client.floodStrikes = 0;
if (op !== 1) continue; // 텍스트 메시지만 처리
try {
handleMessage(client, JSON.parse(full.toString("utf8")));
} catch {
send(client, { type: "error", message: "잘못된 메시지입니다." });
}
}
}
function handleMessage(client, message) {
// 방어: JSON 이 객체가 아니거나 type 이 문자열이 아니면 무시한다.
if (!message || typeof message !== "object" || Array.isArray(message) || typeof message.type !== "string") {
return;
}
// 로그인 전에는 인증/진단 메시지만 처리한다(pre-auth 공격 표면 축소).
if (!client.userId && !PRE_AUTH_TYPES.has(message.type)) {
send(client, { type: "error", message: "로그인이 필요합니다." });
return;
}
if (handleAuthMessage(client, message)) return;
if (handleAdminMessage(client, message)) return;
if (handleChannelMessage(client, message)) return;
if (handleChatMessage(client, message)) return;
if (handleAiMessage(client, message)) return;
if (handleMemoMessage(client, message)) return;
if (handleDrawMessage(client, message)) return;
if (handleLogMessage(client, message)) return;
if (handleDmMessage(client, message)) return;
if (message.type === "join-room") {
joinVoiceRoom(client, String(message.roomId || ""));
return;
}
if (message.type === "leave-room") {
leaveRoom(client, true);
return;
}
if (message.type === "media:intent") {
// 화면/카메라/컴퓨터 사운드 공유 버튼 클릭 즉시 알림(비영속, 발신자 제외 릴레이). 실제 미디어 상태와 무관하다.
const room = rooms.get(client.roomId);
if (!room) return;
const sound = String(message.sound || "");
if (!["screenOn", "screenOff", "soundOn", "soundOff"].includes(sound)) return;
setMediaOn(client, sound.startsWith("screen") ? "screen" : "sound", sound.endsWith("On"));
for (const peerId of room.clients) {
if (peerId === client.id) continue;
send(clients.get(peerId), { type: "media:intent", sound });
}
return;
}
if (message.type === "stats:media") {
if (message.kind === "mic") setMediaOn(client, "mic", Boolean(message.on));
return;
}
if (
message.type === "room:force-mute" ||
message.type === "room:kick-user" ||
message.type === "room:force-screen-off" ||
message.type === "room:force-sound-off"
) {
handleRoomModeration(client, message);
return;
}
if (message.type === "client-log") {
logClientEvent(client, message);
return;
}
if (message.type === "signal") {
const target = clients.get(String(message.target || ""));
const signalKind = getSignalKind(message.data);
if (!target || !client.roomId || target.roomId !== client.roomId) {
logServer(`signal target missing kind=${signalKind} target=${String(message.target || "")}`, client);
return;
}
logServer(`signal kind=${signalKind} target=${target.id}`, client);
send(target, {
type: "signal",
from: client.id,
fromName: client.name,
data: message.data,
});
}
}
// 로그인/회원가입 브루트포스 + scrypt CPU 소진 방어: IP당 창(window) 내 시도 상한.
function authRateLimited(client) {
const now = Date.now();
let rec = authAttempts.get(client.ip);
if (!rec || now > rec.resetAt) {
rec = { count: 0, resetAt: now + AUTH_WINDOW_MS };
authAttempts.set(client.ip, rec);
}
rec.count += 1;
return rec.count > AUTH_ATTEMPT_MAX;
}
function handleAuthMessage(client, message) {
switch (message.type) {
case "register": {
if (authRateLimited(client)) {
send(client, { type: "auth-error", action: "register", message: "시도가 너무 많습니다. 잠시 후 다시 시도해 주세요." });
return true;
}
const result = store.createUser({
username: message.username,
password: message.password,
displayName: message.displayName,
email: message.email,
avatar: message.avatar,
});
if (result.error) {
send(client, { type: "auth-error", action: "register", message: result.error });
return true;
}
finishAuth(client, result.user, "register");
return true;
}
case "login": {
if (authRateLimited(client)) {
send(client, { type: "auth-error", action: "login", message: "시도가 너무 많습니다. 잠시 후 다시 시도해 주세요." });
return true;
}
const result = store.authenticate(message.username, message.password);
if (result.error) {
send(client, { type: "auth-error", action: "login", message: result.error });
return true;
}
finishAuth(client, result.user, "login");
return true;
}
case "auth-token": {
const user = store.getUserByToken(message.token);
if (!user) {
send(client, { type: "auth-expired" });
return true;
}
finishAuth(client, user, "resume", message.token);
return true;
}
case "logout": {
if (message.token) store.destroySession(message.token);
leaveRoom(client, false);
client.userId = "";
client.authToken = "";
client.isAdmin = false;
client.name = "Guest";
client.dmUserId = "";
dropLostViews(client);
broadcastPresence();
return true;
}
case "change-password": {
if (!client.userId) {
send(client, { type: "auth-error", action: "change-password", message: "로그인이 필요합니다." });
return true;
}
const result = store.changePassword(client.userId, message.oldPassword, message.newPassword, client.authToken);
if (result.error) {
send(client, { type: "auth-error", action: "change-password", message: result.error });
return true;
}
// 다른 세션으로 접속해 있던 연결도 끊는다(재접속하면 토큰이 없어져 로그인 화면으로 간다).
for (const c of clients.values()) {
if (c !== client && c.userId === client.userId && c.authToken !== client.authToken) closeClient(c);
}
send(client, { type: "auth-ok", action: "change-password", user: store.sanitizeUser(result.user) });
return true;
}
case "update-profile": {
if (!client.userId) {
send(client, { type: "auth-error", action: "update-profile", message: "로그인이 필요합니다." });
return true;
}
const result = store.updateProfile(client.userId, {
displayName: message.displayName,
avatar: message.avatar,
banner: message.banner,
bannerGradient: message.bannerGradient,
email: message.email,
});
if (result.error) {
send(client, { type: "auth-error", action: "update-profile", message: result.error });
return true;
}
client.name = result.user.displayName;
send(client, { type: "auth-ok", action: "update-profile", user: store.sanitizeUser(result.user) });
// 닉네임/프로필 변경은 여러 채널의 멤버 표시에 영향 → 접속자 전원 채널 목록 갱신.
refreshChannelsForAll();
broadcastPresence();
return true;
}
default:
return false;
}
}
function finishAuth(client, user, action, existingToken) {
const token = existingToken || store.createSession(user.id);
client.authToken = token;
client.userId = user.id;
client.isAdmin = Boolean(user.isAdmin);
client.name = user.displayName;
store.recordConnection(user.id, client.ip, action === "resume" ? "connect" : action);
logServer(`auth ${action} user=${user.username} code=#${user.code} ip=${client.ip}`, client);
send(client, { type: "auth-ok", action, token, user: store.sanitizeUser(user) });
sendChannels(client);
broadcastPresence();
}
function handleAdminMessage(client, message) {
if (typeof message.type !== "string" || !message.type.startsWith("admin:")) return false;
if (!client.isAdmin) {
send(client, { type: "admin-error", message: "관리자 권한이 없습니다." });
return true;
}
switch (message.type) {
case "admin:list-users":
sendAdminUsers(client);
return true;
case "admin:set-admin": {
const result = store.setAdmin(message.userId, message.value);
if (result.error) {
send(client, { type: "admin-error", message: result.error });
return true;
}
notifyUserUpdate(message.userId);
sendAdminUsers(client);
return true;
}
case "admin:set-code": {
const result = store.setUserCode(message.userId, message.code);
if (result.error) {
send(client, { type: "admin-error", message: result.error });
return true;
}
notifyUserUpdate(message.userId);
sendAdminUsers(client);
return true;
}
case "admin:create-user": {
const result = store.createUser({ username: message.username, password: message.password, displayName: message.displayName });
if (result.error) {
send(client, { type: "admin-error", message: result.error });
return true;
}
// 만들면서 미리 채널에 넣어 둔다.
for (const id of Array.isArray(message.channelIds) ? message.channelIds : []) {
if (!store.addMember(String(id), result.user.id).error) notifyChannelMembers(String(id));
}
sendAdminUsers(client);
return true;
}
case "admin:delete-user": {
const userId = String(message.userId || "");
const result = store.deleteUser(userId);
if (result.error) {
send(client, { type: "admin-error", message: result.error });
return true;
}
for (const c of [...clients.values()]) {
if (c.userId !== userId) continue;
send(c, { type: "auth-expired" });
closeClient(c);
}
for (const id of result.channelIds) notifyChannelMembers(id);
sendAdminUsers(client);
return true;
}
case "admin:set-member": {
const channelId = String(message.channelId || "");
const userId = String(message.userId || "");
if (!store.findById(userId)) {
send(client, { type: "admin-error", message: "유저를 찾을 수 없습니다." });
return true;
}
const result = message.value ? store.addMember(channelId, userId) : store.removeMember(channelId, userId);
if (result.error) {
send(client, { type: "admin-error", message: result.error });
return true;
}
// channel:kick 과 같이, 빠진 유저는 채널 방에서 내보내고 목록을 갱신한다.
for (const c of clients.values()) {
if (c.userId !== userId) continue;
if (!message.value) forceLeaveChannelRooms(c, channelId);
sendChannels(c);
}
notifyChannelMembers(channelId);
sendAdminUsers(client);
return true;
}
case "admin:get-ai-prompt":
send(client, { type: "admin-ai-prompt", prompt: store.getAiGlobalPrompt() });
return true;
case "admin:set-ai-prompt": {
const prompt = store.setAiGlobalPrompt(message.prompt);
send(client, { type: "admin-ai-prompt", prompt, saved: true });
return true;
}
default:
return false;
}
}
function sendAdminUsers(client) {
const channels = store.listChannelsForUser("", true).map(({ id, name, ownerId, memberIds }) => ({ id, name, ownerId, memberIds }));
send(client, { type: "admin-users", users: store.listUsers(), online: onlineUserIds(), channels });
}
function onlineUserIds() {
const ids = new Set();
for (const c of clients.values()) if (c.userId) ids.add(c.userId);
return [...ids];
}
// 관리자 지정/코드 변경 등으로 계정이 바뀌면, 접속 중인 해당 유저 클라이언트에 즉시 반영한다.
function notifyUserUpdate(userId) {
const user = store.findById(userId);
if (!user) return;
const payload = { type: "account-updated", user: store.sanitizeUser(user) };
for (const c of clients.values()) {
if (c.userId !== userId) continue;
c.name = user.displayName;
c.isAdmin = Boolean(user.isAdmin);
dropLostViews(c);
send(c, payload);
// 관리자 승격/해제 시 볼 수 있는 채널이 달라지므로 목록도 갱신한다.
sendChannels(c);
}
broadcastPresence();
}
function seedAdminAccount() {
const username = process.env.ADMIN_SEED_USERNAME || "craft374";
const password = process.env.ADMIN_SEED_PASSWORD || "";
const displayName = process.env.ADMIN_SEED_DISPLAYNAME || username;
const result = store.seedAdmin({ username, password, displayName });
if (result.created) console.log(`관리자 계정 생성됨: ${username} (#0000)`);
else if (result.promoted) console.log(`기존 계정을 관리자(#0000)로 승격: ${username} (비밀번호는 ADMIN_SEED_PASSWORD 로 재설정)`);
else if (result.skipped === "no-password") {
console.log("관리자 시드 건너뜀: ADMIN_SEED_PASSWORD 미설정. server.env에 추가하면 첫 실행 시 생성됩니다.");
}
}
function cleanIp(value) {
return String(value || "").replace(/^::ffff:/, "");
}
function clientIpOf(req) {
const ip = cleanIp(req.socket.remoteAddress);
if (!TRUST_PROXY || (ip !== "127.0.0.1" && ip !== "::1")) return ip;
return cleanIp(String(req.headers["x-real-ip"] || "").trim()) || ip;