Spaces:
Running
Running
Update server.js
Browse files30 unmodified lines313233343536373 unmodified lines414243444546195 unmodified lines242243244245246247248249250251252253254255136 unmodified lines39239339439539639743 unmodified lines4414424434444454464474484494502 unmodified lines4534544554564574584594604614624634644654664674686 unmodified lines475476477478479480481482483484485486487193 unmodified lines68168268368468568661 unmodified lines748749750751752753128 unmodified lines88288388488588688788888989089189289389489589689789819 unmodified lines9189199209219229239243 unmodified lines92892993093193293310 unmodified lines9449459469479489499509519529539549557 unmodified lines96396496596696796896997097197297397497527 unmodified lines10031004100510061007100810093 unmodified lines10131014101510161017101810191020102110221023121 unmodified lines11451146114711481149115011517 unmodified lines11591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211837 unmodified lines119111921193119411951196119711981199120012011202120312041205120612071208133 unmodified lines1342134313441345134613471348350 unmodified lines16991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117 unmodified lines174917501751175217531754175517561757175817591760176117621763176412 unmodified lines17771778177917801781178217836 unmodified lines17901791179217931794179510 unmodified lines1806180718081809181018111812181318141815181618178 unmodified lines18261827182818291830183118321833183418351441 unmodified lines32773278327932803281328232833284328532863287328822 unmodified lines3311331233133314331533163317159 unmodified lines347734783479348034813482348334843485348628 unmodified lines35153516351735183519352035213522352324 unmodified lines354835493550355135523553355435553556355735583559356030 unmodified lines}const SECURE_SALT = process.env.SECURE_SALT;const ENCRYPTION_KEY = Buffer.from(process.env.ENCRYPTION_KEY, 'hex');const app = express();const compression = require('compression');app.use(compression());3 unmodified linesconst escapeRegex = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');const PORT = process.env.PORT || 7860;const MONGO_URI = process.env.MONGO_URI;195 unmodified lines};if (!MONGO_URI) {} else {mongoose.connect(MONGO_URI, {serverSelectionTimeoutMS: 5000}).then(async () => {await runMigration();server.listen(PORT, '0.0.0.0', () => {});}).catch((err) => {});}if (!global.privacyMap) global.privacyMap = new Map();136 unmodified linesreturn match ? match[1] : null;};const MAX_SESSIONS = 5;const addSession = async (username, token, device, ip) => {43 unmodified linesconst clarify = (encoded) => {if (!encoded || typeof encoded !== 'string') return "";if (encoded.startsWith("4S_ENC_")) {try {const parts = encoded.replace("4S_ENC_", "").split(":");const iv = Buffer.from(parts[0], 'hex');const authTag = Buffer.from(parts[1], 'hex');const encryptedText = Buffer.from(parts[2], 'hex');2 unmodified lineslet decrypted = decipher.update(encryptedText, 'hex', 'utf8');decrypted += decipher.final('utf8');return decrypted;} catch { return encoded; }}if (encoded.startsWith("4S_")) {try {const decoded = Buffer.from(encoded.replace("4S_", ""), 'base64').toString('utf8');return decoded.includes("||") ? decoded.split("||")[0] : decoded;} catch { return encoded; }}return encoded;};6 unmodified linesencrypted += cipher.final('hex');const authTag = cipher.getAuthTag().toString('hex');return `4S_ENC_${iv.toString('hex')}:${authTag}:${encrypted}`;} catch { return text; }};if (!fs.existsSync('./uploads')) fs.mkdirSync('./uploads');app.use(express.json());app.use(express.urlencoded({ extended: true }));app.use('/uploads', express.static('uploads'));app.get('/api/firebase-config', (req, res) => {res.json({193 unmodified linesMessageSchema.index({ receiver: 1, isService: 1, timestamp: -1 });MessageSchema.index({ sender: 1, receiver: 1 });MessageSchema.index({ dialog_id: 1, isService: 1, timestamp: -1 });const updateDialogLastMessage = async (dialogId) => {try {61 unmodified linesconst Dialog = mongoose.model('Dialog', DialogSchema);const getDialogId = (u1, u2) => [String(u1).toLowerCase(), String(u2).toLowerCase()].sort().join('_');const callTimeouts = new Map();const activeCalls = new Map();128 unmodified linesconst eventName = packet[0];const data = packet[1];if (eventName === 'chat_message' && data && data.sender && data.receiver && !data.receiver.startsWith('room_')) {const canMessage = checkServerPrivacy(data.receiver, data.sender, 'messages');const isMedia = data.isAudio || data.isVideoNote;const canMedia = checkServerPrivacy(data.receiver, data.sender, 'voice_video');if (!canMessage) return socket.emit('error_message', { text: st('Отправка сообщений ограничена настройками приватности.', detectLang(socket)), tempId: data.tempId || null });if (isMedia && !canMedia) return socket.emit('error_message', { text: st('Отправка медиа ограничена настройками приватности.', detectLang(socket)), tempId: data.tempId || null });}if (eventName === 'typing' && data && data.sender && data.receiver && !data.receiver.startsWith('room_')) {if (!checkServerPrivacy(data.receiver, data.sender, 'status')) return nextEvent(new Error('Privacy: Status disabled'));}nextEvent();19 unmodified lineslet finalPath = null;try {if (!req.file) return res.status(400).json({ error: st('Файл не выбран', detectLangReq(req)) });const fsPromises = require('fs').promises;const originalPath = req.file.path;const cleanName = req.file.filename.replace(/[^a-z0-9.]/gi, '_').toLowerCase();3 unmodified linesconst ext = path.extname(cleanName).toLowerCase();finalPath = safePath;if (['.jpg', '.jpeg', '.png', '.webp'].includes(ext)) {try {const tempPath = safePath + '_clean.webp';10 unmodified lines}}const uploadOpts = {folder: "4send_cloud",resource_type: "auto",image_metadata: false};if (['.jpg', '.jpeg', '.png', '.webp', '.gif'].includes(ext)) {uploadOpts.quality = "auto";} else if (['.mp3', '.wav', '.ogg', '.m4a', '.mp4', '.webm', '.mov'].includes(ext)) {7 unmodified linesconst result = await cloudinary.uploader.upload(finalPath, uploadOpts);if (fs.existsSync(finalPath)) await fsPromises.unlink(finalPath);res.json({ url: result.secure_url });} catch (err) {const fsPromises = require('fs').promises;if (req.file && fs.existsSync(req.file.path)) await fsPromises.unlink(req.file.path).catch(()=>{});if (safePath && fs.existsSync(safePath)) await fsPromises.unlink(safePath).catch(()=>{});if (finalPath && fs.existsSync(finalPath)) await fsPromises.unlink(finalPath).catch(()=>{});res.status(500).json({ error: st('Ошибка сервера', detectLangReq(req)) });}});27 unmodified linesapp.post('/auth/register', authLimiter, async (req, res) => {const { username, password, termsAccepted } = req.body;if (!termsAccepted) return res.status(400).json({ error: st('Примите условия использования', detectLangReq(req)) });if (!username || !password) return res.status(400).json({ error: st('Заполните все поля', detectLangReq(req)) });if (username.toLowerCase() === 'username') return res.status(400).json({ error: st('Это имя пользователя запрещено', detectLangReq(req)) });if (!/^[a-z]+$/.test(username) || username.length < 4 || username.length > 20) return res.status(400).json({ error: st('Логин: только строчные буквы, от 4 до 20 символов', detectLangReq(req)) });if (password.length < 8 || password.length > 30) return res.status(400).json({ error: st('Пароль должен быть от 8 до 30 символов', detectLangReq(req)) });3 unmodified linesconst hashed = await bcrypt.hash(password, 10);user = await User.create({ username, password: hashed });const token = jwt.sign({ username: user.username, role: user.role }, JWT_SECRET, { expiresIn: '30d' });const device = req.headers['user-agent'] || 'Unknown Device';const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress || 'Unknown IP';await addSession(user.username, token, device, ip);res.json({ username: user.username, avatar: user.avatar, role: user.role, isVerified: user.isVerified, displayName: user.displayName, token });} catch { res.status(500).json({ error: 'DB Error' }); }});121 unmodified linesapp.post('/auth/login', authLimiter, async (req, res) => {const { username, password } = req.body;if (!username || !password) return res.status(400).json({ error: st('Заполните все поля', detectLangReq(req)) });if (username.length > 20 || password.length > 30) return res.status(400).json({ error: st('Неверный логин или пароль', detectLangReq(req)) });try {let user = await User.findOne({ username });7 unmodified linesif (!(await bcrypt.compare(password, user.password))) {return res.status(400).json({ error: st('Неверный логин или пароль', detectLangReq(req)) });}if (user.twoFactorPassword) {return res.json({ requires2FA: true, username: user.username });}const token = jwt.sign({ username: user.username, role: user.role }, JWT_SECRET, { expiresIn: '30d' });const device = req.headers['user-agent'] || 'Unknown Device';const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress || 'Unknown IP';await addSession(user.username, token, device, ip);await sendLoginNotification(user.username, device, ip, detectLangReq(req));res.json({ username: user.username, avatar: user.avatar, role: user.role, isVerified: user.isVerified, displayName: user.displayName, token });} catch { res.status(500).json({ error: 'DB Error' }); }});app.post('/auth/login/2fa', authLimiter, async (req, res) => {const { username, password, twoFactorPassword } = req.body;if (!username || !password || !twoFactorPassword) return res.status(400).json({ error: st('Заполните все поля', detectLangReq(req)) });if (username.length > 20 || password.length > 30 || twoFactorPassword.length > 30) return res.status(400).json({ error: st('Неверные данные', detectLangReq(req)) });try {let user = await User.findOne({ username });7 unmodified linesif (!(await bcrypt.compare(password, user.password))) {return res.status(400).json({ error: st('Неверный логин или пароль', detectLangReq(req)) });}if (!user.twoFactorPassword || !(await bcrypt.compare(twoFactorPassword, user.twoFactorPassword))) {return res.status(400).json({ error: st('Неверный 2FA пароль', detectLangReq(req)) });}const token = jwt.sign({ username: user.username, role: user.role }, JWT_SECRET, { expiresIn: '30d' });const device = req.headers['user-agent'] || 'Unknown Device';const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress || 'Unknown IP';await addSession(user.username, token, device, ip);await sendLoginNotification(user.username, device, ip, detectLangReq(req));res.json({ username: user.username, avatar: user.avatar, role: user.role, isVerified: user.isVerified, displayName: user.displayName, token });} catch { res.status(500).json({ error: 'DB Error' }); }});133 unmodified linesconst newToken = jwt.sign({ username: newUsername, role: user.role }, JWT_SECRET, { expiresIn: '30d' });const device = req.headers['user-agent'] || 'Unknown Device';const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress || 'Unknown IP';await addSession(newUsername, newToken, device, ip);io.emit('user_updated', { oldUsername, newUsername, avatarUrl: finalAvatar, displayName: user.displayName });350 unmodified linesconst isPrivateIP = (addr) => {if (!addr) return true;if (addr === '0.0.0.0' || addr === '::' || addr === '::1') return true;if (addr === '127.0.0.1' || addr.startsWith('127.')) return true;if (addr.startsWith('10.')) return true;if (addr.startsWith('192.168.')) return true;if (addr.startsWith('172.')) {const second = parseInt(addr.split('.')[1], 10);if (second >= 16 && second <= 31) return true;}if (addr.startsWith('169.254.')) return true;if (addr.startsWith('::ffff:127.')) return true;if (addr.startsWith('::ffff:10.')) return true;if (addr.startsWith('::ffff:192.168.')) return true;if (addr.startsWith('::ffff:172.')) {const second = parseInt(addr.split('.')[1], 10);if (second >= 16 && second <= 31) return true;}if (addr.startsWith('::ffff:169.254.')) return true;if (addr.startsWith('fc') || addr.startsWith('fd')) return true;if (addr.startsWith('fe80:')) return true;if (addr.startsWith('ff')) return true;return false;};app.get('/api/link-preview', authenticateToken, async (req, res) => {const { url } = req.query;if (!url) return res.status(400).json({ error: 'No URL' });try {const parsedUrl = new URL(url);17 unmodified linesconst safeUrl = `${parsedUrl.protocol}//${addr}${parsedUrl.port ? ':' + parsedUrl.port : ''}${parsedUrl.pathname}${parsedUrl.search}`;const response = await axios.get(safeUrl, {timeout: 3000,headers: {'Host': hostname,'User-Agent': 'Mozilla/5.0'},maxContentLength: 5 * 1024 * 1024,signal: AbortSignal.timeout(3000)});const contentType = response.headers['content-type'] || '';if (!contentType.includes('text/html') && !contentType.includes('application/xhtml')) {return res.status(400).json({ error: 'Unsupported content type' });12 unmodified linesapp.post('/upload-multiple', authenticateToken, uploadLimiter, upload.array('files', 10), async (req, res) => {try {if (!req.files || req.files.length === 0) return res.status(400).json({ error: st('Файлы не выбраны', detectLangReq(req)) });const fsPromises = require('fs').promises;const urls =[];6 unmodified linesconst ext = path.extname(cleanName).toLowerCase();let finalPath = safePath;if (['.jpg', '.jpeg', '.png', '.webp'].includes(ext)) {try {const tempPath = safePath + '_clean.webp';10 unmodified lines}}const uploadOpts = {folder: "4send_cloud",resource_type: "auto",image_metadata: false};if (['.jpg', '.jpeg', '.png', '.webp', '.gif'].includes(ext)) {uploadOpts.quality = "auto";} else if (['.mp3', '.wav', '.ogg', '.m4a', '.mp4', '.webm', '.mov'].includes(ext)) {8 unmodified linesif (fs.existsSync(finalPath)) await fsPromises.unlink(finalPath);urls.push(result.secure_url);}res.json({ urls });} catch (err) {res.status(500).json({ error: st('Ошибка сервера', detectLangReq(req)) });}});1441 unmodified linesio.on('connection', (socket) => {socket.use((packet, next) => {const now = Date.now();const userLimits = socketRateLimits.get(socket.id) ||[];const recent = userLimits.filter(t => now - t < 1000);if (recent.length >= 10) return next(new Error('Rate limit exceeded'));recent.push(now);socketRateLimits.set(socket.id, recent);next();});socket.on('join', (user) => handleJoin(socket, user));22 unmodified linessocket.on('mark_read', (data) => handleMarkRead(socket, data));socket.on('delete_msg', (id) => handleDeleteMsg(socket, id));socket.on('disconnect', async () => {socketRateLimits.delete(socket.id);handleDisconnect(socket);const username = socket.username ? socket.username.toLowerCase() : null;if (username) {159 unmodified lines} catch {}});socket.on('call_request', (data) => {const canCall = checkServerPrivacy(data.target, socket.username, 'calls');if (!canCall) return socket.emit('call_error', { reason: 'privacy' });const caller = socket.username.toLowerCase();const target = String(data.target).toLowerCase();activeCalls.set(caller, { target, withVideo: !!data.withVideo, socketId: socket.id });io.to(data.target).emit('call_incoming', { caller: socket.username, withVideo: data.withVideo, ringFile: data.ringFile || 'calling.mp3' });const key = `${caller}_${target}`;28 unmodified lines}, 30000));});socket.on('call_response', async (data) => {io.to(data.target).emit('call_answered', { answer: data.answer });const caller = String(data.target).toLowerCase();const receiver = socket.username.toLowerCase();const key = `${caller}_${receiver}`;if (callTimeouts.has(key)) { clearTimeout(callTimeouts.get(key)); callTimeouts.delete(key); }activeCalls.delete(caller);24 unmodified lines}});socket.on('webrtc_signal', (data) => {io.to(data.target).emit('webrtc_signal', { sender: socket.username, signal: data.signal });});socket.on('call_end', async (data) => {io.to(data.target).emit('call_ended');try {const caller = socket.username.toLowerCase();const target = String(data.target).toLowerCase();activeCalls.delete(caller);activeCalls.delete(target);const key1 = `${caller}_${target}`;30 unmodified lines313233343536373839403 unmodified lines44454647484950515253195 unmodified lines249250251252253254255256257258259260261262263136 unmodified lines40040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643 unmodified lines4804814824834844854864874884894902 unmodified lines4934944954964974984995005015025035045055065075086 unmodified lines515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550193 unmodified lines74474574674774874975061 unmodified lines812813814815816817818819820821822823824128 unmodified lines95395495595695795895996096196296396496596696796896997097197297319 unmodified lines9939949959969979989993 unmodified lines1003100410051006100710081009101010111012101310 unmodified lines1024102510261027102810291030103110321033103410357 unmodified lines104310441045104610471048104910501051105210531054105527 unmodified lines10831084108510861087108810893 unmodified lines10931094109510961097109810991100110111021103121 unmodified lines12251226122712281229123012317 unmodified lines12391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212637 unmodified lines127112721273127412751276127712781279128012811282128312841285128612871288133 unmodified lines1422142314241425142614271428350 unmodified lines1779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181017 unmodified lines18281829183018311832183318341835183618371838183918401841184218431844184512 unmodified lines18581859186018611862186318646 unmodified lines1871187218731874187518761877187818791880188110 unmodified lines1892189318941895189618971898189919001901190219038 unmodified lines19121913191419151916191719181919192019211441 unmodified lines336333643365336633673368336933703371337233733374337533763377337822 unmodified lines3401340234033404340534063407159 unmodified lines356735683569357035713572357335743575357635773578357928 unmodified lines36083609361036113612361336143615361636173618361924 unmodified lines36443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366730 unmodified lines}const SECURE_SALT = process.env.SECURE_SALT;const ENCRYPTION_KEY = Buffer.from(process.env.ENCRYPTION_KEY || '', 'hex');if (ENCRYPTION_KEY.length !== 32) {throw new Error('ENCRYPTION_KEY must be a 32-byte (64 hex chars) value');}const app = express();const compression = require('compression');app.use(compression());3 unmodified linesconst escapeRegex = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');const logError = (scope, err) => {process.stderr.write(`[${new Date().toISOString()}] [${scope}] ${err && err.stack ? err.stack : err}\n`);};const PORT = process.env.PORT || 7860;const MONGO_URI = process.env.MONGO_URI;195 unmodified lines};if (!MONGO_URI) {logError('startup', 'MONGO_URI is not set');} else {mongoose.connect(MONGO_URI, {serverSelectionTimeoutMS: 5000}).then(async () => {await runMigration();server.listen(PORT, '0.0.0.0', () => {});}).catch((err) => {logError('mongo_connect', err);});}if (!global.privacyMap) global.privacyMap = new Map();136 unmodified linesreturn match ? match[1] : null;};const ALLOWED_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.webp', '.gif', '.mp3', '.wav', '.ogg', '.m4a', '.mp4', '.webm', '.mov'];const detectFileSignature = (buf) => {if (!buf || buf.length < 12) return null;const hex = buf.slice(0, 12).toString('hex').toLowerCase();const ascii = buf.slice(0, 12).toString('latin1');if (hex.startsWith('ffd8ff')) return 'image';if (hex.startsWith('89504e47')) return 'image';if (ascii.startsWith('GIF87a') || ascii.startsWith('GIF89a')) return 'image';if (ascii.startsWith('RIFF') && buf.slice(8, 12).toString('latin1') === 'WEBP') return 'image';if (ascii.startsWith('RIFF') && buf.slice(8, 12).toString('latin1') === 'WAVE') return 'media';if (hex.startsWith('494433') || hex.startsWith('fffb') || hex.startsWith('fff3') || hex.startsWith('fff2')) return 'media';if (ascii.startsWith('OggS')) return 'media';if (buf.slice(4, 8).toString('latin1') === 'ftyp') return 'media';if (hex.startsWith('1a45dfa3')) return 'media';return null;};const verifyUploadedFile = async (filePath, ext) => {if (!ALLOWED_EXTENSIONS.includes(ext)) return false;const fsPromises = require('fs').promises;const fd = await fsPromises.open(filePath, 'r');try {const buf = Buffer.alloc(12);await fd.read(buf, 0, 12, 0);return detectFileSignature(buf) !== null;} finally {await fd.close();}};const MAX_SESSIONS = 5;const addSession = async (username, token, device, ip) => {43 unmodified linesconst clarify = (encoded) => {if (!encoded || typeof encoded !== 'string') return "";if (encoded.startsWith("4S_ENC_")) {try {const parts = encoded.replace("4S_ENC_", "").split(":");if (parts.length !== 3) return "";const iv = Buffer.from(parts[0], 'hex');const authTag = Buffer.from(parts[1], 'hex');const encryptedText = Buffer.from(parts[2], 'hex');2 unmodified lineslet decrypted = decipher.update(encryptedText, 'hex', 'utf8');decrypted += decipher.final('utf8');return decrypted;} catch { return ""; }}if (encoded.startsWith("4S_")) {try {const decoded = Buffer.from(encoded.replace("4S_", ""), 'base64').toString('utf8');return decoded.includes("||") ? decoded.split("||")[0] : decoded;} catch { return encoded; }}return encoded;};6 unmodified linesencrypted += cipher.final('hex');const authTag = cipher.getAuthTag().toString('hex');return `4S_ENC_${iv.toString('hex')}:${authTag}:${encrypted}`;} catch {throw new Error('Encryption failed');}};if (!fs.existsSync('./uploads')) fs.mkdirSync('./uploads');app.use(express.json());app.use(express.urlencoded({ extended: true }));const sanitizeMongo = (obj) => {if (!obj || typeof obj !== 'object') return;if (Array.isArray(obj)) {obj.forEach(sanitizeMongo);return;}for (const key of Object.keys(obj)) {if (key.startsWith('$') || key.includes('.')) {delete obj[key];} else {sanitizeMongo(obj[key]);}}};app.use((req, res, next) => {sanitizeMongo(req.body);sanitizeMongo(req.query);sanitizeMongo(req.params);next();});app.use('/uploads', express.static('uploads'));app.get('/api/firebase-config', (req, res) => {res.json({193 unmodified linesMessageSchema.index({ receiver: 1, isService: 1, timestamp: -1 });MessageSchema.index({ sender: 1, receiver: 1 });MessageSchema.index({ dialog_id: 1, isService: 1, timestamp: -1 });MessageSchema.index({ expires_at: 1 }, { expireAfterSeconds: 0 });const updateDialogLastMessage = async (dialogId) => {try {61 unmodified linesconst Dialog = mongoose.model('Dialog', DialogSchema);const getDialogId = (u1, u2) => [String(u1).toLowerCase(), String(u2).toLowerCase()].sort().join('_');const getClientIp = (req) => {const xff = req.headers['x-forwarded-for'];if (typeof xff === 'string' && xff.length > 0) {return xff.split(',')[0].trim();}return req.ip || req.socket.remoteAddress || 'Unknown IP';};const callTimeouts = new Map();const activeCalls = new Map();128 unmodified linesconst eventName = packet[0];const data = packet[1];if (data && typeof data === 'object' && socket.username) {data.sender = socket.username;}if (eventName === 'chat_message' && data && data.receiver && !String(data.receiver).startsWith('room_')) {const canMessage = checkServerPrivacy(data.receiver, socket.username, 'messages');const isMedia = data.isAudio || data.isVideoNote;const canMedia = checkServerPrivacy(data.receiver, socket.username, 'voice_video');if (!canMessage) return socket.emit('error_message', { text: st('Отправка сообщений ограничена настройками приватности.', detectLang(socket)), tempId: data.tempId || null });if (isMedia && !canMedia) return socket.emit('error_message', { text: st('Отправка медиа ограничена настройками приватности.', detectLang(socket)), tempId: data.tempId || null });}if (eventName === 'typing' && data && data.receiver && !String(data.receiver).startsWith('room_')) {if (!checkServerPrivacy(data.receiver, socket.username, 'status')) return nextEvent(new Error('Privacy: Status disabled'));}nextEvent();19 unmodified lineslet finalPath = null;try {if (!req.file) return res.status(400).json({ error: st('Файл не выбран', detectLangReq(req)) });const fsPromises = require('fs').promises;const originalPath = req.file.path;const cleanName = req.file.filename.replace(/[^a-z0-9.]/gi, '_').toLowerCase();3 unmodified linesconst ext = path.extname(cleanName).toLowerCase();finalPath = safePath;if (!(await verifyUploadedFile(safePath, ext))) {if (fs.existsSync(safePath)) await fsPromises.unlink(safePath);return res.status(400).json({ error: st('Некорректный формат изображения', detectLangReq(req)) });}if (['.jpg', '.jpeg', '.png', '.webp'].includes(ext)) {try {const tempPath = safePath + '_clean.webp';10 unmodified lines}}const uploadOpts = {folder: "4send_cloud",resource_type: "auto",image_metadata: false};if (['.jpg', '.jpeg', '.png', '.webp', '.gif'].includes(ext)) {uploadOpts.quality = "auto";} else if (['.mp3', '.wav', '.ogg', '.m4a', '.mp4', '.webm', '.mov'].includes(ext)) {7 unmodified linesconst result = await cloudinary.uploader.upload(finalPath, uploadOpts);if (fs.existsSync(finalPath)) await fsPromises.unlink(finalPath);res.json({ url: result.secure_url });} catch (err) {const fsPromises = require('fs').promises;if (req.file && fs.existsSync(req.file.path)) await fsPromises.unlink(req.file.path).catch(()=>{});if (safePath && fs.existsSync(safePath)) await fsPromises.unlink(safePath).catch(()=>{});if (finalPath && fs.existsSync(finalPath)) await fsPromises.unlink(finalPath).catch(()=>{});res.status(500).json({ error: st('Ошибка сервера', detectLangReq(req)) });}});27 unmodified linesapp.post('/auth/register', authLimiter, async (req, res) => {const { username, password, termsAccepted } = req.body;if (!termsAccepted) return res.status(400).json({ error: st('Примите условия использования', detectLangReq(req)) });if (!username || !password || typeof username !== 'string' || typeof password !== 'string') return res.status(400).json({ error: st('Заполните все поля', detectLangReq(req)) });if (username.toLowerCase() === 'username') return res.status(400).json({ error: st('Это имя пользователя запрещено', detectLangReq(req)) });if (!/^[a-z]+$/.test(username) || username.length < 4 || username.length > 20) return res.status(400).json({ error: st('Логин: только строчные буквы, от 4 до 20 символов', detectLangReq(req)) });if (password.length < 8 || password.length > 30) return res.status(400).json({ error: st('Пароль должен быть от 8 до 30 символов', detectLangReq(req)) });3 unmodified linesconst hashed = await bcrypt.hash(password, 10);user = await User.create({ username, password: hashed });const token = jwt.sign({ username: user.username, role: user.role }, JWT_SECRET, { expiresIn: '30d' });const device = req.headers['user-agent'] || 'Unknown Device';const ip = getClientIp(req);await addSession(user.username, token, device, ip);res.json({ username: user.username, avatar: user.avatar, role: user.role, isVerified: user.isVerified, displayName: user.displayName, token });} catch { res.status(500).json({ error: 'DB Error' }); }});121 unmodified linesapp.post('/auth/login', authLimiter, async (req, res) => {const { username, password } = req.body;if (!username || !password || typeof username !== 'string' || typeof password !== 'string') return res.status(400).json({ error: st('Заполните все поля', detectLangReq(req)) });if (username.length > 20 || password.length > 30) return res.status(400).json({ error: st('Неверный логин или пароль', detectLangReq(req)) });try {let user = await User.findOne({ username });7 unmodified linesif (!(await bcrypt.compare(password, user.password))) {return res.status(400).json({ error: st('Неверный логин или пароль', detectLangReq(req)) });}if (user.twoFactorPassword) {return res.json({ requires2FA: true, username: user.username });}const token = jwt.sign({ username: user.username, role: user.role }, JWT_SECRET, { expiresIn: '30d' });const device = req.headers['user-agent'] || 'Unknown Device';const ip = getClientIp(req);await addSession(user.username, token, device, ip);await sendLoginNotification(user.username, device, ip, detectLangReq(req));res.json({ username: user.username, avatar: user.avatar, role: user.role, isVerified: user.isVerified, displayName: user.displayName, token });} catch { res.status(500).json({ error: 'DB Error' }); }});app.post('/auth/login/2fa', authLimiter, async (req, res) => {const { username, password, twoFactorPassword } = req.body;if (!username || !password || !twoFactorPassword || typeof username !== 'string' || typeof password !== 'string' || typeof twoFactorPassword !== 'string') return res.status(400).json({ error: st('Заполните все поля', detectLangReq(req)) });if (username.length > 20 || password.length > 30 || twoFactorPassword.length > 30) return res.status(400).json({ error: st('Неверные данные', detectLangReq(req)) });try {let user = await User.findOne({ username });7 unmodified linesif (!(await bcrypt.compare(password, user.password))) {return res.status(400).json({ error: st('Неверный логин или пароль', detectLangReq(req)) });}if (!user.twoFactorPassword || !(await bcrypt.compare(twoFactorPassword, user.twoFactorPassword))) {return res.status(400).json({ error: st('Неверный 2FA пароль', detectLangReq(req)) });}const token = jwt.sign({ username: user.username, role: user.role }, JWT_SECRET, { expiresIn: '30d' });const device = req.headers['user-agent'] || 'Unknown Device';const ip = getClientIp(req);await addSession(user.username, token, device, ip);await sendLoginNotification(user.username, device, ip, detectLangReq(req));res.json({ username: user.username, avatar: user.avatar, role: user.role, isVerified: user.isVerified, displayName: user.displayName, token });} catch { res.status(500).json({ error: 'DB Error' }); }});133 unmodified linesconst newToken = jwt.sign({ username: newUsername, role: user.role }, JWT_SECRET, { expiresIn: '30d' });const device = req.headers['user-agent'] || 'Unknown Device';const ip = getClientIp(req);await addSession(newUsername, newToken, device, ip);io.emit('user_updated', { oldUsername, newUsername, avatarUrl: finalAvatar, displayName: user.displayName });350 unmodified linesconst isPrivateIP = (addr) => {if (!addr) return true;const a = addr.replace(/^::ffff:/i, '');if (a === '0.0.0.0' || a === '::' || a === '::1') return true;if (/^127\./.test(a)) return true;if (/^10\./.test(a)) return true;if (/^192\.168\./.test(a)) return true;if (/^169\.254\./.test(a)) return true;if (/^172\.(1[6-9]|2[0-9]|3[0-1])\./.test(a)) return true;if (/^100\.(6[4-9]|[7-9][0-9]|1[0-1][0-9]|12[0-7])\./.test(a)) return true;if (/^192\.0\.0\./.test(a)) return true;if (/^192\.0\.2\./.test(a)) return true;if (/^198\.(1[8-9])\./.test(a)) return true;if (/^198\.51\.100\./.test(a)) return true;if (/^203\.0\.113\./.test(a)) return true;if (/^(22[4-9]|2[3-5][0-9])\./.test(a)) return true;if (/^fc/i.test(a) || /^fd/i.test(a)) return true;if (/^fe80:/i.test(a)) return true;if (/^ff/i.test(a)) return true;const octets = a.split('.');if (octets.length === 4 && octets.some(o => o === '' || /[^0-9]/.test(o) || parseInt(o, 10) > 255)) return true;return false;};app.get('/api/link-preview', authenticateToken, async (req, res) => {const { url } = req.query;if (!url || typeof url !== 'string') return res.status(400).json({ error: 'No URL' });try {const parsedUrl = new URL(url);17 unmodified linesconst safeUrl = `${parsedUrl.protocol}//${addr}${parsedUrl.port ? ':' + parsedUrl.port : ''}${parsedUrl.pathname}${parsedUrl.search}`;const response = await axios.get(safeUrl, {timeout: 3000,maxRedirects: 0,maxContentLength: 5 * 1024 * 1024,validateStatus: (status) => status >= 200 && status < 300,headers: {'Host': hostname,'User-Agent': 'Mozilla/5.0'},signal: AbortSignal.timeout(3000)});const contentType = response.headers['content-type'] || '';if (!contentType.includes('text/html') && !contentType.includes('application/xhtml')) {return res.status(400).json({ error: 'Unsupported content type' });12 unmodified linesapp.post('/upload-multiple', authenticateToken, uploadLimiter, upload.array('files', 10), async (req, res) => {try {if (!req.files || req.files.length === 0) return res.status(400).json({ error: st('Файлы не выбраны', detectLangReq(req)) });const fsPromises = require('fs').promises;const urls =[];6 unmodified linesconst ext = path.extname(cleanName).toLowerCase();let finalPath = safePath;if (!(await verifyUploadedFile(safePath, ext))) {if (fs.existsSync(safePath)) await fsPromises.unlink(safePath);continue;}if (['.jpg', '.jpeg', '.png', '.webp'].includes(ext)) {try {const tempPath = safePath + '_clean.webp';10 unmodified lines}}const uploadOpts = {folder: "4send_cloud",resource_type: "auto",image_metadata: false};if (['.jpg', '.jpeg', '.png', '.webp', '.gif'].includes(ext)) {uploadOpts.quality = "auto";} else if (['.mp3', '.wav', '.ogg', '.m4a', '.mp4', '.webm', '.mov'].includes(ext)) {8 unmodified linesif (fs.existsSync(finalPath)) await fsPromises.unlink(finalPath);urls.push(result.secure_url);}res.json({ urls });} catch (err) {res.status(500).json({ error: st('Ошибка сервера', detectLangReq(req)) });}});1441 unmodified linesio.on('connection', (socket) => {socket.use((packet, next) => {if (packet[1] && typeof packet[1] === 'object') {sanitizeMongo(packet[1]);}const rlKey = socket.username ? socket.username.toLowerCase() : socket.id;const now = Date.now();const userLimits = socketRateLimits.get(rlKey) || [];const recent = userLimits.filter(t => now - t < 1000);if (recent.length >= 10) return next(new Error('Rate limit exceeded'));recent.push(now);socketRateLimits.set(rlKey, recent);next();});socket.on('join', (user) => handleJoin(socket, user));22 unmodified linessocket.on('mark_read', (data) => handleMarkRead(socket, data));socket.on('delete_msg', (id) => handleDeleteMsg(socket, id));socket.on('disconnect', async () => {socketRateLimits.delete(socket.username ? socket.username.toLowerCase() : socket.id);handleDisconnect(socket);const username = socket.username ? socket.username.toLowerCase() : null;if (username) {159 unmodified lines} catch {}});socket.on('call_request', (data) => {if (!data || !data.target) return;const canCall = checkServerPrivacy(data.target, socket.username, 'calls');if (!canCall) return socket.emit('call_error', { reason: 'privacy' });const caller = socket.username.toLowerCase();const target = String(data.target).toLowerCase();if (caller === target) return;if (activeCalls.has(caller) || activeCalls.has(target)) return socket.emit('call_error', { reason: 'busy' });activeCalls.set(caller, { target, withVideo: !!data.withVideo, socketId: socket.id });io.to(data.target).emit('call_incoming', { caller: socket.username, withVideo: data.withVideo, ringFile: data.ringFile || 'calling.mp3' });const key = `${caller}_${target}`;28 unmodified lines}, 30000));});socket.on('call_response', async (data) => {if (!data || !data.target) return;const caller = String(data.target).toLowerCase();const receiver = socket.username.toLowerCase();const call = activeCalls.get(caller);if (!call || call.target !== receiver) return;io.to(data.target).emit('call_answered', { answer: data.answer });const key = `${caller}_${receiver}`;if (callTimeouts.has(key)) { clearTimeout(callTimeouts.get(key)); callTimeouts.delete(key); }activeCalls.delete(caller);24 unmodified lines}});socket.on('webrtc_signal', (data) => {if (!data || !data.target) return;const me = socket.username.toLowerCase();const target = String(data.target).toLowerCase();const call = activeCalls.get(me) || activeCalls.get(target);if (!call) return;const involved = (call.target === target && activeCalls.has(me)) || (call.target === me && activeCalls.has(target));if (!involved) return;io.to(data.target).emit('webrtc_signal', { sender: socket.username, signal: data.signal });});socket.on('call_end', async (data) => {if (!data || !data.target) return;const caller = socket.username.toLowerCase();const target = String(data.target).toLowerCase();const call = activeCalls.get(caller) || activeCalls.get(target);const involved = call && (call.target === target || call.target === caller);io.to(data.target).emit('call_ended');if (!involved) return;try {activeCalls.delete(caller);activeCalls.delete(target);const key1 = `${caller}_${target}`;
server.js+181-74