|
| 1 | +import { createLogger } from '@sim/logger' |
| 2 | +import { getErrorMessage } from '@sim/utils/errors' |
| 3 | +import { type NextRequest, NextResponse } from 'next/server' |
| 4 | +import { |
| 5 | + tiktokWebhookEnvelopeSchema, |
| 6 | + tiktokWebhookHeadersSchema, |
| 7 | +} from '@/lib/api/contracts/webhooks' |
| 8 | +import { |
| 9 | + API_EXECUTION_REQUIRES_PAID_PLAN_MESSAGE, |
| 10 | + isWorkspaceApiExecutionEntitled, |
| 11 | +} from '@/lib/billing/core/api-access' |
| 12 | +import { admissionRejectedResponse, tryAdmit } from '@/lib/core/admission/gate' |
| 13 | +import { generateRequestId } from '@/lib/core/utils/request' |
| 14 | +import { |
| 15 | + assertContentLengthWithinLimit, |
| 16 | + isPayloadSizeLimitError, |
| 17 | + readStreamToBufferWithLimit, |
| 18 | +} from '@/lib/core/utils/stream-limits' |
| 19 | +import { withRouteHandler } from '@/lib/core/utils/with-route-handler' |
| 20 | +import { WEBHOOK_MAX_BODY_BYTES } from '@/lib/webhooks/constants' |
| 21 | +import { |
| 22 | + checkWebhookPreprocessing, |
| 23 | + handlePreDeploymentVerification, |
| 24 | + queueWebhookExecution, |
| 25 | + shouldSkipWebhookEvent, |
| 26 | +} from '@/lib/webhooks/processor' |
| 27 | +import { verifyTikTokSignature } from '@/lib/webhooks/providers/tiktok' |
| 28 | +import { findTikTokWebhooksForOpenId } from '@/lib/webhooks/tiktok-fanout' |
| 29 | +import { blockExistsInDeployment } from '@/lib/workflows/persistence/utils' |
| 30 | + |
| 31 | +const logger = createLogger('TikTokWebhookIngress') |
| 32 | + |
| 33 | +const TIKTOK_BODY_LABEL = 'TikTok webhook body' |
| 34 | + |
| 35 | +export const dynamic = 'force-dynamic' |
| 36 | +export const runtime = 'nodejs' |
| 37 | +export const maxDuration = 60 |
| 38 | + |
| 39 | +async function readTikTokBody(req: Request): Promise<string> { |
| 40 | + assertContentLengthWithinLimit(req.headers, WEBHOOK_MAX_BODY_BYTES, TIKTOK_BODY_LABEL) |
| 41 | + const buffer = await readStreamToBufferWithLimit(req.body, { |
| 42 | + maxBytes: WEBHOOK_MAX_BODY_BYTES, |
| 43 | + label: TIKTOK_BODY_LABEL, |
| 44 | + }) |
| 45 | + return new TextDecoder().decode(buffer) |
| 46 | +} |
| 47 | + |
| 48 | +/** |
| 49 | + * App-level TikTok webhook Callback URL. |
| 50 | + * Portal: `{APP_URL}/api/webhooks/tiktok` (e.g. https://www.sim.ai/api/webhooks/tiktok). |
| 51 | + * Verifies TikTok-Signature once, then fans out by user_openid → credential → workflows. |
| 52 | + */ |
| 53 | +export const POST = withRouteHandler(async (request: NextRequest) => { |
| 54 | + const ticket = tryAdmit() |
| 55 | + if (!ticket) { |
| 56 | + return admissionRejectedResponse() |
| 57 | + } |
| 58 | + |
| 59 | + const requestId = generateRequestId() |
| 60 | + const receivedAt = Date.now() |
| 61 | + |
| 62 | + try { |
| 63 | + let rawBody: string |
| 64 | + try { |
| 65 | + rawBody = await readTikTokBody(request) |
| 66 | + } catch (bodyError) { |
| 67 | + if (isPayloadSizeLimitError(bodyError)) { |
| 68 | + logger.warn(`[${requestId}] Rejected oversized TikTok webhook body`, { |
| 69 | + maxBytes: WEBHOOK_MAX_BODY_BYTES, |
| 70 | + observedBytes: bodyError.observedBytes, |
| 71 | + }) |
| 72 | + return NextResponse.json({ error: 'Request body too large' }, { status: 413 }) |
| 73 | + } |
| 74 | + throw bodyError |
| 75 | + } |
| 76 | + |
| 77 | + const headersResult = tiktokWebhookHeadersSchema.safeParse({ |
| 78 | + 'tiktok-signature': request.headers.get('TikTok-Signature'), |
| 79 | + }) |
| 80 | + if (!headersResult.success) { |
| 81 | + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) |
| 82 | + } |
| 83 | + |
| 84 | + const authError = verifyTikTokSignature( |
| 85 | + rawBody, |
| 86 | + headersResult.data['tiktok-signature'], |
| 87 | + requestId |
| 88 | + ) |
| 89 | + if (authError) { |
| 90 | + return authError |
| 91 | + } |
| 92 | + |
| 93 | + let parsedJson: unknown |
| 94 | + try { |
| 95 | + parsedJson = rawBody ? JSON.parse(rawBody) : {} |
| 96 | + } catch { |
| 97 | + logger.warn(`[${requestId}] TikTok webhook body is not valid JSON`) |
| 98 | + // Ack to avoid retry storms on malformed payloads after a valid signature. |
| 99 | + return NextResponse.json({ ok: true }) |
| 100 | + } |
| 101 | + |
| 102 | + const envelopeResult = tiktokWebhookEnvelopeSchema.safeParse(parsedJson) |
| 103 | + if (!envelopeResult.success) { |
| 104 | + logger.warn(`[${requestId}] Invalid TikTok webhook envelope`, { |
| 105 | + issues: envelopeResult.error.issues, |
| 106 | + }) |
| 107 | + return NextResponse.json({ ok: true }) |
| 108 | + } |
| 109 | + |
| 110 | + const envelope = envelopeResult.data |
| 111 | + const matches = await findTikTokWebhooksForOpenId(envelope.user_openid, requestId) |
| 112 | + |
| 113 | + if (matches.length === 0) { |
| 114 | + logger.info(`[${requestId}] No matching TikTok webhooks; acknowledging`, { |
| 115 | + event: envelope.event, |
| 116 | + userOpenIdPrefix: envelope.user_openid.slice(0, 12), |
| 117 | + }) |
| 118 | + return NextResponse.json({ ok: true }) |
| 119 | + } |
| 120 | + |
| 121 | + let processed = 0 |
| 122 | + for (const { webhook: foundWebhook, workflow: foundWorkflow } of matches) { |
| 123 | + // Schema allows null provider; fan-out already filtered to provider = 'tiktok'. |
| 124 | + const webhookRecord = { |
| 125 | + ...foundWebhook, |
| 126 | + provider: foundWebhook.provider ?? 'tiktok', |
| 127 | + providerConfig: |
| 128 | + (foundWebhook.providerConfig as Record<string, unknown> | null) ?? undefined, |
| 129 | + } |
| 130 | + |
| 131 | + if ( |
| 132 | + foundWorkflow.workspaceId && |
| 133 | + !(await isWorkspaceApiExecutionEntitled(foundWorkflow.workspaceId)) |
| 134 | + ) { |
| 135 | + logger.warn(`[${requestId}] Workspace not entitled for TikTok webhook`, { |
| 136 | + webhookId: webhookRecord.id, |
| 137 | + workspaceId: foundWorkflow.workspaceId, |
| 138 | + }) |
| 139 | + continue |
| 140 | + } |
| 141 | + |
| 142 | + const preprocessResult = await checkWebhookPreprocessing( |
| 143 | + foundWorkflow, |
| 144 | + webhookRecord, |
| 145 | + requestId |
| 146 | + ) |
| 147 | + if (preprocessResult.error) { |
| 148 | + logger.warn(`[${requestId}] Preprocessing failed for TikTok webhook`, { |
| 149 | + webhookId: webhookRecord.id, |
| 150 | + }) |
| 151 | + continue |
| 152 | + } |
| 153 | + |
| 154 | + if (webhookRecord.blockId) { |
| 155 | + const blockExists = await blockExistsInDeployment(foundWorkflow.id, webhookRecord.blockId) |
| 156 | + if (!blockExists) { |
| 157 | + const preDeploymentResponse = handlePreDeploymentVerification(webhookRecord, requestId) |
| 158 | + if (preDeploymentResponse) { |
| 159 | + continue |
| 160 | + } |
| 161 | + logger.info( |
| 162 | + `[${requestId}] Trigger block ${webhookRecord.blockId} not found in deployment for workflow ${foundWorkflow.id}` |
| 163 | + ) |
| 164 | + continue |
| 165 | + } |
| 166 | + } |
| 167 | + |
| 168 | + if (shouldSkipWebhookEvent(webhookRecord, envelope, requestId)) { |
| 169 | + continue |
| 170 | + } |
| 171 | + |
| 172 | + await queueWebhookExecution(webhookRecord, foundWorkflow, envelope, request, { |
| 173 | + requestId, |
| 174 | + path: webhookRecord.path, |
| 175 | + actorUserId: preprocessResult.actorUserId, |
| 176 | + executionId: preprocessResult.executionId, |
| 177 | + correlation: preprocessResult.correlation, |
| 178 | + receivedAt, |
| 179 | + }) |
| 180 | + processed += 1 |
| 181 | + } |
| 182 | + |
| 183 | + if (processed === 0 && matches.length > 0) { |
| 184 | + logger.info(`[${requestId}] TikTok webhooks matched but none processed`, { |
| 185 | + matchCount: matches.length, |
| 186 | + hint: API_EXECUTION_REQUIRES_PAID_PLAN_MESSAGE, |
| 187 | + }) |
| 188 | + } |
| 189 | + |
| 190 | + return NextResponse.json({ ok: true, webhooksProcessed: processed }) |
| 191 | + } catch (error) { |
| 192 | + logger.error(`[${requestId}] TikTok webhook ingress error`, { |
| 193 | + error: getErrorMessage(error, 'Unknown error'), |
| 194 | + }) |
| 195 | + // Still 200 after accept path failures that aren't auth — TikTok retries on non-200. |
| 196 | + return NextResponse.json({ ok: true }) |
| 197 | + } finally { |
| 198 | + ticket.release() |
| 199 | + } |
| 200 | +}) |
0 commit comments