// Webhook events: checking that one really came from Stripe. import { parse } from "std/json" import { floor } from "std/math" import { now } from "std/time" import { constantTimeEqual, hmacSha256 } from "./lib/sha256" /// An event Stripe sent. `data.object` is the object it is about: cast it with `as`, to the type of the event. /// `account` is the connected account it happened on, for Connect endpoints. export type Event = { id: string, type: string, created: float, livemode: boolean?, api_version: string?, account: string?, pending_webhooks: float?, data: { object: json, previous_attributes: json }, } /// Why an event was refused. Answer any of them with a 400. export type WebhookError = | MissingSignature | MalformedSignature { header: string } | SignatureMismatch | TimestampOutOfTolerance { age: float } | MalformedPayload { message: string } /// `tolerance` (300) is how old an event may be, in seconds, against replays; `0` turns the check off. `now` is the time in /// seconds since the epoch (the clock's). export type VerifyOptions = { tolerance?: float, now?: float } fn bytesOf(payload: Bytes | string): Bytes { return payload is string ? Bytes.fromUtf8(payload) : payload } fn signatureOver(payload: Bytes, secret: string, timestamp: float): Bytes { return hmacSha256(Bytes.fromUtf8(secret), Bytes.fromUtf8(`${timestamp}.`).concat(payload)) } /// Checks the `stripe-signature` header against the raw request body, and gives the event. Pass the body exactly as it /// arrived: parsing and re-encoding it changes the bytes the signature covers. /// /// ```weft /// import { verify } from "@weft/stripe/webhooks" /// /// let router = http.router().post("/stripe/webhook", async req => { /// let event, err = try verify(req.body, req.headers.get("stripe-signature") ?? "", secret) /// if err != null { /// return http.status(400) /// } /// if event.type == "checkout.session.completed" { /// let session = try event.data.object as Session /// } /// return http.json({ received: true }) /// }) /// ``` export fn verify( payload: Bytes | string, header: string, secret: string, options: VerifyOptions = {}, ): Event ! WebhookError { if header == "" { fail MissingSignature } let mut timestamp: float? = null let mut signatures: Bytes[] = [] for part of header.split(",") { let at = part.indexOf("=") let name = part.slice(0, at < 0 ? 0 : at).trim() let value = part.slice(at + 1).trim() if name == "t" { timestamp = try float(value) else null } else if name == "v1" { let decoded = try Bytes.fromHex(value) else null if decoded != null { signatures.push(decoded) } } } if timestamp == null || signatures.length == 0 { fail MalformedSignature { header } } let body = bytesOf(payload) let expected = signatureOver(body, secret, timestamp) // Every signature is compared, so the time taken doesn't say which one matched. let mut matched = false for signature of signatures { matched = constantTimeEqual(expected, signature) || matched } if !matched { fail SignatureMismatch } let tolerance = options.tolerance ?? 300 let current = options.now ?? floor(now().epochMs / 1000) let age = current - timestamp if tolerance > 0 && age > tolerance { fail TimestampOutOfTolerance { age } } let parsed, bad = try parse(body.toUtf8()) if bad != null { fail MalformedPayload { message: bad.message } } let event, wrong = try parsed as Event if wrong != null { fail MalformedPayload { message: `${wrong.path} isn't ${wrong.expected}` } } return event } /// A `stripe-signature` header for `payload`, for tests of your own webhook handler. export fn signature(payload: Bytes | string, secret: string, timestamp: float): string { return `t=${timestamp},v1=${signatureOver(bytesOf(payload), secret, timestamp).toHex()}` }