Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .github/renovate.json
Original file line number Diff line number Diff line change
Expand Up @@ -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 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"],
"dependencyDashboardApproval": true
},
{
"matchManagers": ["npm"],
"matchUpdateTypes": ["patch"],
Expand Down
12 changes: 8 additions & 4 deletions BILLING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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.

Expand All @@ -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 `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 `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 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, 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)).

Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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**, 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)
Expand Down
5 changes: 3 additions & 2 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,15 +69,16 @@ 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` 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`.
- **FAIL IF** anything from an event's body is written to `subscriptions`, `checkouts` or `accounts`, or its `created` time or arrival order decides a write. The body may only choose whose state to resync — the owner of the customer it names, or for a `charge.dispute.*` event the customer Stripe returns for its charge — and which row `context.subscription` reads back, filtered to that owner; the state comes from `synchronize`, which lists the customer's subscriptions from Stripe only after locking the owner's `accounts` row. An event naming a customer pgstencil did not create resyncs nobody; inspect `webhook`, `synchronize` and `ownerOfCustomer`.
- **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`: `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

Expand Down
4 changes: 2 additions & 2 deletions packages/stripe/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 (`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.
10 changes: 9 additions & 1 deletion packages/stripe/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,15 @@ 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 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 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. */
Expand Down Expand Up @@ -1077,7 +1085,7 @@ export class Billing<P extends string = string> {
}
if (
event.livemode !== this.config.live ||
event.api_version !== STRIPE_API_VERSION ||
!event.api_version?.endsWith(`.${STRIPE_API_RELEASE}`) ||
event.account
)
throw new BillingError('Unexpected Stripe event configuration.', 400);
Expand Down
Loading