(
account: Account,
db: PrismaClient,
)
| 61 | * the calling job fails with a clear error. |
| 62 | */ |
| 63 | export const ensureFreshAccountToken = async ( |
| 64 | account: Account, |
| 65 | db: PrismaClient, |
| 66 | ): Promise<string> => { |
| 67 | if (!account.access_token) { |
| 68 | throw new Error(`Account ${account.id} (${account.providerId}) has no access token.`); |
| 69 | } |
| 70 | |
| 71 | if (!isSupportedProvider(account.providerType)) { |
| 72 | // Non-refreshable provider — just decrypt and return whatever is stored. |
| 73 | const token = decryptOAuthToken(account.access_token); |
| 74 | if (!token) { |
| 75 | throw new Error(`Failed to decrypt access token for account ${account.id}.`); |
| 76 | } |
| 77 | return token; |
| 78 | } |
| 79 | |
| 80 | const now = Math.floor(Date.now() / 1000); |
| 81 | const isExpiredOrNearExpiry = |
| 82 | account.expires_at !== null && |
| 83 | account.expires_at > 0 && |
| 84 | now >= account.expires_at - EXPIRY_BUFFER_S; |
| 85 | |
| 86 | if (!isExpiredOrNearExpiry) { |
| 87 | const token = decryptOAuthToken(account.access_token); |
| 88 | if (!token) { |
| 89 | throw new Error(`Failed to decrypt access token for account ${account.id}.`); |
| 90 | } |
| 91 | return token; |
| 92 | } |
| 93 | |
| 94 | if (!account.refresh_token) { |
| 95 | const message = `Account ${account.id} (${account.providerId}) token is expired and has no refresh token.`; |
| 96 | logger.error(message); |
| 97 | await setTokenRefreshError(account.id, message, db); |
| 98 | throw new Error(message); |
| 99 | } |
| 100 | |
| 101 | const refreshToken = decryptOAuthToken(account.refresh_token); |
| 102 | if (!refreshToken) { |
| 103 | const message = `Failed to decrypt refresh token for account ${account.id} (${account.providerId}).`; |
| 104 | logger.error(message); |
| 105 | await setTokenRefreshError(account.id, message, db); |
| 106 | throw new Error(message); |
| 107 | } |
| 108 | |
| 109 | logger.debug(`Refreshing OAuth token for account ${account.id} (${account.providerId})...`); |
| 110 | |
| 111 | const refreshResponse = await refreshOAuthToken( |
| 112 | account.providerId, |
| 113 | account.providerType, |
| 114 | refreshToken |
| 115 | ); |
| 116 | |
| 117 | if (!refreshResponse) { |
| 118 | const message = `OAuth token refresh failed for account ${account.id} (${account.providerId}).`; |
| 119 | logger.error(message); |
| 120 | await setTokenRefreshError(account.id, message, db); |
no test coverage detected