Spaces:
Running
Running
dev
#1
by 4send - opened
This view is limited to 50 files because it contains too many changes. See the raw diff here.
Files changed (50)
- .gitattributes-2
- Dockerfile+3-5
- app.jsDeleted-101
- config/cloudinary.jsDeleted-21
- config/env.jsDeleted-11
- config/firebase.jsDeleted-13
- constants/allowed.jsDeleted-6
- constants/limits.jsDeleted-66
- constants/translations.jsDeleted-141
- docs/oauth.mdDeleted-306
- index.jsDeleted-36
- jobs/autoDeleteUsers.jsDeleted-36
- jobs/messageExpiry.jsDeleted-37
- jobs/notificationRepeat.jsDeleted-41
- jobs/sessionCleanup.jsDeleted-33
- middleware/authenticateToken.jsDeleted-37
- middleware/botDetection.jsDeleted-14
- middleware/privacyWrapper.jsDeleted-50
- middleware/sanitizeMongo.jsDeleted-24
- middleware/securityHeaders.jsDeleted-28
- models/BlackList.jsDeleted-10
- models/ChatAction.jsDeleted-12
- models/Dialog.jsDeleted-27
- models/Message.jsDeleted-43
- models/OAuthApp.jsDeleted-17
- models/OAuthCode.jsDeleted-16
- models/OAuthRequest.jsDeleted-24
- models/OAuthToken.jsDeleted-18
- models/Pin.jsDeleted-15
- models/PreKey.jsDeleted-23
- models/Reaction.jsDeleted-11
- models/Room.jsDeleted-25
- models/User.jsDeleted-33
- package-lock.jsonDeleted
- package.json+28-29
- public/assets/AvatarCropper-43twomjP.cssDeleted-1
- public/assets/AvatarCropper-DDqz46Dp.jsDeleted-1
- public/assets/EmojiPanel-Bf-sbcJk.cssDeleted-1
- public/assets/EmojiPanel-DjvqtDVy.jsDeleted-1
- public/assets/EncryptionModal-Bk9GLrBN.cssDeleted-1
- public/assets/EncryptionModal-BmkhNiaW.jsDeleted-1
- public/assets/MessengerPage-C5heixc4.jsDeleted
- public/assets/MessengerPage-DQJ6Dqhc.cssDeleted
- public/assets/ModalShell-DH5TxKnz.jsDeleted-1
- public/assets/ModalShell-DxpX6TOZ.cssDeleted-1
- public/assets/OAuthAuthorizePage-BEN3iQn0.jsDeleted-1
- public/assets/OAuthAuthorizePage-Dv6k8Z10.cssDeleted-1
- public/assets/__vite-browser-external-BRm5n2qg.jsDeleted-1
- public/assets/encryption-DWQ3YZ9S.jsDeleted-2
- public/assets/index-C49_c6F1.jsDeleted
34 unmodified lines353637383934 unmodified lines*tfevents* filter=lfs diff=lfs merge=lfs -textpublic/calling.mp3 filter=lfs diff=lfs merge=lfs -textpublic/calling2.mp3 filter=lfs diff=lfs merge=lfs -textcalling.mp3 filter=lfs diff=lfs merge=lfs -textcalling2.mp3 filter=lfs diff=lfs merge=lfs -text34 unmodified lines35363734 unmodified lines*tfevents* filter=lfs diff=lfs merge=lfs -textpublic/calling.mp3 filter=lfs diff=lfs merge=lfs -textpublic/calling2.mp3 filter=lfs diff=lfs merge=lfs -text
3 unmodified lines45678910111213141516171819203 unmodified linesCOPY package*.json ./RUN npm install --omit=devCOPY . .RUN mkdir -p uploads && chown -R node:node /appUSER nodeENV PORT=7860ENV NODE_ENV=productionEXPOSE 7860CMD ["node", "index.js"]3 unmodified lines4567891011121314151617183 unmodified linesCOPY package*.json ./RUN npm install --omit=dev && npm install -g pm2COPY . .RUN mkdir -p uploadsENV PORT=7860ENV NODE_ENV=productionEXPOSE 7860CMD ["pm2-runtime", "start", "server.js", "-i", "1"]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101const express = require('express');const path = require('path');const session = require('express-session');const MongoStore = require('connect-mongo');const rateLimit = require('express-rate-limit');const compression = require('compression');const { MONGO_URI } = require('./constants/allowed');const { SESSION_SECRET } = require('./config/env');const fs = require('fs');const { sanitizeMiddleware } = require('./middleware/sanitizeMongo');const { botDetection } = require('./middleware/botDetection');const { corsHeaders, securityHeaders, cspMiddleware } = require('./middleware/securityHeaders');const { privacyWrapper } = require('./middleware/privacyWrapper');
const app = express();app.use(compression());app.set('trust proxy', 1);app.use(express.static(path.join(__dirname, 'public')));if (!global.privacyMap) global.privacyMap = new Map();if (!fs.existsSync(path.join(__dirname, 'uploads'))) fs.mkdirSync(path.join(__dirname, 'uploads'));
app.use(corsHeaders);
const sessionLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 10000, validate: { xForwardedForHeader: false }, keyGenerator: (req) => req.session?.username || req.ip, message: 'Too many requests'});app.use(sessionLimiter);
app.use(session({ name: '4send_sid', secret: SESSION_SECRET, resave: false, saveUninitialized: false, store: MongoStore.create({ mongoUrl: MONGO_URI, collectionName: 'sessions', ttl: 24 * 60 * 60 }), cookie: { httpOnly: true, secure: process.env.NODE_ENV === 'production', sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax', maxAge: 24 * 60 * 60 * 1000 }}));
const User = require('./models/User');app.use(async (req, res, next) => { if (req.session && req.session.username && !req.session.avatar) { try { const user = await User.findOne({ username: req.session.username }).select('avatar').lean(); if (user && user.avatar) req.session.avatar = user.avatar; } catch (e) {} } next();});
app.use(express.json({ limit: '10mb' }));app.use(express.urlencoded({ extended: true, limit: '10mb' }));app.use(botDetection);app.use(securityHeaders);app.use(cspMiddleware);app.use(sanitizeMiddleware);app.use(privacyWrapper);
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', require('./routes/root'));app.use('/', require('./routes/auth'));app.use('/', require('./routes/users'));app.use('/', require('./routes/upload'));app.use('/', require('./routes/chats'));app.use('/', require('./routes/rooms'));app.use('/', require('./routes/admin'));app.use('/', require('./routes/settings'));app.use('/', require('./routes/security'));app.use('/', require('./routes/block'));app.use('/', require('./routes/media'));app.use('/', require('./routes/pins'));app.use('/', require('./routes/link'));app.use('/', require('./routes/push'));app.use('/', require('./routes/account'));app.use('/', require('./routes/sessions'));app.use('/', require('./routes/oauth'));app.use('/', require('./routes/oauthApps'));app.use('/', require('./routes/ai'));app.use('/', require('./routes/firebase'));app.use('/', require('./routes/keys'));app.use('/', require('./routes/reports'));
const API_PREFIXES = ['/auth', '/api', '/upload', '/history', '/chats-extended', '/socket.io', '/languages', '/fonts', '/oauth'];
app.get('*', (req, res) => { if (req.path === '/oauth/authorize' || req.path === '/oauth/authorize/') { return res.sendFile(path.join(__dirname, 'public', 'index.html')); } if (API_PREFIXES.some(p => req.path.startsWith(p))) { return res.status(404).send('Not found'); } res.sendFile(path.join(__dirname, 'public', 'index.html'));});
app.use((req, res) => res.status(404).send('Not found'));app.use((err, req, res, next) => { res.status(500).send('Server error'); });
module.exports = app;123456789101112131415161718192021const cloudinary = require('cloudinary').v2;
const cloudName = process.env.CLOUDINARY_NAME;const apiKey = process.env.CLOUDINARY_KEY;const apiSecret = process.env.CLOUDINARY_SECRET;
if (!cloudName || !apiKey || !apiSecret) { console.error('[CLOUDINARY] Missing env vars:', { CLOUDINARY_NAME: !!cloudName, CLOUDINARY_KEY: !!apiKey, CLOUDINARY_SECRET: !!apiSecret });}
cloudinary.config({ cloud_name: cloudName, api_key: apiKey, api_secret: apiSecret});
module.exports = cloudinary;1234567891011const crypto = require('crypto');
const JWT_SECRET = process.env.JWT_SECRET;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 SESSION_SECRET = process.env.SESSION_SECRET || crypto.randomBytes(64).toString('hex');
module.exports = { JWT_SECRET, SECURE_SALT, ENCRYPTION_KEY, SESSION_SECRET };12345678910111213const admin = require('firebase-admin');
try { if (process.env.FIREBASE_SERVICE_ACCOUNT) { const serviceAccount = JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT); admin.initializeApp({ credential: admin.credential.cert(serviceAccount) }); }} catch (err) {}
module.exports = admin;123456const ALLOWED_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.webp', '.gif', '.mp3', '.wav', '.ogg', '.m4a', '.mp4', '.webm', '.mov'];const MAX_SESSIONS = 5;const PORT = process.env.PORT || 7860;const MONGO_URI = process.env.MONGO_URI;
module.exports = { ALLOWED_EXTENSIONS, MAX_SESSIONS, PORT, MONGO_URI };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566const rateLimit = require('express-rate-limit');
const authLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 5, keyGenerator: (req) => req.ip, message: { error: 'Слишком много попыток входа. Попробуйте позже.' }, standardHeaders: true, legacyHeaders: false});
const uploadLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 30, keyGenerator: (req) => req.ip, message: { error: 'Превышен лимит загрузки файлов. Попробуйте позже.' }, standardHeaders: true, legacyHeaders: false});
const securityLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 10, keyGenerator: (req) => req.ip, message: { error: 'Слишком много попыток. Попробуйте позже.' }, standardHeaders: true, legacyHeaders: false});
const aiLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 10, keyGenerator: (req) => req.ip, message: { error: 'Слишком много AI запросов. Попробуйте позже.' }, standardHeaders: true, legacyHeaders: false});
const oauthLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 40, keyGenerator: (req) => `${String(req.body && req.body.username || '').toLowerCase()}:${req.ip}`, message: { error: 'Слишком много попыток. Попробуйте позже.' }, standardHeaders: true, legacyHeaders: false});
const oauthCodeLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 40, keyGenerator: (req) => `${String(req.body && req.body.challenge || '').slice(0, 24)}:${req.ip}`, message: { error: 'Слишком много попыток. Попробуйте позже.' }, standardHeaders: true, legacyHeaders: false});
const oauthTokenLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 300, keyGenerator: (req) => req.ip, message: { error: 'Слишком много запросов. Попробуйте позже.' }, standardHeaders: true, legacyHeaders: false});
module.exports = { authLimiter, uploadLimiter, securityLimiter, aiLimiter, oauthLimiter, oauthCodeLimiter, oauthTokenLimiter };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141const serverTranslations = { 'Системные уведомления': { ru: 'Системные уведомления', en: 'System notifications' }, 'Поддержка 4SEND': { ru: 'Поддержка 4SEND', en: '4SEND Support' }, 'Уведомления от системы.': { ru: 'Уведомления от системы.', en: 'System notifications.' }, 'Решу вашу проблему за минуту, уверяю.': { ru: 'Решу вашу проблему за минуту, уверяю.', en: "I'll solve your problem in a minute, I promise." }, 'установил(а) таймер автоудаления сообщений': { ru: 'установил(а) таймер автоудаления сообщений', en: 'set auto-delete timer for messages' }, 'отключил(а) автоудаление сообщений': { ru: 'отключил(а) автоудаление сообщений', en: 'disabled auto-delete for messages' }, 'включил(а) запрет копирования': { ru: 'включил(а) запрет копирования', en: 'enabled copy protection' }, 'выключил(а) запрет копирования': { ru: 'выключил(а) запрет копирования', en: 'disabled copy protection' }, 'скрыл(а) информацию о пересылке': { ru: 'скрыл(а) информацию о пересылке', en: 'hidden forward info' }, 'открыл(а) информацию о пересылке': { ru: 'открыл(а) информацию о пересылке', en: 'shown forward info' }, 'включил(а) уведомления о скриншотах': { ru: 'включил(а) уведомления о скриншотах', en: 'enabled screenshot notifications' }, 'выключил(а) уведомления о скриншотах': { ru: 'выключил(а) уведомления о скриншотах', en: 'disabled screenshot notifications' }, 'переслал(а) сообщение': { ru: 'переслал(а) сообщение', en: 'forwarded a message' }, 'закрепил(а)': { ru: 'закрепил(а)', en: 'pinned' }, 'открепил(а) сообщение': { ru: 'открепил(а) сообщение', en: 'unpinned message' }, 'сделал(а) скриншот': { ru: 'сделал(а) скриншот', en: 'took a screenshot' }, 'скрыто': { ru: 'скрыто', en: 'hidden' }, 'Сохраненные сообщения': { ru: 'Сохраненные сообщения', en: 'Saved messages' }, 'Канал': { ru: 'Канал', en: 'Channel' }, 'Группа': { ru: 'Группа', en: 'Group' }, 'был(а) давно': { ru: 'был(а) давно', en: 'was online long ago' }, 'Новый вход в аккаунт': { ru: 'Новый вход в аккаунт', en: 'New account login' }, 'Устройство:': { ru: 'Устройство:', en: 'Device:' }, 'IP-адрес:': { ru: 'IP-адрес:', en: 'IP address:' }, 'Время:': { ru: 'Время:', en: 'Time:' }, 'Системное уведомление': { ru: 'Системное уведомление', en: 'System notification' }, 'У вас есть непрочитанные сообщения': { ru: 'У вас есть непрочитанные сообщения', en: 'You have unread messages' }, 'Непрочитанных сообщений:': { ru: 'Непрочитанных сообщений:', en: 'Unread messages:' }, 'Переслано от': { ru: 'Переслано от', en: 'Forwarded from' }, '📁 Файл': { ru: '📁 Файл', en: '📁 File' }, '📹 Видеосообщение': { ru: '📹 Видеосообщение', en: '📹 Video message' }, '🎤 Голосовое сообщение': { ru: '🎤 Голосовое сообщение', en: '🎤 Voice message' }, '🎵 Аудиозапись': { ru: '🎵 Аудиозапись', en: '🎵 Audio recording' }, '📷 Фотография': { ru: '📷 Фотография', en: '📷 Photo' }, '📷 Фотографии': { ru: '📷 Фотографии', en: '📷 Photos' }, '📹 Видео': { ru: '📹 Видео', en: '📹 Video' }, '📂 Пересланное': { ru: '📂 Пересланное', en: '📂 Forwarded' }, 'Файл не выбран': { ru: 'Файл не выбран', en: 'No file selected' }, 'Некорректный формат изображения': { ru: 'Некорректный формат изображения', en: 'Invalid image format' }, 'Ошибка сервера': { ru: 'Ошибка сервера', en: 'Server error' }, 'Требуется пароль': { ru: 'Требуется пароль', en: 'Password required' }, 'Неверный пароль': { ru: 'Неверный пароль', en: 'Wrong password' }, 'Примите условия использования': { ru: 'Примите условия использования', en: 'Accept terms of use' }, 'Заполните все поля': { ru: 'Заполните все поля', en: 'Fill in all fields' }, 'Это имя пользователя запрещено': { ru: 'Это имя пользователя запрещено', en: 'This username is forbidden' }, 'Пользователь уже существует': { ru: 'Пользователь уже существует', en: 'User already exists' }, 'Неверный логин или пароль': { ru: 'Неверный логин или пароль', en: 'Invalid username or password' }, 'Неверный 2FA пароль': { ru: 'Неверный 2FA пароль', en: 'Invalid 2FA password' }, 'Неверные данные': { ru: 'Неверные данные', en: 'Invalid data' }, 'Неверный основной пароль': { ru: 'Неверный основной пароль', en: 'Invalid main password' }, 'Не найден': { ru: 'Не найден', en: 'Not found' }, 'Старый пароль неверен': { ru: 'Старый пароль неверен', en: 'Old password is incorrect' }, 'Нет доступа к чужой переписке': { ru: 'Нет доступа к чужой переписке', en: 'No access to other users chats' }, 'Нет доступа к этой группе': { ru: 'Нет доступа к этой группе', en: 'No access to this group' }, 'Нет доступа': { ru: 'Нет доступа', en: 'Access denied' }, 'Файлы не выбраны': { ru: 'Файлы не выбраны', en: 'No files selected' }, 'Некорректные данные получателя.': { ru: 'Некорректные данные получателя.', en: 'Invalid recipient data.' }, 'Комната недоступна.': { ru: 'Комната недоступна.', en: 'Room is unavailable.' }, 'Только создатель может писать в канал.': { ru: 'Только создатель может писать в канал.', en: 'Only the creator can post in the channel.' }, 'Отправка сообщений ограничена.': { ru: 'Отправка сообщений ограничена.', en: 'Message sending is restricted.' }, 'Ошибка отправки сообщения.': { ru: 'Ошибка отправки сообщения.', en: 'Error sending message.' }, 'Ссылка уже занята': { ru: 'Ссылка уже занята', en: 'Link already taken' }, 'Данные не полные': { ru: 'Данные не полные', en: 'Incomplete data' }, 'Ошибка базы данных': { ru: 'Ошибка базы данных', en: 'Database error' }, 'Наши лучшие специалисты изучают вашу проблему и пытаются найти решение. Подождите немного...': { ru: 'Наши лучшие специалисты изучают вашу проблему и пытаются найти решение. Подождите немного...', en: 'Our best specialists are looking into your problem and trying to find a solution. Please wait...' }, 'Слишком много запросов. Попробуйте позже.': { ru: 'Слишком много запросов. Попробуйте позже.', en: 'Too many requests. Try again later.' }, 'Слишком много попыток входа. Попробуйте позже.': { ru: 'Слишком много попыток входа. Попробуйте позже.', en: 'Too many login attempts. Try again later.' }, 'Превышен лимит загрузки файлов. Попробуйте позже.': { ru: 'Превышен лимит загрузки файлов. Попробуйте позже.', en: 'File upload limit exceeded. Try again later.' }, 'Отправка сообщений ограничена настройками приватности.': { ru: 'Отправка сообщений ограничена настройками приватности.', en: 'Message sending is restricted by privacy settings.' }, 'Отправка медиа ограничена настройками приватности.': { ru: 'Отправка медиа ограничена настройками приватности.', en: 'Media sending is restricted by privacy settings.' }, 'Если это были не вы, немедленно завершите сеанс в Настройки -> Конфиденциальность -> Активные сеансы и измените пароль.': { ru: 'Если это были не вы, немедленно завершите сеанс в Настройки -> Конфиденциальность -> Активные сеансы и измените пароль.', en: 'If this wasn\'t you, immediately end the session in Settings -> Privacy -> Active sessions and change your password.' }, '2FA пароль должен быть от 4 до 30 символов': { ru: '2FA пароль должен быть от 4 до 30 символов', en: '2FA password must be 4-30 characters' }, 'Логин: только строчные буквы, от 4 до 20 символов': { ru: 'Логин: только строчные буквы, от 4 до 20 символов', en: 'Username: lowercase letters only, 4-20 characters' }, 'Имя не должно превышать 30 символов': { ru: 'Имя не должно превышать 30 символов', en: 'Name must not exceed 30 characters' }, 'Пароль должен быть от 8 до 30 символов': { ru: 'Пароль должен быть от 8 до 30 символов', en: 'Password must be 8-30 characters' }, 'Пароль должен быть от 4 до 30 символов': { ru: 'Пароль должен быть от 4 до 30 символов', en: 'Password must be 4-30 characters' }, 'Пароль не установлен': { ru: 'Пароль не установлен', en: 'Password not set' }, '❌ Ошибка: Нет ссылки на аудиофайл.': { ru: '❌ Ошибка: Нет ссылки на аудиофайл.', en: '❌ Error: No audio file link.' }, '❌ Ошибка: Недопустимый источник файла.': { ru: '❌ Ошибка: Недопустимый источник файла.', en: '❌ Error: Invalid file source.' }, '❌ Ошибка: API ключи Gemini не настроены в Secrets.': { ru: '❌ Ошибка: API ключи Gemini не настроены в Secrets.', en: '❌ Error: Gemini API keys not configured in Secrets.' }, '❌ Ошибка: Не удалось скачать аудиофайл (лимит 5 МБ).': { ru: '❌ Ошибка: Не удалось скачать аудиофайл (лимит 5 МБ).', en: '❌ Error: Failed to download audio file (limit 5 MB).' }, 'Неизвестная ошибка': { ru: 'Неизвестная ошибка', en: 'Unknown error' }, '❌ Нейросеть заблокировала ответ из-за внутренних фильтров безопасности Google.': { ru: '❌ Нейросеть заблокировала ответ из-за внутренних фильтров безопасности Google.', en: '❌ AI blocked the response due to Google safety filters.' }, 'Внутренняя ошибка сервера при обработке.': { ru: 'Внутренняя ошибка сервера при обработке.', en: 'Internal server error while processing.' }, 'Текст слишком короткий': { ru: 'Текст слишком короткий', en: 'Text too short' }, 'Опишите стиль': { ru: 'Опишите стиль', en: 'Describe the style' }, 'Текст слишком длинный (макс. 2000 символов)': { ru: 'Текст слишком длинный (макс. 2000 символов)', en: 'Text too long (max 2000 characters)' }, 'API ключи не настроены': { ru: 'API ключи не настроены', en: 'API keys not configured' }, 'Нет доступных моделей': { ru: 'Нет доступных моделей', en: 'No available models' }, 'Ошибка получения моделей: ': { ru: 'Ошибка получения моделей: ', en: 'Error fetching models: ' }, 'Ошибка нейросети: ': { ru: 'Ошибка нейросети: ', en: 'AI error: ' }, 'Внутренняя ошибка сервера': { ru: 'Внутренняя ошибка сервера', en: 'Internal server error' }, '⏳ Наши лучшие специалисты изучают вашу проблему и пытаются найти решение. Подождите немного...': { ru: '⏳ Наши лучшие специалисты изучают вашу проблему и пытаются найти решение. Подождите немного...', en: '⏳ Our best specialists are looking into your problem. Please wait...' }, 'Неизвестная ошибка API': { ru: 'Неизвестная ошибка API', en: 'Unknown API error' }, 'Медиафайл': { ru: 'Медиафайл', en: 'Media file' }, 'Привет': { ru: 'Привет', en: 'Hello' }, 'Нет доступных моделей для этого ключа': { ru: 'Нет доступных моделей для этого ключа', en: 'No available models for this key' }, 'Ошибка получения списка моделей: ': { ru: 'Ошибка получения списка моделей: ', en: 'Error fetching model list: ' }, 'Внутренняя ошибка API: ': { ru: 'Внутренняя ошибка API: ', en: 'Internal API error: ' }, 'Ключи API не настроены': { ru: 'Ключи API не настроены', en: 'API keys not configured' }, 'Превышен лимит символов (1000).': { ru: 'Превышен лимит символов (1000).', en: 'Character limit exceeded (1000).' }, 'Тревожный пароль должен быть от 8 до 30 символов': { ru: 'Тревожный пароль должен быть от 8 до 30 символов', en: 'Panic password must be 8-30 characters' }, 'Тревожный пароль не должен совпадать с основным': { ru: 'Тревожный пароль не должен совпадать с основным', en: 'Panic password must not match the main password' }, 'Неподдерживаемый тип медиа': { ru: 'Неподдерживаемый тип медиа', en: 'Unsupported media type' }, 'Файл слишком большой. Лимит 25 МБ': { ru: 'Файл слишком большой. Лимит 25 МБ', en: 'File too large. Limit 25 MB' }, 'Ошибка загрузки файла': { ru: 'Ошибка загрузки файла', en: 'File upload error' }, 'Недопустимый формат файла': { ru: 'Недопустимый формат файла', en: 'Invalid file format' }, 'Не удалось загрузить ни один файл': { ru: 'Не удалось загрузить ни один файл', en: 'Failed to upload any files' }, 'Код для входа': { ru: 'Код для входа', en: 'Sign-in code' }, 'Код входа:': { ru: 'Код входа:', en: 'Sign-in code:' }, 'Код действует 10 минут. Никому его не сообщайте.': { ru: 'Код действует 10 минут. Никому его не сообщайте.', en: 'The code is valid for 10 minutes. Do not share it.' }, 'Если это были не вы, смените пароль.': { ru: 'Если это были не вы, смените пароль.', en: 'If this was not you, change your password.' }};
const st = (key, lang) => { if (!key) return ''; const entry = serverTranslations[key]; if (!entry) return key; return entry[lang] || entry.ru || key;};
const detectLang = (socket) => { try { const customLang = socket.handshake?.query?.lang; if (customLang === 'en' || customLang === 'ru') return customLang; const acceptLang = socket.handshake?.headers?.['accept-language'] || ''; return acceptLang.toLowerCase().startsWith('en') ? 'en' : 'ru'; } catch { return 'ru'; }};
const detectLangReq = (req) => { try { const customLang = req.headers?.['x-language']; if (customLang === 'en' || customLang === 'ru') return customLang; const acceptLang = req.headers?.['accept-language'] || ''; return acceptLang.toLowerCase().startsWith('en') ? 'en' : 'ru'; } catch { return 'ru'; }};
module.exports = { serverTranslations, st, detectLang, detectLangReq };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306# Вход через 4SEND
4SEND поддерживает OAuth 2.0 Authorization Code Flow с PKCE. Сторонний сервис открывает страницу 4SEND, пользователь вводит логин и пароль, подтверждает вход шестизначным кодом из «Системных уведомлений» и возвращается в сервис с одноразовым кодом авторизации.
Пользователь видит приложение в разделе «Настройки → Конфиденциальность → Активные сессии» и может завершить его сеанс в любой момент.
## Возможности
- Authorization Code Flow с PKCE (`S256`)- Публичные клиенты без `client_secret`- Конфиденциальные клиенты с `client_secret`- Вращающиеся refresh-токены- Opaque access-токены и refresh-токены- Поддержка 2FA-пароля 4SEND- Одноразовые коды авторизации- Отображение стороннего приложения в активных сессиях- Отзыв сессии пользователем, приложением или администратором- Отзыв всех сессий приложения при его отключении или смене секрета
## Точки входа
Базовый адрес: `https://4send-messenger.hf.space`.
| Назначение | Адрес ||---|---|| Метаданные | `/.well-known/oauth-authorization-server` || Страница входа | `/oauth/authorize` || Обмен кода | `/oauth/token` || Профиль | `/oauth/userinfo` || Проверка токена | `/oauth/introspect` || Отзыв токена | `/oauth/revoke` |
Дополнительно сервер отдаёт метаданные с адресами и поддерживаемыми параметрами:
```bashcurl https://4send-messenger.hf.space/.well-known/oauth-authorization-server```
Для самостоятельного развёртывания задайте `PUBLIC_BASE_URL`, чтобы метаданные и адреса возврата формировались с правильным доменом.
## Регистрация приложения
Приложение создаёт администратор 4SEND. Нужен обычный JWT администратора.
```bashcurl -X POST https://4send-messenger.hf.space/api/oauth/apps \ -H "Authorization: Bearer ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "name": "My Service", "redirectUris": ["https://my-service.example/oauth/callback"], "website": "https://my-service.example", "scopes": ["profile"], "public": false }'```
Ответ содержит `clientId` и, для конфиденциального клиента, `clientSecret`. Секрет показывается только один раз.
Публичный клиент (`"public": true`) не получает секрет и обязан использовать PKCE.
Управление приложениями:
```bashGET /api/oauth/appsPATCH /api/oauth/apps/:clientIdPOST /api/oauth/apps/:clientId/rotate-secretDELETE /api/oauth/apps/:clientId```
`DELETE` отключает приложение и завершает все его сессии. Смена секрета также завершает все сессии приложения.
Правила для `redirectUris`:
- От 1 до 10 адресов.- Точное совпадение при авторизации.- Только `https://`, либо `http://localhost`, `http://127.0.0.1`, `http://[::1]` для разработки.- Можно использовать собственные схемы мобильных приложений, например `myapp://callback`.
## Авторизация
Сервис перенаправляет браузер пользователя на страницу 4SEND:
```https://4send-messenger.hf.space/oauth/authorize ?client_id=4send_xxx &redirect_uri=https%3A%2F%2Fmy-service.example%2Foauth%2Fcallback &response_type=code &scope=profile &state=random_csrf_value &code_challenge=BASE64URL_SHA256_OF_VERIFIER &code_challenge_method=S256```
Параметры:
| Параметр | Обязателен | Описание ||---|---|---|| `client_id` | Да | Идентификатор приложения || `redirect_uri` | Да | Точный адрес из настроек приложения || `response_type` | Да | Только `code` || `scope` | Нет | `profile` по умолчанию || `state` | Рекомендуется | Защита от CSRF, возвращается без изменений || `code_challenge` | Для публичных клиентов | S256-хэш PKCE-verifier || `code_challenge_method` | Для публичных клиентов | Только `S256` |
Пользователь вводит логин и пароль. Если включён 2FA, страница запросит второй пароль. Затем 4SEND отправит шестизначный код от бота `4send_system` в «Системные уведомления» и запросит его на странице.
Код действует 10 минут. Допускается 5 попыток ввода и 3 повторные отправки с интервалом 30 секунд.
После подтверждения браузер возвращается на `redirect_uri`:
```https://my-service.example/oauth/callback?code=AUTHORIZATION_CODE&state=random_csrf_value```
Код авторизации действует 60 секунд и используется один раз.
Если пользователь отклонил вход:
```https://my-service.example/oauth/callback?error=access_denied&state=random_csrf_value```
## Обмен кода на токены
Конфиденциальный клиент:
```bashcurl -X POST https://4send-messenger.hf.space/oauth/token \ -u "CLIENT_ID:CLIENT_SECRET" \ -H "Content-Type: application/x-www-form-urlencoded" \ --data-urlencode "grant_type=authorization_code" \ --data-urlencode "code=AUTHORIZATION_CODE" \ --data-urlencode "redirect_uri=https://my-service.example/oauth/callback"```
Публичный клиент:
```bashcurl -X POST https://4send-messenger.hf.space/oauth/token \ -H "Content-Type: application/x-www-form-urlencoded" \ --data-urlencode "grant_type=authorization_code" \ --data-urlencode "client_id=CLIENT_ID" \ --data-urlencode "code=AUTHORIZATION_CODE" \ --data-urlencode "redirect_uri=https://my-service.example/oauth/callback" \ --data-urlencode "code_verifier=PKCE_VERIFIER"```
Ответ:
```json{ "access_token": "opaque-access-token", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "opaque-refresh-token", "scope": "profile", "client": { "id": "4send_xxx", "name": "My Service" }, "user": { "sub": "username", "username": "username", "preferred_username": "username", "displayName": "", "avatar": null, "isVerified": false }}```
Access-токен действует 1 час. Refresh-токен действует 30 дней и при каждом обновлении заменяется новым.
## Обновление токенов
```bashcurl -X POST https://4send-messenger.hf.space/oauth/token \ -u "CLIENT_ID:CLIENT_SECRET" \ -H "Content-Type: application/x-www-form-urlencoded" \ --data-urlencode "grant_type=refresh_token" \ --data-urlencode "refresh_token=REFRESH_TOKEN"```
Старый refresh-токен после обновления недействителен. Если сессия завершена пользователем или приложение отключено, обновление вернёт `invalid_grant`.
## Профиль пользователя
```bashcurl https://4send-messenger.hf.space/oauth/userinfo \ -H "Authorization: Bearer ACCESS_TOKEN"```
```json{ "sub": "username", "username": "username", "preferred_username": "username", "displayName": "", "avatar": null, "isVerified": false, "scope": "profile", "client": { "id": "4send_xxx", "name": "My Service" }, "updated_at": "2026-01-01T00:00:00.000Z"}```
Доступ к чатам, сообщениям, файлам и контактам не предоставляется.
## Проверка и отзыв токена
```bashcurl -X POST https://4send-messenger.hf.space/oauth/introspect \ -u "CLIENT_ID:CLIENT_SECRET" \ -H "Content-Type: application/x-www-form-urlencoded" \ --data-urlencode "token=ACCESS_TOKEN"```
```json{ "active": true, "sub": "username", "username": "username", "client_id": "4send_xxx", "scope": "profile", "token_type": "Bearer", "exp": 1767225600, "iat": 1767222000}```
```bashcurl -X POST https://4send-messenger.hf.space/oauth/revoke \ -u "CLIENT_ID:CLIENT_SECRET" \ -H "Content-Type: application/x-www-form-urlencoded" \ --data-urlencode "token=ACCESS_OR_REFRESH_TOKEN"```
Отзыв токена завершает всю сессию приложения для этого пользователя.
## Активные сессии
После успешного обмена кода в профиле пользователя появляется сессия:
- `kind`: `oauth`- `clientId`- `clientName`- `scopes`- `device`: название приложения- `ip`- `lastActive`
В интерфейсе она отображается как стороннее приложение с названием и запрошенным доступом. Пользователь может завершить её кнопкой в «Активных сессиях» или через `POST /api/sessions/revoke` с `sessionId`.
При завершении сессии удаляются access- и refresh-токены, поэтому приложение сразу теряет доступ.
## Безопасность
- Пароль 4SEND никогда не передаётся стороннему приложению.- Access- и refresh-токены хранятся только в виде SHA-256-хэшей.- Коды авторизации хранятся в виде хэшей и действуют 60 секунд.- Шестизначный код хранится в виде HMAC и проверяется без раскрытия.- Для публичных клиентов PKCE обязателен.- `redirect_uri` проверяется по точному списку.- Одноразовые коды нельзя использовать повторно.- Код входа приходит только в «Системные уведомления» 4SEND и не отправляется на сторонние адреса.- При смене логина все OAuth-сессии пользователя завершаются.- При смене пароля или выходе из аккаунта сторонние сессии перестают быть действительными.- При отключении приложения, смене его секрета или удалении завершаются все его сессии.- Действуют отдельные лимиты на вход, ввод кода, обмен токена и проверку токена.- Ответы с токенами отдаются с `Cache-Control: no-store`.
## Ошибки
Стандартный формат:
```json{ "error": "invalid_grant", "error_description": "Код недействителен или истёк"}```
Основные коды:
| Код | Значение ||---|---|| `invalid_request` | Некорректные параметры запроса || `invalid_client` | Приложение не найдено, отключено или неверный секрет || `invalid_credentials` | Неверный логин, пароль или 2FA || `invalid_code` | Неверный шестизначный код || `invalid_grant` | Код авторизации, refresh-токен или сессия недействительны || `invalid_scope` | Запрошено неизвестное разрешение || `invalid_token` | Access-токен недействителен || `access_denied` | Пользователь или сервер отклонили вход || `too_many_requests` | Превышено число попыток || `slow_down` | Слишком частая повторная отправка кода || `server_error` | Внутренняя ошибка |
## Проверка state
Сторонний сервис обязан проверять `state` при возврате пользователя. Значение `state` не должно содержать секретов и должно быть связано с текущей попыткой входа, например храниться в серверной сессии.123456789101112131415161718192021222324252627282930313233343536const http = require('http');const mongoose = require('mongoose');const app = require('./app');const { initSocket } = require('./socket/index');const { PORT, MONGO_URI } = require('./constants/allowed');const { runMigration, loadPrivacyMap, dedupPins } = require('./services/migration');const { startAutoDeleteJob } = require('./jobs/autoDeleteUsers');const { startNotificationRepeatJob } = require('./jobs/notificationRepeat');const { startSessionCleanupJob } = require('./jobs/sessionCleanup');const { startMessageExpiryJob } = require('./jobs/messageExpiry');
if (!MONGO_URI) { process.stderr.write('MONGO_URI is not set\n'); process.exit(1);}
const server = http.createServer(app);initSocket(server);
mongoose.connect(MONGO_URI, { serverSelectionTimeoutMS: 5000 }) .then(async () => { await runMigration(); await loadPrivacyMap(); await dedupPins(); startAutoDeleteJob(); startNotificationRepeatJob(); startSessionCleanupJob(); startMessageExpiryJob(); server.listen(PORT, '0.0.0.0'); }) .catch((err) => { process.stderr.write(`[MONGO] ${err.message}\n`); process.exit(1); });
module.exports = app;123456789101112131415161718192021222324252627282930313233343536const User = require('../models/User');const { nukeUserAccount } = require('../services/auth');
const DAY_MS = 24 * 60 * 60 * 1000;
const runOnce = async () => { try { const users = await User.find({ role: { $ne: 'admin' } }).lean(); const now = Date.now();
for (const user of users) { const lastSeen = user.last_seen ? new Date(user.last_seen).getTime() : now; const daysInactive = Math.floor((now - lastSeen) / DAY_MS); const limitMonths = [3, 6, 12].includes(user.autoDeleteMonths) ? user.autoDeleteMonths : 6; const limitDays = limitMonths * 30;
if (daysInactive >= limitDays) { try { await nukeUserAccount(user.username); process.stdout.write(`[autoDeleteUsers] deleted ${user.username} after ${daysInactive}d\n`); } catch (err) { process.stderr.write(`[autoDeleteUsers] ${user.username}: ${err.message}\n`); } } } } catch (err) { process.stderr.write(`[autoDeleteUsers] ${err.message}\n`); }};
const startAutoDeleteJob = () => { setTimeout(runOnce, 15 * 1000); setInterval(runOnce, 24 * 60 * 60 * 1000);};
module.exports = { startAutoDeleteJob, runOnce };12345678910111213141516171819202122232425262728293031323334353637const fs = require('fs');const path = require('path');const Message = require('../models/Message');const Reaction = require('../models/Reaction');const { getIO } = require('../socket/io');
const startMessageExpiryJob = () => { setInterval(async () => { try { const expired = await Message.find({ expires_at: { $ne: null, $lte: new Date() } }).lean();
if (expired?.length > 0) { const io = getIO(); for (const msg of expired) { if (msg.fileUrl) { const cleanPath = msg.fileUrl.startsWith('/') ? msg.fileUrl.substring(1) : msg.fileUrl; const filePath = path.join(process.cwd(), cleanPath); if (fs.existsSync(filePath)) { try { fs.unlinkSync(filePath); } catch {} } }
const msgIdStr = msg._id.toString(); await Message.deleteOne({ _id: msg._id }); await Reaction.deleteMany({ message_id: msg._id }); io.to(msg.sender).to(msg.receiver).emit('msg_deleted', msgIdStr); } } } catch (err) { if (err.name === 'MissingSchemaError') return; } }, 10000);};
module.exports = { startMessageExpiryJob };1234567891011121314151617181920212223242526272829303132333435363738394041const User = require('../models/User');const Message = require('../models/Message');const { sendPushNotification } = require('../services/push');const { st } = require('../constants/translations');
const startNotificationRepeatJob = () => { setInterval(async () => { try { const now = new Date(); const users = await User.find({ notificationRepeat: { $gt: 0 }, pushToken: { $ne: null } }).lean();
for (const u of users) { const repeatMs = u.notificationRepeat * 60000; const cutoff = new Date(now.getTime() - repeatMs);
const unreadMsgs = await Message.find({ receiver: u.username, is_read: false, timestamp: { $lte: cutoff }, $or: [ { last_notified: { $exists: false } }, { last_notified: { $lte: cutoff } } ] }).lean();
if (unreadMsgs.length > 0) { const msgIds = unreadMsgs.map(m => m._id); await Message.updateMany({ _id: { $in: msgIds } }, { $set: { last_notified: now } });
await sendPushNotification(u.username, { notification: { title: st('У вас есть непрочитанные сообщения', 'ru'), body: `${st('Непрочитанных сообщений:', 'ru')} ${unreadMsgs.length}` }, android: { notification: { channelId: '4send_channel', priority: 'high', sound: 'default', icon: '/ico.png', tag: 'unread_reminder' } }, apns: { payload: { aps: { sound: 'default', badge: unreadMsgs.length, 'thread-id': 'unread_reminder' } } } }); } } } catch (err) {} }, 60000);};
module.exports = { startNotificationRepeatJob };123456789101112131415161718192021222324252627282930313233const User = require('../models/User');const OAuthToken = require('../models/OAuthToken');const { kickSessions } = require('../socket/kick');
const startSessionCleanupJob = () => { setInterval(async () => { try { const users = await User.find({ "sessions.0": { $exists: true } }).lean(); const now = new Date();
for (const u of users) { const limitDays = u.autoLogoutDays || 7; const limitMs = limitDays * 24 * 60 * 60 * 1000;
const expired = u.sessions.filter(s => (now - new Date(s.lastActive)) >= limitMs); if (!expired.length) continue;
const expiredTokens = new Set(expired.map(s => s.token)); const expiredSessionIds = expired.map(s => s.sessionId).filter(Boolean); const validSessions = u.sessions.filter(s => !expiredTokens.has(s.token)); await User.updateOne({ _id: u._id }, { $set: { sessions: validSessions } }); if (expiredSessionIds.length > 0) { await OAuthToken.deleteMany({ username: u.username, sessionId: { $in: expiredSessionIds } }); } kickSessions(u.username, t => expiredTokens.has(t)); } } catch (err) { console.error('[sessionCleanup]', err); } }, 60 * 60 * 1000);};
module.exports = { startSessionCleanupJob };12345678910111213141516171819202122232425262728293031323334353637const jwt = require('jsonwebtoken');const User = require('../models/User');const { JWT_SECRET } = require('../config/env');const { shouldUpdateLastActive } = require('../utils/lastActive');
const authenticateToken = (req, res, next) => { const authHeader = req.headers['authorization']; const token = authHeader && authHeader.split(' ')[1]; if (!token || !JWT_SECRET) return res.status(401).json({ error: 'Unauthorized' }); jwt.verify(token, JWT_SECRET, async (err, decoded) => { if (err || !decoded || typeof decoded.username !== 'string') { const msg = err && err.name === 'TokenExpiredError' ? 'Session expired' : 'Unauthorized'; return res.status(401).json({ error: msg }); } try { const username = decoded.username.trim().toLowerCase(); if (!/^[a-z]{4,20}$/.test(username)) return res.status(401).json({ error: 'Unauthorized' }); const user = await User.findOne({ username }).lean(); if (!user || user.role === 'banned') return res.status(403).json({ error: 'Banned' }); const isValid = Array.isArray(user.sessions) && user.sessions.some(s => s && s.token === token); if (!isValid) return res.status(401).json({ error: 'Session expired' }); if (shouldUpdateLastActive(username, token)) { await User.updateOne( { username, "sessions.token": token }, { $set: { "sessions.$.lastActive": new Date(), last_seen: new Date() } } ); } req.user = { ...decoded, username, role: user.role }; req.token = token; next(); } catch { res.status(500).json({ error: 'Server error' }); } });};
module.exports = { authenticateToken };1234567891011121314const botDetection = (req, res, next) => { const dangerousChars = /["';<>]/g; ['user-agent', 'referer', 'x-forwarded-for'].forEach(h => { if (req.headers[h] && dangerousChars.test(req.headers[h])) { req.headers[h] = req.headers[h].replace(dangerousChars, ""); } }); const ua = req.headers['user-agent']; if (!ua || ua.length < 10) return res.status(403).send('Bot detected'); if (req.headers['content-length'] > 30 * 1024 * 1024) return res.status(413).send('Too large'); next();};
module.exports = { botDetection };1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950const checkServerPrivacy = (owner, requester, type) => { if (!owner || !requester) return true; if (owner.toLowerCase() === requester.toLowerCase()) return true; const p = global.privacyMap.get(owner.toLowerCase()); if (!p) return true;
if (p[type] === 'none') return false; if (p[type] === 'selected') { return p.exceptions && p.exceptions[type] && p.exceptions[type].includes(requester.toLowerCase()); } return true;};
const privacyWrapper = (req, res, next) => { const origJson = res.json; res.json = function(data) { let requester = null; if (req.user && req.user.username) requester = req.user.username.toLowerCase(); else if (req.query.me) requester = req.query.me.toLowerCase();
if (requester && data && typeof data === 'object') { const cleanUser = (u) => { const targetName = u.username || u.name; if (!targetName || u.roomId) return; const targetLower = targetName.toLowerCase(); if (targetLower === requester) return;
if (!checkServerPrivacy(targetLower, requester, 'avatar')) u.avatar = null; if (!checkServerPrivacy(targetLower, requester, 'status')) { u.last_seen = null; u.isOnline = false; } };
if (Array.isArray(data)) { data.forEach(cleanUser); } else { const targetName = req.params.user || req.params.username || data.username || data.sender; if (targetName && !data.roomId) { if (!checkServerPrivacy(targetName, requester, 'avatar')) data.avatar = null; if (!checkServerPrivacy(targetName, requester, 'status')) data.last_seen = null; } } } return origJson.call(this, data); }; next();};
module.exports = { checkServerPrivacy, privacyWrapper };123456789101112131415161718192021222324const sanitizeMongo = (obj, depth = 0) => { if (!obj || typeof obj !== 'object') return; if (depth > 10) return; if (Array.isArray(obj)) { obj.forEach(item => sanitizeMongo(item, depth + 1)); return; } for (const key of Object.keys(obj)) { if (key.startsWith('$') || key.includes('.') || key === '__proto__' || key === 'constructor' || key === 'prototype') { delete obj[key]; } else { sanitizeMongo(obj[key], depth + 1); } }};
const sanitizeMiddleware = (req, res, next) => { sanitizeMongo(req.body); sanitizeMongo(req.query); sanitizeMongo(req.params); next();};
module.exports = { sanitizeMongo, sanitizeMiddleware };12345678910111213141516171819202122232425262728const corsHeaders = (req, res, next) => { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Language'); if (req.method === 'OPTIONS') return res.sendStatus(200); next();};
const securityHeaders = (req, res, next) => { res.removeHeader("X-Powered-By"); res.removeHeader("Server"); res.setHeader('X-Content-Type-Options', 'nosniff'); res.setHeader('X-Frame-Options', 'SAMEORIGIN'); res.setHeader('Referrer-Policy', 'no-referrer'); res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0'); res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()'); if (req.secure || req.headers['x-forwarded-proto'] === 'https') { res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload'); } next();};
const cspMiddleware = (req, res, next) => { res.setHeader('Content-Security-Policy', "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https://res.cloudinary.com; media-src 'self' https://res.cloudinary.com; connect-src 'self' wss: https://api-inference.huggingface.co;"); next();};
module.exports = { corsHeaders, securityHeaders, cspMiddleware };12345678910const mongoose = require('mongoose');
const BlackListSchema = new mongoose.Schema({ user_id: { type: String, index: true }, blocked_id: { type: String, index: true }});
BlackListSchema.index({ user_id: 1, blocked_id: 1 }, { unique: true });
module.exports = mongoose.model('BlackList', BlackListSchema);123456789101112const mongoose = require('mongoose');
const ActionSchema = new mongoose.Schema({ user: { type: String, index: true }, contact: { type: String, index: true }, type: { type: String, enum: ['pin', 'archive', 'mute'] }});
ActionSchema.index({ user: 1, contact: 1 });ActionSchema.index({ user: 1, contact: 1, type: 1 });
module.exports = mongoose.model('ChatAction', ActionSchema);123456789101112131415161718192021222324252627const mongoose = require('mongoose');
const DialogSchema = new mongoose.Schema({ dialog_id: { type: String, unique: true, index: true }, participants: [{ type: String, index: true }], lastMessageText: { type: String }, lastSender: { type: String }, lastMessageTimestamp: { type: Date, index: true }, unreadCounts: { type: Map, of: Number, default: {} }, lastIsAudio: { type: Boolean, default: false }, lastIsMusic: { type: Boolean, default: false }, lastIsVideoNote: { type: Boolean, default: false }, lastFileUrl: { type: String, default: null }, lastFileName: { type: String, default: null }, copyRestriction: { type: Boolean, default: false }, autoDeleteTimer: { type: Number, default: 0 }, forwardRestriction: { type: Boolean, default: false }, lastCallType: { type: String, default: null }, lastCallDuration: { type: Number, default: 0 }, lastCallWithVideo: { type: Boolean, default: false }, screenshotNotification: { type: Boolean, default: false }, lastIsEncrypted: { type: Boolean, default: false }});
DialogSchema.index({ participants: 1, lastMessageTimestamp: -1 });
module.exports = mongoose.model('Dialog', DialogSchema);12345678910111213141516171819202122232425262728293031323334353637383940414243const mongoose = require('mongoose');
const MessageSchema = new mongoose.Schema({ dialog_id: { type: String, index: true }, sender: { type: String, index: true }, receiver: { type: String, index: true }, text: { type: String }, fileUrl: { type: String, default: null }, fileUrls: { type: [String], default: [] }, fileName: { type: String, default: null, maxlength: 255 }, isAudio: { type: Boolean, default: false }, isMusic: { type: Boolean, default: false }, isVideoNote: { type: Boolean, default: false }, reply_to: { type: String, default: null, maxlength: 300 }, reply_to_id: { type: String, default: null, maxlength: 100, index: true }, is_read: { type: Boolean, default: false }, read_by: [{ type: String }], is_edited: { type: Boolean, default: false }, expires_at: { type: Date, default: null }, isService: { type: Boolean, default: false }, is_encrypted: { type: Boolean, default: false }, encrypted_text: { type: String, default: null }, encrypted_ratchet_key: { type: String, default: null }, encrypted_nonce: { type: String, default: null }, encrypted_ratchet_index: { type: Number, default: null }, callType: { type: String, default: null }, callDuration: { type: Number, default: 0 }, callWithVideo: { type: Boolean, default: false }, tempId: { type: String, default: null, maxlength: 100 }, last_notified: { type: Date }, timestamp: { type: Date, default: Date.now, index: true }});
MessageSchema.index({ dialog_id: 1, timestamp: -1 });MessageSchema.index({ receiver: 1, is_read: 1 });MessageSchema.index({ receiver: 1, timestamp: -1 });MessageSchema.index({ receiver: 1, read_by: 1 });MessageSchema.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 });
module.exports = mongoose.model('Message', MessageSchema);1234567891011121314151617const mongoose = require('mongoose');
const OAuthAppSchema = new mongoose.Schema({ name: { type: String, required: true, maxlength: 48 }, clientId: { type: String, required: true, unique: true, index: true }, clientSecretHash: { type: String, default: null }, redirectUris: { type: [String], default: [] }, scopes: { type: [String], default: ['profile'] }, website: { type: String, default: null }, isPublic: { type: Boolean, default: false }, active: { type: Boolean, default: true }, createdBy: { type: String, default: null }, createdAt: { type: Date, default: Date.now }, updatedAt: { type: Date, default: Date.now }}, { collection: 'oauth_apps' });
module.exports = mongoose.model('OAuthApp', OAuthAppSchema);12345678910111213141516const mongoose = require('mongoose');
const OAuthCodeSchema = new mongoose.Schema({ codeHash: { type: String, required: true, unique: true, index: true }, clientId: { type: String, required: true, index: true }, redirectUri: { type: String, required: true }, scope: { type: String, default: 'profile' }, codeChallenge: { type: String, default: null }, codeChallengeMethod: { type: String, default: null }, username: { type: String, required: true, index: true }, usedAt: { type: Date, default: null }, expiresAt: { type: Date, required: true, expires: 0 }, createdAt: { type: Date, default: Date.now }}, { collection: 'oauth_codes' });
module.exports = mongoose.model('OAuthCode', OAuthCodeSchema);123456789101112131415161718192021222324const mongoose = require('mongoose');
const OAuthRequestSchema = new mongoose.Schema({ challengeHash: { type: String, required: true, unique: true, index: true }, codeHash: { type: String, required: true }, clientId: { type: String, required: true, index: true }, redirectUri: { type: String, required: true }, scope: { type: String, default: 'profile' }, codeChallenge: { type: String, default: null }, codeChallengeMethod: { type: String, default: null }, username: { type: String, required: true, index: true }, device: { type: String, default: null }, ip: { type: String, default: null }, lang: { type: String, default: 'ru' }, state: { type: String, default: null }, attempts: { type: Number, default: 0 }, resendCount: { type: Number, default: 0 }, lastSentAt: { type: Date, default: null }, codeExpiresAt: { type: Date, required: true }, expiresAt: { type: Date, required: true, expires: 0 }, createdAt: { type: Date, default: Date.now }}, { collection: 'oauth_requests' });
module.exports = mongoose.model('OAuthRequest', OAuthRequestSchema);123456789101112131415161718const mongoose = require('mongoose');
const OAuthTokenSchema = new mongoose.Schema({ accessTokenHash: { type: String, required: true, unique: true, index: true }, refreshTokenHash: { type: String, required: true, unique: true, index: true }, sessionId: { type: String, required: true, index: true }, username: { type: String, required: true, index: true }, clientId: { type: String, required: true, index: true }, clientName: { type: String, required: true }, scope: { type: String, default: 'profile' }, accessExpiresAt: { type: Date, required: true }, refreshExpiresAt: { type: Date, required: true, expires: 0 }, revokedAt: { type: Date, default: null }, lastUsedAt: { type: Date, default: null }, createdAt: { type: Date, default: Date.now }}, { collection: 'oauth_tokens' });
module.exports = mongoose.model('OAuthToken', OAuthTokenSchema);123456789101112131415const mongoose = require('mongoose');
const PinSchema = new mongoose.Schema({ message_id: { type: mongoose.Schema.Types.ObjectId, ref: 'Message' }, chat_id: { type: String, index: true }, pinner_id: { type: String }, pin_type: { type: String, enum: ['both', 'me', 'self'], default: 'both' }, text_preview: { type: String }, timestamp: { type: Date, default: Date.now }});
PinSchema.index({ chat_id: 1, pinner_id: 1 });PinSchema.index({ message_id: 1, chat_id: 1, pinner_id: 1 }, { unique: true });
module.exports = mongoose.model('Pin', PinSchema);1234567891011121314151617181920212223const mongoose = require('mongoose');
const PreKeySchema = new mongoose.Schema({ username: { type: String, unique: true, index: true, lowercase: true }, identityKey: { type: String, required: true }, signingPublicKey: { type: String }, signedPreKey: { keyId: { type: Number, required: true }, publicKey: { type: String, required: true }, signature: { type: String, required: true }, }, oneTimePreKeys: [{ keyId: { type: Number }, publicKey: { type: String }, used: { type: Boolean, default: false }, }], version: { type: Number, default: 1 }, updatedAt: { type: Date, default: Date.now },}, { collection: 'prekeys' });
PreKeySchema.index({ 'oneTimePreKeys.used': 1 });
module.exports = mongoose.model('PreKey', PreKeySchema);1234567891011const mongoose = require('mongoose');
const ReactionSchema = new mongoose.Schema({ message_id: { type: mongoose.Schema.Types.ObjectId, ref: 'Message', index: true }, user: { type: String }, emoji: { type: String }});
ReactionSchema.index({ message_id: 1, user: 1 });
module.exports = mongoose.model('Reaction', ReactionSchema);12345678910111213141516171819202122232425const mongoose = require('mongoose');
const RoomSchema = new mongoose.Schema({ roomId: { type: String, unique: true, index: true }, name: { type: String, maxlength: 20, match: /^[a-zA-Z]{4,20}$/ }, description: { type: String, default: '', maxlength: 500 }, type: { type: String, enum: ['group', 'channel'] }, isPublic: { type: Boolean, default: false }, publicLink: { type: String, lowercase: true, trim: true, match: /^[a-z0-9-]{3,30}$/, index: true, sparse: true }, owner: { type: String, index: true }, members: [{ type: String }], joinRequests: [{ type: String }], avatar: { type: String, default: null }, isVerified: { type: Boolean, default: false }, timestamp: { type: Date, default: Date.now }, copyRestriction: { type: Boolean, default: false }, autoDeleteTimer: { type: Number, default: 0 }, forwardRestriction: { type: Boolean, default: false }, screenshotNotification: { type: Boolean, default: false }});
RoomSchema.index({ members: 1 });RoomSchema.index({ members: 1, timestamp: -1 });
module.exports = mongoose.model('Room', RoomSchema);123456789101112131415161718192021222324252627282930313233const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({ username: { type: String, unique: true, index: true }, displayName: { type: String, default: '', maxlength: 30, match: /^[a-zA-Z]{0,30}$/ }, bio: { type: String, default: '', maxlength: 100 }, password: { type: String }, twoFactorPassword: { type: String, default: null }, panicPassword: { type: String, default: null }, avatar: { type: String, default: null }, last_seen: { type: Date, default: Date.now }, pushToken: { type: String, default: null }, isVerified: { type: Boolean, default: false }, role: { type: String, default: 'user', enum: ['user', 'admin', 'banned'] }, privacy: { type: String, default: '{}' }, autoDeleteMonths: { type: Number, default: 6 }, autoLogoutDays: { type: Number, default: 7 }, archivePassword: { type: String, default: null }, notificationRepeat: { type: Number, default: 5 }, sessions: [{ token: String, device: String, ip: String, lastActive: { type: Date, default: Date.now }, kind: { type: String, default: 'messenger' }, sessionId: { type: String, default: null }, clientId: { type: String, default: null }, clientName: { type: String, default: null }, scopes: { type: [String], default: [] } }]}, { collection: 'users' });
module.exports = mongoose.model('User', UserSchema);1234567891011121314151617181920212223242526272829{"name": "messenger-4send","version": "1.1.0","description": "4SEND - Messenger","main": "index.js","scripts": {"start": "node index.js"},"author": "4SEND Team","license": "ISC","dependencies": {"axios": "^1.6.0","bcryptjs": "^2.4.3","cheerio": "^1.0.0-rc.12","cloudinary": "^2.0.0","compression": "^1.7.4","connect-mongo": "^5.1.0","express": "^4.18.2","express-rate-limit": "^7.1.5","express-session": "^1.19.0","ffmpeg-static": "^5.3.0","firebase-admin": "^12.0.0","jsonwebtoken": "^9.0.2","mongoose": "^8.0.0","multer": "^1.4.5-lts.1","sharp": "^0.33.2","socket.io": "^4.7.0"}}12345678910111213141516171819202122232425262728{"name": "messenger-4send","version": "1.1.0","description": "4SEND - Messenger","main": "server.js","scripts": {"start": "node server.js"},"author": "4SEND Team","license": "ISC","dependencies": {"axios": "^1.6.0","bcryptjs": "^2.4.3","cheerio": "^1.0.0-rc.12","cloudinary": "^2.0.0","compression": "^1.7.4","connect-mongo": "^5.1.0","express": "^4.18.2","express-rate-limit": "^7.1.5","express-session": "^1.19.0","firebase-admin": "^12.0.0","jsonwebtoken": "^9.0.2","mongoose": "^8.0.0","multer": "^1.4.5-lts.1","sharp": "^0.33.2","socket.io": "^4.7.0"}}
1._overlay_17o5h_1{z-index:2147483647;-webkit-backdrop-filter:blur();background:0 0;justify-content:center;align-items:center;width:100%;height:100%;transition:background .5s,-webkit-backdrop-filter .5s,backdrop-filter .5s;display:flex;position:fixed;top:0;left:0}._overlay_17o5h_1._open_17o5h_17{-webkit-backdrop-filter:blur(10px);background:#000000b3}._overlay_17o5h_1._closing_17o5h_23{-webkit-backdrop-filter:blur();pointer-events:none;background:0 0}._box_17o5h_30{border:1px solid rgba(var(--accent-rgb,167, 79, 255), .3);opacity:0;background:#1c1c23;border-radius:24px;flex-direction:column;align-items:center;gap:16px;width:340px;max-width:92vw;padding:25px;transition:all .5s cubic-bezier(.34,1.56,.64,1);display:flex;transform:scale(.9);box-shadow:0 20px 50px #00000080}._boxOpen_17o5h_47{opacity:1;transform:scale(1)}._boxClosing_17o5h_52{opacity:0;transition:all .4s cubic-bezier(.4,0,.2,1);transform:scale(.8)translateY(20px)}._title_17o5h_58{color:#fff;font-family:Plus Jakarta Sans,sans-serif;font-size:calc(18px * var(--font-size-scale));margin:0;font-weight:700}._stage_17o5h_66{touch-action:none;cursor:grab;-webkit-user-select:none;user-select:none;border:2px solid rgba(var(--accent-rgb,167, 79, 255), .4);background:#111;border-radius:50%;transition:border-color .3s;position:relative;overflow:hidden}._stage_17o5h_66:active{cursor:grabbing;border-color:var(--accent-solid,#a74fff)}._canvas_17o5h_83{pointer-events:none;width:100%;height:100%;position:absolute;inset:0}._ring_17o5h_91{pointer-events:none;border:2px solid #ffffffd9;border-radius:50%;position:absolute;inset:0;box-shadow:0 0 0 9999px #00000080}._zoomLabel_17o5h_100{color:#888;text-transform:uppercase;letter-spacing:.5px;width:100%;font-size:12px}._zoom_17o5h_100{width:100%;accent-color:var(--accent-solid,#a74fff);height:6px}._actions_17o5h_114{gap:10px;width:100%;margin-top:4px;display:flex}._cancel_17o5h_121,._done_17o5h_122{cursor:pointer;border:none;border-radius:14px;flex:1;padding:12px;font-family:inherit;font-size:15px;font-weight:600;transition:background .2s,transform .15s}._cancel_17o5h_121{color:#ccc;background:#ffffff14}._cancel_17o5h_121:hover{background:#ffffff24}._cancel_17o5h_121:active{transform:scale(.96)}._done_17o5h_122{background:var(--accent-solid,#a74fff);color:var(--on-accent,#fff)}._done_17o5h_122:hover{filter:brightness(1.1)}._done_17o5h_122:active{transform:scale(.96)}1import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{d as t,t as n,u as r}from"./vendor-CdeZI4gz.js";import{u as i}from"./index-C49_c6F1.js";var a=e(t(),1),o=e(r(),1),s={overlay:`_overlay_17o5h_1`,open:`_open_17o5h_17`,closing:`_closing_17o5h_23`,box:`_box_17o5h_30`,boxOpen:`_boxOpen_17o5h_47`,boxClosing:`_boxClosing_17o5h_52`,title:`_title_17o5h_58`,stage:`_stage_17o5h_66`,canvas:`_canvas_17o5h_83`,ring:`_ring_17o5h_91`,zoomLabel:`_zoomLabel_17o5h_100`,zoom:`_zoom_17o5h_100`,actions:`_actions_17o5h_114`,cancel:`_cancel_17o5h_121`,done:`_done_17o5h_122`},c=n(),l=260,u=512;function d({file:e,onCancel:t,onCrop:n}){let{t:r}=i(),d=(0,a.useRef)(null),f=(0,a.useRef)(null),p=(0,a.useRef)(null),[m,h]=(0,a.useState)(1),[g,_]=(0,a.useState)({x:0,y:0}),v=(0,a.useRef)(null),[y,b]=(0,a.useState)(!0),[x,S]=(0,a.useState)(!1),[C,w]=(0,a.useState)(!1);(0,a.useEffect)(()=>{let e=requestAnimationFrame(()=>{requestAnimationFrame(()=>S(!0))});return()=>cancelAnimationFrame(e)},[]),(0,a.useEffect)(()=>{if(!C)return;let e=setTimeout(()=>{b(!1),w(!1),S(!1),t()},400);return()=>clearTimeout(e)},[C,t]);let T=(0,a.useCallback)(()=>{C||w(!0)},[C]);(0,a.useEffect)(()=>{let e=e=>{e.key===`Escape`&&T()};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[T]),(0,a.useEffect)(()=>{let t=new Image;return t.onload=()=>{f.current=t,h(.5),_({x:0,y:0}),E()},t.src=URL.createObjectURL(e),()=>URL.revokeObjectURL(t.src)},[e]);let E=(0,a.useCallback)(()=>{let e=d.current,t=f.current;if(!e||!t)return;let n=e.getContext(`2d`);if(!n)return;n.clearRect(0,0,l,l);let r=m,i=t.width*r,a=t.height*r;n.save(),n.beginPath(),n.arc(l/2,l/2,l/2,0,Math.PI*2),n.closePath(),n.clip(),n.drawImage(t,(l-i)/2+g.x,(l-a)/2+g.y,i,a),n.restore()},[m,g]);(0,a.useEffect)(()=>{E()},[E]);let D=e=>{e.target.setPointerCapture(e.pointerId),v.current={x:e.clientX,y:e.clientY,px:g.x,py:g.y}},O=e=>{if(!v.current)return;let t=e.clientX-v.current.x,n=e.clientY-v.current.y;_({x:v.current.px+t,y:v.current.py+n})},k=()=>{v.current=null};return y?(0,o.createPortal)((0,c.jsx)(`div`,{className:`${s.overlay} ${x&&!C?s.open:``} ${C?s.closing:``}`,onClick:T,children:(0,c.jsxs)(`div`,{className:`${s.box} ${x&&!C?s.boxOpen:``} ${C?s.boxClosing:``}`,onClick:e=>e.stopPropagation(),children:[(0,c.jsx)(`h3`,{className:s.title,children:r(`Обрезка аватара`)}),(0,c.jsxs)(`div`,{ref:p,className:s.stage,style:{width:l,height:l},onPointerDown:D,onPointerMove:O,onPointerUp:k,onPointerLeave:k,children:[(0,c.jsx)(`canvas`,{ref:d,width:l,height:l,className:s.canvas}),(0,c.jsx)(`div`,{className:s.ring})]}),(0,c.jsx)(`div`,{className:s.zoomLabel,children:r(`Масштаб`)}),(0,c.jsx)(`input`,{className:s.zoom,type:`range`,min:.5,max:4,step:.01,value:m,onChange:e=>h(parseFloat(e.target.value))}),(0,c.jsxs)(`div`,{className:s.actions,children:[(0,c.jsx)(`button`,{className:s.cancel,onClick:T,children:r(`Отмена`)}),(0,c.jsx)(`button`,{className:s.done,onClick:()=>{let e=document.createElement(`canvas`);e.width=u,e.height=u;let t=e.getContext(`2d`);if(!t||!f.current)return;t.beginPath(),t.arc(u/2,u/2,u/2,0,Math.PI*2),t.closePath(),t.clip();let r=u/l,i=m*r,a=f.current.width*i,o=f.current.height*i;t.drawImage(f.current,(u-a)/2+g.x*r,(u-o)/2+g.y*r,a,o),e.toBlob(e=>{e&&n(new File([e],`avatar.png`,{type:`image/png`}))},`image/png`)},children:r(`Готово`)})]})]})}),document.body):null}export{d as default};1._overlay_1qhis_1{z-index:9999;position:fixed;bottom:80px;left:auto;right:12px}._panel_1qhis_9{background:rgba(var(--card-rgb,42, 38, 51), .95);-webkit-backdrop-filter:blur(25px)saturate(180%);scrollbar-width:none;scrollbar-color:rgba(var(--accent-rgb,167, 79, 255), .3) transparent;will-change:transform, opacity;border:1px solid #ffffff1a;border-radius:20px;width:320px;max-height:380px;padding:10px;overflow-y:auto;box-shadow:0 15px 40px #0009}._panel_1qhis_9[data-entered]{transition:transform .3s cubic-bezier(.34,1.56,.64,1),opacity .25s}._panel_1qhis_9::-webkit-scrollbar{display:none}._tabs_1qhis_33{background:#0003;border-bottom:1px solid #ffffff0d;gap:0;margin-bottom:12px;display:flex}._tab_1qhis_33{text-align:center;color:#888;font-size:calc(13px * var(--font-size-scale));cursor:pointer;background:0 0;border:none;border-bottom:2px solid #0000;flex:1;padding:10px;font-weight:600;transition:all .2s}._tab_1qhis_33._active_1qhis_57{color:var(--accent-solid);border-bottom-color:var(--accent-solid);background:rgba(var(--accent-rgb,167, 79, 255), .05)}._category_1qhis_63{margin-bottom:8px}._categoryTitle_1qhis_67{font-size:calc(12px * var(--font-size-scale));color:#888;text-transform:uppercase;letter-spacing:.5px;padding:4px 8px;font-weight:700}._grid_1qhis_76{grid-template-columns:repeat(8,1fr);gap:2px;display:grid}._emojiBtn_1qhis_82{aspect-ratio:1;cursor:pointer;width:100%;font-size:calc(24px * var(--font-size-scale));background:0 0;border:none;border-radius:8px;justify-content:center;align-items:center;transition:background .15s,transform .1s;display:flex}._emojiBtn_1qhis_82:hover{background:#ffffff1a;transform:scale(1.1)}._emojiBtn_1qhis_82:active{transform:scale(.9)}._stickerGrid_1qhis_105{grid-template-columns:repeat(4,1fr);gap:8px;max-height:300px;display:grid;overflow-y:auto}._stickerSlot_1qhis_113{aspect-ratio:1;border:2px dashed rgba(var(--accent-rgb,157, 78, 221), .2);cursor:pointer;border-radius:12px;justify-content:center;align-items:center;transition:all .2s;display:flex;position:relative;overflow:hidden}._stickerSlot_1qhis_113:hover{border-color:var(--accent-solid);background:rgba(var(--accent-rgb,167, 79, 255), .05)}._stickerSlot_1qhis_113 img{object-fit:cover;border-radius:10px;width:100%;height:100%}._stickerDelete_1qhis_138{color:#fff;width:20px;height:20px;font-size:calc(12px * var(--font-size-scale));cursor:pointer;background:#ff3b30e6;border:none;border-radius:50%;justify-content:center;align-items:center;display:none;position:absolute;top:4px;right:4px}._stickerSlot_1qhis_113:hover ._stickerDelete_1qhis_138{display:flex}._stickerPlus_1qhis_159{font-size:calc(24px * var(--font-size-scale));color:rgba(var(--accent-rgb,157, 78, 221), .35);font-weight:300}@media (width<=768px){._overlay_1qhis_1{bottom:80px;left:15px;right:15px}._panel_1qhis_9{width:auto;max-height:380px}}1import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{d as t,t as n}from"./vendor-CdeZI4gz.js";import{u as r}from"./index-C49_c6F1.js";var i=e(t(),1),a={overlay:`_overlay_1qhis_1`,panel:`_panel_1qhis_9`,tabs:`_tabs_1qhis_33`,tab:`_tab_1qhis_33`,active:`_active_1qhis_57`,category:`_category_1qhis_63`,categoryTitle:`_categoryTitle_1qhis_67`,grid:`_grid_1qhis_76`,emojiBtn:`_emojiBtn_1qhis_82`,stickerGrid:`_stickerGrid_1qhis_105`,stickerSlot:`_stickerSlot_1qhis_113`,stickerDelete:`_stickerDelete_1qhis_138`,stickerPlus:`_stickerPlus_1qhis_159`},o=n(),s={Частые:[`😀`,`😂`,`😍`,`🥰`,`😎`,`🤔`,`😅`,`🙌`,`👍`,`👋`,`❤️`,`🔥`,`✨`,`🎉`,`💯`,`🙏`,`😢`,`😤`,`🫡`,`😈`],Смайлики:`😀.😃.😄.😁.😆.😅.🤣.😂.🙂.🙃.😉.😊.😇.🥰.😍.🤩.😘.😗.😚.😙.🥲.😋.😛.😜.🤪.😝.🤑.🤗.🤭.🫢.🤫.🤔.🫡.🤐.🤨.😐.😑.😶.🫥.😏.😒.🙄.😬.🤥.😌.😔.😪.🤤.😴.😷.🤒.🤕.🤢.🤮.🥵.🥶.🥴.😵.🤯.🤠.🥳.🥸.😎.🤓.🧐`.split(`.`),Жесты:`👋.🤚.🖐️.✋.🖖.🫱.🫲.🫳.🫴.👌.🤌.🤏.✌️.🤞.🫰.🤟.🤘.🤙.👈.👉.👆.🖕.👇.☝️.🫵.👍.👎.✊.👊.🤛.🤜.👏.🙌.🫶.👐.🤲.🤝.🙏.💪`.split(`.`),Сердце:[`❤️`,`🧡`,`💛`,`💚`,`💙`,`💜`,`🖤`,`🤍`,`🤎`,`💔`,`❤️🔥`,`❤️🩹`,`❣️`,`💕`,`💞`,`💓`,`💗`,`💖`,`💘`,`💝`],Животные:`🐶.🐱.🐭.🐹.🐰.🦊.🐻.🐼.🐻❄️.🐨.🐯.🦁.🐮.🐷.🐸.🐵.🙈.🙉.🙊.🐒.🐔.🐧.🐦.🐤.🐣.🐥.🦆.🦅.🦉.🦇.🐺.🐗.🐴.🦄.🐝.🪱.🐛.🦋.🐌.🐞`.split(`.`),Еда:`🍎.🍐.🍊.🍋.🍌.🍉.🍇.🍓.🫐.🍈.🍒.🍑.🥭.🍍.🥥.🥝.🍅.🥑.🍆.🥔.🥕.🌽.🌶️.🫑.🥒.🥬.🥦.🧄.🧅.🍄`.split(`.`),Объекты:`⌚.📱.💻.⌨️.🖥️.🖨️.🖱️.🖲️.💾.💿.📀.📼.📷.📸.📹.🎥.📽️.🎞️.📞.☎️.📟.📠.📺.📻.🎙️.🎚️.🎛️.🧭.⏱️.⏰.📦`.split(`.`)};function c(e){try{let t=localStorage.getItem(e);return t?JSON.parse(t):[]}catch{return[]}}function l(e,t){localStorage.setItem(e,JSON.stringify(t))}function u({onSelect:e,onClose:t,sourceRect:n,closing:u}){let{t:d}=r(),[f,p]=(0,i.useState)(`emoji`),[m,h]=(0,i.useState)(()=>c(`4send_saved_stickers`)),[g,_]=(0,i.useState)(()=>c(`4send_saved_gifs`)),v=(0,i.useRef)(null),y=(0,i.useRef)(null),b=(0,i.useRef)(null),[x,S]=(0,i.useState)(!1),[C,w]=(0,i.useState)(!1),[T,E]=(0,i.useState)(!1),[D,O]=(0,i.useState)(`50% 100%`),k=(0,i.useMemo)(()=>Object.keys(s),[]);(0,i.useLayoutEffect)(()=>{if(!T&&n&&b.current){let e=b.current.getBoundingClientRect();if(e.width>0&&e.height>0){let t=(n.left+n.width/2-e.left)/e.width*100,r=(n.top+n.height/2-e.top)/e.height*100;O(`${t}% ${r}%`),E(!0)}}},[n,T]),(0,i.useEffect)(()=>{T&&!C&&requestAnimationFrame(()=>{requestAnimationFrame(()=>w(!0))})},[T,C]),(0,i.useEffect)(()=>{u&&!x&&(S(!0),setTimeout(t,300))},[u,x,t]);let A=(0,i.useCallback)(()=>{x||(S(!0),setTimeout(t,300))},[t,x]);(0,i.useEffect)(()=>{if(x)return;let e=e=>{e.key===`Escape`&&A()};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[x,A]);let j=(0,i.useMemo)(()=>T?{transformOrigin:D,transform:C&&!x?`scale(1)`:`scale(0)`,opacity:C&&!x?1:0}:{visibility:`hidden`,opacity:0},[D,T,C,x]),M=(0,i.useCallback)(t=>{e(t)},[e]),N=(0,i.useCallback)(e=>{let t=e.target.files?.[0];if(!t)return;let n=new FileReader;n.onload=()=>{let e=n.result,t=[...m,e];h(t),l(`4send_saved_stickers`,t)},n.readAsDataURL(t),e.target.value=``},[m]),P=(0,i.useCallback)(e=>{let t=e.target.files?.[0];if(!t)return;let n=new FileReader;n.onload=()=>{let e=n.result,t=[...g,e];_(t),l(`4send_saved_gifs`,t)},n.readAsDataURL(t),e.target.value=``},[g]),F=(0,i.useCallback)(e=>{let t=m.filter((t,n)=>n!==e);h(t),l(`4send_saved_stickers`,t)},[m]),I=(0,i.useCallback)(e=>{let t=g.filter((t,n)=>n!==e);_(t),l(`4send_saved_gifs`,t)},[g]);return(0,o.jsx)(`div`,{className:a.overlay,onClick:A,children:(0,o.jsxs)(`div`,{ref:b,className:a.panel,"data-entered":T||void 0,style:j,onClick:e=>e.stopPropagation(),children:[(0,o.jsxs)(`div`,{className:a.tabs,children:[(0,o.jsx)(`button`,{className:`${a.tab} ${f===`emoji`?a.active:``}`,onClick:()=>p(`emoji`),children:d(`Эмодзи`)}),(0,o.jsx)(`button`,{className:`${a.tab} ${f===`stickers`?a.active:``}`,onClick:()=>p(`stickers`),children:d(`Стикеры`)}),(0,o.jsx)(`button`,{className:`${a.tab} ${f===`gifs`?a.active:``}`,onClick:()=>p(`gifs`),children:`GIF`})]}),f===`emoji`&&k.map(e=>(0,o.jsxs)(`div`,{className:a.category,children:[(0,o.jsx)(`div`,{className:a.categoryTitle,children:d(e)}),(0,o.jsx)(`div`,{className:a.grid,children:s[e].map((t,n)=>(0,o.jsx)(`button`,{className:a.emojiBtn,onClick:()=>M(t),children:t},`${e}-${n}`))})]},e)),f===`stickers`&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(`input`,{ref:v,type:`file`,accept:`image/*`,style:{display:`none`},onChange:N}),(0,o.jsxs)(`div`,{className:a.stickerGrid,children:[m.map((t,n)=>(0,o.jsxs)(`div`,{className:a.stickerSlot,onClick:()=>e(t),children:[(0,o.jsx)(`img`,{src:t,alt:``}),(0,o.jsx)(`button`,{className:a.stickerDelete,onClick:e=>{e.stopPropagation(),F(n)},children:`×`})]},n)),(0,o.jsx)(`div`,{className:a.stickerSlot,onClick:()=>v.current?.click(),children:(0,o.jsx)(`span`,{className:a.stickerPlus,children:`+`})})]})]}),f===`gifs`&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(`input`,{ref:y,type:`file`,accept:`image/gif`,style:{display:`none`},onChange:P}),(0,o.jsxs)(`div`,{className:a.stickerGrid,style:{gridTemplateColumns:`repeat(3, 1fr)`},children:[g.map((t,n)=>(0,o.jsxs)(`div`,{className:a.stickerSlot,onClick:()=>e(t),children:[(0,o.jsx)(`img`,{src:t,alt:``}),(0,o.jsx)(`button`,{className:a.stickerDelete,onClick:e=>{e.stopPropagation(),I(n)},children:`×`})]},n)),(0,o.jsx)(`div`,{className:a.stickerSlot,onClick:()=>y.current?.click(),children:(0,o.jsx)(`span`,{className:a.stickerPlus,children:`+`})})]})]})]})})}export{u as default};1._step_1q5ed_1{flex-direction:column;align-items:center;gap:16px;padding:4px 0;display:flex}._heroIcon_1q5ed_9{margin-bottom:2px;animation:.5s cubic-bezier(.34,1.56,.64,1) _fadeInScale_1q5ed_1}@keyframes _fadeInScale_1q5ed_1{0%{opacity:0;transform:scale(.8)}to{opacity:1;transform:scale(1)}}._infoBlock_1q5ed_19{flex-direction:column;gap:8px;width:100%;display:flex}._infoTitle_1q5ed_26{color:#999;text-transform:uppercase;letter-spacing:.6px;margin:0;font-size:13px;font-weight:600}._infoText_1q5ed_35{color:#bbb;margin:0;font-size:13.5px;line-height:1.55}._featureList_1q5ed_42{flex-direction:column;gap:6px;width:100%;display:flex}._featureItem_1q5ed_49{color:#e0e0e0;background:#ffffff0a;border-radius:12px;align-items:center;gap:10px;padding:10px 14px;font-size:14px;transition:background .15s;display:flex}._featureItem_1q5ed_49:hover{background:#ffffff0f}._dot_1q5ed_65{border-radius:50%;flex-shrink:0;width:7px;height:7px}._muted_1q5ed_72{color:#777;font-size:13px}._warnBox_1q5ed_77{color:#ff9500;background:#ff950014;border:1px solid #ff950033;border-radius:12px;align-items:flex-start;gap:10px;width:100%;padding:12px 14px;font-size:13px;line-height:1.45;display:flex}._warnText_1q5ed_91{margin:0;font-size:13px;line-height:1.45}._warnText_1q5ed_91+._warnText_1q5ed_91{opacity:.8;margin-top:2px}._fieldGroup_1q5ed_102{flex-direction:column;gap:8px;width:100%;display:flex}._fieldLabel_1q5ed_109{color:#999;margin:0;font-size:13px;font-weight:600}._passwordRow_1q5ed_116{gap:10px;width:100%;display:flex}._passwordInput_1q5ed_122{color:#fff;text-align:center;letter-spacing:6px;box-sizing:border-box;text-transform:uppercase;background:#ffffff0f;border:1.5px solid #ffffff1a;border-radius:14px;outline:none;flex:1;min-width:0;padding:14px 12px;font-family:SF Mono,Fira Code,monospace;font-size:22px;font-weight:700;transition:border-color .2s,box-shadow .2s}._passwordInput_1q5ed_122:focus{border-color:var(--accent-solid,#a74fff);box-shadow:0 0 0 3px rgba(var(--accent-rgb,167, 79, 255), .12)}._passwordInput_1q5ed_122::placeholder{color:#ffffff2e;letter-spacing:2px;font-weight:400}._activeBadge_1q5ed_152{color:#34c759;background:#34c7591f;border:1px solid #34c75940;border-radius:20px;align-items:center;gap:6px;padding:6px 16px;font-size:14px;font-weight:600;display:inline-flex}._error_1q5ed_165{color:#ff3b30;text-align:center;box-sizing:border-box;background:#ff3b301a;border:1px solid #ff3b3033;border-radius:10px;width:100%;padding:8px 12px;font-size:13px}._primaryBtn_1q5ed_177{background:var(--accent-solid,#a74fff);width:100%;color:var(--on-accent,#fff);cursor:pointer;border:none;border-radius:14px;padding:14px;font-family:inherit;font-size:16px;font-weight:600;transition:all .2s}._primaryBtn_1q5ed_177:hover:not(:disabled){filter:brightness(1.1);box-shadow:0 4px 16px rgba(var(--accent-rgb,167, 79, 255), .3);transform:translateY(-1px)}._primaryBtn_1q5ed_177:active:not(:disabled){transform:scale(.98)}._primaryBtn_1q5ed_177:disabled{opacity:.5;cursor:not-allowed}._dangerBtn_1q5ed_206{color:#ff3b30;cursor:pointer;background:#ff3b301f;border:1.5px solid #ff3b304d;border-radius:14px;width:100%;padding:14px;font-family:inherit;font-size:16px;font-weight:600;transition:all .2s}._dangerBtn_1q5ed_206:hover:not(:disabled){background:#ff3b3038;box-shadow:0 4px 16px #ff3b3026}._dangerBtn_1q5ed_206:active:not(:disabled){transform:scale(.98)}._dangerBtn_1q5ed_206:disabled{opacity:.5;cursor:not-allowed}._progressBar_1q5ed_234{background:#ffffff14;border-radius:3px;width:100%;height:6px;overflow:hidden}._progressFill_1q5ed_242{background:var(--accent-solid,#a74fff);border-radius:3px;height:100%;transition:width .4s cubic-bezier(.4,0,.2,1)}._progressText_1q5ed_249{color:#ccc;margin:0;font-size:15px}._doneText_1q5ed_255{color:#34c759;margin:0;font-size:18px;font-weight:700}1import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{d as t,t as n}from"./vendor-CdeZI4gz.js";import{r,u as i}from"./index-C49_c6F1.js";import{t as a}from"./ModalShell-DH5TxKnz.js";var o=e(t(),1),s={step:`_step_1q5ed_1`,heroIcon:`_heroIcon_1q5ed_9`,fadeInScale:`_fadeInScale_1q5ed_1`,infoBlock:`_infoBlock_1q5ed_19`,infoTitle:`_infoTitle_1q5ed_26`,infoText:`_infoText_1q5ed_35`,featureList:`_featureList_1q5ed_42`,featureItem:`_featureItem_1q5ed_49`,dot:`_dot_1q5ed_65`,muted:`_muted_1q5ed_72`,warnBox:`_warnBox_1q5ed_77`,warnText:`_warnText_1q5ed_91`,fieldGroup:`_fieldGroup_1q5ed_102`,fieldLabel:`_fieldLabel_1q5ed_109`,passwordRow:`_passwordRow_1q5ed_116`,passwordInput:`_passwordInput_1q5ed_122`,activeBadge:`_activeBadge_1q5ed_152`,error:`_error_1q5ed_165`,primaryBtn:`_primaryBtn_1q5ed_177`,dangerBtn:`_dangerBtn_1q5ed_206`,progressBar:`_progressBar_1q5ed_234`,progressFill:`_progressFill_1q5ed_242`,progressText:`_progressText_1q5ed_249`,doneText:`_doneText_1q5ed_255`},c=n();function l({isOpen:e,onClose:t}){let{t:n}=i(),{isEncrypted:l,enableEncryption:u,disableEncryption:d,isLoading:f,error:p,setError:m}=r(),[h,g]=(0,o.useState)(`main`),[_,v]=(0,o.useState)(``),[y,b]=(0,o.useState)(``),[x,S]=(0,o.useState)(``),[C,w]=(0,o.useState)(``),[T,E]=(0,o.useState)(``),[D,O]=(0,o.useState)(``),[k,A]=(0,o.useState)(0);(0,o.useEffect)(()=>{e&&(g(`main`),m(null))},[e,m]);let j=(0,o.useRef)(null),M=(0,o.useCallback)(async()=>{let e=_.toLowerCase()+y;if(_.length!==3||y.length!==3){m(n(`Введите 3 буквы и 3 цифры`));return}if(e!==x.toLowerCase()+C){m(n(`Пароли не совпадают`));return}if(g(`progress`),A(10),setTimeout(()=>A(30),200),setTimeout(()=>A(60),500),setTimeout(()=>A(90),800),!await u(e)){g(`main`);return}A(100),setTimeout(()=>g(`done`),500)},[_,y,x,C,u,m]),N=(0,o.useCallback)(async()=>{let e=T.toLowerCase()+D;if(T.length!==3||D.length!==3){m(n(`Введите пароль`));return}await d(e)},[T,D,d,m]),P=(0,c.jsxs)(`svg`,{viewBox:`0 0 48 48`,width:`52`,height:`52`,fill:`none`,children:[(0,c.jsx)(`path`,{d:`M24 4L8 12v10c0 11.1 6.8 21.5 16 24 9.2-2.5 16-12.9 16-24V12L24 4z`,fill:`rgba(var(--accent-rgb,167,79,255),0.1)`,stroke:`var(--accent-solid,#a74fff)`,strokeWidth:`2`}),(0,c.jsx)(`path`,{d:`M20 24l3 3 6-6`,stroke:`var(--accent-solid,#a74fff)`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`})]});return(0,c.jsxs)(a,{isOpen:e,onClose:t,title:n(`Шифрование базы`),maxWidth:`400px`,closeRef:j,children:[h===`main`&&!l&&(0,c.jsxs)(`div`,{className:s.step,children:[(0,c.jsx)(`div`,{className:s.heroIcon,children:P}),(0,c.jsxs)(`div`,{className:s.infoBlock,children:[(0,c.jsx)(`p`,{className:s.infoTitle,children:n(`Что зашифровано`)}),(0,c.jsxs)(`div`,{className:s.featureList,children:[(0,c.jsxs)(`div`,{className:s.featureItem,children:[(0,c.jsx)(`span`,{className:s.dot,style:{background:`#34c759`}}),(0,c.jsx)(`span`,{children:n(`Сообщения, медиа, вложения`)})]}),(0,c.jsxs)(`div`,{className:s.featureItem,children:[(0,c.jsx)(`span`,{className:s.dot,style:{background:`#34c759`}}),(0,c.jsx)(`span`,{children:n(`Криптоключи E2EE (сессии, identity)`)})]}),(0,c.jsxs)(`div`,{className:s.featureItem,children:[(0,c.jsx)(`span`,{className:s.dot,style:{background:`#34c759`}}),(0,c.jsx)(`span`,{children:n(`Токен авторизации и данные аккаунтов`)})]}),(0,c.jsxs)(`div`,{className:s.featureItem,children:[(0,c.jsx)(`span`,{className:s.dot,style:{background:`#888`}}),(0,c.jsx)(`span`,{className:s.muted,children:n(`Настройки интерфейса без изменений`)})]})]})]}),(0,c.jsxs)(`div`,{className:s.infoBlock,children:[(0,c.jsx)(`p`,{className:s.infoTitle,children:n(`Как работает`)}),(0,c.jsx)(`p`,{className:s.infoText,children:n(`При включении задаётся пароль (3 буквы + 3 цифры). Данные шифруются на устройстве алгоритмом Argon2id + XChaCha20. При каждом запуске приложения потребуется ввести пароль.`)})]}),(0,c.jsxs)(`div`,{className:s.warnBox,children:[(0,c.jsx)(`svg`,{viewBox:`0 0 20 20`,width:`16`,height:`16`,fill:`#ff9500`,style:{flexShrink:0,marginTop:1},children:(0,c.jsx)(`path`,{d:`M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 10-2 0 1 1 0 002 0zm-1-2a.75.75 0 01-.75-.75v-3.5a.75.75 0 011.5 0v3.5A.75.75 0 0110 11z`})}),(0,c.jsxs)(`div`,{children:[(0,c.jsx)(`p`,{className:s.warnText,children:n(`Восстановление пароля невозможно.`)}),(0,c.jsx)(`p`,{className:s.warnText,children:n(`При потере пароля данные будут безвозвратно утеряны.`)})]})]}),(0,c.jsxs)(`div`,{className:s.fieldGroup,children:[(0,c.jsx)(`label`,{className:s.fieldLabel,children:n(`Пароль`)}),(0,c.jsxs)(`div`,{className:s.passwordRow,children:[(0,c.jsx)(`input`,{className:s.passwordInput,type:`text`,maxLength:3,placeholder:`ABC`,value:_,onChange:e=>v(e.target.value.replace(/[^a-zA-Z]/g,``).slice(0,3)),autoComplete:`off`,autoCapitalize:`off`}),(0,c.jsx)(`input`,{className:s.passwordInput,type:`text`,maxLength:3,placeholder:`123`,value:y,onChange:e=>b(e.target.value.replace(/\D/g,``).slice(0,3)),autoComplete:`off`})]})]}),(0,c.jsxs)(`div`,{className:s.fieldGroup,children:[(0,c.jsx)(`label`,{className:s.fieldLabel,children:n(`Подтвердите пароль`)}),(0,c.jsxs)(`div`,{className:s.passwordRow,children:[(0,c.jsx)(`input`,{className:s.passwordInput,type:`text`,maxLength:3,placeholder:`ABC`,value:x,onChange:e=>S(e.target.value.replace(/[^a-zA-Z]/g,``).slice(0,3)),autoComplete:`off`,autoCapitalize:`off`}),(0,c.jsx)(`input`,{className:s.passwordInput,type:`text`,maxLength:3,placeholder:`123`,value:C,onChange:e=>w(e.target.value.replace(/\D/g,``).slice(0,3)),autoComplete:`off`})]})]}),p&&(0,c.jsx)(`div`,{className:s.error,children:p}),(0,c.jsx)(`button`,{className:s.primaryBtn,onClick:M,disabled:f||_.length<3||y.length<3,children:n(f?`Шифрование...`:`Включить шифрование`)})]}),h===`main`&&l&&(0,c.jsxs)(`div`,{className:s.step,children:[(0,c.jsx)(`div`,{className:s.heroIcon,children:(0,c.jsxs)(`svg`,{viewBox:`0 0 48 48`,width:`52`,height:`52`,fill:`none`,children:[(0,c.jsx)(`path`,{d:`M24 4L8 12v10c0 11.1 6.8 21.5 16 24 9.2-2.5 16-12.9 16-24V12L24 4z`,fill:`rgba(52,199,89,0.1)`,stroke:`#34c759`,strokeWidth:`2`}),(0,c.jsx)(`path`,{d:`M20 24l3 3 6-6`,stroke:`#34c759`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`})]})}),(0,c.jsx)(`div`,{className:s.activeBadge,children:n(`Шифрование активно`)}),(0,c.jsx)(`div`,{className:s.infoBlock,children:(0,c.jsx)(`p`,{className:s.infoText,children:n(`Сообщения, ключи E2EE и данные аккаунтов зашифрованы на этом устройстве.`)})}),(0,c.jsxs)(`div`,{className:s.infoBlock,children:[(0,c.jsx)(`p`,{className:s.infoTitle,children:n(`Отключение шифрования`)}),(0,c.jsx)(`p`,{className:s.infoText,children:n(`Все данные будут расшифрованы и сохранены в открытом виде. Пароль введите для подтверждения.`)})]}),(0,c.jsxs)(`div`,{className:s.fieldGroup,children:[(0,c.jsx)(`label`,{className:s.fieldLabel,children:n(`Пароль`)}),(0,c.jsxs)(`div`,{className:s.passwordRow,children:[(0,c.jsx)(`input`,{className:s.passwordInput,type:`text`,maxLength:3,placeholder:`ABC`,value:T,onChange:e=>E(e.target.value.replace(/[^a-zA-Z]/g,``).slice(0,3)),autoComplete:`off`,autoCapitalize:`off`}),(0,c.jsx)(`input`,{className:s.passwordInput,type:`text`,maxLength:3,placeholder:`123`,value:D,onChange:e=>O(e.target.value.replace(/\D/g,``).slice(0,3)),autoComplete:`off`})]})]}),p&&(0,c.jsx)(`div`,{className:s.error,children:p}),(0,c.jsx)(`button`,{className:s.dangerBtn,onClick:N,disabled:f||T.length<3||D.length<3,children:n(f?`Расшифровка...`:`Отключить шифрование`)})]}),h===`progress`&&(0,c.jsxs)(`div`,{className:s.step,children:[(0,c.jsx)(`div`,{className:s.heroIcon,children:P}),(0,c.jsx)(`p`,{className:s.progressText,children:n(`Шифрование базы данных...`)}),(0,c.jsx)(`div`,{className:s.progressBar,children:(0,c.jsx)(`div`,{className:s.progressFill,style:{width:`${k}%`}})})]}),h===`done`&&(0,c.jsxs)(`div`,{className:s.step,children:[(0,c.jsx)(`div`,{className:s.heroIcon,children:(0,c.jsxs)(`svg`,{viewBox:`0 0 48 48`,width:`52`,height:`52`,fill:`none`,children:[(0,c.jsx)(`circle`,{cx:`24`,cy:`24`,r:`20`,fill:`rgba(52,199,89,0.12)`,stroke:`#34c759`,strokeWidth:`2`}),(0,c.jsx)(`path`,{d:`M16 24l5 5 11-11`,stroke:`#34c759`,strokeWidth:`3`,strokeLinecap:`round`,strokeLinejoin:`round`})]})}),(0,c.jsx)(`p`,{className:s.doneText,children:n(`Шифрование активно`)}),(0,c.jsx)(`p`,{className:s.muted,children:n(`При следующем запуске потребуется ввести пароль.`)}),(0,c.jsx)(`button`,{className:s.primaryBtn,onClick:()=>j.current?.(),children:n(`Готово`)})]})]})}export{l as default};1import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{d as t,t as n}from"./vendor-CdeZI4gz.js";import{u as r}from"./index-C49_c6F1.js";var i=e(t(),1),a={overlay:`_overlay_jh7o2_11`,open:`_open_jh7o2_27`,closing:`_closing_jh7o2_33`,content:`_content_jh7o2_40`,dangerBorder:`_dangerBorder_jh7o2_72`,title:`_title_jh7o2_77`,closeBtn:`_closeBtn_jh7o2_86`,backBtn:`_backBtn_jh7o2_110`,fadeIn:`_fadeIn_jh7o2_1`,fadeOut:`_fadeOut_jh7o2_1`},o=n();function s({isOpen:e,onClose:t,children:n,maxWidth:s=`380px`,title:c,showClose:l=!0,danger:u=!1,dangerColor:d,onBack:f,closeRef:p}){let{t:m}=r(),[h,g]=(0,i.useState)(e),[_,v]=(0,i.useState)(!1),[y,b]=(0,i.useState)(!1),x=(0,i.useRef)(t);x.current=t;let S=(0,i.useCallback)(()=>{_||v(!0)},[_]);return(0,i.useEffect)(()=>{p&&(p.current=S)},[p,S]),(0,i.useEffect)(()=>{if(e){g(!0),v(!1),b(!1);let e=requestAnimationFrame(()=>{requestAnimationFrame(()=>{b(!0)})});return()=>cancelAnimationFrame(e)}},[e]),(0,i.useEffect)(()=>{if(!_)return;let e=setTimeout(()=>{g(!1),v(!1),b(!1),x.current()},400);return()=>clearTimeout(e)},[_]),(0,i.useEffect)(()=>{if(!e)return;let t=e=>{e.key===`Escape`&&S()};return document.addEventListener(`keydown`,t),()=>document.removeEventListener(`keydown`,t)},[e,S]),h?(0,o.jsx)(`div`,{className:`${a.overlay} ${y&&!_?a.open:``} ${_?a.closing:``}`,onClick:S,children:(0,o.jsxs)(`div`,{className:`${a.content} ${u?a.dangerBorder:``}`,style:{maxWidth:s},onClick:e=>e.stopPropagation(),children:[f&&(0,o.jsx)(`button`,{className:a.backBtn,onClick:f,children:(0,o.jsx)(`svg`,{viewBox:`0 0 24 24`,width:`22`,height:`22`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,o.jsx)(`polyline`,{points:`15 18 9 12 15 6`})})}),c&&(0,o.jsx)(`h3`,{className:a.title,style:u?{color:d||`#ff3b30`}:void 0,children:m(c)}),n,l&&(0,o.jsx)(`button`,{className:a.closeBtn,onClick:S,children:m(`Закрыть`)})]})}):null}export{s as t};1@keyframes _fadeIn_jh7o2_1{0%{opacity:0}to{opacity:1}}@keyframes _fadeOut_jh7o2_1{0%{opacity:1}to{opacity:0}}._overlay_jh7o2_11{z-index:11000;background:rgba(var(--overlay-rgb,30, 27, 36), 0);-webkit-backdrop-filter:blur();justify-content:center;align-items:center;width:100%;height:100%;transition:background .5s,-webkit-backdrop-filter .5s,backdrop-filter .5s;display:flex;position:fixed;top:0;left:0}._overlay_jh7o2_11._open_jh7o2_27{background:rgba(var(--overlay-rgb,30, 27, 36), .95);-webkit-backdrop-filter:blur(20px)}._overlay_jh7o2_11._closing_jh7o2_33{background:rgba(var(--overlay-rgb,30, 27, 36), 0);-webkit-backdrop-filter:blur();pointer-events:none}._content_jh7o2_40{background:rgba(var(--card-rgb,42, 38, 51), .95);-webkit-backdrop-filter:blur(40px);border:1px solid rgba(var(--accent-rgb,157, 78, 221), .2);opacity:0;scrollbar-width:none;border-radius:24px;width:90%;max-width:380px;max-height:85vh;margin:0 auto;padding:32px 24px;transition:all .5s cubic-bezier(.34,1.56,.64,1);position:relative;overflow-y:auto;transform:scale(.9);box-shadow:0 20px 60px #00000080}._content_jh7o2_40::-webkit-scrollbar{display:none}._overlay_jh7o2_11._open_jh7o2_27 ._content_jh7o2_40{opacity:1;transform:translateY(0)scale(1)}._overlay_jh7o2_11._closing_jh7o2_33 ._content_jh7o2_40{opacity:0;transition:all .4s cubic-bezier(.4,0,.2,1);transform:scale(.8)translateY(20px)}._dangerBorder_jh7o2_72{border-color:#ff3b304d;box-shadow:0 20px 60px #00000080,0 0 40px #ff3b3033}._title_jh7o2_77{color:#fff;font-size:calc(22px * var(--font-size-scale));text-align:center;margin:0 0 24px;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;font-weight:700}._closeBtn_jh7o2_86{background:rgba(var(--accent-rgb,157, 78, 221), .15);width:100%;color:var(--on-accent,#fff);border:2px solid rgba(var(--accent-rgb,157, 78, 221), .3);cursor:pointer;font-size:calc(16px * var(--font-size-scale));border-radius:14px;margin-top:12px;padding:16px;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;font-weight:600;transition:all .2s}._closeBtn_jh7o2_86:hover{background:rgba(var(--accent-rgb,157, 78, 221), .25);border-color:rgba(var(--accent-rgb,157, 78, 221), .5)}._closeBtn_jh7o2_86:active{transform:scale(.97)}._backBtn_jh7o2_110{cursor:pointer;color:#8e8e93;z-index:1;background:#ffffff14;border:none;border-radius:50%;justify-content:center;align-items:center;width:36px;height:36px;transition:all .2s;display:flex;position:absolute;top:24px;left:20px}._backBtn_jh7o2_110:hover{color:#fff;background:#ffffff26}._backBtn_jh7o2_110:active{transform:scale(.92)}1import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{d as t,t as n}from"./vendor-CdeZI4gz.js";import{o as r,u as i}from"./index-C49_c6F1.js";var a=e(t(),1),o={screen:`_screen_a036l_1`,topbar:`_topbar_a036l_47`,brand:`_brand_a036l_56`,langButton:`_langButton_a036l_79`,content:`_content_a036l_98`,card:`_card_a036l_109`,cardIn:`_cardIn_a036l_1`,appRow:`_appRow_a036l_134`,appIcon:`_appIcon_a036l_140`,appMeta:`_appMeta_a036l_155`,overline:`_overline_a036l_160`,appName:`_appName_a036l_169`,appSite:`_appSite_a036l_180`,secureBadge:`_secureBadge_a036l_195`,lead:`_lead_a036l_208`,scopeBox:`_scopeBox_a036l_215`,scopeTitle:`_scopeTitle_a036l_222`,scopeList:`_scopeList_a036l_231`,scopeItem:`_scopeItem_a036l_237`,check:`_check_a036l_243`,scopeName:`_scopeName_a036l_257`,scopeDescription:`_scopeDescription_a036l_265`,privacyNote:`_privacyNote_a036l_273`,steps:`_steps_a036l_282`,stepDot:`_stepDot_a036l_289`,stepActive:`_stepActive_a036l_305`,stepDone:`_stepDone_a036l_312`,stepLine:`_stepLine_a036l_318`,stepLineActive:`_stepLineActive_a036l_327`,form:`_form_a036l_331`,formIn:`_formIn_a036l_1`,field:`_field_a036l_338`,twoFactorField:`_twoFactorField_a036l_385`,primaryButton:`_primaryButton_a036l_389`,denyButton:`_denyButton_a036l_422`,accountPill:`_accountPill_a036l_446`,codeTitle:`_codeTitle_a036l_465`,codeHint:`_codeHint_a036l_474`,codeRow:`_codeRow_a036l_482`,codeBox:`_codeBox_a036l_489`,codeMeta:`_codeMeta_a036l_516`,expired:`_expired_a036l_526`,linkButton:`_linkButton_a036l_531`,error:`_error_a036l_552`,stateBox:`_stateBox_a036l_565`,stateTitle:`_stateTitle_a036l_574`,stateText:`_stateText_a036l_581`,spinner:`_spinner_a036l_589`,spin:`_spin_a036l_589`,errorIcon:`_errorIcon_a036l_599`,successIcon:`_successIcon_a036l_600`,secondaryButton:`_secondaryButton_a036l_622`,footer:`_footer_a036l_643`},s=n(),c=``,l=[`client_id`,`redirect_uri`,`response_type`,`scope`,`state`,`code_challenge`,`code_challenge_method`],u={ru:{secure:`Безопасный вход`,connecting:`Проверяем приложение`,signingIn:`Вход через 4SEND`,appAccess:`запрашивает доступ к вашему аккаунту`,willReceive:`Приложение получит`,privacyNote:`Доступ к чатам, сообщениям и файлам не предоставляется.`,username:`Имя пользователя`,password:`Пароль`,twoFactor:`Пароль двухфакторной аутентификации`,signIn:`Войти`,sending:`Отправляем код...`,codeTitle:`Подтвердите вход`,codeSent:`Код отправлен в «Системные уведомления»`,codeFor:`Аккаунт`,codeLabel:`Шестизначный код`,confirm:`Подтвердить`,checking:`Проверяем...`,resend:`Отправить код ещё раз`,resendIn:`Повторить через {s} с`,expires:`Код действует ещё {s}`,expired:`Срок действия кода истёк`,back:`Войти другим аккаунтом`,cancel:`Отмена`,deny:`Отклонить`,success:`Готово`,redirecting:`Перенаправляем в приложение...`,fatal:`Не удалось открыть страницу входа`,close:`Вернуться на главную`,retry:`Попробовать снова`,codeError:`Введите шестизначный код`,credentialsError:`Введите имя пользователя и пароль`,twoFactorRequired:`Введите пароль двухфакторной аутентификации`,expiredError:`Код истёк. Начните вход заново.`,footer:`4SEND не раскрывает ваш пароль и не передаёт данные сессии приложению.`},en:{secure:`Secure sign-in`,connecting:`Checking the application`,signingIn:`Sign in with 4SEND`,appAccess:`wants access to your account`,willReceive:`The app will receive`,privacyNote:`Access to chats, messages and files is not granted.`,username:`Username`,password:`Password`,twoFactor:`Two-factor authentication password`,signIn:`Sign in`,sending:`Sending code...`,codeTitle:`Confirm sign-in`,codeSent:`A code was sent to System notifications`,codeFor:`Account`,codeLabel:`Six-digit code`,confirm:`Confirm`,checking:`Checking...`,resend:`Send the code again`,resendIn:`Retry in {s}s`,expires:`Code expires in {s}`,expired:`The code has expired`,back:`Use another account`,cancel:`Cancel`,deny:`Deny`,success:`Done`,redirecting:`Redirecting to the application...`,fatal:`Unable to open the sign-in page`,close:`Back to home`,retry:`Try again`,codeError:`Enter the six-digit code`,credentialsError:`Enter your username and password`,twoFactorRequired:`Enter your two-factor authentication password`,expiredError:`The code has expired. Start over.`,footer:`4SEND never shares your password or hands session data to the app.`}};function d({value:e,label:t,disabled:n,onChange:r}){let i=(0,a.useRef)([]),c=e.replace(/\D/g,``).slice(0,6),l=(0,a.useCallback)((e,t)=>{let n=t.replace(/\D/g,``);if(!n)return;r(`${c.slice(0,e)}${n}${c.slice(e+1)}`.replace(/\D/g,``).slice(0,6));let a=Math.min(5,e+n.length);i.current[a]?.focus()},[c,r]),u=(0,a.useCallback)((e,t)=>{if(t.key===`Backspace`){t.preventDefault(),c[e]?(r(`${c.slice(0,e)}${c.slice(e+1)}`),i.current[e]?.focus()):e>0&&(r(c.slice(0,e-1)),i.current[e-1]?.focus());return}t.key===`ArrowLeft`&&e>0&&(t.preventDefault(),i.current[e-1]?.focus()),t.key===`ArrowRight`&&e<5&&(t.preventDefault(),i.current[e+1]?.focus())},[c,r]),d=(0,a.useCallback)(e=>{e.preventDefault();let t=e.clipboardData.getData(`text`).replace(/\D/g,``).slice(0,6);t&&(r(t),i.current[Math.min(5,t.length)]?.focus())},[r]);return(0,s.jsx)(`div`,{className:o.codeRow,children:Array.from({length:6},(e,r)=>(0,s.jsx)(`input`,{ref:e=>{i.current[r]=e},className:o.codeBox,type:`text`,inputMode:`numeric`,autoComplete:r===0?`one-time-code`:`off`,autoFocus:r===0,maxLength:1,value:c[r]||``,onChange:e=>l(r,e.target.value),onKeyDown:e=>u(r,e),onPaste:d,disabled:n,"aria-label":`${t} ${r+1}`},r))})}function f(e,t){if(e&&typeof e==`object`){let t=e;if(typeof t.error_description==`string`&&t.error_description)return t.error_description;if(typeof t.error==`string`&&t.error&&t.error!==`Error`)return t.error;if(typeof t.message==`string`&&t.message)return t.message}return t}function p(){let{lang:e,switchLanguage:t}=i(),n=(0,a.useCallback)((t,n)=>{let r=(e===`ru`?u.ru:u.en)[t]||u.ru[t]||t;return n&&Object.entries(n).forEach(([e,t])=>{r=r.replace(RegExp(`\\{${e}\\}`,`g`),String(t))}),r},[e]),p=(0,a.useMemo)(()=>new URLSearchParams(window.location.search),[]),m=(0,a.useMemo)(()=>{let e={};return l.forEach(t=>{let n=p.get(t);n!==null&&(e[t]=n)}),e.response_type||=`code`,e},[p]),[h,g]=(0,a.useState)(`loading`),[_,v]=(0,a.useState)(null),[y,b]=(0,a.useState)(``),[x,S]=(0,a.useState)(``),[C,w]=(0,a.useState)(``),[T,E]=(0,a.useState)(``),[D,O]=(0,a.useState)(!1),[k,A]=(0,a.useState)(``),[j,M]=(0,a.useState)(``),[N,P]=(0,a.useState)(``),[F,I]=(0,a.useState)(0),[L,R]=(0,a.useState)(0),[z,B]=(0,a.useState)(!1),V=(0,a.useRef)(!1),H=(0,a.useRef)(null),U=(0,a.useRef)(!1),W=(0,a.useCallback)(async(t,n)=>{let r=await fetch(`${c}${t}`,{...n,headers:{"Content-Type":`application/json`,"X-Language":e===`ru`?`ru`:`en`,...n?.headers||{}}}),i=await r.json().catch(()=>({}));if(!r.ok)throw i;return i},[e]);(0,a.useEffect)(()=>{document.title=`4SEND · OAuth`,!U.current&&(U.current=!0,(async()=>{if(!m.client_id||!m.redirect_uri){b(n(`fatal`)),g(`error`);return}try{let e=new URLSearchParams(m).toString(),t=await W(`/oauth/authorize/info?${e}`);v(t),g(`login`)}catch(e){b(f(e,n(`fatal`))),g(`error`)}})())},[m,W,n]),(0,a.useEffect)(()=>{if(h!==`code`)return;let e=window.setInterval(()=>{I(e=>Math.max(0,e-1)),R(e=>Math.max(0,e-1))},1e3);return()=>window.clearInterval(e)},[h]),(0,a.useEffect)(()=>()=>{H.current!==null&&window.clearTimeout(H.current)},[]);let G=(0,a.useCallback)(e=>{V.current||(V.current=!0,g(`success`),H.current=window.setTimeout(()=>{window.location.replace(e)},350))},[]),K=(0,a.useCallback)(async e=>{if(e?.preventDefault(),z||!_)return;let t=x.trim().toLowerCase();if(!t||!C){b(n(`credentialsError`));return}if(D&&!T){b(n(`twoFactorRequired`));return}B(!0),b(``);try{let e={...m,username:t,password:C};D&&(e.twoFactorPassword=T);let r=await W(`/oauth/authorize/login`,{method:`POST`,body:JSON.stringify(e)});if(r.requires2FA){O(!0),b(``);return}if(!r.challenge){b(n(`fatal`));return}O(!1),E(``),A(r.challenge),M(r.maskedUsername||t),I(r.expiresIn||_.codeExpiresIn||600),R(r.resendAfter||30),P(``),w(``),g(`code`)}catch(e){b(f(e,n(`fatal`)))}finally{B(!1)}},[m,z,_,C,W,D,n,T,x]),q=(0,a.useCallback)(async e=>{if(e?.preventDefault(),!(z||!k)){if(!/^\d{6}$/.test(N)){b(n(`codeError`));return}B(!0),b(``);try{let e=await W(`/oauth/authorize/verify`,{method:`POST`,body:JSON.stringify({challenge:k,code:N})});if(!e.redirectUrl){b(n(`fatal`));return}G(e.redirectUrl)}catch(e){let t=f(e,n(`fatal`)),r=e&&typeof e==`object`&&e.error===`expired_token`;b(r?n(`expiredError`):t),r&&(g(`login`),A(``),P(``))}finally{B(!1)}}},[z,k,N,G,W,n]),J=(0,a.useCallback)(async()=>{if(!(z||!k||L>0)){B(!0),b(``);try{let e=await W(`/oauth/authorize/resend`,{method:`POST`,body:JSON.stringify({challenge:k})});I(e.expiresIn||600),R(e.resendAfter||30),P(``)}catch(e){b(f(e,n(`fatal`)))}finally{B(!1)}}},[z,k,W,L,n]),Y=(0,a.useCallback)(async()=>{if(!(z||!m.client_id||!m.redirect_uri)){B(!0),b(``);try{let e=await W(`/oauth/authorize/deny`,{method:`POST`,body:JSON.stringify({client_id:m.client_id,redirect_uri:m.redirect_uri,state:m.state||``})});e.redirectUrl&&G(e.redirectUrl)}catch(e){b(f(e,n(`fatal`))),B(!1)}}},[m,z,G,W,n]),X=(0,a.useCallback)(()=>{g(`login`),A(``),P(``),M(``),b(``)},[]),Z=(0,a.useCallback)(()=>{t(e===`ru`?`en`:`ru`)},[e,t]),Q=(0,a.useMemo)(()=>{if(!_?.client.website)return``;try{return new URL(_.client.website).hostname}catch{return``}},[_]),$=(_?.client.name||`4`).trim().charAt(0).toUpperCase();return(0,s.jsxs)(`div`,{className:o.screen,children:[(0,s.jsx)(r,{}),(0,s.jsxs)(`header`,{className:o.topbar,children:[(0,s.jsxs)(`a`,{className:o.brand,href:`/`,children:[(0,s.jsx)(`img`,{src:`/ico.png`,alt:`4SEND`,width:`34`,height:`34`}),(0,s.jsx)(`span`,{children:`4SEND`})]}),(0,s.jsx)(`button`,{type:`button`,className:o.langButton,onClick:Z,children:e===`ru`?`EN`:`RU`})]}),(0,s.jsxs)(`main`,{className:o.content,children:[(0,s.jsxs)(`section`,{className:o.card,children:[h===`loading`&&(0,s.jsxs)(`div`,{className:o.stateBox,children:[(0,s.jsx)(`span`,{className:o.spinner}),(0,s.jsx)(`h1`,{className:o.stateTitle,children:n(`connecting`)})]}),h===`error`&&(0,s.jsxs)(`div`,{className:o.stateBox,children:[(0,s.jsx)(`div`,{className:o.errorIcon,children:(0,s.jsxs)(`svg`,{viewBox:`0 0 24 24`,width:`26`,height:`26`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,children:[(0,s.jsx)(`circle`,{cx:`12`,cy:`12`,r:`9`}),(0,s.jsx)(`path`,{d:`M12 7v6M12 17h.01`})]})}),(0,s.jsx)(`h1`,{className:o.stateTitle,children:n(`fatal`)}),(0,s.jsx)(`p`,{className:o.stateText,children:y}),(0,s.jsx)(`a`,{className:o.secondaryButton,href:`/`,children:n(`close`)})]}),_&&h!==`loading`&&h!==`error`&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)(`div`,{className:o.appRow,children:[(0,s.jsx)(`div`,{className:o.appIcon,children:$}),(0,s.jsxs)(`div`,{className:o.appMeta,children:[(0,s.jsx)(`div`,{className:o.overline,children:n(`signingIn`)}),(0,s.jsx)(`h1`,{className:o.appName,children:_.client.name}),Q&&(0,s.jsxs)(`a`,{className:o.appSite,href:_.client.website||`#`,target:`_blank`,rel:`noreferrer noopener`,children:[Q,(0,s.jsx)(`svg`,{viewBox:`0 0 24 24`,width:`12`,height:`12`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,s.jsx)(`path`,{d:`M7 17L17 7M9 7h8v8`})})]})]}),(0,s.jsx)(`div`,{className:o.secureBadge,title:n(`secure`),children:(0,s.jsxs)(`svg`,{viewBox:`0 0 24 24`,width:`15`,height:`15`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,s.jsx)(`rect`,{x:`4`,y:`10`,width:`16`,height:`10`,rx:`2`}),(0,s.jsx)(`path`,{d:`M8 10V7a4 4 0 018 0v3`})]})})]}),(0,s.jsx)(`p`,{className:o.lead,children:n(`appAccess`)}),(0,s.jsxs)(`div`,{className:o.scopeBox,children:[(0,s.jsx)(`div`,{className:o.scopeTitle,children:n(`willReceive`)}),(0,s.jsx)(`div`,{className:o.scopeList,children:_.scopes.map(e=>(0,s.jsxs)(`div`,{className:o.scopeItem,children:[(0,s.jsx)(`span`,{className:o.check,children:(0,s.jsx)(`svg`,{viewBox:`0 0 24 24`,width:`12`,height:`12`,fill:`none`,stroke:`currentColor`,strokeWidth:`3`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,s.jsx)(`path`,{d:`M5 12l4 4L19 6`})})}),(0,s.jsxs)(`span`,{children:[(0,s.jsx)(`span`,{className:o.scopeName,children:e.title}),(0,s.jsx)(`span`,{className:o.scopeDescription,children:e.description})]})]},e.id))}),(0,s.jsx)(`div`,{className:o.privacyNote,children:n(`privacyNote`)})]}),(0,s.jsxs)(`div`,{className:o.steps,children:[(0,s.jsx)(`span`,{className:`${o.stepDot} ${h===`login`?o.stepActive:o.stepDone}`,children:`1`}),(0,s.jsx)(`span`,{className:`${o.stepLine} ${h===`code`?o.stepLineActive:``}`}),(0,s.jsx)(`span`,{className:`${o.stepDot} ${h===`code`?o.stepActive:``}`,children:`2`})]}),h===`login`&&(0,s.jsxs)(`form`,{className:o.form,onSubmit:K,children:[(0,s.jsxs)(`div`,{className:o.field,children:[(0,s.jsxs)(`svg`,{viewBox:`0 0 24 24`,width:`18`,height:`18`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.8`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,s.jsx)(`circle`,{cx:`12`,cy:`8`,r:`3.5`}),(0,s.jsx)(`path`,{d:`M5 20c0-3.3 3.1-6 7-6s7 2.7 7 6`})]}),(0,s.jsx)(`input`,{type:`text`,value:x,onChange:e=>S(e.target.value.replace(/[^a-zA-Z]/g,``).toLowerCase().slice(0,20)),placeholder:n(`username`),"aria-label":n(`username`),autoComplete:`username`,autoCapitalize:`off`,spellCheck:!1,disabled:z})]}),(0,s.jsxs)(`div`,{className:o.field,children:[(0,s.jsxs)(`svg`,{viewBox:`0 0 24 24`,width:`18`,height:`18`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.8`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,s.jsx)(`rect`,{x:`4`,y:`10`,width:`16`,height:`10`,rx:`2`}),(0,s.jsx)(`path`,{d:`M8 10V7a4 4 0 018 0v3`})]}),(0,s.jsx)(`input`,{type:`password`,value:C,onChange:e=>w(e.target.value),placeholder:n(`password`),"aria-label":n(`password`),autoComplete:`current-password`,maxLength:30,disabled:z})]}),D&&(0,s.jsxs)(`div`,{className:`${o.field} ${o.twoFactorField}`,children:[(0,s.jsxs)(`svg`,{viewBox:`0 0 24 24`,width:`18`,height:`18`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.8`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,s.jsx)(`path`,{d:`M12 3l7 3v6c0 4.4-3 7.4-7 9-4-1.6-7-4.6-7-9V6l7-3z`}),(0,s.jsx)(`path`,{d:`M9 12l2 2 4-4`})]}),(0,s.jsx)(`input`,{type:`password`,value:T,onChange:e=>E(e.target.value),placeholder:n(`twoFactor`),"aria-label":n(`twoFactor`),autoComplete:`off`,maxLength:30,disabled:z})]}),(0,s.jsx)(`button`,{type:`submit`,className:o.primaryButton,disabled:z,children:n(z?`sending`:`signIn`)}),(0,s.jsx)(`button`,{type:`button`,className:o.denyButton,onClick:Y,disabled:z,children:n(`cancel`)})]}),h===`code`&&(0,s.jsxs)(`form`,{className:o.form,onSubmit:q,children:[(0,s.jsx)(`h2`,{className:o.codeTitle,children:n(`codeTitle`)}),(0,s.jsxs)(`div`,{className:o.accountPill,children:[(0,s.jsx)(`span`,{children:n(`codeFor`)}),(0,s.jsx)(`strong`,{children:j})]}),(0,s.jsx)(`p`,{className:o.codeHint,children:n(`codeSent`)}),(0,s.jsx)(d,{value:N,label:n(`codeLabel`),onChange:P,disabled:z||F===0}),(0,s.jsxs)(`div`,{className:o.codeMeta,children:[(0,s.jsx)(`span`,{className:F===0?o.expired:``,children:F===0?n(`expired`):n(`expires`,{s:`${Math.floor(F/60)}:${String(F%60).padStart(2,`0`)}`})}),(0,s.jsx)(`button`,{type:`button`,className:o.linkButton,onClick:J,disabled:z||L>0||F===0,children:L>0?n(`resendIn`,{s:L}):n(`resend`)})]}),(0,s.jsx)(`button`,{type:`submit`,className:o.primaryButton,disabled:z||N.length!==6||F===0,children:n(z?`checking`:`confirm`)}),(0,s.jsx)(`button`,{type:`button`,className:o.denyButton,onClick:X,disabled:z,children:n(`back`)})]}),h===`success`&&(0,s.jsxs)(`div`,{className:o.stateBox,children:[(0,s.jsx)(`div`,{className:o.successIcon,children:(0,s.jsx)(`svg`,{viewBox:`0 0 24 24`,width:`26`,height:`26`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.4`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,s.jsx)(`path`,{d:`M5 12l4 4L19 6`})})}),(0,s.jsx)(`h1`,{className:o.stateTitle,children:n(`success`)}),(0,s.jsx)(`p`,{className:o.stateText,children:n(`redirecting`)})]}),y&&(0,s.jsx)(`div`,{className:o.error,role:`alert`,children:y})]})]}),(0,s.jsx)(`p`,{className:o.footer,children:n(`footer`)})]})]})}export{p as default};1._screen_a036l_1{color:#fff;min-height:100vh;font-family:var(--font-main);box-sizing:border-box;background:#0b0b0e;flex-direction:column;display:flex;position:relative;overflow:hidden}._screen_a036l_1 *,._screen_a036l_1 :before,._screen_a036l_1 :after{box-sizing:border-box}._screen_a036l_1:before{content:"";background:radial-gradient(circle, rgba(var(--accent-rgb,167, 79, 255), .18) 0, transparent 68%);pointer-events:none;z-index:0;width:760px;height:760px;position:absolute;top:-220px;left:50%;transform:translate(-50%)}._screen_a036l_1:after{content:"";pointer-events:none;z-index:0;opacity:.5;background-color:#0000;background-image:linear-gradient(#ffffff06 1px,#0000 1px),linear-gradient(90deg,#ffffff06 1px,#0000 1px);background-position:0 0,0 0;background-repeat:repeat,repeat;background-size:64px 64px;background-attachment:scroll,scroll;background-origin:padding-box,padding-box;background-clip:border-box,border-box;position:absolute;inset:0;-webkit-mask-image:radial-gradient(circle at 50% 35%,#000,#0000 72%);mask-image:radial-gradient(circle at 50% 35%,#000,#0000 72%)}._topbar_a036l_47{z-index:3;justify-content:space-between;align-items:center;padding:22px 30px;display:flex;position:relative}._brand_a036l_56{color:#fff;letter-spacing:1.6px;align-items:center;gap:10px;font-size:16px;font-weight:800;text-decoration:none;display:inline-flex}._brand_a036l_56 img{border-radius:10px;box-shadow:0 8px 20px #00000073}._brand_a036l_56 span{background:linear-gradient(90deg,#fff,#d4aaff);-webkit-text-fill-color:transparent;-webkit-background-clip:text;background-clip:text}._langButton_a036l_79{color:#9b9ba5;letter-spacing:1px;cursor:pointer;background:#ffffff0a;border:1px solid #ffffff1a;border-radius:10px;padding:7px 12px;font-size:12px;font-weight:700;transition:all .2s}._langButton_a036l_79:hover{color:#fff;border-color:rgba(var(--accent-rgb,167, 79, 255), .45);background:rgba(var(--accent-rgb,167, 79, 255), .1)}._content_a036l_98{z-index:2;flex-direction:column;flex:1;justify-content:center;align-items:center;padding:18px 16px 34px;display:flex;position:relative}._card_a036l_109{-webkit-backdrop-filter:blur(24px);background:linear-gradient(#1b1b26d6,#111117c7);border:1px solid #ffffff17;border-radius:28px;width:100%;max-width:432px;padding:28px;animation:.55s cubic-bezier(.2,.8,.2,1) _cardIn_a036l_1;position:relative;overflow:hidden;box-shadow:0 32px 80px #0000009e,inset 0 1px #ffffff14}._card_a036l_109:before{content:"";background:linear-gradient(90deg, transparent, rgba(var(--accent-rgb,167, 79, 255), .85), transparent);height:1px;position:absolute;top:0;left:12%;right:12%}._appRow_a036l_134{align-items:center;gap:13px;display:flex}._appIcon_a036l_140{color:#fff;background:linear-gradient(145deg, rgba(var(--accent-rgb,167, 79, 255), .95), #571ea0f2);width:52px;height:52px;box-shadow:0 10px 24px rgba(var(--accent-rgb,167, 79, 255), .28), inset 0 1px 0 #ffffff40;border-radius:16px;flex-shrink:0;justify-content:center;align-items:center;font-size:24px;font-weight:900;display:flex}._appMeta_a036l_155{flex:1;min-width:0}._overline_a036l_160{letter-spacing:1.8px;text-transform:uppercase;color:#ffffff6b;margin-bottom:3px;font-size:10px;font-weight:700}._appName_a036l_169{letter-spacing:-.3px;text-overflow:ellipsis;white-space:nowrap;margin:0;font-size:24px;font-weight:800;line-height:1.2;overflow:hidden}._appSite_a036l_180{color:#ffffff75;align-items:center;gap:4px;margin-top:4px;font-size:12px;text-decoration:none;transition:color .2s;display:inline-flex}._appSite_a036l_180:hover{color:var(--accent-solid)}._secureBadge_a036l_195{color:#4cd67a;background:#4cd67a1a;border:1px solid #4cd67a33;border-radius:10px;flex-shrink:0;justify-content:center;align-items:center;width:32px;height:32px;display:flex}._lead_a036l_208{color:#a3a3ad;margin:14px 0 18px;font-size:14px;line-height:1.5}._scopeBox_a036l_215{background:#0000003d;border:1px solid #ffffff0f;border-radius:16px;padding:14px}._scopeTitle_a036l_222{letter-spacing:1.5px;text-transform:uppercase;color:#ffffff61;margin-bottom:10px;font-size:10px;font-weight:700}._scopeList_a036l_231{flex-direction:column;gap:9px;display:flex}._scopeItem_a036l_237{align-items:flex-start;gap:10px;display:flex}._check_a036l_243{color:#4cd67a;background:#4cd67a1f;border:1px solid #4cd67a38;border-radius:50%;flex-shrink:0;justify-content:center;align-items:center;width:20px;height:20px;margin-top:1px;display:flex}._scopeName_a036l_257{color:#f2f2f5;font-size:13px;font-weight:700;line-height:1.35;display:block}._scopeDescription_a036l_265{color:#85858f;margin-top:1px;font-size:12px;line-height:1.4;display:block}._privacyNote_a036l_273{color:#777781;border-top:1px solid #ffffff0f;margin-top:12px;padding-top:10px;font-size:11px;line-height:1.45}._steps_a036l_282{align-items:center;gap:8px;margin:20px 0 16px;display:flex}._stepDot_a036l_289{color:#74747e;background:#ffffff0d;border:1px solid #ffffff14;border-radius:50%;flex-shrink:0;justify-content:center;align-items:center;width:24px;height:24px;font-size:11px;font-weight:800;transition:all .3s;display:flex}._stepActive_a036l_305{color:#fff;background:linear-gradient(135deg, var(--accent-solid), var(--accent-hover));box-shadow:0 0 18px rgba(var(--accent-rgb,167, 79, 255), .4);border-color:#0000}._stepDone_a036l_312{color:var(--accent-solid);background:rgba(var(--accent-rgb,167, 79, 255), .12);border-color:rgba(var(--accent-rgb,167, 79, 255), .28)}._stepLine_a036l_318{background:#ffffff12;border-radius:2px;flex:1;height:2px;transition:background .3s;overflow:hidden}._stepLineActive_a036l_327{background:linear-gradient(90deg, var(--accent-solid), rgba(var(--accent-rgb,167, 79, 255), .3))}._form_a036l_331{flex-direction:column;gap:11px;animation:.3s _formIn_a036l_1;display:flex}._field_a036l_338{width:100%;position:relative}._field_a036l_338 svg{color:#64646e;pointer-events:none;transition:color .2s;position:absolute;top:50%;left:15px;transform:translateY(-50%)}._field_a036l_338 input{color:#fff;width:100%;font-family:var(--font-main);font-size:calc(14px * var(--font-size-scale));background:#00000047;border:1px solid #ffffff17;border-radius:14px;outline:none;padding:14px 14px 14px 44px;transition:border-color .2s,background .2s,box-shadow .2s}._field_a036l_338 input::placeholder{color:#676771}._field_a036l_338 input:focus{border-color:rgba(var(--accent-rgb,167, 79, 255), .75);background:rgba(var(--accent-rgb,167, 79, 255), .06);box-shadow:0 0 0 3px rgba(var(--accent-rgb,167, 79, 255), .1)}._field_a036l_338 input:focus+svg,._field_a036l_338:focus-within svg{color:var(--accent-solid)}._field_a036l_338 input:disabled{opacity:.6}._twoFactorField_a036l_385{animation:.25s _formIn_a036l_1}._primaryButton_a036l_389{background:linear-gradient(135deg, var(--accent-solid), var(--accent-hover));width:100%;color:var(--on-accent,#fff);font-family:var(--font-main);font-size:calc(14px * var(--font-size-scale));letter-spacing:.4px;cursor:pointer;box-shadow:0 12px 28px rgba(var(--accent-rgb,167, 79, 255), .28);border:none;border-radius:14px;margin-top:3px;padding:14px 18px;font-weight:800;transition:transform .2s,box-shadow .2s,filter .2s,opacity .2s}._primaryButton_a036l_389:hover:not(:disabled){filter:brightness(1.08);box-shadow:0 16px 34px rgba(var(--accent-rgb,167, 79, 255), .38);transform:translateY(-1px)}._primaryButton_a036l_389:active:not(:disabled){transform:scale(.985)}._primaryButton_a036l_389:disabled{opacity:.55;cursor:not-allowed;box-shadow:none}._denyButton_a036l_422{color:#85858f;width:100%;font-family:var(--font-main);font-size:calc(13px * var(--font-size-scale));cursor:pointer;background:0 0;border:none;border-radius:12px;padding:11px 18px;font-weight:600;transition:color .2s,background .2s}._denyButton_a036l_422:hover:not(:disabled){color:#fff;background:#ffffff0a}._denyButton_a036l_422:disabled{opacity:.5;cursor:not-allowed}._accountPill_a036l_446{background:rgba(var(--accent-rgb,167, 79, 255), .07);border:1px solid rgba(var(--accent-rgb,167, 79, 255), .17);color:#9c9ca6;border-radius:12px;justify-content:center;align-items:center;gap:7px;padding:10px 12px;font-size:12px;display:flex}._accountPill_a036l_446 strong{color:#fff;letter-spacing:.6px;font-weight:700}._codeTitle_a036l_465{text-align:center;letter-spacing:-.2px;color:#f4f4f7;margin:4px 0 0;font-size:18px;font-weight:800}._codeHint_a036l_474{text-align:center;color:#9898a2;margin:2px 0;font-size:12.5px;line-height:1.45}._codeRow_a036l_482{gap:8px;width:100%;margin:4px 0 2px;display:flex}._codeBox_a036l_489{color:#fff;min-width:0;height:54px;font-family:var(--font-main);text-align:center;caret-color:var(--accent-solid);background:#0000004d;border:1px solid #ffffff1a;border-radius:13px;outline:none;flex:1;font-size:23px;font-weight:800;transition:border-color .2s,box-shadow .2s,background .2s}._codeBox_a036l_489:focus{border-color:rgba(var(--accent-rgb,167, 79, 255), .85);background:rgba(var(--accent-rgb,167, 79, 255), .08);box-shadow:0 0 0 3px rgba(var(--accent-rgb,167, 79, 255), .12)}._codeBox_a036l_489:disabled{opacity:.55}._codeMeta_a036l_516{color:#74747e;font-variant-numeric:tabular-nums;justify-content:space-between;align-items:center;gap:10px;font-size:11.5px;display:flex}._codeMeta_a036l_516 ._expired_a036l_526,._expired_a036l_526{color:#ff6b6b}._linkButton_a036l_531{color:var(--accent-solid);font-family:var(--font-main);cursor:pointer;background:0 0;border:none;padding:0;font-size:11.5px;font-weight:700;transition:color .2s,opacity .2s}._linkButton_a036l_531:hover:not(:disabled){color:#c79bff}._linkButton_a036l_531:disabled{color:#5c5c66;cursor:not-allowed}._error_a036l_552{color:#f77;text-align:center;background:#ff4d4d17;border:1px solid #ff4d4d38;border-radius:12px;margin-top:14px;padding:10px 12px;font-size:12.5px;line-height:1.45;animation:.2s _formIn_a036l_1}._stateBox_a036l_565{text-align:center;flex-direction:column;align-items:center;padding:22px 0 8px;animation:.3s _formIn_a036l_1;display:flex}._stateTitle_a036l_574{letter-spacing:-.2px;margin:14px 0 6px;font-size:20px;font-weight:800}._stateText_a036l_581{color:#8f8f99;max-width:300px;margin:0;font-size:13px;line-height:1.5}._spinner_a036l_589{background:conic-gradient(from 0deg, transparent 0 35%, var(--accent-solid) 80%, #d4aaff 100%);border-radius:50%;width:38px;height:38px;animation:.9s linear infinite _spin_a036l_589;-webkit-mask-image:radial-gradient(#0000 57%,#000 58%);mask-image:radial-gradient(#0000 57%,#000 58%)}._errorIcon_a036l_599,._successIcon_a036l_600{border-radius:50%;justify-content:center;align-items:center;width:54px;height:54px;display:flex}._errorIcon_a036l_599{color:#ff6b6b;background:#ff4d4d1a;border:1px solid #ff4d4d38}._successIcon_a036l_600{color:#4cd67a;background:#4cd67a1a;border:1px solid #4cd67a38;box-shadow:0 0 30px #4cd67a26}._secondaryButton_a036l_622{color:#d6d6dc;border:1px solid #ffffff1a;border-radius:12px;justify-content:center;align-items:center;margin-top:18px;padding:11px 18px;font-size:13px;font-weight:700;text-decoration:none;transition:all .2s;display:inline-flex}._secondaryButton_a036l_622:hover{border-color:rgba(var(--accent-rgb,167, 79, 255), .45);background:rgba(var(--accent-rgb,167, 79, 255), .08);color:#fff}._footer_a036l_643{text-align:center;color:#55555f;width:100%;max-width:350px;margin:18px 0 0;font-size:11px;line-height:1.55}@keyframes _cardIn_a036l_1{0%{opacity:0;filter:blur(8px);transform:translateY(22px)scale(.985)}to{opacity:1;filter:blur();transform:translateY(0)scale(1)}}@keyframes _formIn_a036l_1{0%{opacity:0;transform:translateY(6px)}to{opacity:1;transform:translateY(0)}}@keyframes _spin_a036l_589{to{transform:rotate(360deg)}}@media (width<=480px){._topbar_a036l_47{padding:16px 18px}._content_a036l_98{justify-content:flex-start;padding:8px 12px 24px}._card_a036l_109{border-radius:24px;padding:22px 18px}._appName_a036l_169{font-size:21px}._codeRow_a036l_482{gap:6px}._codeBox_a036l_489{border-radius:11px;height:50px;font-size:20px}._footer_a036l_643{margin-top:14px}}@media (prefers-reduced-motion:reduce){._card_a036l_109,._form_a036l_331,._stateBox_a036l_565,._spinner_a036l_589{animation:none}}1import{t as e}from"./rolldown-runtime-QTnfLwEv.js";var t=e(((e,t)=>{t.exports={}}));export{t};12const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/libsodium-wrappers-DIT7SeqD.js","assets/__vite-browser-external-BRm5n2qg.js","assets/rolldown-runtime-QTnfLwEv.js"])))=>i.map(i=>d[i]);import{n as e}from"./rolldown-runtime-QTnfLwEv.js";import{c as t}from"./vendor-CdeZI4gz.js";var n=e({createVerificationBlob:()=>g,decrypt:()=>h,decryptValue:()=>b,deriveKey:()=>f,encrypt:()=>p,encryptValue:()=>y,encryptWithSalt:()=>m,ensureReady:()=>u,generateSalt:()=>d,validatePasswordFormat:()=>v,verifyPassword:()=>_}),r=16,i=24,a=32,o=`4SEND_VERIFIED`,s=!1,c;async function l(){if(!c){let e=await t(()=>import(`./libsodium-wrappers-DIT7SeqD.js`),__vite__mapDeps([0,1,2]));c=e.default||e}return c}async function u(){s||=(await(await l()).ready,!0)}async function d(){return(await l()).randombytes_buf(r)}async function f(e,t){await u();let n=c;return n.crypto_pwhash(a,e,t,n.crypto_pwhash_OPSLIMIT_INTERACTIVE,n.crypto_pwhash_MEMLIMIT_INTERACTIVE,n.crypto_pwhash_ALG_ARGON2ID13)}async function p(e,t,n){await u();let r=c,a=r.randombytes_buf(i),o=r.crypto_aead_xchacha20poly1305_ietf_encrypt(r.from_string(e),r.from_string(n),null,a,t);return{v:2,salt:``,iv:r.to_base64(a),aad:n,data:r.to_base64(o)}}async function m(e,t,n,r){let i=await p(e,t,r);return i.salt=(await l()).to_base64(n),i}async function h(e,t){await u();let n=c,r=n.from_base64(e.iv),i=n.from_base64(e.data),a=n.from_string(e.aad),o=n.crypto_aead_xchacha20poly1305_ietf_decrypt(null,i,a,r,t);return n.to_string(o)}async function g(e,t){return m(o,e,t,`verify`)}async function _(e,t,n){try{return await h(n,await f(e,(await l()).from_base64(t)))===o}catch{return!1}}function v(e){return/^[a-zA-Z]{3}\d{3}$/.test(e)}async function y(e,t,n){return p(JSON.stringify(e),t,n)}async function b(e,t){let n=await h(e,t);return JSON.parse(n)}export{p as a,u as c,_ as d,f as i,d as l,h as n,y as o,b as r,n as s,g as t,v as u};.gitattributes-2
Dockerfile+3-5
app.jsDeleted-101
config/cloudinary.jsDeleted-21
config/env.jsDeleted-11
config/firebase.jsDeleted-13
constants/allowed.jsDeleted-6
constants/limits.jsDeleted-66
constants/translations.jsDeleted-141
docs/oauth.mdDeleted-306
index.jsDeleted-36
jobs/autoDeleteUsers.jsDeleted-36
jobs/messageExpiry.jsDeleted-37
jobs/notificationRepeat.jsDeleted-41
jobs/sessionCleanup.jsDeleted-33
middleware/authenticateToken.jsDeleted-37
middleware/botDetection.jsDeleted-14
middleware/privacyWrapper.jsDeleted-50
middleware/sanitizeMongo.jsDeleted-24
middleware/securityHeaders.jsDeleted-28
models/BlackList.jsDeleted-10
models/ChatAction.jsDeleted-12
models/Dialog.jsDeleted-27
models/Message.jsDeleted-43
models/OAuthApp.jsDeleted-17
models/OAuthCode.jsDeleted-16
models/OAuthRequest.jsDeleted-24
models/OAuthToken.jsDeleted-18
models/Pin.jsDeleted-15
models/PreKey.jsDeleted-23
models/Reaction.jsDeleted-11
models/Room.jsDeleted-25
models/User.jsDeleted-33
package-lock.jsonDeleted
package.json+28-29
public/assets/AvatarCropper-43twomjP.cssDeleted-1
public/assets/AvatarCropper-DDqz46Dp.jsDeleted-1
public/assets/EmojiPanel-Bf-sbcJk.cssDeleted-1
public/assets/EmojiPanel-DjvqtDVy.jsDeleted-1
public/assets/EncryptionModal-Bk9GLrBN.cssDeleted-1
public/assets/EncryptionModal-BmkhNiaW.jsDeleted-1
public/assets/MessengerPage-C5heixc4.jsDeleted
public/assets/MessengerPage-DQJ6Dqhc.cssDeleted
public/assets/ModalShell-DH5TxKnz.jsDeleted-1
public/assets/ModalShell-DxpX6TOZ.cssDeleted-1
public/assets/OAuthAuthorizePage-BEN3iQn0.jsDeleted-1
public/assets/OAuthAuthorizePage-Dv6k8Z10.cssDeleted-1
public/assets/__vite-browser-external-BRm5n2qg.jsDeleted-1
public/assets/encryption-DWQ3YZ9S.jsDeleted-2
public/assets/index-C49_c6F1.jsDeleted