(encryptedText: string | null | undefined)
| 200 | * Decrypts OAuth token using AUTH_SECRET. Returns plaintext tokens unchanged during migration. |
| 201 | */ |
| 202 | export function decryptOAuthToken(encryptedText: string | null | undefined): string | undefined { |
| 203 | if (!encryptedText) { |
| 204 | return undefined; |
| 205 | } |
| 206 | |
| 207 | if (!isOAuthTokenEncrypted(encryptedText)) { |
| 208 | return encryptedText; |
| 209 | } |
| 210 | |
| 211 | try { |
| 212 | const decoded = Buffer.from(encryptedText, 'base64').toString('utf8'); |
| 213 | const tokenData = encryptedOAuthTokenSchema.parse(JSON.parse(decoded)); |
| 214 | |
| 215 | const salt = Buffer.from(tokenData.salt, 'hex'); |
| 216 | const iv = Buffer.from(tokenData.iv, 'hex'); |
| 217 | const tag = Buffer.from(tokenData.tag, 'hex'); |
| 218 | const encrypted = Buffer.from(tokenData.data, 'hex'); |
| 219 | |
| 220 | const key = deriveOAuthKey(env.AUTH_SECRET, salt); |
| 221 | const decipher = crypto.createDecipheriv(oauthAlgorithm, key, iv); |
| 222 | decipher.setAuthTag(tag); |
| 223 | |
| 224 | return decipher.update(encrypted, undefined, 'utf8') + decipher.final('utf8'); |
| 225 | } catch { |
| 226 | // Decryption failed - likely a plaintext token, return as-is |
| 227 | return encryptedText; |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | export function encryptActivationCode(code: string): string { |
| 232 | const { iv, encryptedData } = encrypt(code); |
no test coverage detected