(token: string)
| 36 | * Verify and decode a session token. |
| 37 | */ |
| 38 | export function verifySessionToken(token: string): SessionPayload | null { |
| 39 | try { |
| 40 | const secret = getSessionSecret(); |
| 41 | const decoded = Buffer.from(token, 'base64').toString('utf-8'); |
| 42 | const lastDot = decoded.lastIndexOf('.'); |
| 43 | if (lastDot === -1) return null; |
| 44 | |
| 45 | const payload = decoded.slice(0, lastDot); |
| 46 | const signature = decoded.slice(lastDot + 1); |
| 47 | |
| 48 | const hmac = crypto.createHmac('sha256', secret); |
| 49 | hmac.update(payload); |
| 50 | const expectedSignature = hmac.digest('hex'); |
| 51 | |
| 52 | if (signature.length !== expectedSignature.length) return null; |
| 53 | const signatureMatch = crypto.timingSafeEqual( |
| 54 | Buffer.from(signature), |
| 55 | Buffer.from(expectedSignature), |
| 56 | ); |
| 57 | if (!signatureMatch) return null; |
| 58 | |
| 59 | const parsed = JSON.parse(payload) as SessionPayload; |
| 60 | if (typeof parsed.ts !== 'number') return null; |
| 61 | if (Date.now() - parsed.ts > SESSION_COOKIE_MAX_AGE) return null; |
| 62 | return parsed; |
| 63 | } catch { |
| 64 | return null; |
| 65 | } |
| 66 | } |
no test coverage detected