🪻 distributed transcription service thistle.dunkirk.sh
1
fork

Configure Feed

Select the types of activity you want to include in your feed.

chore: limit user sessions to 10

+56
+34
src/lib/auth.test.ts
··· 130 130 }; 131 131 expect(typeof result.count).toBe("number"); 132 132 }); 133 + 134 + test("enforces maximum session limit per user", () => { 135 + const userId = 999; 136 + 137 + // Clean up any existing sessions for this user 138 + db.run("DELETE FROM sessions WHERE user_id = ?", [userId]); 139 + 140 + // Create 11 sessions (limit is 10) 141 + const sessionIds: string[] = []; 142 + for (let i = 0; i < 11; i++) { 143 + const sessionId = createSession(userId, `192.168.1.${i}`, `Agent ${i}`); 144 + sessionIds.push(sessionId); 145 + } 146 + 147 + // Count total sessions for user 148 + const sessionCount = db 149 + .query<{ count: number }, [number]>( 150 + "SELECT COUNT(*) as count FROM sessions WHERE user_id = ?", 151 + ) 152 + .get(userId); 153 + 154 + expect(sessionCount?.count).toBe(10); 155 + 156 + // First session should be deleted (oldest) 157 + const firstSession = getSession(sessionIds[0]); 158 + expect(firstSession).toBeNull(); 159 + 160 + // Last session should exist (newest) 161 + const lastSession = getSession(sessionIds[10]); 162 + expect(lastSession).not.toBeNull(); 163 + 164 + // Cleanup 165 + db.run("DELETE FROM sessions WHERE user_id = ?", [userId]); 166 + });
+22
src/lib/auth.ts
··· 1 1 import db from "../db/schema"; 2 2 3 3 const SESSION_DURATION = 7 * 24 * 60 * 60; // 7 days in seconds 4 + const MAX_SESSIONS_PER_USER = 10; // Maximum number of sessions per user 4 5 5 6 export type UserRole = "user" | "admin"; 6 7 ··· 30 31 ): string { 31 32 const sessionId = crypto.randomUUID(); 32 33 const expiresAt = Math.floor(Date.now() / 1000) + SESSION_DURATION; 34 + 35 + // Check current session count for user 36 + const sessionCount = db 37 + .query<{ count: number }, [number]>( 38 + "SELECT COUNT(*) as count FROM sessions WHERE user_id = ?", 39 + ) 40 + .get(userId); 41 + 42 + // If at or over limit, delete oldest session(s) 43 + if (sessionCount && sessionCount.count >= MAX_SESSIONS_PER_USER) { 44 + const sessionsToDelete = sessionCount.count - MAX_SESSIONS_PER_USER + 1; 45 + db.run( 46 + `DELETE FROM sessions WHERE id IN ( 47 + SELECT id FROM sessions 48 + WHERE user_id = ? 49 + ORDER BY created_at ASC 50 + LIMIT ? 51 + )`, 52 + [userId, sessionsToDelete], 53 + ); 54 + } 33 55 34 56 db.run( 35 57 "INSERT INTO sessions (id, user_id, ip_address, user_agent, expires_at) VALUES (?, ?, ?, ?, ?)",