Merge pull request #74 from kitpdr/fix/cloudflare-global-scope
fix(cloudflare): remove setInterval from global scope
3 files · +88 -27
M README.md +43 -0
| @@ -76,6 +76,49 @@ Vous pouvez visualiser et gérer vos données via le dashboard Convex : | |||
| 76 | 76 | npx convex dashboard | |
| 77 | 77 | ``` | |
| 78 | 78 | ||
| 79 | + | ## Déploiement Cloudflare Pages | |
| 80 | + | ||
| 81 | + | Le projet est déployé sur [Cloudflare Pages](https://pages.cloudflare.com/). Les Workers Cloudflare ont des **limitations strictes** à respecter. | |
| 82 | + | ||
| 83 | + | ### Opérations interdites au niveau global/module | |
| 84 | + | ||
| 85 | + | Cloudflare Workers **n'autorisent PAS** les opérations suivantes au niveau global (en dehors des handlers de requête) : | |
| 86 | + | ||
| 87 | + | ```typescript | |
| 88 | + | // INTERDIT - provoque "Disallowed operation called within global scope" | |
| 89 | + | setInterval(() => { ... }, 1000); | |
| 90 | + | setTimeout(() => { ... }, 1000); | |
| 91 | + | fetch('https://api.example.com'); | |
| 92 | + | crypto.getRandomValues(new Uint8Array(16)); | |
| 93 | + | ||
| 94 | + | // AUTORISE - à l'intérieur d'un handler | |
| 95 | + | export const GET: RequestHandler = async () => { | |
| 96 | + | const random = crypto.getRandomValues(new Uint8Array(16)); | |
| 97 | + | const response = await fetch('https://api.example.com'); | |
| 98 | + | // ... | |
| 99 | + | }; | |
| 100 | + | ``` | |
| 101 | + | ||
| 102 | + | ### Bonnes pratiques | |
| 103 | + | ||
| 104 | + | | A eviter | Alternative | | |
| 105 | + | | ----------------------------------------------------- | ------------------------------------------------------ | | |
| 106 | + | | `setInterval` pour cleanup | Lazy cleanup à chaque requête | | |
| 107 | + | | `fetch()` au chargement du module | `fetch()` dans les handlers | | |
| 108 | + | | Création de clients API au niveau module | Création lazy ou dans les handlers | | |
| 109 | + | | `process.exit()` | Retourner une Response avec status d'erreur | | |
| 110 | + | | Bibliothèques avec worker threads (ex: `pino-pretty`) | Versions compatibles edge (ex: `pino` sans transports) | | |
| 111 | + | ||
| 112 | + | ### Variables d'environnement | |
| 113 | + | ||
| 114 | + | - Utilisez `$env/dynamic/private` (runtime) au lieu de `$env/static/private` (build-time) | |
| 115 | + | - Les variables définies dans le dashboard Cloudflare ne sont disponibles qu'au runtime | |
| 116 | + | ||
| 117 | + | ### Références | |
| 118 | + | ||
| 119 | + | - [Cloudflare Workers Runtime APIs](https://developers.cloudflare.com/workers/runtime-apis/) | |
| 120 | + | - [SvelteKit Cloudflare Adapter](https://svelte.dev/docs/kit/adapter-cloudflare) | |
| 121 | + | ||
| 79 | 122 | ## Documentation et Ressources | |
| 80 | 123 | ||
| 81 | 124 | Si vous n'avez jamais utilisé Svelte/Kit ou Convex, référez-vous aux documentations officielles : | |
| @@ -76,6 +76,49 @@ Vous pouvez visualiser et gérer vos données via le dashboard Convex : | |||||
| 76 | npx convex dashboard | 76 | npx convex dashboard | ||
| 77 | ``` | 77 | ``` | ||
| 78 | 78 | ||||
| 79 | + | ## Déploiement Cloudflare Pages | |||
| 80 | + | ||||
| 81 | + | Le projet est déployé sur [Cloudflare Pages](https://pages.cloudflare.com/). Les Workers Cloudflare ont des **limitations strictes** à respecter. | |||
| 82 | + | ||||
| 83 | + | ### Opérations interdites au niveau global/module | |||
| 84 | + | ||||
| 85 | + | Cloudflare Workers **n'autorisent PAS** les opérations suivantes au niveau global (en dehors des handlers de requête) : | |||
| 86 | + | ||||
| 87 | + | ```typescript | |||
| 88 | + | // INTERDIT - provoque "Disallowed operation called within global scope" | |||
| 89 | + | setInterval(() => { ... }, 1000); | |||
| 90 | + | setTimeout(() => { ... }, 1000); | |||
| 91 | + | fetch('https://api.example.com'); | |||
| 92 | + | crypto.getRandomValues(new Uint8Array(16)); | |||
| 93 | + | ||||
| 94 | + | // AUTORISE - à l'intérieur d'un handler | |||
| 95 | + | export const GET: RequestHandler = async () => { | |||
| 96 | + | const random = crypto.getRandomValues(new Uint8Array(16)); | |||
| 97 | + | const response = await fetch('https://api.example.com'); | |||
| 98 | + | // ... | |||
| 99 | + | }; | |||
| 100 | + | ``` | |||
| 101 | + | ||||
| 102 | + | ### Bonnes pratiques | |||
| 103 | + | ||||
| 104 | + | | A eviter | Alternative | | |||
| 105 | + | | ----------------------------------------------------- | ------------------------------------------------------ | | |||
| 106 | + | | `setInterval` pour cleanup | Lazy cleanup à chaque requête | | |||
| 107 | + | | `fetch()` au chargement du module | `fetch()` dans les handlers | | |||
| 108 | + | | Création de clients API au niveau module | Création lazy ou dans les handlers | | |||
| 109 | + | | `process.exit()` | Retourner une Response avec status d'erreur | | |||
| 110 | + | | Bibliothèques avec worker threads (ex: `pino-pretty`) | Versions compatibles edge (ex: `pino` sans transports) | | |||
| 111 | + | ||||
| 112 | + | ### Variables d'environnement | |||
| 113 | + | ||||
| 114 | + | - Utilisez `$env/dynamic/private` (runtime) au lieu de `$env/static/private` (build-time) | |||
| 115 | + | - Les variables définies dans le dashboard Cloudflare ne sont disponibles qu'au runtime | |||
| 116 | + | ||||
| 117 | + | ### Références | |||
| 118 | + | ||||
| 119 | + | - [Cloudflare Workers Runtime APIs](https://developers.cloudflare.com/workers/runtime-apis/) | |||
| 120 | + | - [SvelteKit Cloudflare Adapter](https://svelte.dev/docs/kit/adapter-cloudflare) | |||
| 121 | + | ||||
| 79 | ## Documentation et Ressources | 122 | ## Documentation et Ressources | ||
| 80 | 123 | ||||
| 81 | Si vous n'avez jamais utilisé Svelte/Kit ou Convex, référez-vous aux documentations officielles : | 124 | Si vous n'avez jamais utilisé Svelte/Kit ou Convex, référez-vous aux documentations officielles : | ||
M src/lib/api/rate-limiter.ts +29 -15
| @@ -41,23 +41,34 @@ const RATE_LIMITS = { | |||
| 41 | 41 | // In-memory store for rate limiting | |
| 42 | 42 | const ipRequests = new Map<string, Array<{ timestamp: number }>>(); | |
| 43 | 43 | ||
| 44 | - | // Cleanup old entries every 5 minutes | |
| 45 | - | setInterval( | |
| 46 | - | () => { | |
| 47 | - | const now = Date.now(); | |
| 48 | - | for (const [ip, timestamps] of ipRequests.entries()) { | |
| 49 | - | // Remove entries older than the maximum duration we care about (5 minutes) | |
| 50 | - | const filtered = timestamps.filter((t) => now - t.timestamp < 5 * 60 * 1000); | |
| 51 | - | if (filtered.length === 0) { | |
| 52 | - | ipRequests.delete(ip); | |
| 53 | - | } else { | |
| 54 | - | ipRequests.set(ip, filtered); | |
| 55 | - | } | |
| 56 | - | } | |
| 57 | - | }, | |
| 58 | - | 5 * 60 * 1000 | |
| 44 | + | // Compute max duration across all rate limits for cleanup | |
| 45 | + | const MAX_RATE_LIMIT_DURATION = Math.max( | |
| 46 | + | RATE_LIMITS.auth.durationMs, | |
| 47 | + | RATE_LIMITS.public.durationMs, | |
| 48 | + | RATE_LIMITS.protected.durationMs, | |
| 49 | + | RATE_LIMITS.sse.authenticated.durationMs, | |
| 50 | + | RATE_LIMITS.sse.unauthenticated.durationMs | |
| 59 | 51 | ); | |
| 60 | 52 | ||
| 53 | + | // Lazy cleanup: remove stale entries on each check (Cloudflare Workers don't allow setInterval at global scope) | |
| 54 | + | let lastCleanup = 0; | |
| 55 | + | ||
| 56 | + | function cleanupStaleEntries() { | |
| 57 | + | const now = Date.now(); | |
| 58 | + | // Run cleanup at most once per max duration window | |
| 59 | + | if (now - lastCleanup < MAX_RATE_LIMIT_DURATION) return; | |
| 60 | + | lastCleanup = now; | |
| 61 | + | ||
| 62 | + | for (const [ip, timestamps] of ipRequests.entries()) { | |
| 63 | + | const filtered = timestamps.filter((t) => now - t.timestamp < MAX_RATE_LIMIT_DURATION); | |
| 64 | + | if (filtered.length === 0) { | |
| 65 | + | ipRequests.delete(ip); | |
| 66 | + | } else { | |
| 67 | + | ipRequests.set(ip, filtered); | |
| 68 | + | } | |
| 69 | + | } | |
| 70 | + | } | |
| 71 | + | ||
| 61 | 72 | function getEndpointType(pathname: string, isPublic: boolean): keyof typeof RATE_LIMITS { | |
| 62 | 73 | if (pathname.startsWith('/api/session/login') || pathname.startsWith('/api/register')) { | |
| 63 | 74 | return 'auth'; | |
| @@ -88,6 +99,9 @@ function isRateLimited( | |||
| 88 | 99 | endpointType: keyof typeof RATE_LIMITS, | |
| 89 | 100 | isAuthenticated: boolean = false | |
| 90 | 101 | ): { limited: boolean; retryAfter?: number } { | |
| 102 | + | // Lazy cleanup on each check (replaces setInterval for Cloudflare compatibility) | |
| 103 | + | cleanupStaleEntries(); | |
| 104 | + | ||
| 91 | 105 | // Skip rate limiting completely in development for localhost | |
| 92 | 106 | if (isDev && (ip === '127.0.0.1' || ip === '::1' || ip === 'localhost')) { | |
| 93 | 107 | return { limited: false }; | |
| @@ -41,23 +41,34 @@ const RATE_LIMITS = { | |||||
| 41 | // In-memory store for rate limiting | 41 | // In-memory store for rate limiting | ||
| 42 | const ipRequests = new Map<string, Array<{ timestamp: number }>>(); | 42 | const ipRequests = new Map<string, Array<{ timestamp: number }>>(); | ||
| 43 | 43 | ||||
| 44 | - | // Cleanup old entries every 5 minutes | 44 | + | // Compute max duration across all rate limits for cleanup |
| 45 | - | setInterval( | 45 | + | const MAX_RATE_LIMIT_DURATION = Math.max( |
| 46 | - | () => { | 46 | + | RATE_LIMITS.auth.durationMs, |
| 47 | - | const now = Date.now(); | 47 | + | RATE_LIMITS.public.durationMs, |
| 48 | - | for (const [ip, timestamps] of ipRequests.entries()) { | 48 | + | RATE_LIMITS.protected.durationMs, |
| 49 | - | // Remove entries older than the maximum duration we care about (5 minutes) | 49 | + | RATE_LIMITS.sse.authenticated.durationMs, |
| 50 | - | const filtered = timestamps.filter((t) => now - t.timestamp < 5 * 60 * 1000); | 50 | + | RATE_LIMITS.sse.unauthenticated.durationMs |
| 51 | - | if (filtered.length === 0) { | |||
| 52 | - | ipRequests.delete(ip); | |||
| 53 | - | } else { | |||
| 54 | - | ipRequests.set(ip, filtered); | |||
| 55 | - | } | |||
| 56 | - | } | |||
| 57 | - | }, | |||
| 58 | - | 5 * 60 * 1000 | |||
| 59 | ); | 51 | ); | ||
| 60 | 52 | ||||
| 53 | + | // Lazy cleanup: remove stale entries on each check (Cloudflare Workers don't allow setInterval at global scope) | |||
| 54 | + | let lastCleanup = 0; | |||
| 55 | + | ||||
| 56 | + | function cleanupStaleEntries() { | |||
| 57 | + | const now = Date.now(); | |||
| 58 | + | // Run cleanup at most once per max duration window | |||
| 59 | + | if (now - lastCleanup < MAX_RATE_LIMIT_DURATION) return; | |||
| 60 | + | lastCleanup = now; | |||
| 61 | + | ||||
| 62 | + | for (const [ip, timestamps] of ipRequests.entries()) { | |||
| 63 | + | const filtered = timestamps.filter((t) => now - t.timestamp < MAX_RATE_LIMIT_DURATION); | |||
| 64 | + | if (filtered.length === 0) { | |||
| 65 | + | ipRequests.delete(ip); | |||
| 66 | + | } else { | |||
| 67 | + | ipRequests.set(ip, filtered); | |||
| 68 | + | } | |||
| 69 | + | } | |||
| 70 | + | } | |||
| 71 | + | ||||
| 61 | function getEndpointType(pathname: string, isPublic: boolean): keyof typeof RATE_LIMITS { | 72 | function getEndpointType(pathname: string, isPublic: boolean): keyof typeof RATE_LIMITS { | ||
| 62 | if (pathname.startsWith('/api/session/login') || pathname.startsWith('/api/register')) { | 73 | if (pathname.startsWith('/api/session/login') || pathname.startsWith('/api/register')) { | ||
| 63 | return 'auth'; | 74 | return 'auth'; | ||
| @@ -88,6 +99,9 @@ function isRateLimited( | |||||
| 88 | endpointType: keyof typeof RATE_LIMITS, | 99 | endpointType: keyof typeof RATE_LIMITS, | ||
| 89 | isAuthenticated: boolean = false | 100 | isAuthenticated: boolean = false | ||
| 90 | ): { limited: boolean; retryAfter?: number } { | 101 | ): { limited: boolean; retryAfter?: number } { | ||
| 102 | + | // Lazy cleanup on each check (replaces setInterval for Cloudflare compatibility) | |||
| 103 | + | cleanupStaleEntries(); | |||
| 104 | + | ||||
| 91 | // Skip rate limiting completely in development for localhost | 105 | // Skip rate limiting completely in development for localhost | ||
| 92 | if (isDev && (ip === '127.0.0.1' || ip === '::1' || ip === 'localhost')) { | 106 | if (isDev && (ip === '127.0.0.1' || ip === '::1' || ip === 'localhost')) { | ||
| 93 | return { limited: false }; | 107 | return { limited: false }; | ||
M src/routes/api/session/login/+server.ts +16 -12
| @@ -14,25 +14,29 @@ const log = createLogger('login-server'); | |||
| 14 | 14 | // In-memory map to track failed login attempts per IP | |
| 15 | 15 | const loginAttempts = new Map<string, { count: number; lastAttempt: number }>(); | |
| 16 | 16 | const MAX_ATTEMPTS = 3; | |
| 17 | + | const ONE_HOUR = 60 * 60 * 1000; | |
| 17 | 18 | const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); | |
| 18 | 19 | ||
| 19 | - | // Cleanup old entries every hour | |
| 20 | - | setInterval( | |
| 21 | - | () => { | |
| 22 | - | const now = Date.now(); | |
| 23 | - | const ONE_HOUR = 60 * 60 * 1000; | |
| 24 | - | for (const [ip, data] of loginAttempts.entries()) { | |
| 25 | - | if (now - data.lastAttempt > ONE_HOUR) { | |
| 26 | - | loginAttempts.delete(ip); | |
| 27 | - | } | |
| 20 | + | // Lazy cleanup: Cloudflare Workers don't allow setInterval at global scope | |
| 21 | + | let lastCleanup = 0; | |
| 22 | + | function cleanupOldAttempts() { | |
| 23 | + | const now = Date.now(); | |
| 24 | + | if (now - lastCleanup < ONE_HOUR) return; | |
| 25 | + | lastCleanup = now; | |
| 26 | + | ||
| 27 | + | for (const [ip, data] of loginAttempts.entries()) { | |
| 28 | + | if (now - data.lastAttempt > ONE_HOUR) { | |
| 29 | + | loginAttempts.delete(ip); | |
| 28 | 30 | } | |
| 29 | - | }, | |
| 30 | - | 60 * 60 * 1000 | |
| 31 | - | ); | |
| 31 | + | } | |
| 32 | + | } | |
| 32 | 33 | ||
| 33 | 34 | export const POST: RequestHandler = async ({ request, cookies }) => { | |
| 34 | 35 | log.debug('New login attempt received'); | |
| 35 | 36 | ||
| 37 | + | // Lazy cleanup on each request (replaces setInterval for Cloudflare compatibility) | |
| 38 | + | cleanupOldAttempts(); | |
| 39 | + | ||
| 36 | 40 | if (request.method !== 'POST') { | |
| 37 | 41 | log.warn('Invalid method used', { method: request.method }); | |
| 38 | 42 | return new Response(JSON.stringify({ error: 'Method Not Allowed' } as LoginResponseError), { | |
| @@ -14,25 +14,29 @@ const log = createLogger('login-server'); | |||||
| 14 | // In-memory map to track failed login attempts per IP | 14 | // In-memory map to track failed login attempts per IP | ||
| 15 | const loginAttempts = new Map<string, { count: number; lastAttempt: number }>(); | 15 | const loginAttempts = new Map<string, { count: number; lastAttempt: number }>(); | ||
| 16 | const MAX_ATTEMPTS = 3; | 16 | const MAX_ATTEMPTS = 3; | ||
| 17 | + | const ONE_HOUR = 60 * 60 * 1000; | |||
| 17 | const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); | 18 | const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); | ||
| 18 | 19 | ||||
| 19 | - | // Cleanup old entries every hour | 20 | + | // Lazy cleanup: Cloudflare Workers don't allow setInterval at global scope |
| 20 | - | setInterval( | 21 | + | let lastCleanup = 0; |
| 21 | - | () => { | 22 | + | function cleanupOldAttempts() { |
| 22 | - | const now = Date.now(); | 23 | + | const now = Date.now(); |
| 23 | - | const ONE_HOUR = 60 * 60 * 1000; | 24 | + | if (now - lastCleanup < ONE_HOUR) return; |
| 24 | - | for (const [ip, data] of loginAttempts.entries()) { | 25 | + | lastCleanup = now; |
| 25 | - | if (now - data.lastAttempt > ONE_HOUR) { | 26 | + | |
| 26 | - | loginAttempts.delete(ip); | 27 | + | for (const [ip, data] of loginAttempts.entries()) { |
| 27 | - | } | 28 | + | if (now - data.lastAttempt > ONE_HOUR) { |
| 29 | + | loginAttempts.delete(ip); | |||
| 28 | } | 30 | } | ||
| 29 | - | }, | 31 | + | } |
| 30 | - | 60 * 60 * 1000 | 32 | + | } |
| 31 | - | ); | |||
| 32 | 33 | ||||
| 33 | export const POST: RequestHandler = async ({ request, cookies }) => { | 34 | export const POST: RequestHandler = async ({ request, cookies }) => { | ||
| 34 | log.debug('New login attempt received'); | 35 | log.debug('New login attempt received'); | ||
| 35 | 36 | ||||
| 37 | + | // Lazy cleanup on each request (replaces setInterval for Cloudflare compatibility) | |||
| 38 | + | cleanupOldAttempts(); | |||
| 39 | + | ||||
| 36 | if (request.method !== 'POST') { | 40 | if (request.method !== 'POST') { | ||
| 37 | log.warn('Invalid method used', { method: request.method }); | 41 | log.warn('Invalid method used', { method: request.method }); | ||
| 38 | return new Response(JSON.stringify({ error: 'Method Not Allowed' } as LoginResponseError), { | 42 | return new Response(JSON.stringify({ error: 'Method Not Allowed' } as LoginResponseError), { | ||