Receive a signed webhook with a function #

View this page as Markdown

On this page

Prompt:

Build me a small endpoint that accepts signed Stripe events and keeps a copy of each one.

Start by choosing a serverless application and environment. Declare Storage, then use a function to check each delivery before it stores the event. For an existing server application, use Receive a signed webhook.

What your AI does #

  • Chooses the function route for a short request that can finish after one Storage write.
  • Uses the chosen environment's signing secret and keeps it out of source, logs and responses.
  • Checks a signed delivery, a repeat and a changed body against the deployed endpoint and reads back the Storage file.

What you need #

  • A connected, signed-in AI assistant and a serverless application, or the owner's choice to create one.
  • Access to the sender's test endpoint settings and its signing secret. Keep the secret in a private file outside the application folder.

Steps #

1. Choose the environment and declare Storage #

Use Deploy functions to check the application's kind. For a new app, choose kind: "serverless" without a size. Ask the owner before enabling development. Use development for test deliveries when the application has that environment.

This manifest is for a new app with a public webhook path. It declares a shared Storage area for accepted events. For an existing app, keep its other declarations and follow Open the path under a private audience if the sender needs a session-free path.

{
  "manifest_version": 1,
  "services": [
    {
      "kind": "object_storage",
      "areas": [{ "name": "webhook-events", "account_keyed": false }]
    }
  ],
  "region": "usa",
  "egress": [],
  "audience": { "kind": "public" },
  "packages": [],
  "settings": {
    "STRIPE_WEBHOOK_SECRET": { "secret": "stripe-webhook-secret" }
  }
}

Submit the whole manifest with submit_manifest for that application. The shared area belongs to the app, and the webhook exposes no route for reading its files. Keep access to stored payloads limited to people and services that need them.

2. Store the endpoint's signing secret #

Read the chosen environment's public hostname with read_status. Use that hostname with /webhooks/stripe when you set up the test endpoint at the sender, then obtain its signing secret. For a test you sign yourself, use a test secret you choose.

Follow Store a webhook signing secret. Use the name stripe-webhook-secret and the application and environment chosen in step 1. The manifest binds it to STRIPE_WEBHOOK_SECRET. Store a separate secret for each environment that will receive deliveries.

If the sender needs a callback URL before it gives you the signing secret, leave the STRIPE_WEBHOOK_SECRET binding out of the first manifest. Write the function in step 3, then follow step 4's deploy instructions to get its URL. The function answers 503 receiver_not_configured and stores nothing while the secret is missing.

When the secret arrives, store it as described above, add the binding and submit the whole manifest again. Deploy to the same environment before sending test deliveries.

3. Write the function #

Save this as functions/webhooks/stripe.js. The function buffers up to 256 KiB of a delivery. It checks the signature over the original request bytes before decoding the JSON. To use a different sender, follow that sender's signing rules.

const path = '/webhooks/stripe'
const maxBytes = 256 * 1024
const encoder = new TextEncoder()

function reply(status, error, headers) {
  return Response.json({ error }, { status, headers })
}

async function readBody(request) {
  if (!request.body) return new Uint8Array()
  const reader = request.body.getReader()
  const chunks = []
  let size = 0

  try {
    for (;;) {
      const { value, done } = await reader.read()
      if (done) break
      size += value.byteLength
      if (size > maxBytes) {
        await reader.cancel()
        return null
      }
      chunks.push(value)
    }
  } finally {
    reader.releaseLock()
  }

  const body = new Uint8Array(size)
  let offset = 0
  for (const chunk of chunks) {
    body.set(chunk, offset)
    offset += chunk.byteLength
  }
  return body
}

async function verifies(header, body, secret) {
  const fields = header.split(',').map(field => field.trim())
  const timestamps = fields.filter(field => field.startsWith('t='))
  if (timestamps.length !== 1) return false
  const timestamp = timestamps[0].slice(2)
  if (!/^\d{1,12}$/.test(timestamp) ||
      Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp)) > 300) {
    return false
  }

  const prefix = encoder.encode(timestamp + '.')
  const signed = new Uint8Array(prefix.length + body.length)
  signed.set(prefix)
  signed.set(body, prefix.length)
  const key = await crypto.subtle.importKey(
    'raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']
  )

  for (const field of fields) {
    if (!/^v1=[0-9a-f]{64}$/.test(field)) continue
    const signature = Uint8Array.from(
      field.slice(3).match(/../g), pair => Number.parseInt(pair, 16)
    )
    if (await crypto.subtle.verify('HMAC', key, signature, signed)) return true
  }
  return false
}

export default {
  async fetch(request) {
    if (new URL(request.url).pathname !== path) return reply(404, 'not_found')
    if (request.method !== 'POST') return reply(405, 'method_not_allowed', { allow: 'POST' })

    const secret = process.env.STRIPE_WEBHOOK_SECRET
    const origin = process.env.TURNZERO_CLOUD_GATEWAY_URL || process.env.TURNZERO_CLOUD_API
    const credential = process.env.TURNZERO_CLOUD_APP_TOKEN
    if (!secret || !origin || !credential) return reply(503, 'receiver_not_configured')

    const header = request.headers.get('stripe-signature')
    if (!header) return reply(400, 'invalid_signature')
    let body
    try {
      body = await readBody(request)
    } catch {
      return reply(400, 'unreadable_body')
    }
    if (!body) return reply(413, 'payload_too_large')
    if (!await verifies(header, body, secret)) return reply(400, 'invalid_signature')

    let event
    try {
      event = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(body))
    } catch {
      return reply(400, 'invalid_event')
    }
    if (typeof event?.id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(event.id)) {
      return reply(400, 'invalid_event')
    }

    try {
      const saved = await fetch(new URL('/storage/v0/areas/webhook-events/files/' + event.id + '.json', origin), {
        method: 'PUT',
        redirect: 'error',
        headers: {
          authorization: 'Bearer ' + credential,
          'content-type': 'application/json',
          'if-none-match': '*',
          'x-acting-identity': 'stripe-webhook'
        },
        body
      })
      if (saved.ok) {
        await saved.text()
        return Response.json({ accepted: true, duplicate: false })
      }
      const failure = await saved.json()
      if (saved.status === 412 && failure?.error === 'version_mismatch') {
        return Response.json({ accepted: true, duplicate: true })
      }
    } catch {
      // A retry can find the event if the write landed before its response was lost.
    }
    return reply(503, 'storage_unavailable')
  }
}

Storage's conditional write prevents a second delivery with the same event ID from replacing the first. The function waits for Storage before sending 200. The example archives events without performing any business action.

For the HTTP status codes and response fields of a conditional write, see the file PUT row in Storage file routes.

4. Deploy and send test deliveries #

Follow Deploy the handler for the chosen environment. Read the completed version's functions list and use its public hostname with /webhooks/stripe. Check that it matches the HTTPS URL you registered with the sender. Use Stripe's webhook instructions for the endpoint and signing details.

Send a new signed test event, then resend it. When testing without Stripe, use the signed test script with your private test secret and the function's URL. Give each fresh check a new event ID. Extend the check to send the same signed bytes twice before changing the body.

5. Read back the stored event #

Use Store files to read webhook-events/<event ID>.json in the environment that handled the request. Compare its bytes with the signed test body. After the repeat the file should have the same bytes and version. Change the test event ID without signing the new bytes. Expect 400 and verify that the new ID has no file.

Check read_logs with source: "pool" if the handler fails. Once development passes, follow Test in development, then promote if the owner wants the receiver in production. Configure the live URL and secret separately.

Expected result #

The first valid delivery returns 200 with accepted: true and duplicate: false. A verified repeat returns 200 with duplicate: true and leaves the original file intact. Invalid deliveries create no file. A failed Storage write gets an error response so the sender can retry.

Refusals #

What you see Cause Remedy
400 invalid_signature The signature is missing or invalid, or its timestamp differs from the receiver's clock by more than five minutes. Check the endpoint secret and sign the bytes you actually send. Send a freshly signed delivery.
400 unreadable_body or invalid_event The body could not be read, or the signed body failed the JSON or event-ID check. Send a complete UTF-8 JSON body with the event ID. Preserve those bytes after signing.
404 not_found or 405 method_not_allowed The path differs from the receiver's path, or the method is wrong. Send POST to /webhooks/stripe on the hostname for the deployed environment.
413 payload_too_large The delivery exceeds the function example's 256 KiB limit. Limit the payload or choose a bound you have checked against the function's limits.
setting_secret_missing The deploy or promote cannot find the bound secret in its target environment. Store the matching endpoint secret in that environment and retry the deploy or promote.
503 receiver_not_configured The running function lacks the secret, Storage origin or platform credential. Check the deploy's environment and secret binding. Use the deployed function's injected settings.
503 storage_unavailable Storage did not confirm a successful write or an existing file. Check the area declaration, credential and environment. After correcting the failure, resend the event.
429 function_busy The function's app or account reached a runtime limit. Read the detail and follow Deploy functions' refusals.