detached 13a549c

Merge pull request #74 from kitpdr/fix/cloudflare-global-scope

fix(cloudflare): remove setInterval from global scope
commit
13a549c37424552958ef0ee20f71b4e7d341913f
author
KiT · · 2026-01-18 21:49 UTC
committer
GitHub · · 2026-01-18 21:49 UTC
merge of
6968ec0 + fe68614 · diff against the first parent
signature
GPG UnverifiedB5690EEEBB952194 The key is unknown
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 :
7676 npx convex dashboard
7777 ```
7878
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+
79122 ## Documentation et Ressources
80123
81124 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 dashboard76 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 Ressources122 ## 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 = {
4141 // In-memory store for rate limiting
4242 const ipRequests = new Map<string, Array<{ timestamp: number }>>();
4343
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
5951 );
6052
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+
6172 function getEndpointType(pathname: string, isPublic: boolean): keyof typeof RATE_LIMITS {
6273 if (pathname.startsWith('/api/session/login') || pathname.startsWith('/api/register')) {
6374 return 'auth';
@@ -88,6 +99,9 @@ function isRateLimited(
8899 endpointType: keyof typeof RATE_LIMITS,
89100 isAuthenticated: boolean = false
90101 ): { limited: boolean; retryAfter?: number } {
102+ // Lazy cleanup on each check (replaces setInterval for Cloudflare compatibility)
103+ cleanupStaleEntries();
104+
91105 // Skip rate limiting completely in development for localhost
92106 if (isDev && (ip === '127.0.0.1' || ip === '::1' || ip === 'localhost')) {
93107 return { limited: false };
@@ -41,23 +41,34 @@ const RATE_LIMITS = {
41 // In-memory store for rate limiting41 // 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 minutes44+// 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 = false100 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 localhost105 // 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');
1414 // In-memory map to track failed login attempts per IP
1515 const loginAttempts = new Map<string, { count: number; lastAttempt: number }>();
1616 const MAX_ATTEMPTS = 3;
17+const ONE_HOUR = 60 * 60 * 1000;
1718 const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
1819
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);
2830 }
29- },
30- 60 * 60 * 1000
31-);
31+ }
32+}
3233
3334 export const POST: RequestHandler = async ({ request, cookies }) => {
3435 log.debug('New login attempt received');
3536
37+ // Lazy cleanup on each request (replaces setInterval for Cloudflare compatibility)
38+ cleanupOldAttempts();
39+
3640 if (request.method !== 'POST') {
3741 log.warn('Invalid method used', { method: request.method });
3842 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 IP14 // 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 hour20+// 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 * 100032+}
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), {

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 3

Tags 8

↑↓ moveenter openesc close