// Receiving Stripe and GitHub webhooks, refusing any that were not signed with the secret.
//
//   quillo run webhooks.qwe      then open http://localhost:8080/selftest
//
// Point Stripe at POST /hooks/stripe and GitHub at POST /hooks/github.

use "webhooks.qwer"

let STRIPE_SECRET = env("STRIPE_WEBHOOK_SECRET") ?? "whsec_test_quillo"
let GITHUB_SECRET = env("GITHUB_WEBHOOK_SECRET") ?? "quillo-github-secret"

route POST /hooks/stripe {
    let ok = webhook_verify("stripe", request.body, request.headers, STRIPE_SECRET, 300)
    if is_err(ok) { reply 400 ok.error }
    { received: request.json.type }
}

route POST /hooks/github {
    let ok = webhook_verify("github", request.body, request.headers, GITHUB_SECRET, 0)
    if is_err(ok) { reply 401 ok.error }
    { received: request.headers["x-github-event"] ?? "ping" }
}

// What a sender's signature looks like, and the checks on it.
route GET /selftest {
    let body = json.stringify({ type: "invoice.paid", data: { id: "in_42" } })
    let stripe = webhook_sign("stripe", body, STRIPE_SECRET, 0, "")?
    let old = webhook_sign("stripe", body, STRIPE_SECRET, int(now() / 1000) - 3600, "")?
    // GitHub's header is HMAC-SHA256 in hex: Quillo's own crypto.hmac makes the same one.
    let github = { "x-hub-signature-256": `sha256=${crypto.hmac(GITHUB_SECRET, body)}` }
    {
        stripe: webhook_verify("stripe", body, stripe, STRIPE_SECRET, 300)?,
        stripe_changed_body: webhook_verify("stripe", replace(body, "42", "43"), stripe, STRIPE_SECRET, 300).error,
        stripe_replayed: webhook_verify("stripe", body, old, STRIPE_SECRET, 300).error,
        github: webhook_verify("github", body, github, GITHUB_SECRET, 0)?,
        shopify: webhook_verify("shopify", body, webhook_sign("shopify", body, "shpss_1", 0, "")?, "shpss_1", 0)?,
    }
}
