Skip to content

Verify a Stripe webhook ​

A webhook is a request anyone can send, so the server checks that it really comes from the service: the service signs the body with a secret you share, and you compute the same signature and compare. std/crypto has the pieces: hmac, and timingSafeEqual to compare without leaking how much of a guess was right.

The signature ​

Stripe sends Stripe-Signature: t=1794744000,v1=5257a8…: an HMAC-SHA256 of "<t>.<body>" with the endpoint's secret, in hex. GitHub's X-Hub-Signature-256: sha256=… is the same idea over the body alone.

lib/server/webhooks.weft
weft
import { hmac, timingSafeEqual } from "std/crypto"
import { parseNumber } from "std/math"
import * as Math from "std/math"

/// Whether `payload` (the body exactly as received) is signed by `secret`, and recent (Stripe's
/// tolerance is five minutes, against replays).
export fn fromStripe(payload: string, header: string, secret: string, nowSeconds: number): boolean {
  let mut t = ""
  let mut signatures: string[] = []
  for part of header.split(",") {
    if part.startsWith("t=") { t = part.slice(2) }
    if part.startsWith("v1=") { signatures.push(part.slice(3)) }
  }
  let sent = try parseNumber(t) else -1
  if sent < 0 || Math.abs(nowSeconds - sent) > 300 { return false }
  let expected = hmac("sha256", secret, `${t}.${payload}`).toHex()
  return signatures.some(s => timingSafeEqual(s, expected))
}

/// GitHub's `X-Hub-Signature-256: sha256=<hex>`.
export fn fromGitHub(payload: string, header: string, secret: string): boolean {
  return timingSafeEqual(header, `sha256=${hmac("sha256", secret, payload).toHex()}`)
}

Compare with timingSafeEqual, never ==: == stops at the first different character, and the time that takes tells an attacker how many leading characters of a forged signature were right.

The endpoint ​

routes/api/stripe/server.weft
weft
import { json, status } from "std/http"
import type { Request, Response } from "std/http"
import { env } from "std/process"
import { now } from "std/time"
import { log } from "std/log"
import { fromStripe } from "lib/server/webhooks"

export async fn POST(req: Request): Response {
  let secret = env("STRIPE_WEBHOOK_SECRET") ?? ""
  let signature = req.headers.get("stripe-signature") ?? ""
  if !fromStripe(req.text(), signature, secret, now().epochMs / 1000) {
    return status(400, "bad signature")
  }
  let event = try req.json()
  log(`stripe: ${event.type}`)
  return json({ received: true })
}

Verify the body as it arrived (req.text()), before parsing: JSON parsed and written again isn't the same bytes. Answer quickly with a 2xx and do slow work afterwards; Stripe retries what fails.

Signed tokens ​

The same module signs and checks JSON Web Tokens, for an API's own tokens or ones from an identity provider:

lib/server/tokens.weft
weft
import { jwt } from "std/crypto"
import type { JwtError, KeyError } from "std/crypto"
import * as json from "std/json"

let secret = "a long random secret from the environment"

/// A token for `user`, valid for an hour.
export fn issue(user: string): string ! JwtError | KeyError {
  let claims = try json.parse(`{"sub":${json.stringify(user)}}`) else null
  return try jwt.sign(claims, "HS256", secret, { expiresIn: 3600, issuer: "api" })
}

/// The user a token is for; it fails with `JwtError` (its `reason`: `signature`, `expired`,
/// `issuer`, …) for one that is forged, expired or not ours.
export fn userOf(token: string): string ! JwtError | KeyError {
  let claims = try jwt.verify(token, "HS256", secret, { issuer: "api" })
  return `${claims.sub}`
}

jwt.verify takes the algorithm from you, not from the token, so a token can't choose a weaker one (or none). For RS256 or ES256 tokens from a provider, pass its public key as PEM or a JWK from its JWKS. The reference is std/crypto.

Weft is in development. The reference is the spec as it stands today.