/
Alcatraz
/
Wagomon
Обзор
Документация
Войти
/
Alcatraz
/
Wagomon
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/hooks.server.js
69 строк
2 KB
saitgalineu
vkr
26 май 2026, 10:08
26 май 2026, 10:08
f9b2919
Код
Авторство
О чём код?
import { readSessionCookie } from '$lib/server/session.js'; const RATE_LIMIT_WINDOW_MS = 60_000; const RATE_LIMIT_MAX_REQUESTS = 60; const rateLimitStore = new Map(); function isRateLimited(ip) { const now = Date.now(); const existing = rateLimitStore.get(ip); if (!existing || now - existing.windowStart > RATE_LIMIT_WINDOW_MS) { rateLimitStore.set(ip, { count: 1, windowStart: now }); return false; } existing.count += 1; rateLimitStore.set(ip, existing); return existing.count > RATE_LIMIT_MAX_REQUESTS; } export async function handle({ event, resolve }) { const session = readSessionCookie(event.cookies); event.locals.user = session ? { id: session.id, login: session.login, role: session.role, permissions: session.permissions ?? {} } : null; const normalizedPathname = event.url.pathname.replace(/\/+$/, ''); if (normalizedPathname !== event.url.pathname) { event.url.pathname = normalizedPathname; } const pathname = event.url.pathname; const isTelegramWebhook = pathname === '/api/telegram'; const isMattermostActions = pathname === '/api/mattermost/actions'; if (!event.locals.user) { if (!isTelegramWebhook && !isMattermostActions) { const ip = event.getClientAddress ? event.getClientAddress() : 'unknown'; if (isRateLimited(ip)) { if (pathname.startsWith('/api/')) { return new Response(JSON.stringify({ error: 'Too Many Requests' }), { status: 429, headers: { 'content-type': 'application/json' } }); } return new Response('Too Many Requests', { status: 429 }); } } } const isLoginArea = pathname.startsWith('/login'); const isApiAuthFree = pathname.startsWith('/api/') && (isTelegramWebhook || isMattermostActions); const requiresAuth = !isLoginArea && !isApiAuthFree; if (requiresAuth && !event.locals.user) { if (pathname.startsWith('/api/')) { return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401, headers: { 'content-type': 'application/json' } }); } return Response.redirect(new URL('/login', event.url), 303); } return resolve(event); }