From b669297d68d747e914e09e8c8442fd594862191b Mon Sep 17 00:00:00 2001 From: Ned Twigg Date: Sat, 28 Nov 2026 10:09:55 -0800 Subject: [PATCH 1/2] Accept Stripe webhooks across one API major release verifyWebhook accepted only the installed SDK's exact STRIPE_API_VERSION, so every stripe minor release, which moves that version a month, was a webhook endpoint cut-over. Stripe's monthly versions within a major release add fields and break none, so it now accepts every version of the endive major release from 2026-10-28.endive (stripe 23.1, the bottom of the peer range) on. stripe minors and patches become routine updates. EARLIEST_STRIPE_API_VERSION and acceptsStripeApiVersion are exported so an application can test its endpoint's version. SECURITY.md gains the rule and its pinning test; BILLING.md, the package README, the changelog and the Renovate policy say that only a stripe major moves an endpoint. Co-Authored-By: Claude Opus 5.5 --- .github/renovate.json | 7 +++++ BILLING.md | 12 +++++--- CHANGELOG.md | 1 + SECURITY.md | 5 ++-- packages/stripe/README.md | 4 +-- packages/stripe/src/index.ts | 24 +++++++++++++++- tests/integration/billing.test.ts | 18 ++++++++++++ tests/unit/stripe-api-version.test.ts | 41 +++++++++++++++++++++++++++ 8 files changed, 103 insertions(+), 9 deletions(-) create mode 100644 tests/unit/stripe-api-version.test.ts diff --git a/.github/renovate.json b/.github/renovate.json index 8ecb752..3b96bdc 100644 --- a/.github/renovate.json +++ b/.github/renovate.json @@ -75,6 +75,13 @@ "ignoreUnstable": false, "respectLatest": false }, + { + "description": "A stripe minor or patch only moves the SDK within a Stripe API major release, whose webhooks verifyWebhook already accepts, so it is routine. A stripe major follows a new major release: tests/unit/stripe-api-version.test.ts fails until EARLIEST_STRIPE_API_VERSION moves in the same PR, a breaking change for every application's webhook endpoint (BILLING.md -> Moving to a new Stripe API version)", + "matchManagers": ["npm"], + "matchPackageNames": ["stripe"], + "matchUpdateTypes": ["major"], + "dependencyDashboardApproval": true + }, { "matchManagers": ["npm"], "matchUpdateTypes": ["patch"], diff --git a/BILLING.md b/BILLING.md index d356c30..d5e9b0c 100644 --- a/BILLING.md +++ b/BILLING.md @@ -101,7 +101,7 @@ pgstencil reads subscriptions, not invoices, charges or refunds. A refund alone Create the product and one recurring Price per configured Price ID in the appropriate Stripe account. Configure the customer portal for payment-method updates, invoices and cancellation at period end. If you enable plan switching in the portal, explicitly choose and test its proration/effective-date behavior in your Stripe sandbox; the package does not silently choose that policy for you. Restrict the portal to the application's allowlisted prices. -Configure a webhook endpoint with the exact `STRIPE_API_VERSION` exported by the installed SDK: `2026-10-28.endive` for `stripe` 23.1. In the Dashboard choose that API version when adding the endpoint, or create it with `stripe.webhookEndpoints.create({ url, enabled_events, api_version: STRIPE_API_VERSION })`. Stripe cannot change an existing endpoint's version, so another version means another endpoint, with its own signing secret; see [Moving to a new Stripe API version](#moving-to-a-new-stripe-api-version). Send `customer.subscription.*`, `checkout.session.*`, and `invoice.*` events to your adapter, and `charge.dispute.*` when the application acts on disputes. The example endpoint is `POST /api/stripe/webhook`. Preserve the raw body, forward `Stripe-Signature`, enforce a body limit, and return 2xx only after `billing.webhook()` completes. The SDK checks signatures and a 300-second tolerance between the delivery's signed timestamp and the injected clock. Stripe signs each delivery attempt when it sends it, so a retry hours later verifies, and the event ledger makes it a no-op once processed; a captured delivery replayed later does not verify; the service also rejects unexpected API versions, test/live modes and Connect account events. Stripe Connect is outside this package's scope. +Configure a webhook endpoint at an API version `verifyWebhook` accepts: the `endive` major release, from `EARLIEST_STRIPE_API_VERSION` (`2026-10-28.endive`) on. The installed SDK's `STRIPE_API_VERSION` is always one, so the simplest choice is `stripe.webhookEndpoints.create({ url, enabled_events, api_version: STRIPE_API_VERSION })`, or that version in the Dashboard; `acceptsStripeApiVersion(version)` tells an application whether an existing endpoint's version is accepted. Stripe cannot change an existing endpoint's version, so another version means another endpoint, with its own signing secret; see [Moving to a new Stripe API version](#moving-to-a-new-stripe-api-version). Send `customer.subscription.*`, `checkout.session.*`, and `invoice.*` events to your adapter, and `charge.dispute.*` when the application acts on disputes. The example endpoint is `POST /api/stripe/webhook`. Preserve the raw body, forward `Stripe-Signature`, enforce a body limit, and return 2xx only after `billing.webhook()` completes. The SDK checks signatures and a 300-second tolerance between the delivery's signed timestamp and the injected clock. Stripe signs each delivery attempt when it sends it, so a retry hours later verifies, and the event ledger makes it a no-op once processed; a captured delivery replayed later does not verify; the service also rejects unexpected API versions, test/live modes and Connect account events. Stripe Connect is outside this package's scope. An application that reads an event before processing it calls `verifyWebhook(body, signature)` once and passes the returned event to `webhook(event, apply)`; `webhook` accepts only an event that `verifyWebhook` on the same `Billing` returned, never a parsed body. @@ -117,11 +117,15 @@ Customer and Checkout creation save their idempotency keys before calling Stripe > Not yet exercised end to end. These steps follow from the code and the SDK; no deployment has run them against Stripe. -`STRIPE_API_VERSION` is the pinned version of the `stripe` SDK the application installs, and every SDK minor release moves it: 23.0 pins `2026-09-30.endive`, 23.1 `2026-10-28.endive`. `verifyWebhook` refuses an event at any other version, so any SDK update that changes `STRIPE_API_VERSION` is a cut-over, not a routine bump. Pin `stripe` with `~` or an exact version so it changes only through these steps: +Stripe releases an API version every month and a major release, named after the dot, twice a year. Only a major release breaks compatibility: within one, a later version adds fields and changes none ([Stripe's versioning](https://docs.stripe.com/api/versioning)). Each `stripe` minor release pins the month's version, so `STRIPE_API_VERSION` moves with it: 23.0 pins `2026-09-30.endive`, 23.1 `2026-10-28.endive`, 23.2 `2026-11-18.endive`. -1. Read the SDK changelog and Stripe's API changelog for every version in between, then run the application's tests against StripeDev with the new SDK. StripeDev always signs events at the installed SDK's version, so it cannot show an endpoint mismatch. +`verifyWebhook` accepts every version of the `endive` major release from `EARLIEST_STRIPE_API_VERSION` (`2026-10-28.endive`) on, whatever the installed SDK pins. A `stripe` minor or patch release is therefore a routine update: the requests the SDK sends move to the new month's version, which breaks nothing, and the webhook endpoint stays where it is. Keep `stripe` current within its major for its fixes. + +An endpoint moves only when a pgstencil release moves to another major release or raises `EARLIEST_STRIPE_API_VERSION` above the endpoint's version, which its changelog records as a breaking change. An application may also move an endpoint to a later version of the same major release whenever it likes, for fields pgstencil does not read. For either move: + +1. Read the SDK changelog and Stripe's API changelog for every version in between, then run the application's tests against StripeDev with the new SDK. StripeDev signs events at the installed SDK's version, so check the endpoint's version with `acceptsStripeApiVersion` as well. 2. Before the first instance of the new release starts, create a second webhook endpoint at the new version, for the same events, preferably at a URL path only the new release serves. Give the new release that endpoint's signing secret as `webhookSecret`. -3. Deploy. Each event created from now on reaches both endpoints with the same event ID. An instance verifies only its own endpoint's deliveries, at its own version, and answers 400 to the other's, which Stripe retries. The `events` ledger applies each event once, whichever copy lands first, and `apply` sees the payload at the version of the release that applied it. +3. Deploy. Each event created from now on reaches both endpoints with the same event ID. An instance verifies only its own endpoint's deliveries, by their signing secret, and answers 400 to the other's, which Stripe retries. The `events` ledger applies each event once, whichever copy lands first, and `apply` sees the payload at the version of the release that applied it. 4. An event created before step 2 reaches only the old endpoint, so let the old endpoint drain its pending deliveries before the last old instance stops; creating the new endpoint well before the deploy leaves little to drain. After that, disable the old endpoint: its remaining deliveries, which new instances refuse, duplicate the new endpoint's. 5. Reconcile every billing owner once with `reconcileAll()`, to repair anything a refused or abandoned delivery left behind; each owner it reports changed is an event that was lost. `reconcileStale` alone does not cover it (see [Access in SQL](#access-in-sql)). diff --git a/CHANGELOG.md b/CHANGELOG.md index a100473..1e631a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ The three packages (`pgstencil`, `@pgstencil/auth`, `@pgstencil/stripe`) share o ### Changed +- **`@pgstencil/stripe`: `verifyWebhook` accepts every Stripe API version of the `endive` major release from `2026-10-28.endive` on**, where it accepted only the installed SDK's exact `STRIPE_API_VERSION`. Stripe's monthly versions within a major release add fields and break none, so a `stripe` minor or patch release is now a routine update: the webhook endpoint stays at its version, and no endpoint cut-over is needed. Nothing an application relied on is refused. The new exports `EARLIEST_STRIPE_API_VERSION` and `acceptsStripeApiVersion(version)` say what is accepted, so an application can check its endpoint's version in a test instead of pinning `stripe` with `~`; it can loosen that pin to `^23.1.0` and take `stripe` minor releases again. An endpoint moves only when a release changes the major release or raises `EARLIEST_STRIPE_API_VERSION`, which this changelog will record as breaking ([BILLING.md](BILLING.md#moving-to-a-new-stripe-api-version)). - **`@pgstencil/auth` moves its exact Better Auth pin from 1.7.18 to 1.7.28**, which changes an application's lockfile and any dependency disclosure it publishes. Better Auth's own fixes in that range change what an application can observe: sending a new email OTP replaces the earlier code for that address instead of keeping it; deleting a user, `/revoke-session` and revoking all of a user's sessions now answer an error, `FAILED_TO_DELETE_USER` for a delete, where they reported success while the row or the cached sessions survived; and `user.delete.before` runs before the session and account deletes. An application that hooks user deletion or revokes sessions should check that it handles the new errors. Better Auth draws its random IDs in a different order, so an application that snapshots IDs under a seeded `RandomSource` sees them change once. ## 0.5.1 (2026-11-10) diff --git a/SECURITY.md b/SECURITY.md index 510d9d7..44f4578 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -69,7 +69,8 @@ Pinned by `integration/better-auth-workers.test.ts`: `normal Workers build uses ## Stripe webhooks -- **FAIL IF** `verifyWebhook` parses the body before `constructEventAsync` checks its signature against `webhookSecret`, passes a tolerance other than 300 seconds or a clock other than the injected `Time`, or returns an event whose `livemode` differs from `live`, whose `api_version` is not `STRIPE_API_VERSION`, or that carries a Connect `account`; or a refusal is anything but a `BillingError` with status 400, raised before `webhook` touches the ledger; inspect `verifyWebhook` and `webhook`. +- **FAIL IF** `verifyWebhook` parses the body before `constructEventAsync` checks its signature against `webhookSecret`, passes a tolerance other than 300 seconds or a clock other than the injected `Time`, or returns an event whose `livemode` differs from `live`, whose `api_version` `acceptsStripeApiVersion` refuses, or that carries a Connect `account`; or a refusal is anything but a `BillingError` with status 400, raised before `webhook` touches the ledger; inspect `verifyWebhook` and `webhook`. +- **FAIL IF** `acceptsStripeApiVersion` accepts anything but a string of the form `YYYY-MM-DD.release` whose release is `EARLIEST_STRIPE_API_VERSION`'s and whose date is on or after it, or the installed `stripe` SDK's `STRIPE_API_VERSION` falls outside what it accepts; or the package reads an event field that `EARLIEST_STRIPE_API_VERSION` does not render; inspect `acceptsStripeApiVersion` and the event fields `webhook` and `completedCheckout` read. - **FAIL IF** `webhook(event)` accepts an object that this same `Billing` instance's `verifyWebhook` did not return — a parsed body, a copy, or an event another instance verified; inspect `verified` in `webhook`. - **FAIL IF** the ledger row, the owner's resync and `apply` do not share one transaction that marks the event processed only after `apply` returns; an event whose ledger row is already processed reaches the resync or `apply` again; concurrent deliveries of one event are not serialized on that row; or a failure — upstream, database or `apply` — commits any billing or application write instead of leaving the event recorded `failed` and unprocessed for a retry; inspect `webhook`. - **FAIL IF** `pruneEvents` deletes an event that was never processed or is marked `failed`, deletes one processed within the retention it was given, measures that retention by anything but the injected `Time`, or accepts a retention under 30 days; inspect `pruneEvents`. @@ -77,7 +78,7 @@ Pinned by `integration/better-auth-workers.test.ts`: `normal Workers build uses - **FAIL IF** `completedCheckout` reports a Checkout other than a stored operation whose ID and session ID both match the event's and whose owner is the session's `client_reference_id`, or reports fields other than that stored operation's; inspect `completedCheckout`. - **FAIL IF** a `billing.webhook.*` diagnostic names a `stripeEventId` from a delivery that failed verification, or carries anything beyond what `diagnostic` and `diagnosticError` in `packages/pgstencil/src/diagnostics.ts` allow — never the body, the `Stripe-Signature` header, the webhook secret, or the message of a Stripe, database or `apply` error; inspect `webhook`. -Pinned by `integration/billing.test.ts`: `checkout ownership, card policy, signatures, mode and API version are enforced`, `pruneEvents deletes only events processed before the retention window`, `the five-minute tolerance reads the delivery signature: a retry signed hours later applies once, an old signature never`, `application fulfillment and the webhook ledger share one transaction`, `duplicate and out-of-order webhooks reconcile authoritative state exactly once`, `an upstream outage rolls back entitlement changes and a failed event can retry`, `a deleted webhook racing end() waits on the owner lock and reads its reason`, `owner and customer lookups, dispute owners through their charge, and an already-verified event`, `a checkout ref is validated, kept across retries, and read back from the completion event`, `payment diagnostics keep verified event IDs and report failure before recovery without payloads`; `integration/billing-security.test.ts`: `webhook(event) takes only an event this Billing verified, and a rejected delivery reaches neither the ledger nor apply`, `concurrent deliveries of one event run apply once and record one attempt`, `event content never grants access: the resync reads Stripe, and context and completions are matched to the owner`, `webhook diagnostics name an event only once it verifies, and never carry a body, signature, secret or message`; `integration/billing-workers.test.ts`: `Billing in workerd: fetch client, Web Crypto webhooks, founding offer and purchase counts`. +Pinned by `unit/stripe-api-version.test.ts`: `webhook API versions: one major release, from the earliest version on, and the installed SDK inside it`; `integration/billing.test.ts`: `checkout ownership, card policy, signatures, mode and API version are enforced`, `pruneEvents deletes only events processed before the retention window`, `the five-minute tolerance reads the delivery signature: a retry signed hours later applies once, an old signature never`, `application fulfillment and the webhook ledger share one transaction`, `duplicate and out-of-order webhooks reconcile authoritative state exactly once`, `an upstream outage rolls back entitlement changes and a failed event can retry`, `a deleted webhook racing end() waits on the owner lock and reads its reason`, `owner and customer lookups, dispute owners through their charge, and an already-verified event`, `a checkout ref is validated, kept across retries, and read back from the completion event`, `payment diagnostics keep verified event IDs and report failure before recovery without payloads`; `integration/billing-security.test.ts`: `webhook(event) takes only an event this Billing verified, and a rejected delivery reaches neither the ledger nor apply`, `concurrent deliveries of one event run apply once and record one attempt`, `event content never grants access: the resync reads Stripe, and context and completions are matched to the owner`, `webhook diagnostics name an event only once it verifies, and never carry a body, signature, secret or message`; `integration/billing-workers.test.ts`: `Billing in workerd: fetch client, Web Crypto webhooks, founding offer and purchase counts`. ## Checkout diff --git a/packages/stripe/README.md b/packages/stripe/README.md index 0507b56..cd81e68 100644 --- a/packages/stripe/README.md +++ b/packages/stripe/README.md @@ -5,9 +5,9 @@ Stripe SaaS subscriptions with named plans, optional card-required trials, durab > **Built for our own applications.** pgstencil is developed alongside DiffPlug's products and published so they can share it. It is 0.x: a minor release may break compatibility, and there is no support promise. ```sh -pnpm add @pgstencil/stripe pgstencil kysely stripe@~23.1.0 +pnpm add @pgstencil/stripe pgstencil kysely stripe@^23.1.0 ``` The packages after the first are peer dependencies: your application owns their versions and shares one copy with pgstencil. See [PACKAGES.md](https://github.com/diffplug/pgstencil/blob/main/PACKAGES.md) for usage and the dependency policy, and [SECURITY.md](https://github.com/diffplug/pgstencil/blob/main/SECURITY.md) for the audited security rules. Source: [diffplug/pgstencil](https://github.com/diffplug/pgstencil). -It peers on `stripe` 23. `STRIPE_API_VERSION`, which webhooks must match, is the installed SDK's pinned API version (`2026-10-28.endive` for 23.1) and moves with every SDK minor release, so pin `stripe` with `~` and follow [Moving to a new Stripe API version](https://github.com/diffplug/pgstencil/blob/main/BILLING.md#moving-to-a-new-stripe-api-version) to change it. +It peers on `stripe` 23. Webhooks are accepted at any version of Stripe's `endive` major release from `EARLIEST_STRIPE_API_VERSION` (`2026-10-28.endive`) on, so a `stripe` minor or patch release, which moves the SDK's own `STRIPE_API_VERSION` within that release, is a routine update and the webhook endpoint stays where it is. See [Moving to a new Stripe API version](https://github.com/diffplug/pgstencil/blob/main/BILLING.md#moving-to-a-new-stripe-api-version) for when an endpoint must move. diff --git a/packages/stripe/src/index.ts b/packages/stripe/src/index.ts index 636f504..bebe17b 100644 --- a/packages/stripe/src/index.ts +++ b/packages/stripe/src/index.ts @@ -5,7 +5,29 @@ import { token, type Time, type RandomSource } from 'pgstencil'; import type { BillingDB } from './db.ts'; export type { BillingDB } from './db.ts'; export { Stripe }; +/** The API version the installed `stripe` SDK sends its requests at. */ export const STRIPE_API_VERSION = Stripe.API_VERSION; +/** + * The earliest Stripe API version whose webhook events `verifyWebhook` + * accepts: the version `stripe` 23.1, the bottom of the peer range, pins. + * Stripe's monthly versions within one major release (the name after the + * dot) add fields without breaking any, so this package reads only fields + * this version already renders and accepts every later version of the same + * major release. Raising it, or moving to another major release, is a + * breaking change: an application's webhook endpoint must be at or above it. + */ +export const EARLIEST_STRIPE_API_VERSION = '2026-10-28.endive'; +const API_VERSION = /^(\d{4}-\d{2}-\d{2})\.([a-z]+)$/; +/** + * Whether `verifyWebhook` accepts an event rendered at `version`: the major + * release of `EARLIEST_STRIPE_API_VERSION`, dated on or after it. An + * application can check its webhook endpoint's version against it. + */ +export function acceptsStripeApiVersion(version: unknown): boolean { + const [, since, release] = API_VERSION.exec(EARLIEST_STRIPE_API_VERSION)!; + const match = typeof version === 'string' ? API_VERSION.exec(version) : null; + return !!match && match[2] === release && match[1]! >= since!; +} /** Several Stripe Prices for one plan, and the server-side choice of which one checkout offers. */ export interface PlanPrices { /** Every Price that grants this plan: the one offered now, earlier ones, and any later steps. */ @@ -1077,7 +1099,7 @@ export class Billing

{ } if ( event.livemode !== this.config.live || - event.api_version !== STRIPE_API_VERSION || + !acceptsStripeApiVersion(event.api_version) || event.account ) throw new BillingError('Unexpected Stripe event configuration.', 400); diff --git a/tests/integration/billing.test.ts b/tests/integration/billing.test.ts index 5625704..e4ec0f1 100644 --- a/tests/integration/billing.test.ts +++ b/tests/integration/billing.test.ts @@ -8,6 +8,7 @@ import { connectDatabase } from '../../packages/pgstencil/src/database.ts'; import { Billing, BillingError, + EARLIEST_STRIPE_API_VERSION, purchaseStanding, STRIPE_API_VERSION, SUBSCRIBED, @@ -414,6 +415,11 @@ billingTest( for (const invalid of [ { ...event, livemode: true }, { ...event, api_version: '2000-01-01' }, + // Before the earliest version, or in another major release. + { ...event, api_version: '2026-09-30.endive' }, + { ...event, api_version: '2026-10-28.dahlia' }, + { ...event, api_version: '2027-03-31.zinnia' }, + { ...event, api_version: null }, { ...event, account: 'acct_other' }, ]) { const s = f.dev.signed(invalid as typeof event); @@ -422,6 +428,18 @@ billingTest( ); } expect(event.api_version).toBe(STRIPE_API_VERSION); + // An endpoint at any version of the major release from the earliest on + // verifies, whichever monthly version the installed SDK pins. + for (const version of [ + EARLIEST_STRIPE_API_VERSION, + '2026-12-16.endive', + STRIPE_API_VERSION, + ]) { + const s = f.dev.signed({ ...event, api_version: version }); + await expect( + f.billing.verifyWebhook(s.body, s.signature), + ).resolves.toMatchObject({ id: event.id, api_version: version }); + } f.time.advanceMilliseconds(301000); await expect( f.billing.webhook(signed.body, signed.signature), diff --git a/tests/unit/stripe-api-version.test.ts b/tests/unit/stripe-api-version.test.ts new file mode 100644 index 0000000..11594a8 --- /dev/null +++ b/tests/unit/stripe-api-version.test.ts @@ -0,0 +1,41 @@ +import { expect, test } from 'vitest'; +import { + acceptsStripeApiVersion, + EARLIEST_STRIPE_API_VERSION, + STRIPE_API_VERSION, +} from '../../packages/stripe/src/index.ts'; + +test('webhook API versions: one major release, from the earliest version on, and the installed SDK inside it', () => { + expect(EARLIEST_STRIPE_API_VERSION).toBe('2026-10-28.endive'); + for (const accepted of [ + '2026-10-28.endive', + '2026-10-29.endive', + '2026-11-18.endive', + '2027-02-24.endive', + ]) + expect(acceptsStripeApiVersion(accepted), accepted).toBe(true); + for (const refused of [ + '2026-10-27.endive', + '2026-09-30.endive', + '2026-08-26.dahlia', + '2026-11-18.dahlia', + '2027-03-31.zinnia', + '2026-11-18.Endive', + '2026-11-18.endive ', + ' 2026-11-18.endive', + '2026-11-18', + 'endive', + '2026-11-18.endive.extra', + '', + null, + undefined, + 20261118, + ]) + expect(acceptsStripeApiVersion(refused), String(refused)).toBe(false); + // A stripe SDK outside the accepted major release would refuse its own + // StripeDev events; moving the peer range to one is a deliberate change of + // EARLIEST_STRIPE_API_VERSION (BILLING.md, Moving to a new Stripe API version). + expect(acceptsStripeApiVersion(STRIPE_API_VERSION), STRIPE_API_VERSION).toBe( + true, + ); +}); From 4245d64de46f9dfeac77684d77034ab5e7ee7424 Mon Sep 17 00:00:00 2001 From: Ned Twigg Date: Sat, 28 Nov 2026 10:23:46 -0800 Subject: [PATCH 2/2] Check the Stripe API major release with endsWith The signature is verified before api_version is read, so the version string comes from Stripe and needs no format check, and Stripe says any version within a major release is safe. Replace EARLIEST_STRIPE_API_VERSION and acceptsStripeApiVersion with STRIPE_API_RELEASE = 'endive'. Co-Authored-By: Claude Opus 5.5 --- .github/renovate.json | 2 +- BILLING.md | 8 ++--- CHANGELOG.md | 2 +- SECURITY.md | 6 ++-- packages/stripe/README.md | 2 +- packages/stripe/src/index.ts | 26 ++++------------- tests/integration/billing.test.ts | 12 ++++---- tests/unit/stripe-api-version.test.ts | 42 +++++---------------------- 8 files changed, 28 insertions(+), 72 deletions(-) diff --git a/.github/renovate.json b/.github/renovate.json index 3b96bdc..7525a70 100644 --- a/.github/renovate.json +++ b/.github/renovate.json @@ -76,7 +76,7 @@ "respectLatest": false }, { - "description": "A stripe minor or patch only moves the SDK within a Stripe API major release, whose webhooks verifyWebhook already accepts, so it is routine. A stripe major follows a new major release: tests/unit/stripe-api-version.test.ts fails until EARLIEST_STRIPE_API_VERSION moves in the same PR, a breaking change for every application's webhook endpoint (BILLING.md -> Moving to a new Stripe API version)", + "description": "A stripe minor or patch only moves the SDK within a Stripe API major release, whose webhooks verifyWebhook already accepts, so it is routine. A stripe major follows a new major release: tests/unit/stripe-api-version.test.ts fails until STRIPE_API_RELEASE moves in the same PR, a breaking change for every application's webhook endpoint (BILLING.md -> Moving to a new Stripe API version)", "matchManagers": ["npm"], "matchPackageNames": ["stripe"], "matchUpdateTypes": ["major"], diff --git a/BILLING.md b/BILLING.md index d5e9b0c..f56a210 100644 --- a/BILLING.md +++ b/BILLING.md @@ -101,7 +101,7 @@ pgstencil reads subscriptions, not invoices, charges or refunds. A refund alone Create the product and one recurring Price per configured Price ID in the appropriate Stripe account. Configure the customer portal for payment-method updates, invoices and cancellation at period end. If you enable plan switching in the portal, explicitly choose and test its proration/effective-date behavior in your Stripe sandbox; the package does not silently choose that policy for you. Restrict the portal to the application's allowlisted prices. -Configure a webhook endpoint at an API version `verifyWebhook` accepts: the `endive` major release, from `EARLIEST_STRIPE_API_VERSION` (`2026-10-28.endive`) on. The installed SDK's `STRIPE_API_VERSION` is always one, so the simplest choice is `stripe.webhookEndpoints.create({ url, enabled_events, api_version: STRIPE_API_VERSION })`, or that version in the Dashboard; `acceptsStripeApiVersion(version)` tells an application whether an existing endpoint's version is accepted. Stripe cannot change an existing endpoint's version, so another version means another endpoint, with its own signing secret; see [Moving to a new Stripe API version](#moving-to-a-new-stripe-api-version). Send `customer.subscription.*`, `checkout.session.*`, and `invoice.*` events to your adapter, and `charge.dispute.*` when the application acts on disputes. The example endpoint is `POST /api/stripe/webhook`. Preserve the raw body, forward `Stripe-Signature`, enforce a body limit, and return 2xx only after `billing.webhook()` completes. The SDK checks signatures and a 300-second tolerance between the delivery's signed timestamp and the injected clock. Stripe signs each delivery attempt when it sends it, so a retry hours later verifies, and the event ledger makes it a no-op once processed; a captured delivery replayed later does not verify; the service also rejects unexpected API versions, test/live modes and Connect account events. Stripe Connect is outside this package's scope. +Configure a webhook endpoint at any API version of the `STRIPE_API_RELEASE` major release, `endive`, which `verifyWebhook` accepts. The installed SDK's `STRIPE_API_VERSION` is always one, so the simplest choice is `stripe.webhookEndpoints.create({ url, enabled_events, api_version: STRIPE_API_VERSION })`, or that version in the Dashboard. Stripe cannot change an existing endpoint's version, so another version means another endpoint, with its own signing secret; see [Moving to a new Stripe API version](#moving-to-a-new-stripe-api-version). Send `customer.subscription.*`, `checkout.session.*`, and `invoice.*` events to your adapter, and `charge.dispute.*` when the application acts on disputes. The example endpoint is `POST /api/stripe/webhook`. Preserve the raw body, forward `Stripe-Signature`, enforce a body limit, and return 2xx only after `billing.webhook()` completes. The SDK checks signatures and a 300-second tolerance between the delivery's signed timestamp and the injected clock. Stripe signs each delivery attempt when it sends it, so a retry hours later verifies, and the event ledger makes it a no-op once processed; a captured delivery replayed later does not verify; the service also rejects unexpected API versions, test/live modes and Connect account events. Stripe Connect is outside this package's scope. An application that reads an event before processing it calls `verifyWebhook(body, signature)` once and passes the returned event to `webhook(event, apply)`; `webhook` accepts only an event that `verifyWebhook` on the same `Billing` returned, never a parsed body. @@ -119,11 +119,11 @@ Customer and Checkout creation save their idempotency keys before calling Stripe Stripe releases an API version every month and a major release, named after the dot, twice a year. Only a major release breaks compatibility: within one, a later version adds fields and changes none ([Stripe's versioning](https://docs.stripe.com/api/versioning)). Each `stripe` minor release pins the month's version, so `STRIPE_API_VERSION` moves with it: 23.0 pins `2026-09-30.endive`, 23.1 `2026-10-28.endive`, 23.2 `2026-11-18.endive`. -`verifyWebhook` accepts every version of the `endive` major release from `EARLIEST_STRIPE_API_VERSION` (`2026-10-28.endive`) on, whatever the installed SDK pins. A `stripe` minor or patch release is therefore a routine update: the requests the SDK sends move to the new month's version, which breaks nothing, and the webhook endpoint stays where it is. Keep `stripe` current within its major for its fixes. +`verifyWebhook` accepts every version of the `STRIPE_API_RELEASE` major release, `endive`, whatever the installed SDK pins. A `stripe` minor or patch release is therefore a routine update: the requests the SDK sends move to the new month's version, which breaks nothing, and the webhook endpoint stays where it is. Keep `stripe` current within its major for its fixes. -An endpoint moves only when a pgstencil release moves to another major release or raises `EARLIEST_STRIPE_API_VERSION` above the endpoint's version, which its changelog records as a breaking change. An application may also move an endpoint to a later version of the same major release whenever it likes, for fields pgstencil does not read. For either move: +An endpoint moves only when a pgstencil release moves `STRIPE_API_RELEASE` to another major release, which its changelog records as a breaking change. An application may also move an endpoint to a later version of the same major release whenever it likes, for fields pgstencil does not read. For either move: -1. Read the SDK changelog and Stripe's API changelog for every version in between, then run the application's tests against StripeDev with the new SDK. StripeDev signs events at the installed SDK's version, so check the endpoint's version with `acceptsStripeApiVersion` as well. +1. Read the SDK changelog and Stripe's API changelog for every version in between, then run the application's tests against StripeDev with the new SDK. StripeDev signs events at the installed SDK's version, so also check that the endpoint's version ends in `.${STRIPE_API_RELEASE}`. 2. Before the first instance of the new release starts, create a second webhook endpoint at the new version, for the same events, preferably at a URL path only the new release serves. Give the new release that endpoint's signing secret as `webhookSecret`. 3. Deploy. Each event created from now on reaches both endpoints with the same event ID. An instance verifies only its own endpoint's deliveries, by their signing secret, and answers 400 to the other's, which Stripe retries. The `events` ledger applies each event once, whichever copy lands first, and `apply` sees the payload at the version of the release that applied it. 4. An event created before step 2 reaches only the old endpoint, so let the old endpoint drain its pending deliveries before the last old instance stops; creating the new endpoint well before the deploy leaves little to drain. After that, disable the old endpoint: its remaining deliveries, which new instances refuse, duplicate the new endpoint's. diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e631a7..3c550c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ The three packages (`pgstencil`, `@pgstencil/auth`, `@pgstencil/stripe`) share o ### Changed -- **`@pgstencil/stripe`: `verifyWebhook` accepts every Stripe API version of the `endive` major release from `2026-10-28.endive` on**, where it accepted only the installed SDK's exact `STRIPE_API_VERSION`. Stripe's monthly versions within a major release add fields and break none, so a `stripe` minor or patch release is now a routine update: the webhook endpoint stays at its version, and no endpoint cut-over is needed. Nothing an application relied on is refused. The new exports `EARLIEST_STRIPE_API_VERSION` and `acceptsStripeApiVersion(version)` say what is accepted, so an application can check its endpoint's version in a test instead of pinning `stripe` with `~`; it can loosen that pin to `^23.1.0` and take `stripe` minor releases again. An endpoint moves only when a release changes the major release or raises `EARLIEST_STRIPE_API_VERSION`, which this changelog will record as breaking ([BILLING.md](BILLING.md#moving-to-a-new-stripe-api-version)). +- **`@pgstencil/stripe`: `verifyWebhook` accepts every Stripe API version of the `endive` major release**, where it accepted only the installed SDK's exact `STRIPE_API_VERSION`. Stripe's monthly versions within a major release add fields and break none, so a `stripe` minor or patch release is now a routine update: the webhook endpoint stays at its version, and no endpoint cut-over is needed. Nothing an application relied on is refused. The new export `STRIPE_API_RELEASE` (`'endive'`) names the accepted major release, so an application can check its endpoint's version in a test instead of pinning `stripe` with `~`; it can loosen that pin to `^23.1.0` and take `stripe` minor releases again. An endpoint moves only when a release changes `STRIPE_API_RELEASE`, which this changelog will record as breaking ([BILLING.md](BILLING.md#moving-to-a-new-stripe-api-version)). - **`@pgstencil/auth` moves its exact Better Auth pin from 1.7.18 to 1.7.28**, which changes an application's lockfile and any dependency disclosure it publishes. Better Auth's own fixes in that range change what an application can observe: sending a new email OTP replaces the earlier code for that address instead of keeping it; deleting a user, `/revoke-session` and revoking all of a user's sessions now answer an error, `FAILED_TO_DELETE_USER` for a delete, where they reported success while the row or the cached sessions survived; and `user.delete.before` runs before the session and account deletes. An application that hooks user deletion or revokes sessions should check that it handles the new errors. Better Auth draws its random IDs in a different order, so an application that snapshots IDs under a seeded `RandomSource` sees them change once. ## 0.5.1 (2026-11-10) diff --git a/SECURITY.md b/SECURITY.md index 44f4578..d3592b7 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -69,8 +69,8 @@ Pinned by `integration/better-auth-workers.test.ts`: `normal Workers build uses ## Stripe webhooks -- **FAIL IF** `verifyWebhook` parses the body before `constructEventAsync` checks its signature against `webhookSecret`, passes a tolerance other than 300 seconds or a clock other than the injected `Time`, or returns an event whose `livemode` differs from `live`, whose `api_version` `acceptsStripeApiVersion` refuses, or that carries a Connect `account`; or a refusal is anything but a `BillingError` with status 400, raised before `webhook` touches the ledger; inspect `verifyWebhook` and `webhook`. -- **FAIL IF** `acceptsStripeApiVersion` accepts anything but a string of the form `YYYY-MM-DD.release` whose release is `EARLIEST_STRIPE_API_VERSION`'s and whose date is on or after it, or the installed `stripe` SDK's `STRIPE_API_VERSION` falls outside what it accepts; or the package reads an event field that `EARLIEST_STRIPE_API_VERSION` does not render; inspect `acceptsStripeApiVersion` and the event fields `webhook` and `completedCheckout` read. +- **FAIL IF** `verifyWebhook` parses the body before `constructEventAsync` checks its signature against `webhookSecret`, passes a tolerance other than 300 seconds or a clock other than the injected `Time`, or returns an event whose `livemode` differs from `live`, whose `api_version` does not end in `.${STRIPE_API_RELEASE}`, or that carries a Connect `account`; or a refusal is anything but a `BillingError` with status 400, raised before `webhook` touches the ledger; inspect `verifyWebhook` and `webhook`. +- **FAIL IF** the installed `stripe` SDK's `STRIPE_API_VERSION` is outside the `STRIPE_API_RELEASE` major release, or the package reads an event field that the release's first version does not render; inspect `STRIPE_API_RELEASE` and the event fields `webhook` and `completedCheckout` read. - **FAIL IF** `webhook(event)` accepts an object that this same `Billing` instance's `verifyWebhook` did not return — a parsed body, a copy, or an event another instance verified; inspect `verified` in `webhook`. - **FAIL IF** the ledger row, the owner's resync and `apply` do not share one transaction that marks the event processed only after `apply` returns; an event whose ledger row is already processed reaches the resync or `apply` again; concurrent deliveries of one event are not serialized on that row; or a failure — upstream, database or `apply` — commits any billing or application write instead of leaving the event recorded `failed` and unprocessed for a retry; inspect `webhook`. - **FAIL IF** `pruneEvents` deletes an event that was never processed or is marked `failed`, deletes one processed within the retention it was given, measures that retention by anything but the injected `Time`, or accepts a retention under 30 days; inspect `pruneEvents`. @@ -78,7 +78,7 @@ Pinned by `integration/better-auth-workers.test.ts`: `normal Workers build uses - **FAIL IF** `completedCheckout` reports a Checkout other than a stored operation whose ID and session ID both match the event's and whose owner is the session's `client_reference_id`, or reports fields other than that stored operation's; inspect `completedCheckout`. - **FAIL IF** a `billing.webhook.*` diagnostic names a `stripeEventId` from a delivery that failed verification, or carries anything beyond what `diagnostic` and `diagnosticError` in `packages/pgstencil/src/diagnostics.ts` allow — never the body, the `Stripe-Signature` header, the webhook secret, or the message of a Stripe, database or `apply` error; inspect `webhook`. -Pinned by `unit/stripe-api-version.test.ts`: `webhook API versions: one major release, from the earliest version on, and the installed SDK inside it`; `integration/billing.test.ts`: `checkout ownership, card policy, signatures, mode and API version are enforced`, `pruneEvents deletes only events processed before the retention window`, `the five-minute tolerance reads the delivery signature: a retry signed hours later applies once, an old signature never`, `application fulfillment and the webhook ledger share one transaction`, `duplicate and out-of-order webhooks reconcile authoritative state exactly once`, `an upstream outage rolls back entitlement changes and a failed event can retry`, `a deleted webhook racing end() waits on the owner lock and reads its reason`, `owner and customer lookups, dispute owners through their charge, and an already-verified event`, `a checkout ref is validated, kept across retries, and read back from the completion event`, `payment diagnostics keep verified event IDs and report failure before recovery without payloads`; `integration/billing-security.test.ts`: `webhook(event) takes only an event this Billing verified, and a rejected delivery reaches neither the ledger nor apply`, `concurrent deliveries of one event run apply once and record one attempt`, `event content never grants access: the resync reads Stripe, and context and completions are matched to the owner`, `webhook diagnostics name an event only once it verifies, and never carry a body, signature, secret or message`; `integration/billing-workers.test.ts`: `Billing in workerd: fetch client, Web Crypto webhooks, founding offer and purchase counts`. +Pinned by `unit/stripe-api-version.test.ts`: `webhooks accept the endive major release, and the installed SDK is inside it`; `integration/billing.test.ts`: `checkout ownership, card policy, signatures, mode and API version are enforced`, `pruneEvents deletes only events processed before the retention window`, `the five-minute tolerance reads the delivery signature: a retry signed hours later applies once, an old signature never`, `application fulfillment and the webhook ledger share one transaction`, `duplicate and out-of-order webhooks reconcile authoritative state exactly once`, `an upstream outage rolls back entitlement changes and a failed event can retry`, `a deleted webhook racing end() waits on the owner lock and reads its reason`, `owner and customer lookups, dispute owners through their charge, and an already-verified event`, `a checkout ref is validated, kept across retries, and read back from the completion event`, `payment diagnostics keep verified event IDs and report failure before recovery without payloads`; `integration/billing-security.test.ts`: `webhook(event) takes only an event this Billing verified, and a rejected delivery reaches neither the ledger nor apply`, `concurrent deliveries of one event run apply once and record one attempt`, `event content never grants access: the resync reads Stripe, and context and completions are matched to the owner`, `webhook diagnostics name an event only once it verifies, and never carry a body, signature, secret or message`; `integration/billing-workers.test.ts`: `Billing in workerd: fetch client, Web Crypto webhooks, founding offer and purchase counts`. ## Checkout diff --git a/packages/stripe/README.md b/packages/stripe/README.md index cd81e68..3d32d42 100644 --- a/packages/stripe/README.md +++ b/packages/stripe/README.md @@ -10,4 +10,4 @@ pnpm add @pgstencil/stripe pgstencil kysely stripe@^23.1.0 The packages after the first are peer dependencies: your application owns their versions and shares one copy with pgstencil. See [PACKAGES.md](https://github.com/diffplug/pgstencil/blob/main/PACKAGES.md) for usage and the dependency policy, and [SECURITY.md](https://github.com/diffplug/pgstencil/blob/main/SECURITY.md) for the audited security rules. Source: [diffplug/pgstencil](https://github.com/diffplug/pgstencil). -It peers on `stripe` 23. Webhooks are accepted at any version of Stripe's `endive` major release from `EARLIEST_STRIPE_API_VERSION` (`2026-10-28.endive`) on, so a `stripe` minor or patch release, which moves the SDK's own `STRIPE_API_VERSION` within that release, is a routine update and the webhook endpoint stays where it is. See [Moving to a new Stripe API version](https://github.com/diffplug/pgstencil/blob/main/BILLING.md#moving-to-a-new-stripe-api-version) for when an endpoint must move. +It peers on `stripe` 23. Webhooks are accepted at any version of Stripe's `endive` major release (`STRIPE_API_RELEASE`), so a `stripe` minor or patch release, which moves the SDK's own `STRIPE_API_VERSION` within that release, is a routine update and the webhook endpoint stays where it is. See [Moving to a new Stripe API version](https://github.com/diffplug/pgstencil/blob/main/BILLING.md#moving-to-a-new-stripe-api-version) for when an endpoint must move. diff --git a/packages/stripe/src/index.ts b/packages/stripe/src/index.ts index bebe17b..60ad443 100644 --- a/packages/stripe/src/index.ts +++ b/packages/stripe/src/index.ts @@ -8,26 +8,12 @@ export { Stripe }; /** The API version the installed `stripe` SDK sends its requests at. */ export const STRIPE_API_VERSION = Stripe.API_VERSION; /** - * The earliest Stripe API version whose webhook events `verifyWebhook` - * accepts: the version `stripe` 23.1, the bottom of the peer range, pins. - * Stripe's monthly versions within one major release (the name after the - * dot) add fields without breaking any, so this package reads only fields - * this version already renders and accepts every later version of the same - * major release. Raising it, or moving to another major release, is a - * breaking change: an application's webhook endpoint must be at or above it. + * The Stripe API major release whose webhook events `verifyWebhook` accepts, + * at any of its monthly versions (`YYYY-MM-DD.endive`). Stripe's versions + * within a major release add fields and break none. Moving to another major + * release is a breaking change for every application's webhook endpoint. */ -export const EARLIEST_STRIPE_API_VERSION = '2026-10-28.endive'; -const API_VERSION = /^(\d{4}-\d{2}-\d{2})\.([a-z]+)$/; -/** - * Whether `verifyWebhook` accepts an event rendered at `version`: the major - * release of `EARLIEST_STRIPE_API_VERSION`, dated on or after it. An - * application can check its webhook endpoint's version against it. - */ -export function acceptsStripeApiVersion(version: unknown): boolean { - const [, since, release] = API_VERSION.exec(EARLIEST_STRIPE_API_VERSION)!; - const match = typeof version === 'string' ? API_VERSION.exec(version) : null; - return !!match && match[2] === release && match[1]! >= since!; -} +export const STRIPE_API_RELEASE = 'endive'; /** Several Stripe Prices for one plan, and the server-side choice of which one checkout offers. */ export interface PlanPrices { /** Every Price that grants this plan: the one offered now, earlier ones, and any later steps. */ @@ -1099,7 +1085,7 @@ export class Billing

{ } if ( event.livemode !== this.config.live || - !acceptsStripeApiVersion(event.api_version) || + !event.api_version?.endsWith(`.${STRIPE_API_RELEASE}`) || event.account ) throw new BillingError('Unexpected Stripe event configuration.', 400); diff --git a/tests/integration/billing.test.ts b/tests/integration/billing.test.ts index e4ec0f1..30d2990 100644 --- a/tests/integration/billing.test.ts +++ b/tests/integration/billing.test.ts @@ -8,7 +8,6 @@ import { connectDatabase } from '../../packages/pgstencil/src/database.ts'; import { Billing, BillingError, - EARLIEST_STRIPE_API_VERSION, purchaseStanding, STRIPE_API_VERSION, SUBSCRIBED, @@ -415,9 +414,8 @@ billingTest( for (const invalid of [ { ...event, livemode: true }, { ...event, api_version: '2000-01-01' }, - // Before the earliest version, or in another major release. - { ...event, api_version: '2026-09-30.endive' }, - { ...event, api_version: '2026-10-28.dahlia' }, + // Another major release. + { ...event, api_version: '2026-08-26.dahlia' }, { ...event, api_version: '2027-03-31.zinnia' }, { ...event, api_version: null }, { ...event, account: 'acct_other' }, @@ -428,10 +426,10 @@ billingTest( ); } expect(event.api_version).toBe(STRIPE_API_VERSION); - // An endpoint at any version of the major release from the earliest on - // verifies, whichever monthly version the installed SDK pins. + // An endpoint at any version of the major release verifies, whichever + // monthly version the installed SDK pins. for (const version of [ - EARLIEST_STRIPE_API_VERSION, + '2026-09-30.endive', '2026-12-16.endive', STRIPE_API_VERSION, ]) { diff --git a/tests/unit/stripe-api-version.test.ts b/tests/unit/stripe-api-version.test.ts index 11594a8..fe29db9 100644 --- a/tests/unit/stripe-api-version.test.ts +++ b/tests/unit/stripe-api-version.test.ts @@ -1,41 +1,13 @@ import { expect, test } from 'vitest'; import { - acceptsStripeApiVersion, - EARLIEST_STRIPE_API_VERSION, + STRIPE_API_RELEASE, STRIPE_API_VERSION, } from '../../packages/stripe/src/index.ts'; -test('webhook API versions: one major release, from the earliest version on, and the installed SDK inside it', () => { - expect(EARLIEST_STRIPE_API_VERSION).toBe('2026-10-28.endive'); - for (const accepted of [ - '2026-10-28.endive', - '2026-10-29.endive', - '2026-11-18.endive', - '2027-02-24.endive', - ]) - expect(acceptsStripeApiVersion(accepted), accepted).toBe(true); - for (const refused of [ - '2026-10-27.endive', - '2026-09-30.endive', - '2026-08-26.dahlia', - '2026-11-18.dahlia', - '2027-03-31.zinnia', - '2026-11-18.Endive', - '2026-11-18.endive ', - ' 2026-11-18.endive', - '2026-11-18', - 'endive', - '2026-11-18.endive.extra', - '', - null, - undefined, - 20261118, - ]) - expect(acceptsStripeApiVersion(refused), String(refused)).toBe(false); - // A stripe SDK outside the accepted major release would refuse its own - // StripeDev events; moving the peer range to one is a deliberate change of - // EARLIEST_STRIPE_API_VERSION (BILLING.md, Moving to a new Stripe API version). - expect(acceptsStripeApiVersion(STRIPE_API_VERSION), STRIPE_API_VERSION).toBe( - true, - ); +test('webhooks accept the endive major release, and the installed SDK is inside it', () => { + expect(STRIPE_API_RELEASE).toBe('endive'); + // A stripe SDK in another major release would refuse its own StripeDev + // events; moving the peer range to one moves STRIPE_API_RELEASE with it + // (BILLING.md, Moving to a new Stripe API version). + expect(STRIPE_API_VERSION).toMatch(/\.endive$/); });