({
req,
db,
logger,
}: PostLogoutDeps)
| 28 | }) |
| 29 | |
| 30 | export async function postLogout({ |
| 31 | req, |
| 32 | db, |
| 33 | logger, |
| 34 | }: PostLogoutDeps): Promise<NextResponse> { |
| 35 | let body: unknown |
| 36 | try { |
| 37 | body = await req.json() |
| 38 | } catch { |
| 39 | return NextResponse.json({ error: 'Invalid request body' }, { status: 400 }) |
| 40 | } |
| 41 | |
| 42 | const parsed = reqSchema.safeParse(body) |
| 43 | if (!parsed.success) { |
| 44 | return NextResponse.json({ error: 'Invalid request body' }, { status: 400 }) |
| 45 | } |
| 46 | |
| 47 | const { |
| 48 | authToken: bodyToken, |
| 49 | userId, |
| 50 | fingerprintId, |
| 51 | fingerprintHash, |
| 52 | } = parsed.data |
| 53 | const authToken = extractApiKeyFromHeader(req) ?? bodyToken |
| 54 | |
| 55 | if (!authToken) { |
| 56 | return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) |
| 57 | } |
| 58 | |
| 59 | try { |
| 60 | const tokenSessions = await db.getSessionByToken(authToken, userId) |
| 61 | const tokenValid = tokenSessions.length > 0 |
| 62 | if (!tokenValid) { |
| 63 | return NextResponse.json({ success: true }) |
| 64 | } |
| 65 | |
| 66 | const fingerprintSessionsDeleted = await db.deleteSessionsByFingerprint( |
| 67 | userId, |
| 68 | fingerprintId, |
| 69 | ) |
| 70 | const fingerprintMatchFound = fingerprintSessionsDeleted.length > 0 |
| 71 | |
| 72 | // Always fetch fingerprint data for subsequent logic |
| 73 | const fingerprintRows = await db.getFingerprintData(fingerprintId) |
| 74 | const fingerprintData = fingerprintRows[0] |
| 75 | |
| 76 | if (fingerprintMatchFound) { |
| 77 | // Also clean up orphaned web sessions (fingerprint_id = null) for this user |
| 78 | await db.deleteOrphanedWebSessions(userId) |
| 79 | } else if (fingerprintData?.created_at) { |
| 80 | // Intermediate strategy: delete web sessions created around the same time as the fingerprint |
| 81 | const timeWindowDeleted = await db.deleteWebSessionsInTimeWindow( |
| 82 | userId, |
| 83 | fingerprintData.created_at, |
| 84 | ) |
| 85 | if (timeWindowDeleted.length === 0) { |
| 86 | // Final fallback: delete all web sessions when time-window deletion finds nothing |
| 87 | await db.deleteAllWebSessions(userId) |
no test coverage detected