( token: string, deploymentId: string, authType: string, encryptedPassword?: string | null )
| 36 | * invalidates existing sessions. |
| 37 | */ |
| 38 | export function validateAuthToken( |
| 39 | token: string, |
| 40 | deploymentId: string, |
| 41 | authType: string, |
| 42 | encryptedPassword?: string | null |
| 43 | ): boolean { |
| 44 | try { |
| 45 | const decoded = Buffer.from(token, 'base64').toString() |
| 46 | const lastColon = decoded.lastIndexOf(':') |
| 47 | if (lastColon === -1) return false |
| 48 | |
| 49 | const payload = decoded.slice(0, lastColon) |
| 50 | const sig = decoded.slice(lastColon + 1) |
| 51 | |
| 52 | const expectedSig = signPayload(payload) |
| 53 | if (!safeCompare(sig, expectedSig)) { |
| 54 | return false |
| 55 | } |
| 56 | |
| 57 | const parts = payload.split(':') |
| 58 | if (parts.length < 4) return false |
| 59 | const [storedId, storedType, timestamp, storedPwSlot] = parts |
| 60 | |
| 61 | if (storedId !== deploymentId) return false |
| 62 | |
| 63 | // Bind the cookie to the auth type so a token minted under one mode (e.g. a |
| 64 | // `public` share, which has an empty password slot) can't satisfy another |
| 65 | // mode (e.g. `email` OTP) after the share's auth type is changed. |
| 66 | if (storedType !== authType) return false |
| 67 | |
| 68 | const expectedPwSlot = passwordSlot(encryptedPassword) |
| 69 | if (storedPwSlot !== expectedPwSlot) return false |
| 70 | |
| 71 | const createdAt = Number.parseInt(timestamp) |
| 72 | const expireTime = 24 * 60 * 60 * 1000 |
| 73 | if (Date.now() - createdAt > expireTime) return false |
| 74 | |
| 75 | return true |
| 76 | } catch (_e) { |
| 77 | return false |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | /** The kind of deployed resource an auth cookie/token belongs to. */ |
| 82 | export type DeploymentAuthKind = 'chat' | 'file' |
no test coverage detected