Skip to content

Commit a911fd7

Browse files
authored
Move to stripe 23, and add a reconcile that covers every owner (#97)
2 parents a2a7e0e + ee83505 commit a911fd7

11 files changed

Lines changed: 360 additions & 27 deletions

File tree

‎BILLING.md‎

Lines changed: 21 additions & 5 deletions
Large diffs are not rendered by default.

‎PACKAGES.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ Every archive carries `package/dist/provenance.json`, holding the 40-character `
1212

1313
## Dependencies
1414

15-
Applications declare pgstencil's peer dependencies themselves: `kysely` for every package, `hono` for `@pgstencil/auth`, and `stripe` for `@pgstencil/stripe`. Auth and billing also peer on the `pgstencil` released with them. A library is a peer when the application and pgstencil must share one copy. Either objects cross the boundary, or the library holds module-level state. Kysely and Hono classes have private fields, so two copies are incompatible types. `pgstencil/diagnostics` keeps its request scope in `AsyncLocalStorage`. The application's Renovate updates each shared library once, and pgstencil uses that copy. pnpm reports a release outside a peer range; pgstencil must widen the range first.
15+
Applications declare pgstencil's peer dependencies themselves: `kysely` for every package, `hono` for `@pgstencil/auth`, and `stripe` for `@pgstencil/stripe`. Auth and billing also peer on the `pgstencil` released with them. A library is a peer when the application and pgstencil must share one copy. Either objects cross the boundary, or the library holds module-level state. Kysely and Hono classes have private fields, so two copies are incompatible types. `pgstencil/diagnostics` keeps its request scope in `AsyncLocalStorage`. The application's Renovate updates each shared library once, and pgstencil uses that copy. pnpm reports a release outside a peer range; pgstencil must widen the range first. `stripe` is the exception to taking each update as it comes: every minor release changes the Stripe API version that webhooks must match, so an application pins it with `~` and moves it as [BILLING.md](BILLING.md#moving-to-a-new-stripe-api-version) describes.
1616

1717
Every other dependency is private: pgstencil owns its version and applications do not import it. Better Auth is deliberately private. pgstencil imports its internal subpaths and tests login and linking rules against specific releases, so it is pinned to the exact release CI tested. Even a patch can change internals pgstencil reads (1.7.7 renamed its OAuth state rows), so each Better Auth upgrade reaches applications only through a pgstencil release. A new login provider or Better Auth plugin belongs in `@pgstencil/auth`, not in an application. Private ranges start at the version pgstencil's CI tested. [`.github/renovate.json`](.github/renovate.json) raises that floor, and the next release carries it into each application.
1818

‎examples/login/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
"pgstencil": "workspace:*",
1111
"@pgstencil/auth": "workspace:*",
1212
"hono": "^4.13.7",
13-
"stripe": "^22.6.1"
13+
"stripe": "^23.1.0"
1414
},
1515
"devDependencies": {
1616
"node-pg-migrate": "^9.0.0",

‎packages/stripe/README.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@ Stripe SaaS subscriptions with named plans, optional card-required trials, durab
55
> **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.
66
77
```sh
8-
pnpm add @pgstencil/stripe pgstencil kysely stripe
8+
pnpm add @pgstencil/stripe pgstencil kysely stripe@~23.1.0
99
```
1010

1111
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).
12+
13+
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.

‎packages/stripe/package.json‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,12 @@
1010
"peerDependencies": {
1111
"kysely": "^0.29.5",
1212
"pgstencil": "workspace:^",
13-
"stripe": "^22.6.1"
13+
"stripe": "^23.1.0"
1414
},
1515
"devDependencies": {
1616
"kysely": "^0.29.5",
1717
"pgstencil": "workspace:*",
18-
"stripe": "^22.6.1"
18+
"stripe": "^23.1.0"
1919
},
2020
"engines": {
2121
"node": ">=24"

‎packages/stripe/src/index.ts‎

Lines changed: 92 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,14 @@ export type WebhookApply = (
5555
trx: Transaction<BillingDB>,
5656
context: WebhookContext,
5757
) => Promise<void>;
58+
/** An owner `reconcileAll` changed: its subscription rows before and after, ordered by ID. */
59+
export interface ReconciledChange {
60+
ownerId: string;
61+
before: BillingSubscription[];
62+
after: BillingSubscription[];
63+
}
64+
/** Thrown to roll back a dry run's transaction. */
65+
class RolledBack extends Error {}
5866
/** A completed subscription Checkout, read from its verified completion event. */
5967
export interface CompletedCheckout {
6068
/** The operation ID `checkout` returned. */
@@ -458,7 +466,8 @@ export class Billing<P extends string = string> {
458466
client_reference_id: ownerId,
459467
line_items: [{ price: operation.price_id, quantity: 1 }],
460468
payment_method_collection: 'always',
461-
payment_method_types: ['card'],
469+
// Filters the account's dynamically eligible methods down to cards.
470+
allowed_payment_method_types: ['card'],
462471
...(this.config.managedPayments
463472
? { managed_payments: { enabled: true } }
464473
: {}),
@@ -849,6 +858,86 @@ export class Billing<P extends string = string> {
849858
);
850859
return { reconciled, failed };
851860
}
861+
/**
862+
* Reconciles every owner holding a Stripe customer, one at a time in owner
863+
* ID order, reading `pageSize` (1-1000, default 100) owners per query: one
864+
* `subscriptions.list` request each, for a one-off pass such as after a
865+
* Stripe API version move. Returns how many owners it checked, each owner
866+
* whose subscription rows changed, with the rows before and after, and each
867+
* failure, without stopping. `dryRun` reconciles inside a transaction it
868+
* rolls back, so it reports what would change and writes nothing.
869+
*/
870+
async reconcileAll(
871+
options: { dryRun?: boolean; pageSize?: number } = {},
872+
): Promise<{
873+
checked: number;
874+
changed: ReconciledChange[];
875+
failed: { ownerId: string; error: unknown }[];
876+
}> {
877+
const { dryRun = false, pageSize = 100 } = options;
878+
if (!Number.isInteger(pageSize) || pageSize < 1 || pageSize > 1000)
879+
throw new Error('pageSize must be an integer between 1 and 1000');
880+
const changed: ReconciledChange[] = [];
881+
const failed: { ownerId: string; error: unknown }[] = [];
882+
let checked = 0;
883+
let cursor: string | undefined;
884+
for (;;) {
885+
let query = this.db
886+
.selectFrom('accounts')
887+
.select('owner_id')
888+
.where('customer_id', 'is not', null)
889+
.orderBy('owner_id')
890+
.limit(pageSize);
891+
if (cursor !== undefined) query = query.where('owner_id', '>', cursor);
892+
const page = await query.execute();
893+
for (const { owner_id: ownerId } of page) {
894+
checked++;
895+
await this.reconcileReporting(ownerId, dryRun).then(
896+
(change) => change && changed.push(change),
897+
(error: unknown) => failed.push({ ownerId, error }),
898+
);
899+
}
900+
if (page.length < pageSize) break;
901+
cursor = page.at(-1)!.owner_id;
902+
}
903+
return { checked, changed, failed };
904+
}
905+
private async reconcileReporting(
906+
ownerId: string,
907+
dryRun: boolean,
908+
): Promise<ReconciledChange | null> {
909+
const rows = (trx: Transaction<BillingDB>) =>
910+
trx
911+
.selectFrom('subscriptions')
912+
.selectAll()
913+
.where('owner_id', '=', ownerId)
914+
.orderBy('id')
915+
.execute();
916+
// Every resync rewrites `updated_at`, so it alone is no change.
917+
const comparable = (subscriptions: BillingSubscription[]) =>
918+
JSON.stringify(subscriptions.map(({ updated_at: _, ...row }) => row));
919+
let change: ReconciledChange | null = null;
920+
try {
921+
await this.db.transaction().execute(async (trx) => {
922+
// `before` is read under the owner lock, so no webhook lands between it and the resync.
923+
await trx
924+
.selectFrom('accounts')
925+
.select('owner_id')
926+
.where('owner_id', '=', ownerId)
927+
.forUpdate()
928+
.execute();
929+
const before = await rows(trx);
930+
await this.synchronize(trx, ownerId);
931+
const after = await rows(trx);
932+
if (comparable(before) !== comparable(after))
933+
change = { ownerId, before, after };
934+
if (dryRun) throw new RolledBack();
935+
});
936+
} catch (error) {
937+
if (!(error instanceof RolledBack)) throw error;
938+
}
939+
return change;
940+
}
852941
async status(ownerId: string) {
853942
const [account, subscriptions, entitled] = await Promise.all([
854943
this.db
@@ -972,6 +1061,8 @@ export class Billing<P extends string = string> {
9721061
body,
9731062
signature,
9741063
this.config.webhookSecret,
1064+
// Seconds between the delivery's signed `t=` (Stripe signs every
1065+
// attempt afresh, so retries pass) and the injected clock.
9751066
300,
9761067
Stripe.createSubtleCryptoProvider(),
9771068
this.time.now().getTime(),

‎packages/stripe/src/testing.ts‎

Lines changed: 56 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,16 @@ export async function createStripeDev(
125125
ended_at: null,
126126
canceled_at: null,
127127
trial_end: days ? seconds() + days * 86400 : null,
128+
trial_settings: {
129+
end_behavior: {
130+
billing_cycle_anchor: null,
131+
missing_payment_method:
132+
p.get(
133+
'subscription_data[trial_settings][end_behavior][missing_payment_method]',
134+
) ?? 'create_invoice',
135+
},
136+
},
137+
pending_update: null,
128138
cancel_at: null,
129139
cancel_at_period_end: false,
130140
metadata: Object.fromEntries(
@@ -142,6 +152,8 @@ export async function createStripeDev(
142152
id: id('si'),
143153
quantity: 1,
144154
price: { id: price },
155+
current_trial: null,
156+
current_period_start: seconds(),
145157
current_period_end: days
146158
? seconds() + days * 86400
147159
: periodEnd(price),
@@ -206,28 +218,58 @@ export async function createStripeDev(
206218
sub.ended_at = seconds();
207219
return event('customer.subscription.deleted', sub);
208220
}
221+
/** Starts the item's next billing period now. */
222+
function newPeriod(sub: Stripe.Subscription) {
223+
const item = sub.items.data[0]!;
224+
item.current_period_start = seconds();
225+
item.current_period_end = periodEnd(item.price.id);
226+
}
209227
function transition(
210228
subscriptionId: string,
211229
action:
212230
| 'renew'
213231
| 'payment-failed'
214232
| 'cancel'
215233
| 'cancel-at-period-end'
216-
| 'portal-cancel',
234+
| 'portal-cancel'
235+
| 'pause'
236+
| 'resume',
217237
) {
218238
const sub = subscriptions.get(subscriptionId);
219239
if (!sub) throw new Error('Subscription not found');
220240
let result: Stripe.Event;
221241
if (action === 'cancel') result = cancel(sub);
222-
else {
242+
else if (action === 'pause') {
243+
// As the pause endpoint, or the portal's subscription_pause flow, makes:
244+
// the period stops advancing until the subscription resumes.
245+
if (!['active', 'trialing', 'past_due'].includes(sub.status))
246+
throw new Error('Only an active subscription can be paused');
247+
sub.status = 'paused';
248+
sub.status_details = {
249+
paused: {
250+
type: 'subscription',
251+
subscription: { type: 'pause_requested' },
252+
transitioned_at: seconds(),
253+
},
254+
};
255+
event('customer.subscription.updated', sub);
256+
result = event('customer.subscription.paused', sub);
257+
} else if (action === 'resume') {
258+
// Resuming resets the billing cycle anchor to now, Stripe's default.
259+
if (sub.status !== 'paused')
260+
throw new Error('Subscription is not paused');
261+
sub.status = 'active';
262+
delete sub.status_details;
263+
newPeriod(sub);
264+
event('customer.subscription.updated', sub);
265+
result = event('customer.subscription.resumed', sub);
266+
} else {
223267
if (action === 'cancel-at-period-end') sub.cancel_at_period_end = true;
224268
else if (action === 'portal-cancel')
225269
sub.cancel_at = sub.items.data[0]!.current_period_end;
226270
else {
227271
sub.status = action === 'renew' ? 'active' : 'past_due';
228-
sub.items.data[0]!.current_period_end = periodEnd(
229-
sub.items.data[0]!.price.id,
230-
);
272+
newPeriod(sub);
231273
}
232274
result = event('customer.subscription.updated', sub);
233275
}
@@ -327,6 +369,14 @@ export async function createStripeDev(
327369
result as Record<string, unknown>,
328370
);
329371
} else if (path === '/v1/checkout/sessions' && req.method === 'POST') {
372+
// Removed from Checkout creation at the endive API versions.
373+
if (
374+
[...body.keys()].some((key) => key.startsWith('payment_method_types'))
375+
)
376+
throw new Error('Received unknown parameter: payment_method_types');
377+
const allowed = [...body]
378+
.filter(([key]) => /^allowed_payment_method_types\[\d+\]$/.test(key))
379+
.map(([, value]) => value);
330380
const sessionId = id('cs');
331381
const session = {
332382
id: sessionId,
@@ -341,6 +391,7 @@ export async function createStripeDev(
341391
.map(([key, value]) => [key.slice(9, -1), value]),
342392
),
343393
subscription: null,
394+
allowed_payment_method_types: allowed.length ? allowed : null,
344395
payment_status: 'unpaid',
345396
livemode: false,
346397
expires_at: Number(body.get('expires_at')),

‎pnpm-lock.yaml‎

Lines changed: 9 additions & 9 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)