-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
2052 lines (1972 loc) · 117 KB
/
Copy pathserver.js
File metadata and controls
2052 lines (1972 loc) · 117 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
// =====================================================================
// REQUIRED ENVIRONMENT VARIABLES (read this before deploying!)
// ---------------------------------------------------------------------
// When DB_HOST is set, you MUST also set DB_PORT — otherwise db.js silently
// defaults to port 4000 (its TiDB/Cloud-test fallback). With MySQL on 3306
// you will get ECONNREFUSED retries forever. Set DB_PORT=3306 explicitly.
//
// Also recommended when DB_HOST is set:
// DB_USER — sql user
// DB_PASS — sql password (use a secret manager; do NOT commit)
// DB_NAME — schema name
// DB_SSL=true — for managed MySQL/TiDB
// REDIS_HOST — 127.0.0.1 in dev, your cache host in prod
// DB_POOL — connection-pool size (default 10)
//
// Examples:
// Dev (local MySQL): DB_HOST=127.0.0.1 DB_PORT=3306 DB_USER=dialog DB_PASS=dialog DB_NAME=dialog
// Prod (managed/TLS): DB_HOST=mysql.example.com DB_PORT=3306 DB_USER=app DB_PASS=*** DB_NAME=dialog DB_SSL=true
// =====================================================================
import "dotenv/config";
import express from "express";
import { createServer as createHttp } from "http";
import { createServer as createHttps } from "https";
import { Server } from "socket.io";
import { fileURLToPath } from "url";
import { dirname, join } from "path";
import { readFileSync, existsSync } from "fs";
import { exec } from "child_process";
import { networkInterfaces } from "os";
import crypto from "crypto";
import webpush from "web-push";
import { AccessToken } from "livekit-server-sdk";
import * as auth from "./auth.js";
import {
initSchema, waitForDb, saveMessage, recentMessages, messagesBefore, deleteMessage, editMessage, toggleReaction,
createGroup, getUserGroups, isGroupMember, getGroupMembers, getGroup, leaveGroup,
isGroupOwner, getGroupAvatar, getGroupMembersDetailed, addGroupMembers, removeGroupMember, renameGroup, setGroupAvatar, setGroupOwner, deleteGroup,
createGroupInvite, getGroupInvites, revokeGroupInvite, getInviteByHash, createPendingInvite, getGroupPending, deletePendingInvite,
updateProfile, getAvatar, getBanner, getProfileCard, getStatus, getUser, searchUsers,
createBot, isBot, getBotByTokenHash, getBot, listBotsByOwner, countBotsByOwner, updateBot, setBotTokenHash, deleteBot,
queueBotUpdate, getBotUpdates, deleteBotUpdatesBelow, pruneBotUpdates,
setRelation, removeRelation, getRelationsFull, getFriendLogins, areFriends, shareGroup, isBlockedBy,
sendFriendRequest, acceptFriend, declineFriend, removeFriend, haveMutualFriend, mutualFriends, mutualCounts,
getPrefs, setPrefs, dmOpen, bumpInviteUse,
getUserThemes, getTheme, saveTheme, deleteTheme, setThemePublished, countPublished, listWorkshop, incThemeInstalls, THEME_LIMITS,
getUserDMs, saveUserDMs,
getPinnedChats, savePinnedChats,
savePushSub, getPushSubs, deletePushSub, saveFcmToken, getFcmTokens, deleteFcmToken,
getRoomWatermarks, bumpWatermarks,
getUserByEmail, setUserEmail, markEmailVerified, setNagDismissed,
createEmailToken, getEmailToken, deleteEmailToken,
adminListUsers, adminStats, setUserBanned, setUserName, setUserLastIp,
isIpBanned, banIp, unbanIp, listBannedIps,
createReport, listReports, getReport, resolveReport, countPendingReports,
setUserReportBan, clearUserReport, setEmailWithStamp,
} from "./db.js";
import { sendVerifyEmail, sendResetEmail, sendWelcomeEmail, mailEnabled } from "./mail.js";
const __dirname = dirname(fileURLToPath(import.meta.url));
const HISTORY_LIMIT = 25; // one chunk — initial load + each scroll-up page
// Max file attachment size — must match the client composer cap and the JSON/Socket.IO HTTP limits
// above. Increasing here without bumping the buffer limits silently drops messages with socket.io's
// PayloadTooLarge error; bumping everything in lockstep is required. Value is shared so the push
// preview and the client-side alert stay in sync.
const MAX_FILE_SIZE_MB = 75;
const MAX_FILE_BYTES = MAX_FILE_SIZE_MB * 1024 * 1024;
// ---------- Log capture (admin panel: GET /api/admin/logs) ----------
// Keep the last N console lines in a ring buffer without losing normal stdout.
const LOG_RING = [];
const LOG_RING_MAX = 500;
function pushLog(level, args) {
try {
const line = args.map((a) => (typeof a === "string" ? a : (() => { try { return JSON.stringify(a); } catch { return String(a); } })())).join(" ");
LOG_RING.push({ t: Date.now(), level, line: line.slice(0, 2000) });
if (LOG_RING.length > LOG_RING_MAX) LOG_RING.shift();
} catch {}
}
for (const level of ["log", "info", "warn", "error"]) {
const orig = console[level].bind(console);
console[level] = (...args) => { pushLog(level, args); orig(...args); };
}
// In-memory mirror of banned_ips (ip -> expires|null) so the gate stays synchronous.
const bannedIps = new Map();
// Normalize IPv4-mapped IPv6 (::ffff:1.2.3.4) down to the v4 form for consistent matching.
const normIp = (ip) => String(ip || "").replace(/^::ffff:/, "").trim();
// Synchronous ban check with expiry — lazily forgets a lapsed temporary IP ban.
function ipIsBanned(ip) {
if (!bannedIps.has(ip)) return false;
const exp = bannedIps.get(ip);
if (exp != null && exp < Date.now()) { bannedIps.delete(ip); unbanIp(ip).catch(() => {}); return false; }
return true;
}
// ---------- Web Push ----------
const VAPID_PUBLIC = process.env.VAPID_PUBLIC || "";
const VAPID_PRIVATE = process.env.VAPID_PRIVATE || "";
const pushOn = !!(VAPID_PUBLIC && VAPID_PRIVATE);
if (pushOn) webpush.setVapidDetails(process.env.VAPID_SUBJECT || "mailto:admin@dialog.app", VAPID_PUBLIC, VAPID_PRIVATE);
async function sendPush(login, payload) {
try { // «не беспокоить» — не шлём уведомления
const st = userStatus.has(login) ? userStatus.get(login) : await getStatus(login);
if (st === "dnd") return;
} catch {}
// Web Push (browser / desktop) — VAPID.
if (pushOn) {
let subs = [];
try { subs = await getPushSubs(login); } catch { subs = []; }
const body = JSON.stringify(payload);
await Promise.all(subs.map((s) =>
webpush.sendNotification(s, body).catch((e) => { if (e.statusCode === 404 || e.statusCode === 410) deletePushSub(s.endpoint).catch(() => {}); })
));
}
// FCM (native Android app) — the WebView can't receive Web Push.
sendFcm(login, payload).catch(() => {});
}
// ---------- FCM (Firebase Cloud Messaging, HTTP v1) ----------
// Service account JSON via env FCM_SA (raw JSON) or FCM_SA_PATH (file). Dependency-free:
// we mint the OAuth2 token by signing a JWT with the SA private key (RS256, node:crypto).
let fcmSA = null;
try {
const raw = process.env.FCM_SA || (process.env.FCM_SA_PATH ? readFileSync(process.env.FCM_SA_PATH, "utf8") : "");
if (raw) fcmSA = JSON.parse(raw);
} catch (e) { console.warn("FCM_SA parse failed:", e.message); }
const fcmOn = !!(fcmSA && fcmSA.client_email && fcmSA.private_key && fcmSA.project_id);
if (fcmOn) console.log("FCM push enabled for project", fcmSA.project_id);
let _fcmTok = null, _fcmTokExp = 0;
const b64url = (buf) => Buffer.from(buf).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
async function fcmAccessToken() {
if (_fcmTok && Date.now() < _fcmTokExp - 60000) return _fcmTok;
const now = Math.floor(Date.now() / 1000);
const header = b64url(JSON.stringify({ alg: "RS256", typ: "JWT" }));
const claim = b64url(JSON.stringify({
iss: fcmSA.client_email, scope: "https://www.googleapis.com/auth/firebase.messaging",
aud: "https://oauth2.googleapis.com/token", iat: now, exp: now + 3600,
}));
const sig = b64url(crypto.createSign("RSA-SHA256").update(header + "." + claim).sign(fcmSA.private_key));
const jwt = `${header}.${claim}.${sig}`;
const r = await fetch("https://oauth2.googleapis.com/token", {
method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: jwt }),
});
const j = await r.json();
if (!j.access_token) throw new Error("no fcm access_token");
_fcmTok = j.access_token; _fcmTokExp = Date.now() + (j.expires_in || 3600) * 1000;
return _fcmTok;
}
async function sendFcm(login, payload) {
if (!fcmOn) return;
let tokens = [];
try { tokens = await getFcmTokens(login); } catch { return; }
if (!tokens.length) return;
let at; try { at = await fcmAccessToken(); } catch (e) { console.warn("fcm token", e.message); return; }
const url = `https://fcm.googleapis.com/v1/projects/${fcmSA.project_id}/messages:send`;
// Data-only message so the app renders it (fires even when backgrounded/killed).
await Promise.all(tokens.map((tk) => fetch(url, {
method: "POST", headers: { Authorization: "Bearer " + at, "Content-Type": "application/json" },
body: JSON.stringify({ message: {
token: tk, android: { priority: "high" },
data: { kind: String(payload.kind || ""), title: String(payload.title || "Dialog"), body: String(payload.body || ""), room: String(payload.room || ""), icon: String(payload.icon || "") },
} }),
}).then((r) => { if (r.status === 404 || r.status === 400) deleteFcmToken(tk).catch(() => {}); }).catch(() => {})));
}
// ---------- Express ----------
const app = express();
app.set("trust proxy", 1);
// Client cap is MAX_FILE_SIZE_MB raw bytes, but base64 inflates by ~4/3;
// the JSON/Socket.IO buffer must fit the encoded payload. Compute from the raw limit.
const B64_BUFFER_MB = Math.ceil(MAX_FILE_BYTES * 4 / 3 / (1024 * 1024)) + 8; // +8 MB slack for JSON envelope
app.use(express.json({ limit: B64_BUFFER_MB + "mb" }));
// IP-ban gate — refuse everything from a banned IP (checked against the in-memory mirror).
app.use((req, res, next) => {
if (ipIsBanned(normIp(req.ip))) return res.status(403).send("Your IP has been banned.");
next();
});
const keyPath = join(__dirname, "certs", "key.pem");
const certPath = join(__dirname, "certs", "cert.pem");
const useHttps = existsSync(keyPath) && existsSync(certPath);
const httpServer = useHttps
? createHttps({ key: readFileSync(keyPath), cert: readFileSync(certPath) }, app)
: createHttp(app);
const io = new Server(httpServer, { maxHttpBufferSize: B64_BUFFER_MB * 1024 * 1024 });
// The native apps (Electron desktop / Android WebView) must never see the
// marketing landing or downloads pages — they should stay in the chat. They
// send a recognizable User-Agent, so we bounce any such request to /login.
// This runs BEFORE express.static so it also catches /landing.html etc.
const isNativeApp = (req) =>
/\b(Electron|DialogApp)\b/i.test(req.headers["user-agent"] || "");
const MARKETING_PATHS = new Set([
"/", "/landing.html", "/download", "/downloads", "/download.html"
]);
app.use((req, res, next) => {
if (isNativeApp(req) && MARKETING_PATHS.has(req.path)) {
return res.redirect(302, "/login");
}
next();
});
// index:false so "/" is not auto-served as the SPA — the marketing landing
// page owns "/", the messenger SPA lives at /login and /{lang}/... routes.
app.use(express.static(join(__dirname, "public"), { index: false }));
// Public marketing pages (must be registered before the SPA fallback below).
app.get("/", (_req, res) =>
res.sendFile(join(__dirname, "public", "landing.html"))
);
app.get(["/download", "/downloads"], (_req, res) =>
res.sendFile(join(__dirname, "public", "download.html"))
);
app.get(["/privacy", "/privacy-policy"], (_req, res) =>
res.sendFile(join(__dirname, "public", "privacy.html"))
);
app.get(["/guidelines", "/dcg", "/rules"], (_req, res) =>
res.sendFile(join(__dirname, "public", "guidelines.html"))
);
// Bot API documentation.
app.get(["/bots", "/bot-api", "/docs", "/api-docs"], (_req, res) =>
res.sendFile(join(__dirname, "public", "bots.html"))
);
// Group-invite join page (a dedicated confirmation page, not the full app).
app.get(["/invite/:code", "/join/:code"], (_req, res) =>
res.sendFile(join(__dirname, "public", "invite.html"))
);
const bearer = (req) => (req.headers.authorization || "").replace(/^Bearer\s+/i, "");
async function authUser(req) { return auth.userByToken(bearer(req)); }
// ---------- REST: аутентификация ----------
app.post("/api/register", async (req, res) => {
try {
const { login, name, password, email } = req.body;
const out = await auth.register(login, name, password, email);
setUserLastIp(out.profile.login, normIp(req.ip)).catch(() => {});
const addr = String(email).trim().toLowerCase();
// Fire-and-forget the verification + welcome emails (never block/break signup).
sendVerification(out.profile.login, addr, out.profile.name).catch((e) => console.error("verify mail", e.message));
sendWelcomeEmail(addr, out.profile.name).catch((e) => console.error("welcome mail", e.message));
res.json(out);
} catch (e) { res.status(400).json({ error: e.message }); }
});
app.post("/api/login", async (req, res) => {
try {
const { login, password } = req.body;
const out = await auth.login(login, password);
setUserLastIp(out.profile.login, normIp(req.ip)).catch(() => {});
res.json(out);
} catch (e) { res.status(400).json({ error: e.message }); }
});
app.get("/api/me", async (req, res) => {
const me = await authUser(req);
if (!me) return res.status(401).json({ error: "unauth" });
res.json({ profile: me });
});
app.post("/api/logout", async (req, res) => { await auth.logout(bearer(req)); res.json({ ok: true }); });
// ---------- Email verification + password reset ----------
const APP_ORIGIN = process.env.APP_URL || "https://dialogmsg.xyz";
const sha256 = (s) => crypto.createHash("sha256").update(s).digest("hex");
// Create a single-use token, store only its hash, return the raw token for the URL.
async function makeEmailToken(login, email, purpose, ttlMs) {
const raw = crypto.randomBytes(32).toString("hex");
await createEmailToken(sha256(raw), login, email, purpose, Date.now() + ttlMs);
return raw;
}
async function sendVerification(login, email, name) {
if (!email) return;
const raw = await makeEmailToken(login, email, "verify", 24 * 3600 * 1000);
await sendVerifyEmail(email, name || login, `${APP_ORIGIN}/verify?token=${raw}`);
}
// Consume a token: valid, unexpired, right purpose → returns the row, else null.
async function consumeToken(raw, purpose) {
if (!raw) return null;
const row = await getEmailToken(sha256(String(raw)));
if (!row || row.purpose !== purpose) return null;
await deleteEmailToken(row.token_hash);
if (Number(row.expires) < Date.now()) return null;
return row;
}
function htmlPage(title, heading, body, ok) {
const color = ok ? "#2ec96b" : "#ff5252";
return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${title}</title></head>
<body style="margin:0;background:#050b06;color:#d6e6dc;font-family:-apple-system,Segoe UI,Roboto,Arial,sans-serif;display:grid;place-items:center;min-height:100vh">
<div style="max-width:420px;text-align:center;padding:28px 24px;background:#0b140d;border:1px solid #1c3324;border-radius:16px">
<div style="color:#2ec96b;font-weight:800;font-size:20px">Dialog</div>
<h1 style="font-size:20px;margin:16px 0 6px;color:${color}">${heading}</h1>
<p style="color:#a9c2b3;font-size:14px;line-height:1.5">${body}</p>
<a href="${APP_ORIGIN}/login" style="display:inline-block;margin-top:18px;background:#2ec96b;color:#04180c;text-decoration:none;font-weight:700;padding:11px 22px;border-radius:10px">Open Dialog</a>
</div>
</body></html>`;
}
// Click-through from the verification email.
app.get("/verify", async (req, res) => {
try {
const row = await consumeToken(req.query.token, "verify");
if (!row) return res.status(400).send(htmlPage("Verification", "Link expired or invalid", "Request a new verification email from Dialog settings.", false));
// Only verify if the address still matches the account's current email.
const u = await getUser(row.login);
if (!u || (u.email || "").toLowerCase() !== row.email.toLowerCase()) return res.status(400).send(htmlPage("Verification", "Link no longer valid", "This email address has changed. Request a new verification email.", false));
await markEmailVerified(row.login);
for (const tk of await import("./db.js").then((m) => m.tokensForLogin(row.login))) await import("./cache.js").then((c) => c.cacheDel("sess:" + tk));
res.send(htmlPage("Verified", "Email verified ✓", "Your email is confirmed. You can now recover your account if you ever lose access.", true));
} catch (e) { console.error("verify", e.message); res.status(500).send(htmlPage("Verification", "Something went wrong", "Please try again later.", false)); }
});
// Reset-password page (standalone) — reached from the reset email link.
app.get("/reset", (req, res) => res.sendFile(join(__dirname, "public", "reset.html")));
// Add / change email from the app (nag modal, settings). Changing an existing
// address is rate-limited to once a week; first-time linking is always allowed.
const EMAIL_COOLDOWN_MS = 7 * 24 * 3600 * 1000;
app.post("/api/account/email", async (req, res) => {
try {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
const email = String(req.body.email || "").trim().toLowerCase();
if (!auth.EMAIL_RE.test(email) || email.length > 190) return res.status(400).json({ error: "Введите корректный e-mail" });
const u = await getUser(me.login);
if (email === (u.email || "")) return res.status(400).json({ error: "same_email" });
const last = Number(u.email_changed_at) || 0;
if (u.email && last && Date.now() - last < EMAIL_COOLDOWN_MS) {
return res.status(429).json({ error: "cooldown", retryAt: last + EMAIL_COOLDOWN_MS });
}
const taken = await getUserByEmail(email);
if (taken && taken.login !== me.login) return res.status(400).json({ error: "E-mail уже используется" });
await setEmailWithStamp(me.login, email); // resets email_verified → 0, stamps time
await setNagDismissed(me.login, false);
for (const tk of await import("./db.js").then((m) => m.tokensForLogin(me.login))) await import("./cache.js").then((c) => c.cacheDel("sess:" + tk));
await sendVerification(me.login, email, me.name);
res.json({ ok: true, email, mailSent: mailEnabled(), retryAt: Date.now() + EMAIL_COOLDOWN_MS });
} catch (e) { res.status(400).json({ error: e.message }); }
});
// Change own display name (nickname) from the Account tab.
app.post("/api/account/nickname", async (req, res) => {
try {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
const name = String(req.body.name || "").trim().slice(0, 32);
if (!name) return res.status(400).json({ error: "empty" });
await setUserName(me.login, name);
for (const tk of await import("./db.js").then((m) => m.tokensForLogin(me.login))) await import("./cache.js").then((c) => c.cacheDel("sess:" + tk));
try {
const friends = await getFriendLogins(me.login);
for (const f of friends) notifyUser(f, "profile-updated", { login: me.login, name, avatarChanged: false });
notifyUser(me.login, "profile-updated", { login: me.login, name, avatarChanged: false });
} catch {}
res.json({ ok: true, name });
} catch (e) { res.status(400).json({ error: e.message }); }
});
// ---------- Reports (moderation) ----------
// Report-reason codes double as the Dialog Community Guidelines (DCG) sections.
const REPORT_REASONS = new Set(["harassment", "hate", "threats", "nsfw", "spam", "doxxing", "illegal", "impersonation", "selfharm", "other"]);
app.post("/api/report", async (req, res) => {
try {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
const target = String(req.body.target || "").trim().toLowerCase();
const reason = String(req.body.reason || "").trim();
const description = String(req.body.description || "").trim();
if (!target || target === me.login) return res.status(400).json({ error: "bad_target" });
if (!REPORT_REASONS.has(reason)) return res.status(400).json({ error: "bad_reason" });
// A message is linked when reporting from chat; profile/member-list reports may omit it.
if (!(await getUser(target))) return res.status(400).json({ error: "no_user" });
const id = await createReport({
reporter: me.login, target, room: String(req.body.room || "").slice(0, 64),
message_id: Number(req.body.messageId) || null, msg_preview: String(req.body.msgPreview || ""),
reason, description,
});
// Ping every admin in realtime so the queue badge updates.
for (const a of auth.ADMIN_LOGINS) notifyUser(a, "new-report", { id, target, reason });
res.json({ ok: true, id });
} catch (e) { res.status(400).json({ error: e.message }); }
});
// Resend the verification email for the current address.
app.post("/api/account/resend-verify", async (req, res) => {
try {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
const u = await getUser(me.login);
if (!u || !u.email) return res.status(400).json({ error: "no email on file" });
if (u.email_verified) return res.json({ ok: true, alreadyVerified: true });
await sendVerification(u.login, u.email, u.name);
res.json({ ok: true, mailSent: mailEnabled() });
} catch (e) { res.status(400).json({ error: e.message }); }
});
// "Don't show the email reminder again."
app.post("/api/account/dismiss-nag", async (req, res) => {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
await setNagDismissed(me.login, true);
for (const tk of await import("./db.js").then((m) => m.tokensForLogin(me.login))) await import("./cache.js").then((c) => c.cacheDel("sess:" + tk));
res.json({ ok: true });
});
// Change password from the profile — requires the current password, and can
// only be done once every 3 days.
const PW_COOLDOWN_MS = 3 * 24 * 3600 * 1000;
app.post("/api/account/password", async (req, res) => {
try {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
const { current, password } = req.body || {};
const u = await getUser(me.login);
if (!u) return res.status(400).json({ error: "not found" });
if (!(await auth.verifyPassword(u, String(current || "")))) return res.status(400).json({ error: "wrong_current" });
const last = Number(u.pw_changed_at) || 0;
if (last && Date.now() - last < PW_COOLDOWN_MS) {
return res.status(429).json({ error: "cooldown", retryAt: last + PW_COOLDOWN_MS });
}
await auth.setPassword(me.login, String(password || "")); // validates length, stamps time
// Keep THIS session, drop all others.
const keep = bearer(req);
for (const tk of await import("./db.js").then((m) => m.tokensForLogin(me.login))) {
if (tk === keep) { await import("./cache.js").then((c) => c.cacheDel("sess:" + tk)); continue; }
await import("./db.js").then((m) => m.deleteSession(tk)); await import("./cache.js").then((c) => c.cacheDel("sess:" + tk));
}
res.json({ ok: true, changedAt: Date.now(), retryAt: Date.now() + PW_COOLDOWN_MS });
} catch (e) { res.status(400).json({ error: e.message }); }
});
// Forgot password → email a reset link. Always 200 (don't reveal which emails exist).
app.post("/api/forgot", async (req, res) => {
try {
const email = String(req.body.email || "").trim().toLowerCase();
if (auth.EMAIL_RE.test(email)) {
const u = await getUserByEmail(email);
if (u && u.email_verified) {
const raw = await makeEmailToken(u.login, email, "reset", 3600 * 1000);
await sendResetEmail(email, u.name || u.login, `${APP_ORIGIN}/reset?token=${raw}`).catch((e) => console.error("reset mail", e.message));
}
}
res.json({ ok: true });
} catch (e) { res.json({ ok: true }); }
});
// Perform the reset with a valid token.
app.post("/api/reset", async (req, res) => {
try {
const { token, password } = req.body || {};
const row = await consumeToken(token, "reset");
if (!row) return res.status(400).json({ error: "Ссылка недействительна или устарела" });
await auth.setPassword(row.login, password);
// Invalidate every existing session for safety.
for (const tk of await import("./db.js").then((m) => m.tokensForLogin(row.login))) { await import("./db.js").then((m) => m.deleteSession(tk)); await import("./cache.js").then((c) => c.cacheDel("sess:" + tk)); }
res.json({ ok: true });
} catch (e) { res.status(400).json({ error: e.message }); }
});
// ---------- REST: профиль ----------
app.post("/api/profile", async (req, res) => {
try {
const me = await authUser(req);
if (!me) return res.status(401).json({ error: "unauth" });
const { name, avatar, banner, description, status, activity } = req.body || {};
const patch = {};
if (typeof name === "string" && name.trim()) patch.name = name.trim().slice(0, 64);
if (typeof avatar === "string") patch.avatar = avatar.slice(0, 5_000_000);
if (typeof banner === "string") patch.banner = banner.slice(0, 5_000_000);
if (typeof description === "string") patch.description = description.slice(0, 280);
if (typeof activity === "string") patch.activity = activity.trim().slice(0, 80);
if (["online", "dnd", "invisible"].includes(status)) patch.status = status;
await updateProfile(me.login, patch);
if (patch.status) { userStatus.set(me.login, patch.status); broadcastPresence(me.login); }
// Broadcast name/avatar/banner changes to friends and own devices in realtime
if (patch.name || "avatar" in patch || "banner" in patch) {
try {
const friends = await getFriendLogins(me.login);
const payload = { login: me.login, name: patch.name || me.name, avatarChanged: "avatar" in patch, bannerChanged: "banner" in patch };
for (const f of friends) notifyUser(f, "profile-updated", payload);
notifyUser(me.login, "profile-updated", payload);
} catch (e) { console.error("profile broadcast", e.message); }
}
for (const tk of await import("./db.js").then((m) => m.tokensForLogin(me.login))) await import("./cache.js").then((c) => c.cacheDel("sess:" + tk));
const card = await getProfileCard(me.login);
res.json({ profile: { ...me, ...patch, ...card } });
} catch (e) { console.error(e); res.status(500).json({ error: "server error" }); }
});
app.get("/api/profile/:login", async (req, res) => {
const card = await getProfileCard(req.params.login.toLowerCase());
if (!card) return res.status(404).json({ error: "not found" });
res.json({ ...card, status: effectiveStatus(card.login) });
});
// 1×1 прозрачный PNG — отдаём при отсутствии аватара вместо 404, чтобы не сыпались ошибки в консоли
// у клиентов с большим списком чатов (каждый видимый собеседник без аватара иначе логирует ERR).
const TRANSPARENT_PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=", "base64");
const sendTransparent = (res) => { res.set("Content-Type", "image/png"); res.set("Cache-Control", "public, max-age=60"); res.send(TRANSPARENT_PNG); };
// Default PFP fallback chain: pfp.svg (when user drops the file) > lil_dialog.webp (mini-logo) > 1×1 transparent.
// Served as image/svg+xml so <img> in the browser renders it directly without a data-URL round-trip.
const PFP_DEFAULT_PATH = join(__dirname, "public", "src", "pfp.svg");
const PFP_FALLBACK_PATH = join(__dirname, "public", "src", "lil_dialog.webp");
const sendPfpDefault = (res) => {
res.set("Cache-Control", "public, max-age=60");
if (existsSync(PFP_DEFAULT_PATH)) return res.type("image/svg+xml").sendFile(PFP_DEFAULT_PATH);
if (existsSync(PFP_FALLBACK_PATH)) return res.type("image/webp").sendFile(PFP_FALLBACK_PATH);
sendTransparent(res);
};
app.get("/api/avatar/:login", async (req, res) => {
try {
const dataUrl = await getAvatar(req.params.login.toLowerCase());
if (!dataUrl) return sendPfpDefault(res);
const m = /^data:(.+?);base64,(.*)$/.exec(dataUrl);
if (!m) return sendPfpDefault(res);
res.set("Content-Type", m[1]); res.set("Cache-Control", "public, max-age=60");
res.send(Buffer.from(m[2], "base64"));
} catch { sendPfpDefault(res); }
});
// Profile banner — no default image (unset = 404, client hides the banner strip).
app.get("/api/banner/:login", async (req, res) => {
try {
const dataUrl = await getBanner(req.params.login.toLowerCase());
if (!dataUrl) return res.status(404).end();
const m = /^data:(.+?);base64,(.*)$/.exec(dataUrl);
if (!m) return res.status(404).end();
res.set("Content-Type", m[1]); res.set("Cache-Control", "public, max-age=60");
res.send(Buffer.from(m[2], "base64"));
} catch { res.status(404).end(); }
});
app.get("/api/group-avatar/:id", async (req, res) => {
try {
const dataUrl = await getGroupAvatar(req.params.id);
if (!dataUrl) return sendPfpDefault(res);
const m = /^data:(.+?);base64,(.*)$/.exec(dataUrl); if (!m) return sendPfpDefault(res);
res.set("Content-Type", m[1]); res.set("Cache-Control", "public, max-age=60");
res.send(Buffer.from(m[2], "base64"));
} catch { sendPfpDefault(res); }
});
app.get("/api/user/:login", async (req, res) => {
try {
const u = await getUser(req.params.login.toLowerCase());
if (!u) return res.status(404).json({ error: "not found" });
res.json({ ok: true, login: u.login, name: u.name });
} catch (e) { console.error("user get", e.message); res.status(500).json({ error: "server error" }); }
});
// Public user search (session-authed so anonymous clients can't scrape the roster).
// Powers the "find anyone" chat-search suggestions.
app.get("/api/users/search", async (req, res) => {
const me = await authUser(req);
if (!me) return res.status(401).json({ error: "unauthorized" });
try {
const users = (await searchUsers(req.query.q, 8)).filter((u) => u.login !== me.login);
res.json({ ok: true, users });
} catch (e) { console.error("user search", e.message); res.status(500).json({ error: "server error" }); }
});
// Основные CRUD для групп: list / create / leave.
// ВАЖНО: эти маршруты идут ПЕРВЫМИ — Express сопоставляет по порядку объявления. Если поставить их после , GET /api/groups уйдёт в POST с :id='', а POST /api/groups/:id/leave может перепутаться.
// Клиент (app.js) вызывает вот эти три маршрута, но раньше сервер возвращал 404 — отсюда жалобы «группы сломались».
app.get("/api/groups", async (req, res) => {
try {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
res.json({ groups: await getUserGroups(me.login) });
} catch (e) { console.error("group list", e.message); res.status(500).json({ error: "server error" }); }
});
app.get("/api/groups/:id", async (req, res) => {
try {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
const id = req.params.id;
if (!/^\d+$/.test(id)) return res.status(400).json({ error: "bad id" });
const g = await getGroup(id); if (!g) return res.status(404).json({ error: "not found" });
const members = await getGroupMembersDetailed(id);
res.json({ ok: true, id: g.id, name: g.name, owner: g.owner, members });
} catch (e) { console.error("group get", e.message); res.status(500).json({ error: "server error" }); }
});
app.post("/api/groups", async (req, res) => {
try {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
const name = String(req.body?.name || "").trim();
if (!name) return res.status(400).json({ error: "name required" });
// Дублирруем name обрезкой и лимитом (VARCHAR(64) в schema), отбрасываем пустые.
const cleanName = name.slice(0, 64);
// members — comma-list (UI пикер может отправить несколько за раз). createGroup() сам добавляет owner
// и дедупит INSERT IGNORE по (group_id,login) — дубли и owner-дубли безопасно.
const memberList = [...new Set(String(req.body?.members || "").split(",").map((s) => s.trim().toLowerCase()).filter((l) => l && l !== me.login))];
const id = await createGroup(cleanName, me.login, memberList);
// Опциональный аватар: если передали — ставим отдельным UPDATE (не в createGroup, тот его не принимает). Лимит 3 MB как в rename/avatar верху.
if (typeof req.body?.avatar === "string" && req.body.avatar) await setGroupAvatar(id, req.body.avatar.slice(0, 5_000_000));
// Рассылаем group-updated всем новым участникам (включая овнера), чтобы их клиенты показали группу в списке чатов без ручного refetch.
try { for (const l of await getGroupMembers(id)) notifyUser(l, "group-updated", { id }); } catch {}
res.json({ ok: true, id, name: cleanName });
} catch (e) { console.error("group create", e.message); res.status(500).json({ error: "server error" }); }
});
app.post("/api/groups/:id/leave", async (req, res) => {
try {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
const id = req.params.id;
if (!/^\d+$/.test(id)) return res.status(400).json({ error: "bad id" });
// Проверяем что группа вообще существует и пользователь её участник — иначе 404 вместо молчаливого 200.
const g = await getGroup(id); if (!g) return res.status(404).json({ error: "not found" });
if (!(await isGroupMember(id, me.login))) return res.status(404).json({ error: "not a member" });
// Если уходит овнер — группа становится «безхозной». Мы не передаём владение автоматом (это большой UX-шок) — вместо этого: если овнер в группе один, автоматически удаляем группу; иначе просто выводим из group_members.
const wasOwner = g.owner === me.login;
const membersBefore = await getGroupMembers(id);
const willDelete = wasOwner && membersBefore.length === 1;
if (!willDelete) {
saveSystemMessage("@grp:" + id, me.login, me.name, "leave", "");
}
await leaveGroup(id, me.login);
if (willDelete) {
// Одинокий участник — он же овнер; после leaveGroup() группа пуста, а сообщения в нёй орфаны. Проще всё удалить целиком.
await deleteGroup(id);
notifyUser(me.login, "group-deleted", { id });
} else {
// Если ушёл овнер и в группе остались люди — передаём владение первому по алфавиту
// (getGroupMembersDetailed сортирует по u.name). Иначе chat_groups.owner останется указывать
// на ушедшего, и все owner-only маршруты (rename/avatar/members/delete/pending) начнут 403'ить.
if (wasOwner) {
const remaining = await getGroupMembersDetailed(id);
if (remaining.length) await setGroupOwner(id, remaining[0].login);
}
// Оповещаем оставшихся участников — они должны увидеть обновлённый список без этого юзера.
try { for (const l of await getGroupMembers(id)) notifyUser(l, "group-updated", { id }); } catch {}
}
res.json({ ok: true });
} catch (e) { console.error("group leave", e.message); res.status(500).json({ error: "server error" }); }
});
// Redeem an invite code → auto-join (must be BEFORE "/api/groups/:id" or Express
// matches :id="redeem" and this never runs — that was why joining silently failed).
// Unauthenticated → {loginRequired:true}; authenticated → joins directly.
app.post("/api/groups/redeem", async (req, res) => {
try {
const me = await authUser(req);
if (!me) return res.json({ loginRequired: true });
const code = String(req.body.code || "").trim();
if (!code) return res.status(400).json({ error: "no code" });
const inv = await getInviteByHash(hashInviteCode(code));
if (!inv) return res.json({ ok: false, status: "invalid" });
if (inv.expires != null && inv.expires < Date.now()) { await revokeGroupInvite(inv.id).catch(() => {}); return res.json({ ok: false, status: "expired" }); }
if (inv.max_uses != null && inv.uses >= inv.max_uses) { await revokeGroupInvite(inv.id).catch(() => {}); return res.json({ ok: false, status: "used_up" }); }
if (await isGroupMember(inv.group_id, me.login)) return res.json({ ok: true, status: "already", group: inv.group_id });
await addGroupMembers(inv.group_id, [me.login]); // the link IS the invitation — no approval
const u = await getUser(me.login);
if (u) saveSystemMessage("@grp:" + inv.group_id, me.login, u.name, "join", "");
await bumpInviteUse(inv.id);
for (const l of await getGroupMembers(inv.group_id)) notifyUser(l, "group-updated", { id: inv.group_id });
res.json({ ok: true, status: "joined", group: inv.group_id });
} catch (e) { console.error("redeem", e.message); res.status(500).json({ error: "server error" }); }
});
// Управление (только владелец): rename / avatar / add / remove / delete
async function notifyGroup(id, event, data) { try { for (const l of await getGroupMembers(id)) notifyUser(l, event, data); } catch {} }
app.post("/api/groups/:id", async (req, res) => {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
const id = req.params.id;
if (!(await isGroupOwner(id, me.login))) return res.status(403).json({ error: "not owner" });
const { name, avatar } = req.body || {};
if (typeof name === "string" && name.trim()) await renameGroup(id, name.trim().slice(0, 64));
if (typeof avatar === "string") await setGroupAvatar(id, avatar.slice(0, 5_000_000));
await notifyGroup(id, "group-updated", { id }); res.json({ ok: true });
});
app.post("/api/groups/:id/members", async (req, res) => {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
const id = req.params.id;
if (!(await isGroupOwner(id, me.login))) return res.status(403).json({ error: "not owner" });
const room = "@grp:" + id;
const before = await getGroupMembers(id);
if (Array.isArray(req.body.add)) {
// Skip anyone who has turned off "friends can add me to groups".
const requested = req.body.add.map((l) => String(l).toLowerCase());
const logins = [];
for (const l of requested) { if ((await getPrefs(l)).groupAdd) logins.push(l); }
const blocked = requested.filter((l) => !logins.includes(l));
await addGroupMembers(id, logins);
for (const login of logins) {
const u = await getUser(login);
if (u) saveSystemMessage(room, login, u.name, "join", "");
}
if (blocked.length && !logins.length) { res.json({ ok: false, error: "add_blocked", blocked }); return; }
req._blockedAdds = blocked;
}
if (req.body.remove) {
const login = String(req.body.remove).toLowerCase();
const u = await getUser(login);
await removeGroupMember(id, login);
if (u) saveSystemMessage(room, login, u.name, "leave", "");
}
const after = await getGroupMembers(id);
for (const l of new Set([...before, ...after])) notifyUser(l, "group-updated", { id });
res.json({ ok: true });
});
app.delete("/api/groups/:id", async (req, res) => {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
const id = req.params.id;
if (!(await isGroupOwner(id, me.login))) return res.status(403).json({ error: "not owner" });
const members = await getGroupMembers(id);
await deleteGroup(id);
for (const l of members) notifyUser(l, "group-deleted", { id });
res.json({ ok: true });
});
// ---------- REST: приглашения в группу (invite-codes + suggestion queue) ----------
// Шарабельные коды. Все участники могут создать (любой код — входная точка в группу, можно расшарить).
// Приватный ключ: SHA-256 хеш кода хранится в БД; plaintext 22-символьный код отдаётся клиенту
// ОДИН РАЗ при создании (как пароль). Поиск при redeem — по UNIQUE(code_hash), O(log n).
function genInviteCode() {
// 16 случайных байт в base64url (~22 символа без pad). Трим хвостовых '=' для URL-чистоты.
return crypto.randomBytes(16).toString("base64url").replace(/=+$/, "").slice(0, 22);
}
function hashInviteCode(code) {
// Lowercase trim — чтобы случайные leading/trailing spaces в pasted-коде не ломали lookup.
return crypto.createHash("sha256").update(String(code || "").trim().toLowerCase()).digest("hex");
}
app.post("/api/groups/:id/invites", async (req, res) => {
try {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
const id = req.params.id;
if (!/^\d+$/.test(id) || !(await isGroupMember(id, me.login))) return res.status(403).json({ error: "no access" });
const code = genInviteCode();
// Optional limits: maxUses (>=1) and days (>=1). 0/absent = unlimited / never expires.
const maxUses = Math.max(0, Math.min(9999, Number(req.body.maxUses) || 0)) || null;
const days = Math.max(0, Math.min(365, Number(req.body.days) || 0));
const expires = days > 0 ? Date.now() + days * 86400000 : null;
await createGroupInvite(id, me.login, hashInviteCode(code), maxUses, expires);
// Овнеру И создателю — обоим полезно видеть новую точку входа в списке инвайтов. Создатель не
// получит повторного socket-event потому что генерирует код в своём клиенте и сразу ре-фетчит,
// но emit «на всякий случай» — для апдейта UI без ручного refetch.
const g = await getGroup(id);
if (g) notifyUser(g.owner, "invite-created", { id });
notifyUser(me.login, "invite-created", { id });
res.json({ ok: true, code, url: "/invite/" + encodeURIComponent(code) });
} catch (e) { console.error("invite create", e.message); res.status(500).json({ error: "server error" }); }
});
app.get("/api/groups/:id/invites", async (req, res) => {
try {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
const id = req.params.id;
if (!/^\d+$/.test(id) || !(await isGroupMember(id, me.login))) return res.status(403).json({ error: "no access" });
res.json({ invites: await getGroupInvites(id) });
} catch (e) { console.error("invite list", e.message); res.status(500).json({ error: "server error" }); }
});
app.delete("/api/groups/:id/invites/:invId", async (req, res) => {
try {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
const id = req.params.id;
if (!/^\d+$/.test(id)) return res.status(400).json({ error: "bad id" });
const g = await getGroup(id); if (!g) return res.status(404).json({ error: "not found" });
// Владелец ЛЮБОЙ код может отозвать; обычный участник — только свои (созданные им самим).
const invId = parseInt(req.params.invId, 10);
const all = await getGroupInvites(id);
const target = all.find((x) => x.id === invId);
if (!target) return res.status(404).json({ error: "not found" });
if (g.owner !== me.login && target.creator_login !== me.login) return res.status(403).json({ error: "not allowed" });
await revokeGroupInvite(invId);
notifyGroup(id, "invites-changed", { id });
res.json({ ok: true });
} catch (e) { console.error("invite revoke", e.message); res.status(500).json({ error: "server error" }); }
});
// Public invite preview (no auth) — powers the /invite/<code> join page.
app.get("/api/invite/:code", async (req, res) => {
try {
const inv = await getInviteByHash(hashInviteCode(req.params.code));
if (!inv) return res.json({ ok: false, status: "invalid" });
if (inv.expires != null && inv.expires < Date.now()) return res.json({ ok: false, status: "expired" });
if (inv.max_uses != null && inv.uses >= inv.max_uses) return res.json({ ok: false, status: "used_up" });
const g = await getGroup(inv.group_id);
if (!g) return res.json({ ok: false, status: "invalid" });
const members = await getGroupMembers(inv.group_id);
res.json({ ok: true, group: { id: g.id, name: g.name, members: members.length },
remaining: inv.max_uses == null ? null : Math.max(0, inv.max_uses - inv.uses), expires: inv.expires });
} catch (e) { console.error("invite preview", e.message); res.status(500).json({ error: "server error" }); }
});
// In-app suggestion (любой участник может предложить друга). Цель НЕ добавляется в группу сразу —
// заявка попадает в pending и ждёт одобрения овнера. target — comma-list: пикер в одном сабмите
// может отправить несколько логинов; невалидные/уже-участники/уже-pending молча пропускаются.
app.post("/api/groups/:id/suggest", async (req, res) => {
try {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
const id = req.params.id;
if (!/^\d+$/.test(id) || !(await isGroupMember(id, me.login))) return res.status(403).json({ error: "no access" });
const targets = [...new Set(String(req.body.target || "").split(",").map((s) => s.trim().toLowerCase()).filter(Boolean))]
.filter((l) => l !== me.login);
if (!targets.length) return res.status(400).json({ error: "bad target" });
let created = 0;
for (const target of targets) {
if (!(await getUser(target))) continue;
if (await isGroupMember(id, target)) continue;
if (!(await getPrefs(target)).groupAdd) continue; // target disallows being added to groups
const d = await createPendingInvite(id, target, me.login);
if (!d.duplicate) {
created++;
const g = await getGroup(id);
if (g) notifyUser(g.owner, "pending-new", { id, login: target, by: me.login });
notifyUser(target, "pending-new", { id, login: target, by: me.login });
}
}
res.json({ ok: true, status: "pending", created });
} catch (e) { console.error("suggest", e.message); res.status(500).json({ error: "server error" }); }
});
// Owner-only: список ожидающих заявок (для UI в settings → groups + для refresh после socket-event).
app.get("/api/groups/:id/pending", async (req, res) => {
try {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
const id = req.params.id;
if (!/^\d+$/.test(id) || !(await isGroupOwner(id, me.login))) return res.status(403).json({ error: "not owner" });
res.json({ pending: await getGroupPending(id) });
} catch (e) { console.error("pending list", e.message); res.status(500).json({ error: "server error" }); }
});
// Owner-only: approve/decline. Сначала ВЕРИФИЦИРУЕМ что pid принадлежит именно группе :id
// (подбором из getGroupPending(id) — pid это глобальный PK, но матчим по id для подстраховки).
app.post("/api/groups/:id/pending/:pid", async (req, res) => {
try {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
const id = req.params.id;
if (!/^\d+$/.test(id) || !(await isGroupOwner(id, me.login))) return res.status(403).json({ error: "not owner" });
const pid = parseInt(req.params.pid, 10);
const all = await getGroupPending(id);
const pending = all.find((p) => p.id === pid);
if (!pending) return res.status(404).json({ error: "not found" });
const action = String(req.body.action || "");
if (action !== "approve" && action !== "decline") return res.status(400).json({ error: "bad action" });
await deletePendingInvite(pid);
const gid = parseInt(id, 10);
if (action === "approve") {
await addGroupMembers(id, [pending.login]);
const u = await getUser(pending.login);
if (u) saveSystemMessage("@grp:" + id, pending.login, u.name, "join", "");
// group-updated рассылается notifyGroup/include через addGroupMembers; pending-resolved уходит
// целевому юзеру только. Ид — просто id (не дублируем как group, клиент использует p.id).
notifyUser(pending.login, "pending-resolved", { id: gid, action: "approve" });
} else {
notifyUser(pending.login, "pending-resolved", { id: gid, action: "decline" });
}
res.json({ ok: true });
} catch (e) { console.error("pending resolve", e.message); res.status(500).json({ error: "server error" }); }
});
// ---------- REST: друзья / блокировки ----------
app.get("/api/relations", async (req, res) => {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
res.json(await getRelationsFull(me.login));
});
app.post("/api/relations", async (req, res) => {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
const target = String(req.body.target || "").toLowerCase();
const action = req.body.action;
if (!target || target === me.login) return res.status(400).json({ error: "bad target" });
if (action === "block") { await setRelation(me.login, target, "block"); await removeFriend(me.login, target); notifyUser(target, "relations-changed", {}); }
else if (action === "unblock") await removeRelation(me.login, target, "block");
else return res.status(400).json({ error: "bad action" });
notifyUser(me.login, "relations-changed", {});
res.json({ ok: true });
});
// Can `from` send `to` a friend request, given `to`'s privacy preference?
async function canFriendRequest(from, to) {
const p = await getPrefs(to);
if (p.friendReq === "nobody") return false;
if (p.friendReq === "fof") return await haveMutualFriend(from, to); // friends-of-friends only
return true; // everyone
}
// ---------- REST: privacy preferences ----------
app.get("/api/prefs", async (req, res) => {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
res.json(await getPrefs(me.login));
});
app.post("/api/prefs", async (req, res) => {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
const patch = {};
if (["everyone", "fof", "nobody"].includes(req.body.friendReq)) patch.friendReq = req.body.friendReq;
if (typeof req.body.groupAdd === "boolean") patch.groupAdd = req.body.groupAdd;
if (typeof req.body.readReceipts === "boolean") patch.readReceipts = req.body.readReceipts;
if (typeof req.body.dmOpen === "boolean") patch.dmOpen = req.body.dmOpen;
await setPrefs(me.login, patch);
for (const tk of await import("./db.js").then((m) => m.tokensForLogin(me.login))) await import("./cache.js").then((c) => c.cacheDel("sess:" + tk));
res.json({ ok: true, prefs: await getPrefs(me.login) });
});
// ---------- REST: Themes (studio + workshop) ----------
app.get("/api/themes", async (req, res) => {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
res.json({ themes: await getUserThemes(me.login), limits: THEME_LIMITS, published: await countPublished(me.login) });
});
app.post("/api/themes", async (req, res) => {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
const { id, name, tokens } = req.body || {};
if (!tokens || typeof tokens !== "object") return res.status(400).json({ error: "bad_tokens" });
const out = await saveTheme(me.login, { id: id || null, name, tokens });
if (out.error) return res.status(400).json(out);
res.json({ ok: true, id: out.id });
});
app.delete("/api/themes/:id", async (req, res) => {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
await deleteTheme(me.login, Number(req.params.id) || 0);
res.json({ ok: true });
});
app.post("/api/themes/:id/publish", async (req, res) => {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
const id = Number(req.params.id) || 0;
const th = await getTheme(id);
if (!th || th.owner !== me.login) return res.status(404).json({ error: "not_found" });
const publish = !!req.body.published;
if (publish && !th.published && (await countPublished(me.login)) >= THEME_LIMITS.published) {
return res.status(400).json({ error: "publish_limit", limit: THEME_LIMITS.published });
}
await setThemePublished(me.login, id, publish);
res.json({ ok: true, published: publish });
});
app.get("/api/themes/workshop", async (req, res) => {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
res.json({ themes: await listWorkshop(String(req.query.q || ""), String(req.query.sort || "popular")) });
});
app.post("/api/themes/:id/install", async (req, res) => {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
const th = await getTheme(Number(req.params.id) || 0);
if (!th || !th.published) return res.status(404).json({ error: "not_found" });
await incThemeInstalls(th.id);
res.json({ ok: true, theme: { name: th.name, tokens: th.tokens, owner: th.owner } });
});
app.post("/api/friend", async (req, res) => {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
const target = String(req.body.target || "").toLowerCase();
const action = req.body.action;
if (!target || target === me.login) return res.status(400).json({ error: "bad target" });
if (action === "request") {
if (!(await getUser(target))) return res.status(404).json({ error: "not found" });
// Bots skip the privacy gate and auto-accept (handled in sendFriendRequest).
if (!(await isBot(target)) && !(await canFriendRequest(me.login, target))) return res.status(403).json({ error: "req_blocked" });
await sendFriendRequest(me.login, target);
}
else if (action === "accept") await acceptFriend(me.login, target);
else if (action === "decline") await declineFriend(me.login, target);
else if (action === "remove") await removeFriend(me.login, target);
else return res.status(400).json({ error: "bad action" });
notifyUser(target, "relations-changed", {}); notifyUser(me.login, "relations-changed", {});
res.json({ ok: true });
});
// Mutual friends: a per-contact list, and a one-shot map of counts for all my friends.
app.get("/api/mutual/:login", async (req, res) => {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
try { res.json({ ok: true, mutual: await mutualFriends(me.login, String(req.params.login).toLowerCase()) }); }
catch (e) { console.error("mutual", e.message); res.status(500).json({ error: "server error" }); }
});
app.get("/api/mutuals", async (req, res) => {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
try { res.json({ ok: true, counts: await mutualCounts(me.login) }); }
catch (e) { console.error("mutuals", e.message); res.status(500).json({ error: "server error" }); }
});
// ---------- REST: DM синхронизация ----------
app.get("/api/dms", async (req, res) => {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
res.json(await getUserDMs(me.login));
});
app.post("/api/dms", async (req, res) => {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
const list = Array.isArray(req.body.dms) ? req.body.dms.slice(0, 50) : [];
await saveUserDMs(me.login, list);
res.json({ ok: true });
});
// ---------- REST: закреплённые чаты (серверная синхронизация) ----------
app.get("/api/pins", async (req, res) => {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
res.json(await getPinnedChats(me.login));
});
app.post("/api/pins", async (req, res) => {
const me = await authUser(req); if (!me) return res.status(401).json({ error: "unauth" });
const keys = Array.isArray(req.body.keys) ? req.body.keys.slice(0, 200) : [];
await savePinnedChats(me.login, keys);
res.json({ ok: true });
});
// ---------- REST: Админка (только для ADMIN_LOGINS) ----------
async function requireAdmin(req, res) {
const me = await authUser(req);
if (!me) { res.status(401).json({ error: "unauth" }); return null; }
if (!auth.isAdmin(me.login)) { res.status(403).json({ error: "forbidden" }); return null; }
return me;
}
// Invalidate every session for a login and disconnect all its live sockets.
async function kickAllDevices(login) {
for (const tk of await import("./db.js").then((m) => m.tokensForLogin(login))) {
await import("./db.js").then((m) => m.deleteSession(tk));
await import("./cache.js").then((c) => c.cacheDel("sess:" + tk));
}
const ids = userSockets.get(login);
if (ids) for (const id of [...ids]) {
const s = io.sockets.sockets.get(id);
if (s) { s.emit("force-logout", { reason: "kicked" }); s.disconnect(true); }
}
}
app.get("/api/admin/stats", async (req, res) => {
if (!(await requireAdmin(req, res))) return;
res.json({ ...(await adminStats()), online: userSockets.size, reports: await countPendingReports() });
});
// ---- Reports review ----
app.get("/api/admin/reports", async (req, res) => {
if (!(await requireAdmin(req, res))) return;