馃 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 // Prevent deleting the ghost user
187 if (userId === 0) {
188 throw new Error("Cannot delete ghost user account");
189 }
190
191 // Get user's subscription if they have one
192 const subscription = db
193 .query<{ id: string }, [number]>(
194 "SELECT id FROM subscriptions WHERE user_id = ? ORDER BY created_at DESC LIMIT 1",
195 )
196 .get(userId);
197
198 // Cancel subscription if it exists (soft cancel - keeps access until period end)
199 if (subscription) {
200 try {
201 const { polar } = await import("./polar");
202 await polar.subscriptions.update({
203 id: subscription.id,
204 subscriptionUpdate: { cancelAtPeriodEnd: true },
205 });
206 console.log(
207 `[User Delete] Canceled subscription ${subscription.id} for user ${userId}`,
208 );
209 } catch (error) {
210 console.error(
211 `[User Delete] Failed to cancel subscription ${subscription.id}:`,
212 error,
213 );
214 // Continue with user deletion even if subscription cancellation fails
215 }
216 }
217
218 // Reassign class transcriptions to ghost user (id=0)
219 // Delete personal transcriptions (no class_id)
220 db.run(
221 "UPDATE transcriptions SET user_id = 0 WHERE user_id = ? AND class_id IS NOT NULL",
222 [userId],
223 );
224 db.run(
225 "DELETE FROM transcriptions WHERE user_id = ? AND class_id IS NULL",
226 [userId],
227 );
228
229 // Delete user (CASCADE will handle sessions, passkeys, subscriptions, class_members)
230 db.run("DELETE FROM users WHERE id = ?", [userId]);
231}
232
233export function updateUserEmail(userId: number, newEmail: string): void {
234 db.run("UPDATE users SET email = ? WHERE id = ?", [newEmail, userId]);
235}
236
237export function updateUserName(userId: number, newName: string): void {
238 db.run("UPDATE users SET name = ? WHERE id = ?", [newName, userId]);
239}
240
241export function updateUserAvatar(userId: number, avatar: string): void {
242 db.run("UPDATE users SET avatar = ? WHERE id = ?", [avatar, userId]);
243}
244
245export async function updateUserPassword(
246 userId: number,
247 newPassword: string,
248): Promise<void> {
249 db.run("UPDATE users SET password_hash = ? WHERE id = ?", [
250 newPassword,
251 userId,
252 ]);
253 db.run("DELETE FROM sessions WHERE user_id = ?", [userId]);
254}
255
256/**
257 * Email verification functions
258 */
259
260export function createEmailVerificationToken(userId: number): { code: string; token: string; sentAt: number } {
261 // Generate a 6-digit code for user to enter
262 const code = Math.floor(100000 + Math.random() * 900000).toString();
263 const id = crypto.randomUUID();
264 const token = crypto.randomUUID(); // Separate token for URL
265 const expiresAt = Math.floor(Date.now() / 1000) + 24 * 60 * 60; // 24 hours
266 const sentAt = Math.floor(Date.now() / 1000); // Timestamp when code is created
267
268 // Delete any existing tokens for this user
269 db.run("DELETE FROM email_verification_tokens WHERE user_id = ?", [userId]);
270
271 // Store the code as the token field (for manual entry)
272 db.run(
273 "INSERT INTO email_verification_tokens (id, user_id, token, expires_at) VALUES (?, ?, ?, ?)",
274 [id, userId, code, expiresAt],
275 );
276
277 // Store the URL token as a separate entry
278 db.run(
279 "INSERT INTO email_verification_tokens (id, user_id, token, expires_at) VALUES (?, ?, ?, ?)",
280 [crypto.randomUUID(), userId, token, expiresAt],
281 );
282
283 return { code, token, sentAt };
284}
285
286export function verifyEmailToken(
287 token: string,
288): { userId: number; email: string } | null {
289 const now = Math.floor(Date.now() / 1000);
290
291 const result = db
292 .query<
293 { user_id: number; email: string },
294 [string, number]
295 >(
296 `SELECT evt.user_id, u.email
297 FROM email_verification_tokens evt
298 JOIN users u ON evt.user_id = u.id
299 WHERE evt.token = ? AND evt.expires_at > ?`,
300 )
301 .get(token, now);
302
303 if (!result) return null;
304
305 // Mark email as verified
306 db.run("UPDATE users SET email_verified = 1 WHERE id = ?", [result.user_id]);
307
308 // Delete the token (one-time use)
309 db.run("DELETE FROM email_verification_tokens WHERE token = ?", [token]);
310
311 return { userId: result.user_id, email: result.email };
312}
313
314export function verifyEmailCode(
315 userId: number,
316 code: string,
317): boolean {
318 const now = Math.floor(Date.now() / 1000);
319
320 const result = db
321 .query<
322 { user_id: number },
323 [number, string, number]
324 >(
325 `SELECT user_id
326 FROM email_verification_tokens
327 WHERE user_id = ? AND token = ? AND expires_at > ?`,
328 )
329 .get(userId, code, now);
330
331 if (!result) return false;
332
333 // Mark email as verified
334 db.run("UPDATE users SET email_verified = 1 WHERE id = ?", [userId]);
335
336 // Delete the token (one-time use)
337 db.run("DELETE FROM email_verification_tokens WHERE user_id = ?", [userId]);
338
339 return true;
340}
341
342export function isEmailVerified(userId: number): boolean {
343 const result = db
344 .query<{ email_verified: number }, [number]>(
345 "SELECT email_verified FROM users WHERE id = ?",
346 )
347 .get(userId);
348
349 return result?.email_verified === 1;
350}
351
352export function getVerificationCodeSentAt(userId: number): number | null {
353 const result = db
354 .query<{ created_at: number }, [number]>(
355 "SELECT MAX(created_at) as created_at FROM email_verification_tokens WHERE user_id = ?",
356 )
357 .get(userId);
358
359 return result?.created_at ?? null;
360}
361
362/**
363 * Password reset functions
364 */
365
366export function createPasswordResetToken(userId: number): string {
367 const token = crypto.randomUUID();
368 const id = crypto.randomUUID();
369 const expiresAt = Math.floor(Date.now() / 1000) + 60 * 60; // 1 hour
370
371 // Delete any existing tokens for this user
372 db.run("DELETE FROM password_reset_tokens WHERE user_id = ?", [userId]);
373
374 db.run(
375 "INSERT INTO password_reset_tokens (id, user_id, token, expires_at) VALUES (?, ?, ?, ?)",
376 [id, userId, token, expiresAt],
377 );
378
379 return token;
380}
381
382export function verifyPasswordResetToken(token: string): number | null {
383 const now = Math.floor(Date.now() / 1000);
384
385 const result = db
386 .query<{ user_id: number }, [string, number]>(
387 "SELECT user_id FROM password_reset_tokens WHERE token = ? AND expires_at > ?",
388 )
389 .get(token, now);
390
391 return result?.user_id ?? null;
392}
393
394export function consumePasswordResetToken(token: string): void {
395 db.run("DELETE FROM password_reset_tokens WHERE token = ?", [token]);
396}
397
398export function isUserAdmin(userId: number): boolean {
399 const result = db
400 .query<{ role: UserRole }, [number]>("SELECT role FROM users WHERE id = ?")
401 .get(userId);
402
403 return result?.role === "admin";
404}
405
406export function updateUserRole(userId: number, role: UserRole): void {
407 db.run("UPDATE users SET role = ? WHERE id = ?", [role, userId]);
408}
409
410export function getAllUsers(): Array<{
411 id: number;
412 email: string;
413 name: string | null;
414 avatar: string;
415 created_at: number;
416 role: UserRole;
417}> {
418 return db
419 .query<
420 {
421 id: number;
422 email: string;
423 name: string | null;
424 avatar: string;
425 created_at: number;
426 role: UserRole;
427 last_login: number | null;
428 },
429 []
430 >(
431 "SELECT id, email, name, avatar, created_at, role, last_login FROM users ORDER BY created_at DESC",
432 )
433 .all();
434}
435
436export function getAllTranscriptions(): Array<{
437 id: string;
438 user_id: number;
439 user_email: string;
440 user_name: string | null;
441 original_filename: string;
442 status: string;
443 created_at: number;
444 error_message: string | null;
445}> {
446 return db
447 .query<
448 {
449 id: string;
450 user_id: number;
451 user_email: string;
452 user_name: string | null;
453 original_filename: string;
454 status: string;
455 created_at: number;
456 error_message: string | null;
457 },
458 []
459 >(
460 `SELECT
461 t.id,
462 t.user_id,
463 u.email as user_email,
464 u.name as user_name,
465 t.original_filename,
466 t.status,
467 t.created_at,
468 t.error_message
469 FROM transcriptions t
470 LEFT JOIN users u ON t.user_id = u.id
471 ORDER BY t.created_at DESC`,
472 )
473 .all();
474}
475
476export function deleteTranscription(transcriptionId: string): void {
477 const transcription = db
478 .query<{ id: string; filename: string }, [string]>(
479 "SELECT id, filename FROM transcriptions WHERE id = ?",
480 )
481 .get(transcriptionId);
482
483 if (!transcription) {
484 throw new Error("Transcription not found");
485 }
486
487 // Delete database record
488 db.run("DELETE FROM transcriptions WHERE id = ?", [transcriptionId]);
489
490 // Delete files (audio file and transcript files)
491 try {
492 const audioPath = `./uploads/${transcription.filename}`;
493 const transcriptPath = `./transcripts/${transcriptionId}.txt`;
494 const vttPath = `./transcripts/${transcriptionId}.vtt`;
495
496 if (Bun.file(audioPath).size) {
497 Bun.write(audioPath, "").then(() => {
498 // File deleted by overwriting with empty content, then unlink
499 import("node:fs").then((fs) => {
500 fs.unlinkSync(audioPath);
501 });
502 });
503 }
504
505 if (Bun.file(transcriptPath).size) {
506 import("node:fs").then((fs) => {
507 fs.unlinkSync(transcriptPath);
508 });
509 }
510
511 if (Bun.file(vttPath).size) {
512 import("node:fs").then((fs) => {
513 fs.unlinkSync(vttPath);
514 });
515 }
516 } catch {
517 // Files might not exist, ignore errors
518 }
519}
520
521export function getSessionsForUser(userId: number): Session[] {
522 const now = Math.floor(Date.now() / 1000);
523 return db
524 .query<Session, [number, number]>(
525 "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",
526 )
527 .all(userId, now);
528}
529
530export function deleteSessionById(sessionId: string, userId: number): boolean {
531 const result = db.run("DELETE FROM sessions WHERE id = ? AND user_id = ?", [
532 sessionId,
533 userId,
534 ]);
535 return result.changes > 0;
536}
537
538export function deleteAllUserSessions(userId: number): void {
539 db.run("DELETE FROM sessions WHERE user_id = ?", [userId]);
540}
541
542export function updateUserEmailAddress(userId: number, newEmail: string): void {
543 db.run("UPDATE users SET email = ? WHERE id = ?", [newEmail, userId]);
544}
545
546export interface UserWithStats {
547 id: number;
548 email: string;
549 name: string | null;
550 avatar: string;
551 created_at: number;
552 role: UserRole;
553 last_login: number | null;
554 transcription_count: number;
555 subscription_status: string | null;
556 subscription_id: string | null;
557}
558
559export function getAllUsersWithStats(): UserWithStats[] {
560 return db
561 .query<UserWithStats, []>(
562 `SELECT
563 u.id,
564 u.email,
565 u.name,
566 u.avatar,
567 u.created_at,
568 u.role,
569 u.last_login,
570 COUNT(DISTINCT t.id) as transcription_count,
571 s.status as subscription_status,
572 s.id as subscription_id
573 FROM users u
574 LEFT JOIN transcriptions t ON u.id = t.user_id
575 LEFT JOIN subscriptions s ON u.id = s.user_id AND s.status IN ('active', 'trialing', 'past_due')
576 GROUP BY u.id
577 ORDER BY u.created_at DESC`,
578 )
579 .all();
580}