/
ncit
/
c4panelmodel
Обзор
Документация
Войти
/
ncit
/
c4panelmodel
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
main
src/lib/server/security.ts
75 строк
2 KB
ncit
feat: rewrite hooks.server.ts to use Supabase Auth
07 июн 2026, 19:32
07 июн 2026, 19:32
b6162ab
Код
Авторство
О чём код?
/** * Security utilities: CSRF protection and response security headers. * * CSRF uses a double-submit cookie pattern: * 1. Server sets a `c4panel_csrf` cookie with a random token. * 2. Client reads the cookie and sends the same value in an * `x-csrf-token` header on every state-changing request. * 3. Server compares the header value against the cookie. * * SvelteKit form actions are exempt — SvelteKit already enforces * origin checking via its built-in CSRF protection. */ import { randomBytes } from 'node:crypto'; const CSRF_COOKIE = 'c4panel_csrf'; const CSRF_HEADER = 'x-csrf-token'; // --- CSRF --- export function generateCsrfToken(): string { return randomBytes(32).toString('hex'); } export function setCsrfCookie( cookies: { set: (name: string, value: string, opts: any) => void }, token: string ): void { cookies.set(CSRF_COOKIE, token, { path: '/', httpOnly: false, // readable by JS so the client can echo it sameSite: 'lax', secure: process.env.NODE_ENV === 'production' }); } export function validateCsrf( cookies: { get: (name: string) => string | undefined }, headers: { get: (name: string) => string | null } ): boolean { const cookie = cookies.get(CSRF_COOKIE); const header = headers.get(CSRF_HEADER); if (!cookie || !header) return false; return cookie === header; } export const csrfCookieName = CSRF_COOKIE; // --- Security Headers --- /** * Apply security headers to a Response. * Call this after `resolve(event)` in the handle hook. */ export function applySecurityHeaders(response: Response): Response { const headers = response.headers; headers.set('X-Content-Type-Options', 'nosniff'); headers.set('X-Frame-Options', 'DENY'); headers.set('Referrer-Policy', 'strict-origin-when-cross-origin'); headers.set( 'Permissions-Policy', 'camera=(), microphone=(), geolocation=(), interest-cohort=()' ); // CSP is managed by SvelteKit (csp.mode: 'auto' in svelte.config.js) // so that inline scripts get auto-generated nonces. Do NOT overwrite it here. // HSTS only in production over HTTPS. if (process.env.NODE_ENV === 'production') { headers.set('Strict-Transport-Security', 'max-age=63072000; includeSubDomains; preload'); } return response; }