|
1 | 1 | import { eq } from 'drizzle-orm' |
2 | 2 | import { type NextRequest, NextResponse } from 'next/server' |
3 | 3 | import { getSession } from '@/lib/auth' |
| 4 | +import { env } from '@/lib/env' |
4 | 5 | import { createLogger } from '@/lib/logs/console/logger' |
5 | 6 | import { getUserEntityPermissions } from '@/lib/permissions/utils' |
| 7 | +import { getOAuthToken } from '@/app/api/auth/oauth/utils' |
6 | 8 | import { db } from '@/db' |
7 | 9 | import { webhook, workflow } from '@/db/schema' |
8 | 10 |
|
@@ -242,6 +244,167 @@ export async function DELETE( |
242 | 244 |
|
243 | 245 | const foundWebhook = webhookData.webhook |
244 | 246 |
|
| 247 | + // If it's an Airtable webhook, delete it from Airtable first |
| 248 | + if (foundWebhook.provider === 'airtable') { |
| 249 | + try { |
| 250 | + const { baseId, externalId } = (foundWebhook.providerConfig || {}) as { |
| 251 | + baseId?: string |
| 252 | + externalId?: string |
| 253 | + } |
| 254 | + |
| 255 | + if (!baseId) { |
| 256 | + logger.warn(`[${requestId}] Missing baseId for Airtable webhook deletion.`, { |
| 257 | + webhookId: id, |
| 258 | + }) |
| 259 | + return NextResponse.json( |
| 260 | + { error: 'Missing baseId for Airtable webhook deletion' }, |
| 261 | + { status: 400 } |
| 262 | + ) |
| 263 | + } |
| 264 | + |
| 265 | + // Get access token for the workflow owner |
| 266 | + const userIdForToken = webhookData.workflow.userId |
| 267 | + const accessToken = await getOAuthToken(userIdForToken, 'airtable') |
| 268 | + if (!accessToken) { |
| 269 | + logger.warn( |
| 270 | + `[${requestId}] Could not retrieve Airtable access token for user ${userIdForToken}. Cannot delete webhook in Airtable.`, |
| 271 | + { webhookId: id } |
| 272 | + ) |
| 273 | + return NextResponse.json( |
| 274 | + { error: 'Airtable access token not found for webhook deletion' }, |
| 275 | + { status: 401 } |
| 276 | + ) |
| 277 | + } |
| 278 | + |
| 279 | + // Resolve externalId if missing by listing webhooks and matching our notificationUrl |
| 280 | + let resolvedExternalId: string | undefined = externalId |
| 281 | + |
| 282 | + if (!resolvedExternalId) { |
| 283 | + try { |
| 284 | + const requestOrigin = new URL(request.url).origin |
| 285 | + const effectiveOrigin = requestOrigin.includes('localhost') |
| 286 | + ? env.NEXT_PUBLIC_APP_URL || requestOrigin |
| 287 | + : requestOrigin |
| 288 | + const expectedNotificationUrl = `${effectiveOrigin}/api/webhooks/trigger/${foundWebhook.path}` |
| 289 | + |
| 290 | + const listUrl = `https://api.airtable.com/v0/bases/${baseId}/webhooks` |
| 291 | + const listResp = await fetch(listUrl, { |
| 292 | + headers: { |
| 293 | + Authorization: `Bearer ${accessToken}`, |
| 294 | + }, |
| 295 | + }) |
| 296 | + const listBody = await listResp.json().catch(() => null) |
| 297 | + |
| 298 | + if (listResp.ok && listBody && Array.isArray(listBody.webhooks)) { |
| 299 | + const match = listBody.webhooks.find((w: any) => { |
| 300 | + const url: string | undefined = w?.notificationUrl |
| 301 | + if (!url) return false |
| 302 | + // Prefer exact match; fallback to suffix match to handle origin/host remaps |
| 303 | + return ( |
| 304 | + url === expectedNotificationUrl || |
| 305 | + url.endsWith(`/api/webhooks/trigger/${foundWebhook.path}`) |
| 306 | + ) |
| 307 | + }) |
| 308 | + if (match?.id) { |
| 309 | + resolvedExternalId = match.id as string |
| 310 | + // Persist resolved externalId for future operations |
| 311 | + try { |
| 312 | + await db |
| 313 | + .update(webhook) |
| 314 | + .set({ |
| 315 | + providerConfig: { |
| 316 | + ...(foundWebhook.providerConfig || {}), |
| 317 | + externalId: resolvedExternalId, |
| 318 | + }, |
| 319 | + updatedAt: new Date(), |
| 320 | + }) |
| 321 | + .where(eq(webhook.id, id)) |
| 322 | + } catch { |
| 323 | + // non-fatal persistence error |
| 324 | + } |
| 325 | + logger.info(`[${requestId}] Resolved Airtable externalId by listing webhooks`, { |
| 326 | + baseId, |
| 327 | + externalId: resolvedExternalId, |
| 328 | + }) |
| 329 | + } else { |
| 330 | + logger.warn(`[${requestId}] Could not resolve Airtable externalId from list`, { |
| 331 | + baseId, |
| 332 | + expectedNotificationUrl, |
| 333 | + }) |
| 334 | + } |
| 335 | + } else { |
| 336 | + logger.warn(`[${requestId}] Failed to list Airtable webhooks to resolve externalId`, { |
| 337 | + baseId, |
| 338 | + status: listResp.status, |
| 339 | + body: listBody, |
| 340 | + }) |
| 341 | + } |
| 342 | + } catch (e: any) { |
| 343 | + logger.warn(`[${requestId}] Error attempting to resolve Airtable externalId`, { |
| 344 | + error: e?.message, |
| 345 | + }) |
| 346 | + } |
| 347 | + } |
| 348 | + |
| 349 | + // If still not resolvable, skip remote deletion but proceed with local delete |
| 350 | + if (!resolvedExternalId) { |
| 351 | + logger.info( |
| 352 | + `[${requestId}] Airtable externalId not found; skipping remote deletion and proceeding to remove local record`, |
| 353 | + { baseId } |
| 354 | + ) |
| 355 | + } |
| 356 | + |
| 357 | + if (resolvedExternalId) { |
| 358 | + const airtableDeleteUrl = `https://api.airtable.com/v0/bases/${baseId}/webhooks/${resolvedExternalId}` |
| 359 | + const airtableResponse = await fetch(airtableDeleteUrl, { |
| 360 | + method: 'DELETE', |
| 361 | + headers: { |
| 362 | + Authorization: `Bearer ${accessToken}`, |
| 363 | + }, |
| 364 | + }) |
| 365 | + |
| 366 | + // Attempt to parse error body for better diagnostics |
| 367 | + if (!airtableResponse.ok) { |
| 368 | + let responseBody: any = null |
| 369 | + try { |
| 370 | + responseBody = await airtableResponse.json() |
| 371 | + } catch { |
| 372 | + // ignore parse errors |
| 373 | + } |
| 374 | + |
| 375 | + logger.error( |
| 376 | + `[${requestId}] Failed to delete Airtable webhook in Airtable. Status: ${airtableResponse.status}`, |
| 377 | + { baseId, externalId: resolvedExternalId, response: responseBody } |
| 378 | + ) |
| 379 | + return NextResponse.json( |
| 380 | + { |
| 381 | + error: 'Failed to delete webhook from Airtable', |
| 382 | + details: |
| 383 | + (responseBody && (responseBody.error?.message || responseBody.error)) || |
| 384 | + `Status ${airtableResponse.status}`, |
| 385 | + }, |
| 386 | + { status: 500 } |
| 387 | + ) |
| 388 | + } |
| 389 | + |
| 390 | + logger.info(`[${requestId}] Successfully deleted Airtable webhook in Airtable`, { |
| 391 | + baseId, |
| 392 | + externalId: resolvedExternalId, |
| 393 | + }) |
| 394 | + } |
| 395 | + } catch (error: any) { |
| 396 | + logger.error(`[${requestId}] Error deleting Airtable webhook`, { |
| 397 | + webhookId: id, |
| 398 | + error: error.message, |
| 399 | + stack: error.stack, |
| 400 | + }) |
| 401 | + return NextResponse.json( |
| 402 | + { error: 'Failed to delete webhook from Airtable', details: error.message }, |
| 403 | + { status: 500 } |
| 404 | + ) |
| 405 | + } |
| 406 | + } |
| 407 | + |
245 | 408 | // If it's a Telegram webhook, delete it from Telegram first |
246 | 409 | if (foundWebhook.provider === 'telegram') { |
247 | 410 | try { |
|
0 commit comments