src/examples/webhooks/receiver.ts

Every source

src/examples/webhooks/receiver.ts
import { isSynqError } from '@synqauth/js'
import { verifyWebhook } from '@synqauth/js/server'

import { remember } from '../../lib/deliveries'

// Receiving Synq's webhooks: check each delivery's signature before you
// trust a byte of it, then act on the event. verifyWebhook checks the
// Standard Webhooks signature against the subscription's whsec_ secret, and
// that Synq signed it in the last five minutes, so a captured delivery can't
// be replayed. Read the raw body: parsing the JSON first changes the bytes
// that were signed.

export async function POST(request: Request): Promise<Response> {
  const secret = process.env.SYNQ_WEBHOOK_SECRET
  if (!secret) return new Response('not set up', { status: 503 })
  const body = await request.text()
  try {
    const { id, event } = await verifyWebhook(body, request.headers, secret)
    // `id` is the same on every retry of one delivery: handle each once.
    remember({ id, type: event.type, receivedAt: new Date().toISOString(), data: event.data })
    return new Response(null, { status: 204 })
  } catch (error) {
    // A delivery that fails its check gets a 401; Synq tries it again later.
    if (isSynqError(error)) return new Response(error.code, { status: 401 })
    throw error
  }
}