also looking at this
feat(billing): issue the license from Stripe, not only from the thank-you page
#49
9 files
+439
-2
| @@ -0,0 +1,155 @@ | ||
| 1 | import type { LicenseRecord } from './licenses' | |
| 2 | import process from 'node:process' | |
| 3 | ||
| 4 | /** | |
| 5 | * The Stripe webhook that issues a license when the thank-you page does not. | |
| 6 | * | |
| 7 | * Until this existed, `issue()` had exactly one caller: rendering | |
| 8 | * `/thanks?session_id=...`, which is checkout's `success_url`. So the redirect | |
| 9 | * after payment was the only event in the system that ever created a license, | |
| 10 | * and a buyer who closed the tab, lost the network at that moment, or paid by | |
| 11 | * a method that settles after the redirect, was charged and got nothing. There | |
| 12 | * was no resend path and no way for them to ask (#48). | |
| 13 | * | |
| 14 | * Nothing about issuing is reimplemented here. `issue()` is idempotent by | |
| 15 | * construction: it returns the existing row for a session it has already seen, | |
| 16 | * and only emails a key for one created just now. So the webhook and the page | |
| 17 | * can arrive in either order, or twice, and the buyer ends up with one license | |
| 18 | * and one email. | |
| 19 | */ | |
| 20 | ||
| 21 | /** The events that mean a checkout is paid for and a license is owed. */ | |
| 22 | const ISSUING_EVENTS = new Set([ | |
| 23 | 'checkout.session.completed', | |
| 24 | // Payment methods that settle after the redirect. Stripe sends `completed` | |
| 25 | // first, while `payment_status` is still unpaid, and this once it clears. | |
| 26 | 'checkout.session.async_payment_succeeded', | |
| 27 | ]) | |
| 28 | ||
| 29 | export type WebhookOutcome = | |
| 30 | /** There is a license for this checkout, issued now or already there. */ | |
| 31 | | { kind: 'licensed', key: string } | |
| 32 | /** Verified, and there is nothing to issue: another event, or not paid yet. */ | |
| 33 | | { kind: 'ignored', reason: string } | |
| 34 | /** Not from Stripe, or not signed with this endpoint's secret. */ | |
| 35 | | { kind: 'rejected', reason: string } | |
| 36 | /** No signing secret, so nothing can be verified. Never issue on this. */ | |
| 37 | | { kind: 'unconfigured' } | |
| 38 | /** Verified, and it should have worked. Stripe retries a 500. */ | |
| 39 | | { kind: 'failed', error: string } | |
| 40 | ||
| 41 | export interface WebhookDeps { | |
| 42 | secret: string | |
| 43 | issue: (sessionId: string) => Promise<LicenseRecord | null> | |
| 44 | /** Seconds of clock skew allowed between Stripe and this server. */ | |
| 45 | tolerance?: number | |
| 46 | } | |
| 47 | ||
| 48 | export function webhookSecret(env = process.env): string { | |
| 49 | return (env.STRIPE_WEBHOOK_SECRET ?? '').trim() | |
| 50 | } | |
| 51 | ||
| 52 | /** | |
| 53 | * What to do with one delivery. `raw` must be the bytes Stripe sent: the | |
| 54 | * signature is over those, and a re-serialized JSON body will not match. | |
| 55 | */ | |
| 56 | export async function receiveWebhook(raw: string | null, signature: string | null, deps: WebhookDeps): Promise<WebhookOutcome> { | |
| 57 | if (!deps.secret) | |
| 58 | return { kind: 'unconfigured' } | |
| 59 | if (!raw) | |
| 60 | // The router hands the action `rawBody()`; without it there is nothing to | |
| 61 | // verify, and issuing on an unverified body is worse than not issuing. | |
| 62 | return { kind: 'rejected', reason: 'No request body to verify.' } | |
| 63 | if (!signature) | |
| 64 | return { kind: 'rejected', reason: 'No Stripe-Signature header.' } | |
| 65 | ||
| 66 | try { | |
| 67 | // `@stacksjs/security` rather than the payments package's `constructEvent`: | |
| 68 | // this one is a plain HMAC check with no Stripe client behind it, so it | |
| 69 | // cannot hit the SubtleCrypto trap that made the SDK path 401 every real | |
| 70 | // delivery on Bun (stacksjs/stacks#2355). | |
| 71 | const { verifyStripe } = await import('@stacksjs/security') | |
| 72 | verifyStripe(deps.secret, signature, raw, deps.tolerance === undefined ? undefined : { toleranceSeconds: deps.tolerance }) | |
| 73 | } | |
| 74 | catch (error) { | |
| 75 | return { kind: 'rejected', reason: message(error) } | |
| 76 | } | |
| 77 | ||
| 78 | const event = parse(raw) | |
| 79 | if (!event) | |
| 80 | return { kind: 'rejected', reason: 'Signed, but the body is not a Stripe event.' } | |
| 81 | if (!ISSUING_EVENTS.has(event.type)) | |
| 82 | return { kind: 'ignored', reason: `Nothing to do for ${event.type}.` } | |
| 83 | ||
| 84 | const session = event.data?.object | |
| 85 | if (session?.object !== 'checkout.session' || typeof session.id !== 'string') | |
| 86 | return { kind: 'rejected', reason: `${event.type} carried no checkout session.` } | |
| 87 | ||
| 88 | try { | |
| 89 | const license = await deps.issue(session.id) | |
| 90 | // Null is Stripe saying the session is not paid, or naming a plan this | |
| 91 | // build does not have. Neither improves by being retried: for the first, | |
| 92 | // `async_payment_succeeded` is already on its way. | |
| 93 | return license | |
| 94 | ? { kind: 'licensed', key: license.key } | |
| 95 | : { kind: 'ignored', reason: `${session.id} is not a paid checkout for a plan Uplink sells.` } | |
| 96 | } | |
| 97 | catch (error) { | |
| 98 | // A database or Stripe failure, which a retry may well fix, and the | |
| 99 | // purchase is real either way. | |
| 100 | return { kind: 'failed', error: message(error) } | |
| 101 | } | |
| 102 | } | |
| 103 | ||
| 104 | /** | |
| 105 | * Stripe retries anything that is not a 2xx, so the code says whether trying | |
| 106 | * again could help. A bad signature never improves; a database that was down | |
| 107 | * might. | |
| 108 | */ | |
| 109 | export function statusFor(outcome: WebhookOutcome): 200 | 400 | 500 { | |
| 110 | switch (outcome.kind) { | |
| 111 | case 'licensed': | |
| 112 | case 'ignored': | |
| 113 | return 200 | |
| 114 | case 'rejected': | |
| 115 | return 400 | |
| 116 | case 'unconfigured': | |
| 117 | case 'failed': | |
| 118 | return 500 | |
| 119 | } | |
| 120 | } | |
| 121 | ||
| 122 | /** What to send back. Never the license key: this answers Stripe, not a buyer. */ | |
| 123 | export function bodyFor(outcome: WebhookOutcome): Record<string, unknown> { | |
| 124 | switch (outcome.kind) { | |
| 125 | case 'licensed': | |
| 126 | return { received: true, licensed: true } | |
| 127 | case 'ignored': | |
| 128 | return { received: true, licensed: false, reason: outcome.reason } | |
| 129 | case 'rejected': | |
| 130 | return { error: outcome.reason } | |
| 131 | case 'unconfigured': | |
| 132 | return { error: 'This server has no Stripe webhook secret, so it cannot verify deliveries.' } | |
| 133 | case 'failed': | |
| 134 | return { error: outcome.error } | |
| 135 | } | |
| 136 | } | |
| 137 | ||
| 138 | interface StripeEvent { | |
| 139 | type: string | |
| 140 | data?: { object?: Record<string, any> } | |
| 141 | } | |
| 142 | ||
| 143 | function parse(raw: string): StripeEvent | null { | |
| 144 | try { | |
| 145 | const body = JSON.parse(raw) as StripeEvent | |
| 146 | return body && typeof body.type === 'string' ? body : null | |
| 147 | } | |
| 148 | catch { | |
| 149 | return null | |
| 150 | } | |
| 151 | } | |
| 152 | ||
| 153 | function message(error: unknown): string { | |
| 154 | return error instanceof Error ? error.message : String(error) | |
| 155 | } | |