馃 distributed transcription service thistle.dunkirk.sh
1import db from "../db/schema"; 2 3const SESSION_DURATION = 7 * 24 * 60 * 60; // 7 days in seconds 4 5export type UserRole = "user" | "admin"; 6 7export interface User { 8 id: number; 9 email: string; 10 name: string | null; 11 avatar: string; 12 created_at: number; 13 role: UserRole; 14 last_login: number | null; 15} 16 17export interface Session { 18 id: string; 19 user_id: number; 20 ip_address: string | null; 21 user_agent: string | null; 22 created_at: number; 23 expires_at: number; 24} 25 26export function createSession( 27 userId: number, 28 ipAddress?: string, 29 userAgent?: string, 30): string { 31 const sessionId = crypto.randomUUID(); 32 const expiresAt = Math.floor(Date.now() / 1000) + SESSION_DURATION; 33 34 db.run( 35 "INSERT INTO sessions (id, user_id, ip_address, user_agent, expires_at) VALUES (?, ?, ?, ?, ?)", 36 [sessionId, userId, ipAddress ?? null, userAgent ?? null, expiresAt], 37 ); 38 39 return sessionId; 40} 41 42export function getSession(sessionId: string): Session | null { 43 const now = Math.floor(Date.now() / 1000); 44 45 const session = db 46 .query<Session, [string, number]>( 47 "SELECT id, user_id, ip_address, user_agent, created_at, expires_at FROM sessions WHERE id = ? AND expires_at > ?", 48 ) 49 .get(sessionId, now); 50 51 return session ?? null; 52} 53 54export function getUserBySession(sessionId: string): User | null { 55 const session = getSession(sessionId); 56 if (!session) return null; 57 58 const user = db 59 .query<User, [number]>( 60 "SELECT id, email, name, avatar, created_at, role, last_login FROM users WHERE id = ?", 61 ) 62 .get(session.user_id); 63 64 return user ?? null; 65} 66 67export function getUserByEmail(email: string): User | null { 68 const user = db 69 .query<User, [string]>( 70 "SELECT id, email, name, avatar, created_at, role, last_login FROM users WHERE email = ?", 71 ) 72 .get(email); 73 74 return user ?? null; 75} 76 77export function deleteSession(sessionId: string): void { 78 db.run("DELETE FROM sessions WHERE id = ?", [sessionId]); 79} 80 81export function cleanupExpiredSessions(): void { 82 const now = Math.floor(Date.now() / 1000); 83 db.run("DELETE FROM sessions WHERE expires_at <= ?", [now]); 84} 85 86export async function createUser( 87 email: string, 88 password: string, 89 name?: string, 90): Promise<User> { 91 // Generate deterministic avatar from email 92 const encoder = new TextEncoder(); 93 const data = encoder.encode(email.toLowerCase()); 94 const hashBuffer = await crypto.subtle.digest("SHA-256", data); 95 const hashArray = Array.from(new Uint8Array(hashBuffer)); 96 const avatar = hashArray 97 .map((b) => b.toString(16).padStart(2, "0")) 98 .join("") 99 .substring(0, 16); 100 101 const result = db.run( 102 "INSERT INTO users (email, password_hash, name, avatar) VALUES (?, ?, ?, ?)", 103 [email, password, name ?? null, avatar], 104 ); 105 106 const user = db 107 .query<User, [number]>( 108 "SELECT id, email, name, avatar, created_at, role, last_login FROM users WHERE id = ?", 109 ) 110 .get(Number(result.lastInsertRowid)); 111 112 if (!user) { 113 throw new Error("Failed to create user"); 114 } 115 116 return user; 117} 118 119export async function authenticateUser( 120 email: string, 121 password: string, 122): Promise<User | null> { 123 const result = db 124 .query< 125 { 126 id: number; 127 email: string; 128 name: string | null; 129 avatar: string; 130 password_hash: string; 131 created_at: number; 132 role: UserRole; 133 last_login: number | null; 134 }, 135 [string] 136 >( 137 "SELECT id, email, name, avatar, password_hash, created_at, role, last_login FROM users WHERE email = ?", 138 ) 139 .get(email); 140 141 if (!result) { 142 // Dummy comparison to prevent timing-based account enumeration 143 const dummyHash = "0".repeat(64); 144 password === dummyHash; 145 return null; 146 } 147 148 if (password !== result.password_hash) return null; 149 150 // Update last_login 151 const now = Math.floor(Date.now() / 1000); 152 db.run("UPDATE users SET last_login = ? WHERE id = ?", [now, result.id]); 153 154 return { 155 id: result.id, 156 email: result.email, 157 name: result.name, 158 avatar: result.avatar, 159 created_at: result.created_at, 160 role: result.role, 161 last_login: now, 162 }; 163} 164 165export function getUserSessionsForUser(userId: number): Session[] { 166 const now = Math.floor(Date.now() / 1000); 167 168 const sessions = db 169 .query<Session, [number, number]>( 170 "SELECT id, user_id, ip_address, user_agent, created_at, expires_at FROM sessions WHERE user_id = ? AND expires_at > ? ORDER BY created_at DESC", 171 ) 172 .all(userId, now); 173 174 return sessions; 175} 176 177export function getSessionFromRequest(req: Request): string | null { 178 const cookie = req.headers.get("cookie"); 179 if (!cookie) return null; 180 181 const match = cookie.match(/session=([^;]+)/); 182 return match?.[1] ?? null; 183} 184 185export async function deleteUser(userId: number): Promise<void> { 186 // Get user's subscription if they have one 187 const subscription = db 188 .query<{ id: string }, [number]>( 189 "SELECT id FROM subscriptions WHERE user_id = ? ORDER BY created_at DESC LIMIT 1", 190 ) 191 .get(userId); 192 193 // Revoke subscription if it exists 194 if (subscription) { 195 try { 196 const { polar } = await import("./polar"); 197 await polar.subscriptions.revoke({ id: subscription.id }); 198 console.log( 199 `[User Delete] Revoked subscription ${subscription.id} for user ${userId}`, 200 ); 201 } catch (error) { 202 console.error( 203 `[User Delete] Failed to revoke subscription ${subscription.id}:`, 204 error, 205 ); 206 // Continue with user deletion even if subscription revocation fails 207 } 208 } 209 210 db.run("DELETE FROM users WHERE id = ?", [userId]); 211} 212 213export function updateUserEmail(userId: number, newEmail: string): void { 214 db.run("UPDATE users SET email = ? WHERE id = ?", [newEmail, userId]); 215} 216 217export function updateUserName(userId: number, newName: string): void { 218 db.run("UPDATE users SET name = ? WHERE id = ?", [newName, userId]); 219} 220 221export function updateUserAvatar(userId: number, avatar: string): void { 222 db.run("UPDATE users SET avatar = ? WHERE id = ?", [avatar, userId]); 223} 224 225export async function updateUserPassword( 226 userId: number, 227 newPassword: string, 228): Promise<void> { 229 db.run("UPDATE users SET password_hash = ? WHERE id = ?", [ 230 newPassword, 231 userId, 232 ]); 233 db.run("DELETE FROM sessions WHERE user_id = ?", [userId]); 234} 235 236export function isUserAdmin(userId: number): boolean { 237 const result = db 238 .query<{ role: UserRole }, [number]>("SELECT role FROM users WHERE id = ?") 239 .get(userId); 240 241 return result?.role === "admin"; 242} 243 244export function updateUserRole(userId: number, role: UserRole): void { 245 db.run("UPDATE users SET role = ? WHERE id = ?", [role, userId]); 246} 247 248export function getAllUsers(): Array<{ 249 id: number; 250 email: string; 251 name: string | null; 252 avatar: string; 253 created_at: number; 254 role: UserRole; 255}> { 256 return db 257 .query< 258 { 259 id: number; 260 email: string; 261 name: string | null; 262 avatar: string; 263 created_at: number; 264 role: UserRole; 265 last_login: number | null; 266 }, 267 [] 268 >( 269 "SELECT id, email, name, avatar, created_at, role, last_login FROM users ORDER BY created_at DESC", 270 ) 271 .all(); 272} 273 274export function getAllTranscriptions(): Array<{ 275 id: string; 276 user_id: number; 277 user_email: string; 278 user_name: string | null; 279 original_filename: string; 280 status: string; 281 created_at: number; 282 error_message: string | null; 283}> { 284 return db 285 .query< 286 { 287 id: string; 288 user_id: number; 289 user_email: string; 290 user_name: string | null; 291 original_filename: string; 292 status: string; 293 created_at: number; 294 error_message: string | null; 295 }, 296 [] 297 >( 298 `SELECT 299 t.id, 300 t.user_id, 301 u.email as user_email, 302 u.name as user_name, 303 t.original_filename, 304 t.status, 305 t.created_at, 306 t.error_message 307 FROM transcriptions t 308 LEFT JOIN users u ON t.user_id = u.id 309 ORDER BY t.created_at DESC`, 310 ) 311 .all(); 312} 313 314export function deleteTranscription(transcriptionId: string): void { 315 const transcription = db 316 .query<{ id: string; filename: string }, [string]>( 317 "SELECT id, filename FROM transcriptions WHERE id = ?", 318 ) 319 .get(transcriptionId); 320 321 if (!transcription) { 322 throw new Error("Transcription not found"); 323 } 324 325 // Delete database record 326 db.run("DELETE FROM transcriptions WHERE id = ?", [transcriptionId]); 327 328 // Delete files (audio file and transcript files) 329 try { 330 const audioPath = `./uploads/${transcription.filename}`; 331 const transcriptPath = `./transcripts/${transcriptionId}.txt`; 332 const vttPath = `./transcripts/${transcriptionId}.vtt`; 333 334 if (Bun.file(audioPath).size) { 335 Bun.write(audioPath, "").then(() => { 336 // File deleted by overwriting with empty content, then unlink 337 import("node:fs").then((fs) => { 338 fs.unlinkSync(audioPath); 339 }); 340 }); 341 } 342 343 if (Bun.file(transcriptPath).size) { 344 import("node:fs").then((fs) => { 345 fs.unlinkSync(transcriptPath); 346 }); 347 } 348 349 if (Bun.file(vttPath).size) { 350 import("node:fs").then((fs) => { 351 fs.unlinkSync(vttPath); 352 }); 353 } 354 } catch { 355 // Files might not exist, ignore errors 356 } 357} 358 359export function getSessionsForUser(userId: number): Session[] { 360 const now = Math.floor(Date.now() / 1000); 361 return db 362 .query<Session, [number, number]>( 363 "SELECT id, user_id, ip_address, user_agent, created_at, expires_at FROM sessions WHERE user_id = ? AND expires_at > ? ORDER BY created_at DESC", 364 ) 365 .all(userId, now); 366} 367 368export function deleteSessionById(sessionId: string, userId: number): boolean { 369 const result = db.run("DELETE FROM sessions WHERE id = ? AND user_id = ?", [ 370 sessionId, 371 userId, 372 ]); 373 return result.changes > 0; 374} 375 376export function deleteAllUserSessions(userId: number): void { 377 db.run("DELETE FROM sessions WHERE user_id = ?", [userId]); 378} 379 380export function updateUserEmailAddress(userId: number, newEmail: string): void { 381 db.run("UPDATE users SET email = ? WHERE id = ?", [newEmail, userId]); 382} 383 384export interface UserWithStats { 385 id: number; 386 email: string; 387 name: string | null; 388 avatar: string; 389 created_at: number; 390 role: UserRole; 391 last_login: number | null; 392 transcription_count: number; 393 subscription_status: string | null; 394 subscription_id: string | null; 395} 396 397export function getAllUsersWithStats(): UserWithStats[] { 398 return db 399 .query<UserWithStats, []>( 400 `SELECT 401 u.id, 402 u.email, 403 u.name, 404 u.avatar, 405 u.created_at, 406 u.role, 407 u.last_login, 408 COUNT(DISTINCT t.id) as transcription_count, 409 s.status as subscription_status, 410 s.id as subscription_id 411 FROM users u 412 LEFT JOIN transcriptions t ON u.id = t.user_id 413 LEFT JOIN subscriptions s ON u.id = s.user_id AND s.status IN ('active', 'trialing', 'past_due') 414 GROUP BY u.id 415 ORDER BY u.created_at DESC`, 416 ) 417 .all(); 418}