| 1449 | * @returns {Promise<ICommonObject>} |
| 1450 | */ |
| 1451 | export const refreshOAuth2Token = async ( |
| 1452 | credentialId: string, |
| 1453 | credentialData: ICommonObject, |
| 1454 | options: ICommonObject, |
| 1455 | bufferTimeMs: number = 5 * 60 * 1000 |
| 1456 | ): Promise<ICommonObject> => { |
| 1457 | // Check if token is expired and refresh if needed |
| 1458 | if (credentialData.expires_at) { |
| 1459 | const expiryTime = new Date(credentialData.expires_at) |
| 1460 | const currentTime = new Date() |
| 1461 | |
| 1462 | if (currentTime.getTime() > expiryTime.getTime() - bufferTimeMs) { |
| 1463 | if (!credentialData.refresh_token) { |
| 1464 | throw new Error('Access token is expired and no refresh token is available. Please re-authorize the credential.') |
| 1465 | } |
| 1466 | |
| 1467 | try { |
| 1468 | // Import fetch dynamically to avoid issues |
| 1469 | const fetch = (await import('node-fetch')).default |
| 1470 | |
| 1471 | // Call the refresh API endpoint |
| 1472 | const refreshResponse = await fetch( |
| 1473 | `${options.baseURL || 'http://localhost:3000'}/api/v1/oauth2-credential/refresh/${credentialId}`, |
| 1474 | { |
| 1475 | method: 'POST', |
| 1476 | headers: { |
| 1477 | 'Content-Type': 'application/json' |
| 1478 | } |
| 1479 | } |
| 1480 | ) |
| 1481 | |
| 1482 | if (!refreshResponse.ok) { |
| 1483 | const errorData = await refreshResponse.text() |
| 1484 | throw new Error(`Failed to refresh token: ${refreshResponse.status} ${refreshResponse.statusText} - ${errorData}`) |
| 1485 | } |
| 1486 | |
| 1487 | await refreshResponse.json() |
| 1488 | |
| 1489 | // Get the updated credential data |
| 1490 | const updatedCredentialData = await getCredentialData(credentialId, options) |
| 1491 | |
| 1492 | return updatedCredentialData |
| 1493 | } catch (error) { |
| 1494 | console.error('Failed to refresh access token:', error) |
| 1495 | throw new Error( |
| 1496 | `Failed to refresh access token: ${ |
| 1497 | error instanceof Error ? error.message : 'Unknown error' |
| 1498 | }. Please re-authorize the credential.` |
| 1499 | ) |
| 1500 | } |
| 1501 | } |
| 1502 | } |
| 1503 | |
| 1504 | // Token is not expired, return original data |
| 1505 | return credentialData |
| 1506 | } |
| 1507 | |
| 1508 | export const stripHTMLFromToolInput = (input: string) => { |