better-auth-streampay 3.2.0 → 3.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client.d.cts +2 -2
- package/dist/client.d.ts +2 -2
- package/dist/index.cjs +295 -97
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -2
- package/dist/index.d.ts +7 -2
- package/dist/index.js +295 -97
- package/dist/index.js.map +1 -1
- package/dist/{streampay-B7cFK2CP.d.cts → streampay-idQUxi7x.d.cts} +18 -0
- package/dist/{streampay-B7cFK2CP.d.ts → streampay-idQUxi7x.d.ts} +18 -0
- package/docs/integration.md +6 -2
- package/docs/staging-validation.md +3 -0
- package/docs/state-machines.md +190 -34
- package/docs/subscriptions.md +1 -0
- package/package.json +1 -1
|
@@ -240,6 +240,8 @@ interface Subscription {
|
|
|
240
240
|
periodStart: Date | null;
|
|
241
241
|
periodEnd: Date | null;
|
|
242
242
|
currentCycleNumber: number | null;
|
|
243
|
+
/** Latest provider cycle whose renewal was handled; the baseline for detecting the next renewal. */
|
|
244
|
+
renewedCycleNumber?: number | null;
|
|
243
245
|
/** Event that owns a projected cycle's pending renewal callback. */
|
|
244
246
|
renewalCallbackEventId?: string | null;
|
|
245
247
|
trialStart: Date | null;
|
|
@@ -432,6 +434,11 @@ interface WebhookEventRow {
|
|
|
432
434
|
interface WebhookReplayOptions {
|
|
433
435
|
/** @deprecated No effect: a failed replay keeps a pending event retryable until its attempts are spent. */
|
|
434
436
|
retryUntilExhausted?: boolean;
|
|
437
|
+
/**
|
|
438
|
+
* Set by `processDueStreampayWebhookEvents`: replay only if the event is still pending at this
|
|
439
|
+
* attempt and due. Otherwise the replay fails with `CONFLICT`.
|
|
440
|
+
*/
|
|
441
|
+
dueAttemptCount?: number;
|
|
435
442
|
}
|
|
436
443
|
declare function syncWebhookPayload(ctx: SyncContext, payload: StreamPayWebhookPayload, client: StreamPayClient, plans: ResolvedPlans, callbacks: SubscriptionCallbacks, options?: {
|
|
437
444
|
dedupe?: boolean;
|
|
@@ -440,6 +447,8 @@ declare function syncWebhookPayload(ctx: SyncContext, payload: StreamPayWebhookP
|
|
|
440
447
|
maxAttempts?: number;
|
|
441
448
|
retryOnCallbackError?: boolean;
|
|
442
449
|
retryingRenewalCallback?: boolean;
|
|
450
|
+
/** The inbox table exists. Defaults to `dedupe`; replay processes without dedupe but has an inbox. */
|
|
451
|
+
inboxEnabled?: boolean;
|
|
443
452
|
}): Promise<void>;
|
|
444
453
|
type WebhookSyncFailure = "PERMANENT" | "TRANSIENT";
|
|
445
454
|
declare function classifyWebhookFailure(err: unknown): WebhookSyncFailure;
|
|
@@ -2371,6 +2380,7 @@ declare function subscriptions(subsOptions: SubscriptionsOptions): (options: Str
|
|
|
2371
2380
|
periodStart: Date | null;
|
|
2372
2381
|
periodEnd: Date | null;
|
|
2373
2382
|
currentCycleNumber: number | null;
|
|
2383
|
+
renewedCycleNumber?: number | null;
|
|
2374
2384
|
renewalCallbackEventId?: string | null;
|
|
2375
2385
|
trialStart: Date | null;
|
|
2376
2386
|
trialEnd: Date | null;
|
|
@@ -2450,6 +2460,7 @@ declare function subscriptions(subsOptions: SubscriptionsOptions): (options: Str
|
|
|
2450
2460
|
periodStart: Date | null;
|
|
2451
2461
|
periodEnd: Date | null;
|
|
2452
2462
|
currentCycleNumber: number | null;
|
|
2463
|
+
renewedCycleNumber?: number | null;
|
|
2453
2464
|
renewalCallbackEventId?: string | null;
|
|
2454
2465
|
trialStart: Date | null;
|
|
2455
2466
|
trialEnd: Date | null;
|
|
@@ -2743,6 +2754,11 @@ declare function subscriptions(subsOptions: SubscriptionsOptions): (options: Str
|
|
|
2743
2754
|
readonly type: "number";
|
|
2744
2755
|
readonly required: false;
|
|
2745
2756
|
};
|
|
2757
|
+
readonly renewedCycleNumber: {
|
|
2758
|
+
readonly type: "number";
|
|
2759
|
+
readonly required: false;
|
|
2760
|
+
readonly input: false;
|
|
2761
|
+
};
|
|
2746
2762
|
readonly renewalCallbackEventId: {
|
|
2747
2763
|
readonly type: "string";
|
|
2748
2764
|
readonly required: false;
|
|
@@ -12979,6 +12995,7 @@ declare const streampay: <O extends StreamPayOptions>(options: O) => {
|
|
|
12979
12995
|
periodStart: Date | null;
|
|
12980
12996
|
periodEnd: Date | null;
|
|
12981
12997
|
currentCycleNumber: number | null;
|
|
12998
|
+
renewedCycleNumber?: number | null;
|
|
12982
12999
|
renewalCallbackEventId?: string | null;
|
|
12983
13000
|
trialStart: Date | null;
|
|
12984
13001
|
trialEnd: Date | null;
|
|
@@ -13058,6 +13075,7 @@ declare const streampay: <O extends StreamPayOptions>(options: O) => {
|
|
|
13058
13075
|
periodStart: Date | null;
|
|
13059
13076
|
periodEnd: Date | null;
|
|
13060
13077
|
currentCycleNumber: number | null;
|
|
13078
|
+
renewedCycleNumber?: number | null;
|
|
13061
13079
|
renewalCallbackEventId?: string | null;
|
|
13062
13080
|
trialStart: Date | null;
|
|
13063
13081
|
trialEnd: Date | null;
|
|
@@ -240,6 +240,8 @@ interface Subscription {
|
|
|
240
240
|
periodStart: Date | null;
|
|
241
241
|
periodEnd: Date | null;
|
|
242
242
|
currentCycleNumber: number | null;
|
|
243
|
+
/** Latest provider cycle whose renewal was handled; the baseline for detecting the next renewal. */
|
|
244
|
+
renewedCycleNumber?: number | null;
|
|
243
245
|
/** Event that owns a projected cycle's pending renewal callback. */
|
|
244
246
|
renewalCallbackEventId?: string | null;
|
|
245
247
|
trialStart: Date | null;
|
|
@@ -432,6 +434,11 @@ interface WebhookEventRow {
|
|
|
432
434
|
interface WebhookReplayOptions {
|
|
433
435
|
/** @deprecated No effect: a failed replay keeps a pending event retryable until its attempts are spent. */
|
|
434
436
|
retryUntilExhausted?: boolean;
|
|
437
|
+
/**
|
|
438
|
+
* Set by `processDueStreampayWebhookEvents`: replay only if the event is still pending at this
|
|
439
|
+
* attempt and due. Otherwise the replay fails with `CONFLICT`.
|
|
440
|
+
*/
|
|
441
|
+
dueAttemptCount?: number;
|
|
435
442
|
}
|
|
436
443
|
declare function syncWebhookPayload(ctx: SyncContext, payload: StreamPayWebhookPayload, client: StreamPayClient, plans: ResolvedPlans, callbacks: SubscriptionCallbacks, options?: {
|
|
437
444
|
dedupe?: boolean;
|
|
@@ -440,6 +447,8 @@ declare function syncWebhookPayload(ctx: SyncContext, payload: StreamPayWebhookP
|
|
|
440
447
|
maxAttempts?: number;
|
|
441
448
|
retryOnCallbackError?: boolean;
|
|
442
449
|
retryingRenewalCallback?: boolean;
|
|
450
|
+
/** The inbox table exists. Defaults to `dedupe`; replay processes without dedupe but has an inbox. */
|
|
451
|
+
inboxEnabled?: boolean;
|
|
443
452
|
}): Promise<void>;
|
|
444
453
|
type WebhookSyncFailure = "PERMANENT" | "TRANSIENT";
|
|
445
454
|
declare function classifyWebhookFailure(err: unknown): WebhookSyncFailure;
|
|
@@ -2371,6 +2380,7 @@ declare function subscriptions(subsOptions: SubscriptionsOptions): (options: Str
|
|
|
2371
2380
|
periodStart: Date | null;
|
|
2372
2381
|
periodEnd: Date | null;
|
|
2373
2382
|
currentCycleNumber: number | null;
|
|
2383
|
+
renewedCycleNumber?: number | null;
|
|
2374
2384
|
renewalCallbackEventId?: string | null;
|
|
2375
2385
|
trialStart: Date | null;
|
|
2376
2386
|
trialEnd: Date | null;
|
|
@@ -2450,6 +2460,7 @@ declare function subscriptions(subsOptions: SubscriptionsOptions): (options: Str
|
|
|
2450
2460
|
periodStart: Date | null;
|
|
2451
2461
|
periodEnd: Date | null;
|
|
2452
2462
|
currentCycleNumber: number | null;
|
|
2463
|
+
renewedCycleNumber?: number | null;
|
|
2453
2464
|
renewalCallbackEventId?: string | null;
|
|
2454
2465
|
trialStart: Date | null;
|
|
2455
2466
|
trialEnd: Date | null;
|
|
@@ -2743,6 +2754,11 @@ declare function subscriptions(subsOptions: SubscriptionsOptions): (options: Str
|
|
|
2743
2754
|
readonly type: "number";
|
|
2744
2755
|
readonly required: false;
|
|
2745
2756
|
};
|
|
2757
|
+
readonly renewedCycleNumber: {
|
|
2758
|
+
readonly type: "number";
|
|
2759
|
+
readonly required: false;
|
|
2760
|
+
readonly input: false;
|
|
2761
|
+
};
|
|
2746
2762
|
readonly renewalCallbackEventId: {
|
|
2747
2763
|
readonly type: "string";
|
|
2748
2764
|
readonly required: false;
|
|
@@ -12979,6 +12995,7 @@ declare const streampay: <O extends StreamPayOptions>(options: O) => {
|
|
|
12979
12995
|
periodStart: Date | null;
|
|
12980
12996
|
periodEnd: Date | null;
|
|
12981
12997
|
currentCycleNumber: number | null;
|
|
12998
|
+
renewedCycleNumber?: number | null;
|
|
12982
12999
|
renewalCallbackEventId?: string | null;
|
|
12983
13000
|
trialStart: Date | null;
|
|
12984
13001
|
trialEnd: Date | null;
|
|
@@ -13058,6 +13075,7 @@ declare const streampay: <O extends StreamPayOptions>(options: O) => {
|
|
|
13058
13075
|
periodStart: Date | null;
|
|
13059
13076
|
periodEnd: Date | null;
|
|
13060
13077
|
currentCycleNumber: number | null;
|
|
13078
|
+
renewedCycleNumber?: number | null;
|
|
13061
13079
|
renewalCallbackEventId?: string | null;
|
|
13062
13080
|
trialStart: Date | null;
|
|
13063
13081
|
trialEnd: Date | null;
|
package/docs/integration.md
CHANGED
|
@@ -105,6 +105,7 @@ ALTER TABLE subscription ADD COLUMN IF NOT EXISTS "catalogMapped" boolean DEFAUL
|
|
|
105
105
|
ALTER TABLE subscription ALTER COLUMN "catalogMapped" SET DEFAULT true;
|
|
106
106
|
UPDATE subscription SET "catalogMapped" = true WHERE "catalogMapped" IS NULL;
|
|
107
107
|
ALTER TABLE subscription ADD COLUMN IF NOT EXISTS "renewalCallbackEventId" text;
|
|
108
|
+
ALTER TABLE subscription ADD COLUMN IF NOT EXISTS "renewedCycleNumber" integer;
|
|
108
109
|
```
|
|
109
110
|
|
|
110
111
|
Use your configured table name and your database's boolean syntax when they differ. The column
|
|
@@ -603,8 +604,11 @@ does not provide exactly-once execution of external side effects.
|
|
|
603
604
|
Typed handlers include `onPaymentPartiallyRefunded` and `onSubscriptionCycleRenewedSuccessfully`.
|
|
604
605
|
Successful renewal events reconcile billing state and share renewal inference with completed
|
|
605
606
|
invoices. The cycle update records its callback owner in `renewalCallbackEventId`; an interrupted
|
|
606
|
-
owner can resume on replay, and competing events cannot take its pending callback.
|
|
607
|
-
|
|
607
|
+
owner can resume on replay, and competing events cannot take its pending callback. A renewal is a
|
|
608
|
+
StreamPay cycle number above `renewedCycleNumber`, the last cycle whose renewal the plugin handled,
|
|
609
|
+
so a plan-change webhook or customer action that writes the new cycle first does not absorb the
|
|
610
|
+
callback. Apply both nullable columns before deploying; existing rows need no backfill. External
|
|
611
|
+
callback side effects still need idempotency.
|
|
608
612
|
|
|
609
613
|
The StreamPay SDK does not export webhook payload types. This package provides checked event
|
|
610
614
|
types based on StreamPay's documented payloads.
|
|
@@ -37,6 +37,9 @@ Tests cover the plugin's implemented features, not every feature of the Stream p
|
|
|
37
37
|
| Renewal evidence invokes callbacks twice | PostgreSQL aligns invoice and subscription events at the same old cycle; a conditional update gives one callback winner. |
|
|
38
38
|
| Crash skips a renewal callback | SQLite simulates a lost update response and an interrupted worker; replay uses the durable callback owner. |
|
|
39
39
|
| Paid abandoned checkout loses access | Live sandbox payment of a replaced checkout link: the original code dead-lettered the activation and left `/subscription/current` empty; the fix activated it on the first delivery and StreamPay reported the replacement link `INACTIVE`. Replaced links show "Payment link is inactive". See [state machines](state-machines.md#live-sandbox-evidence-for-f1). |
|
|
40
|
+
| A retried webhook skips its lifecycle callback | Live sandbox subscription with a later cancellation write: on the original code a retried `SUBSCRIPTION_ACTIVATED` completed without a successful `onSubscriptionActivated`; with the fix the retry delivered it. See [state machines](state-machines.md#live-sandbox-evidence-for-f9-and-streampay-timing). |
|
|
41
|
+
| A renewal written by another event skips its callback | Live sandbox subscription renewed from cycle 4 to 5: on the original code a plan-update event that wrote cycle 5 first left `INVOICE_COMPLETED` with no `onSubscriptionRenewed`; with the fix it ran once. See [state machines](state-machines.md#live-sandbox-evidence-for-f9-and-streampay-timing). |
|
|
42
|
+
| Renewal evidence for an unlinked checkout is dropped | Live sandbox subscription at cycle 5 with only its checkout reservation: on 3.3.0 the completed renewal invoice left the reservation unlinked with no callback; with the fix it linked the reservation and reported the renewal once. See [state machines](state-machines.md#live-sandbox-evidence-for-f9-and-streampay-timing). |
|
|
40
43
|
| Checkout activates the wrong reservation | Known payment-link and consumer mismatches cannot bind a pending checkout. |
|
|
41
44
|
| Portal client sends the wrong HTTP method | The real Better Auth client sends POST for the documented no-argument session call. |
|
|
42
45
|
| Consumer lookup misses an existing account | Exact identity searches follow pagination; later-page failures and repeated provider pages fail instead of creating a duplicate consumer. |
|
package/docs/state-machines.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
This document lists every state machine in the plugin, including the ones that exist only as a
|
|
4
4
|
combination of columns. Each section gives the states, the invariants, and a transition table
|
|
5
5
|
that points to the code that performs each transition. The last sections record the invalid
|
|
6
|
-
states and transitions found in the November 2026
|
|
6
|
+
states and transitions found in the November 2026 audits, how each one is reachable, and where it
|
|
7
7
|
is fixed.
|
|
8
8
|
|
|
9
9
|
Keep this file in sync with the code. A change to a status value, a slot rule, a lease rule, or a
|
|
@@ -18,6 +18,10 @@ compare-and-set `where` clause must update the matching table here and add a reg
|
|
|
18
18
|
`src/plugins/subscriptions/types.ts`.
|
|
19
19
|
- **Provider** means StreamPay. Provider state is fetched again on every webhook. The webhook body
|
|
20
20
|
is only a trigger and a source of signed checkout metadata.
|
|
21
|
+
- **Stale event** means an event whose timestamp is older than the stored `providerUpdatedAt`.
|
|
22
|
+
StreamPay stamps an event shortly after the write it reports (0.3 to 1.2 seconds in the
|
|
23
|
+
sandbox), so an event becomes stale only when a later write reaches the row before the event is
|
|
24
|
+
processed: a retry, a reordered concurrent delivery, or a customer action in between.
|
|
21
25
|
|
|
22
26
|
## Inventory
|
|
23
27
|
|
|
@@ -28,7 +32,7 @@ compare-and-set `where` clause must update the matching table here and add a reg
|
|
|
28
32
|
| 3 | Cancellation schedule | Implicit | `cancelAtPeriodEnd`, `cancelAt`, `cancelScheduledAt`, `canceledAt` | `reconcile.ts`, `sync.ts` |
|
|
29
33
|
| 4 | Pending plan/seat change | Implicit | `pendingPlan`, `pendingProductId`, `pendingSeats`, `pending*EffectiveAt` | `reconcile.ts` (`projectPlanFields`), `endpoints.ts` |
|
|
30
34
|
| 5 | Freeze | Provider-driven projection | `status = frozen`, `frozenAt`, `freezeEndAt` | `endpoints.ts`, `lifecycle.ts` |
|
|
31
|
-
| 6 | Renewal callback ownership | Implicit lock | `subscription.renewalCallbackEventId` | `sync.ts` (`handleRenewalEvidence`) |
|
|
35
|
+
| 6 | Renewal callback ownership | Implicit lock plus cycle marker | `subscription.renewalCallbackEventId`, `renewedCycleNumber` | `sync.ts` (`handleRenewalEvidence`) |
|
|
32
36
|
| 7 | Webhook inbox event | Explicit `status`, plus lease | `streampayWebhookEvent.status`, `lockedAt`, `lockedBy`, `attemptCount` | `sync.ts`, `webhooks.ts`, `subscriptions/index.ts`, `admin.ts` |
|
|
33
37
|
| 8 | Webhook request pipeline | Implicit ordering | Request scope | `plugins/webhooks.ts` |
|
|
34
38
|
| 9 | Consumer link | Implicit | `user.streampayConsumerId` (unique) | `hooks/consumer.ts`, `utils/ensure-consumer.ts`, `utils/session.ts` |
|
|
@@ -62,30 +66,46 @@ overlay: StreamPay keeps reporting `ACTIVE` while a renewal payment is outstandi
|
|
|
62
66
|
|
|
63
67
|
| ID | Invariant | Enforced by |
|
|
64
68
|
| --- | --- | --- |
|
|
65
|
-
| S1 | `activeSlotKey` is non-null exactly when the status is not terminal. | `projectSubscriptionFields` clears the slot for terminal statuses. Releases set `incomplete_expired` and a null slot together. Webhook reconciliation
|
|
69
|
+
| S1 | `activeSlotKey` is non-null exactly when the status is not terminal. | `projectSubscriptionFields` clears the slot for terminal statuses. Releases set `incomplete_expired` and a null slot together. Webhook reconciliation and renewal evidence backfill a missing slot for live rows through `liveSlotKey` and the S4 takeover (`sync.ts`). Endpoint projections take a free slot when they observe a revival or a move to another plan group, and skip the write when another row holds it, leaving the conflict to the webhook path (`persistSubscriptionProjection`, F17, F25). |
|
|
66
70
|
| S2 | At most one row holds a slot. | Database unique constraint on `activeSlotKey`. |
|
|
67
71
|
| S3 | A provider subscription maps to at most one row. A payment link maps to at most one row. | Unique `streampaySubscriptionId` and `streampayPaymentLinkId`. |
|
|
68
|
-
| S4 | A provider-confirmed subscription outranks an unpaid reservation (`incomplete` with no StreamPay subscription ID) for the same slot. Two live subscriptions in one slot are never written silently. | `updateReconciledSubscription`
|
|
72
|
+
| S4 | A provider-confirmed subscription outranks an unpaid reservation (`incomplete` with no StreamPay subscription ID) for the same slot. Two live subscriptions in one slot are never written silently. | `updateReconciledSubscription` and `handleRenewalEvidence` run `takeSlotFromReservation` after their stale-state checks (`sync.ts`). |
|
|
69
73
|
| S5 | `billingStatus = past_due` and provider `ACTIVE` imply local `past_due`. | `reconcileProjectionAgainstExisting` (`reconcile.ts`), the renewal stale branch (`sync.ts`). |
|
|
70
74
|
| S6 | `providerUpdatedAt` never moves backwards. | The webhook path throws and retries (`updateReconciledSubscription`). The endpoint path keeps the newer local row (`persistSubscriptionProjection`). |
|
|
71
75
|
| S7 | Every lifecycle write is a CAS on `providerUpdatedAt`, `status`, `billingStatus`, and the correlation IDs. | `updateReconciledSubscription`, `persistSubscriptionProjection`, `handleRenewalEvidence`. |
|
|
76
|
+
| S8 | A stale event loses its lifecycle effects (callback, `past_due`, timestamp stamps) only when the fresh provider snapshot contradicts it. | `providerStateConfirmsEvent` in `reconcileFromStreamPay`; the latest-invoice check in `handleRenewalEvidence` (`sync.ts`). |
|
|
72
77
|
|
|
73
78
|
### Transitions
|
|
74
79
|
|
|
75
80
|
| # | Trigger | From | To | Guard and code |
|
|
76
81
|
| --- | --- | --- | --- | --- |
|
|
77
|
-
| L1 | Paid checkout confirmed by webhook | `incomplete`, `incomplete_expired`, or no row | provider status | Signed metadata row ID, then a payment-link match, then the newest matching reservation (`reconcileFromStreamPay`). Takes the slot from an unpaid holder (S4). The `/subscription/success` fallback also confirms, but only for an `incomplete` row that still holds its slot, matched by consumer, product, and link (`isCheckoutSubscriptionCandidate`). |
|
|
82
|
+
| L1 | Paid checkout confirmed by webhook | `incomplete`, `incomplete_expired`, or no row | provider status | Signed metadata row ID, then a payment-link match, then the newest matching reservation (`reconcileFromStreamPay`). Renewal evidence that finds no linked row links a reservation owning the subscription's checkout link the same way, with the link's signed metadata (`linkCheckoutFromRenewalEvidence`, F28). Takes the slot from an unpaid holder (S4). The `/subscription/success` fallback also confirms, but only for an `incomplete` row that still holds its slot, matched by consumer, product, and link (`isCheckoutSubscriptionCandidate`). |
|
|
78
83
|
| L2 | `SUBSCRIPTION_CYCLE_RENEWAL_FAILED`, not stale | `active` | `past_due`, billing `past_due` | `sync.ts` |
|
|
79
|
-
| L3 | `INVOICE_COMPLETED` or `SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY`, not stale | `past_due` | `active`, billing `current` | `handleRenewalEvidence` (`sync.ts`) |
|
|
84
|
+
| L3 | `INVOICE_COMPLETED` or `SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY`, not stale, or stale while its invoice is the provider's `COMPLETED` `latest_invoice` | `past_due` | `active`, billing `current` | `handleRenewalEvidence` (`sync.ts`) |
|
|
80
85
|
| L4 | Any other projection while billing is `past_due` | `past_due` | `past_due` | S5 |
|
|
81
86
|
| L5 | Provider reports `CANCELED`, `EXPIRED`, or `INACTIVE` | any | terminal, slot null | `projectSubscriptionFields`. `canceledAt` is stamped once. |
|
|
82
|
-
| L6 | Provider revives a terminal subscription (for example `INACTIVE` to `ACTIVE`) | terminal | live, slot reacquired | `sync.ts` existing-row branch
|
|
87
|
+
| L6 | Provider revives a terminal subscription (for example `INACTIVE` to `ACTIVE`) | terminal | live, slot reacquired | `sync.ts` existing-row branch and `handleRenewalEvidence`. An unpaid holder is released. A live holder raises `SubscriptionCorrelationError`, a permanent failure that dead-letters for manual review. |
|
|
83
88
|
| L7 | Freeze, unfreeze, or freeze cancel | `active` and `frozen` | per provider | `endpoints.ts`, then `syncSubscriptionFromUpstream` |
|
|
84
89
|
| L8 | Customer endpoint action (cancel, uncancel, change plan, seats) | live | provider response | `persistSubscriptionProjection`. On CAS loss it keeps the newer local row and logs. The provider action is not rolled back. |
|
|
85
90
|
| L9 | Unmapped product (`catalogMapped = false`) | any | same status, no access | `projectPlanFields` |
|
|
86
91
|
|
|
87
|
-
Stale events
|
|
88
|
-
|
|
92
|
+
Stale events still write the freshly fetched provider state. Their lifecycle callback, the
|
|
93
|
+
`past_due` overlay, and the `cancelScheduledAt` and `canceledAt` stamps apply only when the fresh
|
|
94
|
+
snapshot confirms the event (S8):
|
|
95
|
+
|
|
96
|
+
| Event | Confirmed when the provider shows |
|
|
97
|
+
| --- | --- |
|
|
98
|
+
| `SUBSCRIPTION_CREATED` | always |
|
|
99
|
+
| `SUBSCRIPTION_ACTIVATED`, `SUBSCRIPTION_UNFREEZE_NOW` | `ACTIVE` or `TRIALING` |
|
|
100
|
+
| `SUBSCRIPTION_CANCELED` | `CANCELED` |
|
|
101
|
+
| `SUBSCRIPTION_INACTIVATED` | `INACTIVE` |
|
|
102
|
+
| `SUBSCRIPTION_CANCEL_AT_PERIOD_END` | `cancel_at_period_end` on a live subscription |
|
|
103
|
+
| `SUBSCRIPTION_FROZEN`, `SUBSCRIPTION_FREEZE_NOW` | `FROZEN` |
|
|
104
|
+
| `SUBSCRIPTION_PLAN_CHANGE_SCHEDULED` / `_CANCELED` | a pending change / no pending change |
|
|
105
|
+
| Every other event, including `SUBSCRIPTION_CYCLE_RENEWAL_FAILED` | never (stale effects stay suppressed) |
|
|
106
|
+
|
|
107
|
+
`SUBSCRIPTION_CYCLE_RENEWAL_FAILED` stays suppressed because a late failure event cannot be told
|
|
108
|
+
apart from a failure that was already recovered.
|
|
89
109
|
|
|
90
110
|
## 2. Checkout reservation
|
|
91
111
|
|
|
@@ -119,10 +139,10 @@ StreamPay's hosted checkout. The idempotency window is
|
|
|
119
139
|
| C-b | `createPaymentLink` succeeds | R1 | R2 | CAS on `id`, `referenceId`, `referenceType`, consumer, `link = null` |
|
|
120
140
|
| C-c | `createPaymentLink` throws | R1 | R0 (row deleted) | `deleteReservedSubscription` |
|
|
121
141
|
| C-d | Link has no URL | R1 | R3 | CAS on `status = incomplete` |
|
|
122
|
-
| C-e | Same plan and seats within the window, URL recoverable | R2 | R2 (`reused: true`) | `recoverCheckoutUrl` |
|
|
123
|
-
| C-f | Same plan and seats, link gone (404 or no URL) | R2 | R3, then C-a | CAS on `status = incomplete` |
|
|
142
|
+
| C-e | Same plan and seats within the window, link not `INACTIVE` and URL recoverable | R2 | R2 (`reused: true`) | `recoverCheckoutUrl` |
|
|
143
|
+
| C-f | Same plan and seats, link gone (404, `INACTIVE`, or no URL) | R2 | R3, then C-a | CAS on `status = incomplete` |
|
|
124
144
|
| C-g | Different plan or seats within the window | R1/R2 | R1/R2, request gets `SUBSCRIPTION_CHECKOUT_IN_PROGRESS` | by design |
|
|
125
|
-
| C-h | Any request after the window | R1/R2 | R3, then C-a | Deactivate the link, then CAS on `id`, `status`, slot |
|
|
145
|
+
| C-h | Any request after the window, including the same plan and seats | R1/R2 | R3, then C-a | Deactivate the link, then CAS on `id`, `status`, slot, and the link ID that was read, so a link saved concurrently keeps its reservation (F26). The same-plan conflict path skipped this before F20. |
|
|
126
146
|
| C-i | Reservation released while its link was being created | R1 (released) | R3, request gets `SUBSCRIPTION_CHECKOUT_IN_PROGRESS` | New link deactivated |
|
|
127
147
|
| C-j | Paid subscription arrives for another row of the same slot | R1/R2 | R3 | `takeSlotFromReservation` |
|
|
128
148
|
| C-k | A live row holds the slot when the reservation is created | R0 | R0, request gets `SUBSCRIPTION_ALREADY_ACTIVE` | Previously surfaced the raw unique-constraint error |
|
|
@@ -140,7 +160,8 @@ StreamPay's hosted checkout. The idempotency window is
|
|
|
140
160
|
| Trigger | From | To | Code |
|
|
141
161
|
| --- | --- | --- | --- |
|
|
142
162
|
| `/subscription/cancel` on an active subscription, or `SUBSCRIPTION_CANCEL_AT_PERIOD_END` | Renewing | Scheduled | `reconcileProjectionAgainstExisting` stamps `cancelScheduledAt` if it is still null |
|
|
143
|
-
| Any other webhook that sees `cancel_at_period_end` first | Renewing | Scheduled without a stamp |
|
|
163
|
+
| Any other webhook that sees `cancel_at_period_end` first | Renewing | Scheduled without a stamp | Transient. The cancel event stamps its own timestamp when it arrives, even when stale (S8, F8) |
|
|
164
|
+
| `SUBSCRIPTION_CANCEL_AT_PERIOD_END` after that | Scheduled without a stamp | Scheduled | `reconcileFromStreamPay` stamps the event time. Endpoints never fill a missing stamp, so it is never the time of an unrelated call. |
|
|
144
165
|
| `/subscription/uncancel` | Scheduled | Renewing | `projectSubscriptionFields` clears `cancelScheduledAt` |
|
|
145
166
|
| Provider `CANCELED` | any | Canceled | `canceledAt` is stamped once |
|
|
146
167
|
|
|
@@ -169,15 +190,24 @@ retries without firing for two events of the same cycle.
|
|
|
169
190
|
|
|
170
191
|
| From | Trigger | To | Code |
|
|
171
192
|
| --- | --- | --- | --- |
|
|
172
|
-
| null |
|
|
193
|
+
| null | Renewal evidence that applies (S8) sees a provider cycle above `renewedCycleNumber`, or a later period when StreamPay sends no cycle numbers, and a callback is configured | event ID, with `renewedCycleNumber` advanced (one CAS with the projection) | `handleRenewalEvidence` |
|
|
173
194
|
| event E | Callback succeeds | null (CAS on E) | same |
|
|
174
195
|
| event E | Callback throws with `retryOnCallbackError` | E (event recorded as failed) | same |
|
|
175
196
|
| event E | Redelivery or replay of E | E, then null after success | `pendingCallback === eventId` branch |
|
|
176
197
|
| event E | Renewal evidence for another event | E (other event fails and retries) | `pendingCallback !== eventId` |
|
|
177
|
-
| event E | Admin discards E | null | `adminDiscardWebhookEvent
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
198
|
+
| event E | Admin discards E | null | `adminDiscardWebhookEvent`, after the event is completed |
|
|
199
|
+
| event E, E already `completed` | Renewal evidence for another event | null, and that event continues in the same attempt | `releaseLockOfCompletedRenewal`: a completed owner can never deliver, for example after a discard that stopped before clearing the lock (F27). Skipped when the inbox table is disabled. |
|
|
200
|
+
|
|
201
|
+
Invariants: while the lock is set, its cycle's callback has not been delivered, and other renewal
|
|
202
|
+
evidence for that subscription waits until the lock clears. Only renewal evidence advances
|
|
203
|
+
`renewedCycleNumber`. Every other projection leaves it untouched, or initializes it to the row's
|
|
204
|
+
current cycle when it is still null on a legacy row, so a webhook or endpoint that writes the new
|
|
205
|
+
cycle first cannot absorb the renewal (F13). A subscription first linked after it already renewed starts at the
|
|
206
|
+
first cycle, so its next renewal evidence reports the missed renewal once (F28). Every lifecycle CAS includes the marker, so a
|
|
207
|
+
projection prepared before a renewal callback cannot roll it back and let a second renewal event
|
|
208
|
+
deliver the callback again (F14). StreamPay's cycle counter is the renewal identity because period
|
|
209
|
+
boundaries drift: live sandbox subscriptions started in July read cycle 5 in November, and their
|
|
210
|
+
periods start up to 9 minutes after `started_at`.
|
|
181
211
|
|
|
182
212
|
## 7. Webhook inbox event
|
|
183
213
|
|
|
@@ -192,6 +222,7 @@ the same ID with a `handlers:` prefix.
|
|
|
192
222
|
| E0 absent | none | none | none |
|
|
193
223
|
| E1 leased | `pending` | `lockedAt` under 2 minutes old, `lockedBy` set | stored |
|
|
194
224
|
| E2 retryable | `pending` | none (failure recorded) or expired (crash) | stored |
|
|
225
|
+
| E2p parked | `pending`, `nextAttemptAt = null`, `lastErrorCode = UNREPLAYABLE_PAYLOAD` | none | missing or unparseable |
|
|
195
226
|
| E3 completed | `completed` | none | cleared |
|
|
196
227
|
| E4 dead letter | `dead_letter` | none | stored |
|
|
197
228
|
|
|
@@ -210,17 +241,22 @@ the same ID with a `handlers:` prefix.
|
|
|
210
241
|
| --- | --- | --- | --- | --- |
|
|
211
242
|
| W-a | First delivery | E0 | E1 | `claimOrAdvanceWebhookEvent` create |
|
|
212
243
|
| W-b | Duplicate delivery during the lease | E1 | E1 (duplicate gets HTTP 503 so StreamPay redelivers) | `WebhookEventInProgressError` |
|
|
213
|
-
| W-c | Delivery after a failure or expired lease, attempts left | E2 | E1 | CAS on `status` and `
|
|
214
|
-
| W-d | Delivery with attempts exhausted | E2 | E4 | same CAS |
|
|
244
|
+
| W-c | Delivery after a failure or expired lease, attempts left | E2 or E2p | E1, storing the delivered payload | CAS on `status`, `lockedAt`, and `attemptCount` (F23) |
|
|
245
|
+
| W-d | Delivery with attempts exhausted | E2 | E4, keeping the stored payload when the delivery has none (F22) | same CAS |
|
|
215
246
|
| W-e | Processing succeeds | E1 | E3 | `markWebhookEventCompleted(lockedBy)` |
|
|
216
247
|
| W-f | Transient failure, attempts left | E1 | E2 (`nextAttemptAt` set) | `recordWebhookEventFailure` |
|
|
217
248
|
| W-g | Permanent failure (`SubscriptionCorrelationError`, including two live subscriptions in one slot, or a provider 4xx other than 404 and 429), or attempts exhausted | E1 | E4 | same |
|
|
218
|
-
| W-h | Admin replay, or `processDueStreampayWebhookEvents` for E2 events whose `nextAttemptAt` passed or whose lease expired | E2 or E4 | E1 | `claimWebhookEventForReplay`, `findDueWebhookEvents` |
|
|
249
|
+
| W-h | Admin replay, or `processDueStreampayWebhookEvents` for E2 events whose `nextAttemptAt` passed or whose lease expired | E2 or E4 (admin), E2 still at the selected attempt and still due (processor) | E1 | `claimWebhookEventForReplay` (CAS on `status`, `lockedAt`, and `attemptCount`), `findDueWebhookEvents`, `isStillDueWebhookEvent` (F15) |
|
|
219
250
|
| W-i | Replay fails | E1 | E2 if it came from E2 with attempts left and a transient error, else E4 | #27. Before it, every admin replay failure dead-lettered. |
|
|
220
|
-
| W-j | Admin discard | any | E3 | `
|
|
251
|
+
| W-j | Admin discard | any except E1 | E3 | `completeUnchangedWebhookEvent`, a CAS on the observed `status`, `lockedAt`, and `attemptCount`; 409 on a live lease or a lost CAS. The renewal callback lock is cleared only after the event is completed (F21). |
|
|
252
|
+
| W-k | Replay or due-event processing finds no replayable payload | E2 | E2p (request gets 400) | `parkUnreplayableWebhookEvent`, a CAS on `status`, `lockedAt`, and `attemptCount`, so a redelivery that repaired the row in between wins (F16). Before it, the row stayed due and filled every batch (F12). |
|
|
221
253
|
|
|
222
254
|
E2 events move on a StreamPay redelivery, an admin replay, or a scheduled call to
|
|
223
|
-
`processDueStreampayWebhookEvents`, which selects them by `nextAttemptAt` and expired leases.
|
|
255
|
+
`processDueStreampayWebhookEvents`, which selects them by `nextAttemptAt` and expired leases. E2p
|
|
256
|
+
events wait for a StreamPay redelivery or an admin discard. StreamPay stops after its fifth retry
|
|
257
|
+
(about 20 hours), so an E2p row that outlives that window needs an admin discard. Only rows written without a raw body
|
|
258
|
+
reach E2p: callers of the exported `syncWebhookPayload` that omit `rawBody`, or rows from older
|
|
259
|
+
versions.
|
|
224
260
|
|
|
225
261
|
## 8. Webhook request pipeline
|
|
226
262
|
|
|
@@ -263,9 +299,9 @@ written.
|
|
|
263
299
|
|
|
264
300
|
## Audit findings
|
|
265
301
|
|
|
266
|
-
Severity reflects customer and money impact. Each finding has
|
|
267
|
-
|
|
268
|
-
before the fix and pass after it. CI runs them on SQLite; they were also run locally on
|
|
302
|
+
Severity reflects customer and money impact. Each finding has end-to-end tests that drive a real
|
|
303
|
+
Better Auth instance through HTTP with signed webhooks, and F1 to F7 also have unit tests. All of
|
|
304
|
+
them fail on the code before the fix and pass after it. CI runs them on SQLite; they were also run locally on
|
|
269
305
|
PostgreSQL 17. Run the end-to-end tests on PostgreSQL with `STREAMPAY_E2E_DB=postgres` and a database at
|
|
270
306
|
`postgres://user:password@localhost:5432/better_auth` (hardcoded by `better-auth/test`).
|
|
271
307
|
|
|
@@ -278,7 +314,99 @@ PostgreSQL 17. Run the end-to-end tests on PostgreSQL with `STREAMPAY_E2E_DB=pos
|
|
|
278
314
|
| F5 | Medium | 7 | E2 → E4 on a transient admin replay failure. StreamPay redeliveries and the due-event processor skip the event. | An operator replays a pending subscription event during a StreamPay or database outage. | The redelivery returns 200, the event stays dead-lettered, and no subscription row is created. | #27 |
|
|
279
315
|
| F6 | Medium | 7 | Same as F5 for generic handler events. | Replay of a pending `handlers:` event whose callback fails. | The callback never runs again on redelivery. | #27 |
|
|
280
316
|
| F7 | Low | 7 | Replay ignored `retryOnCallbackError: false`. | Any admin replay or due-event retry with that option set. | The replay returns 500 and dead-letters, although the projection was written. | #27 |
|
|
281
|
-
| F8 | Low | 3 | `cancelAtPeriodEnd = true` with `cancelScheduledAt = null`, permanently. | A webhook other than `SUBSCRIPTION_CANCEL_AT_PERIOD_END` (for example `SUBSCRIPTION_PLAN_UPDATED`) is processed first after a cancellation made in the StreamPay dashboard. That webhook stores a `providerUpdatedAt` later than the cancel event, so the cancel event is stale. | `cancelScheduledAt` stays `null`. |
|
|
317
|
+
| F8 | Low | 3 | `cancelAtPeriodEnd = true` with `cancelScheduledAt = null`, permanently. | A webhook other than `SUBSCRIPTION_CANCEL_AT_PERIOD_END` (for example `SUBSCRIPTION_PLAN_UPDATED`) is processed first after a cancellation made in the StreamPay dashboard. That webhook stores a `providerUpdatedAt` later than the cancel event, so the cancel event is stale. | `cancelScheduledAt` stays `null`. | S8 (Issue 4). The stamp comes only from the cancel event, so endpoints still never stamp an unrelated call time. Supersedes draft #28. |
|
|
318
|
+
| F9 | High | 1, 7 | A paid, live subscription whose lifecycle callback never succeeds, while its inbox event is `completed`. | The first delivery of `SUBSCRIPTION_ACTIVATED` fails (the callback throws, or StreamPay or the database is briefly down), or a sibling event is processed first. Before the retry, any later write reaches the row, for example the customer scheduling a period-end cancellation. The retry is stale, so the callback is skipped and the event completes. Same for `SUBSCRIPTION_CREATED`, `_CANCELED`, `_FROZEN`, and the others in the S8 table. | `onSubscriptionActivated`, the documented place to provision the customer, never runs. Nothing dead-letters, so nobody is alerted. The October sandbox run shows the trigger: `SUBSCRIPTION_ACTIVATED` (16:33:08.45) and `SUBSCRIPTION_CANCEL_AT_PERIOD_END` (16:33:10.41) were processed 4 ms apart, the activation after the cancellation write. Reproduced live; see below. | S8 (Issue 4) |
|
|
319
|
+
| F10 | Medium | 1 | `past_due` (and billing `past_due`) after StreamPay recorded the payment. | A renewal fails. The customer pays the outstanding invoice, then some other write reaches the row before `INVOICE_COMPLETED` is processed (a retry after a failed first delivery, or a customer action). The invoice event is stale and the stale branch keeps `past_due`. This is R1. | `past_due` until the next successful cycle. Apps whose `accessStatuses` exclude `past_due` lock out a paying customer, and `onSubscriptionRenewed` is skipped for that evidence. | S8: stale evidence still clears `past_due` when its invoice is the provider's `latest_invoice` and that invoice is `COMPLETED` (Issue 4) |
|
|
320
|
+
| F11 | Low | 1 | S1 broken: a live status with `activeSlotKey = null`, and a revival that skips S4's duplicate check. | StreamPay revives a terminal subscription and `INVOICE_COMPLETED` (or `SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY`) is processed before any other subscription event. `handleRenewalEvidence` wrote the projection without the slot logic of the reconcile path. | The row is `active` without a slot until another webhook backfills it. If a replacement subscription holds the slot, two live subscriptions exist, and the renewal path never raises the correlation error, so the customer can be billed twice unnoticed. | `liveSlotKey` plus `takeSlotFromReservation` in `handleRenewalEvidence` (Issue 5) |
|
|
321
|
+
| F13 | Medium | 6 | A renewed cycle whose `onSubscriptionRenewed` never runs. | Another writer stores the new cycle before the renewal evidence is processed: `SUBSCRIPTION_PLAN_CHANGED` when a scheduled change applies at renewal, any other subscription event, or a customer action, including during a retry backoff of `INVOICE_COMPLETED`. The evidence then compares against the already advanced row and sees no renewal. This is R9. | No renewal callback for that cycle, so apps that grant per-cycle credits or send receipts skip it silently. | `renewedCycleNumber` (Issue 7). Needs the migration in the integration guide. |
|
|
322
|
+
| F18 | High | 1, 7 | A paid subscription's `SUBSCRIPTION_ACTIVATED` dead-lettered on its first attempt. | Found by Gemini 4 Neon; pre-existing. No live reservation matches (the metadata row is gone or carries no row ID), so two concurrent first deliveries (`SUBSCRIPTION_CREATED` and `SUBSCRIPTION_ACTIVATED`) both take the create path. The second found the first one's new row in the slot and raised `SubscriptionCorrelationError` against its own subscription. | Permanent dead letter, HTTP 200, so StreamPay never retries and `onSubscriptionActivated` never runs. | `takeSlotFromReservation` treats a holder with the same StreamPay subscription ID as a concurrent link and fails transiently |
|
|
323
|
+
| F19 | Medium | 1, 6 | `past_due` and a lost `onSubscriptionRenewed` after a late `SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY`. | Found by Gemini 4 Neon in the F10 fix. The renewal-success event names no invoice, so the latest-invoice check never applied to it when it was stale. | Same as F10 and F13, for StreamPay's renewal-success event. | Stale renewal evidence that names no invoice applies when the latest invoice is `COMPLETED` |
|
|
324
|
+
| F20 | Medium | 2 | An unpayable or long-abandoned checkout returned as `reused: true`, forever. | Found by Gemini 4 Neon; pre-existing. After the 15-minute window, a same-plan, same-seat upgrade hit the slot conflict and resumed the old link without checking its age (C-h). `getPaymentUrl` also returns a URL for `INACTIVE` links (verified in SDK 1.1.3), so a link deactivated in the dashboard was resumed on every retry. | The customer cannot start a payable checkout for that plan and seat count. | The conflict path resumes only inside the window, and an `INACTIVE` link counts as expired (`recoverCheckoutUrl`) |
|
|
325
|
+
| F21 | Low | 6, 7 | `renewalCallbackEventId` left set by an event that is already `completed`. | Found by Gemini 4 Neon; pre-existing. An admin discard ran while a worker held the lease, before the worker wrote the callback lock. | Every later renewal event for that subscription fails with "renewal callback is pending" until the event is discarded again. | Discard returns 409 while a live lease exists, and completes only through a CAS on the observed status, lease, and attempt; the lock is cleared after that succeeds (the re-review found a worker could claim between the read and the write) |
|
|
326
|
+
| F22 | Low | 7 | A dead-lettered event with its stored payload erased. | Found by Gemini 4 Neon. The exhausted-attempts branch of `claimOrAdvanceWebhookEvent` wrote the delivery body even when a direct `syncWebhookPayload` caller passed none. | The dead letter cannot be replayed. | Keep the stored payload when the delivery has no body |
|
|
327
|
+
| F23 | Medium | 7 | One attempt run twice, past the attempt budget. | Found by GPT-6.2 Astra on re-review; pre-existing. Two redeliveries read pending attempt N. The first claims N+1, fails, and releases the lease; the second's claim still matched `pending` and `lockedAt = null`. | Extra provider calls and callback runs. | Delivery claims compare `attemptCount` |
|
|
328
|
+
| F24 | Low | 2 | A same-plan upgrade refused with `SUBSCRIPTION_CHECKOUT_IN_PROGRESS` while the slot is held by a reservation whose link is gone. | Found by GPT-6.2 Astra on re-review; pre-existing. The request misses the reservation in its first read, loses the insert race, and finds the link `INACTIVE` or 404. | The customer cannot start a checkout until the 15-minute window passes. | The conflict path releases a reservation with an expired link and reserves again (C-f) |
|
|
329
|
+
| F25 | Low | 1 | A row in plan group B still holding group A's slot. | Found by Gemini 4 Neon on re-review. StreamPay moves a subscription to a product in another configured group outside the plugin, and a customer endpoint observes it before any webhook. The endpoint wrote the new group but only moved the slot on a revival. | Upgrades in group A are refused as already active, and group B can hold two live rows. | Endpoints move the slot whenever the desired slot differs |
|
|
330
|
+
| F26 | Low | 2 | A released reservation whose link stays payable (breaks C2). | Found by Gemini 4 Neon on re-review. A stale-replacement release read the reservation without a link; its own request saved the link before the release write landed. | A payable link without a live reservation, next to the replacement's link. | The release CAS compares the link ID it read |
|
|
331
|
+
| F27 | Medium | 6 | A renewal callback lock owned by a `completed` event. | Found by GPT-6.2 Astra in the final check of F21's fix. The discard completes the event, then the process stops before it clears the lock. | Every later renewal for that subscription retries until it dead-letters. | Renewal evidence releases a lock whose owning event is completed and continues in the same attempt, so the release cannot spend its last retry; it never queries a disabled inbox |
|
|
332
|
+
| F28 | Medium | 1, 6 | A paid checkout left `incomplete` and its renewals dropped, while every renewal event is `completed`. | The creation webhooks fail past StreamPay's retry window (or are delayed), and renewal evidence arrives first. `handleRenewalEvidence` found no linked row and returned. A later creation replay then started the renewal baseline at the current cycle. This was R11. | The customer has no access until someone replays the creation event, and `onSubscriptionRenewed` never runs for the cycles in between. Reproduced live; see below. | Renewal evidence links the reservation that owns the subscription's checkout link (StreamPay bills every cycle through it), and a first link at a later cycle starts the baseline at cycle 1. If a creation webhook links the row while the evidence is correlating, the evidence continues with that row (found by GPT-6.2 Astra and Gemini 4 Neon in review). Linking reuses the snapshot the evidence fetched, and the cycle-1 baseline applies only to a subscription's first link, never to a linked row that first learns its cycle number |
|
|
333
|
+
| F14 | High | 6 | `renewedCycleNumber` rolled back after its callback ran, so a second renewal event delivers `onSubscriptionRenewed` again. | Found in review of the F13 fix. A customer endpoint (or webhook) reads the row, `INVOICE_COMPLETED` then advances the marker and runs the callback, and the endpoint write restores the old marker. Its CAS matched because the provider timestamp was unchanged. `SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY` then counted as a new renewal. | Duplicate per-cycle side effects. | Projections only initialize the marker, and every CAS includes it |
|
|
334
|
+
| F15 | Medium | 7 | A due-queue retry before its backoff, or an automatic retry of a dead letter. | Pre-existing. Two overlapping `processDueStreampayWebhookEvents` runs select the same row. The first claims it and fails. The second replayed by event ID, re-read the updated row, and claimed it again at once, even after it was dead-lettered. | Extra provider calls and callback runs, and dead letters leaving manual review. | The processor passes the selected attempt (`dueAttemptCount`); replay requires the row to still be that pending attempt and due, and the claim CAS includes `attemptCount` |
|
|
335
|
+
| F16 | Medium | 7 | A repaired event parked as unreplayable. | Found in review of F12. Replay reads a pending row without payload; a redelivery then claims it, stores its payload, fails, and schedules a retry; the stale parking write still matched `pending` and `lockedAt = null`. | The retry time is erased, so the due processor never retries the event. | Parking CAS includes `attemptCount` |
|
|
336
|
+
| F17 | Medium | 1 | Two live subscriptions in one slot, written silently by a customer endpoint. | StreamPay revives subscription A after replacement B took its slot. A customer action on A (for example `/subscription/uncancel`) projects A live with a null slot. This was R10. | Both rows grant access; nothing flags the duplicate billing until a later webhook dead-letters. | Endpoints take the slot when it is free and otherwise skip the write and log; only webhooks resolve slot conflicts |
|
|
337
|
+
| F12 | Low | 7 | A pending inbox row that can never be replayed stays due forever. | A row without a replayable payload (see E2p) gets a `nextAttemptAt`. Replay rejects it before claiming, so nothing changes, and `processDueStreampayWebhookEvents` selects it first on every run. This is R8. | Enough such rows fill every batch, and other due events are never retried. A redelivery that reclaimed the row also did not store its payload. | W-k and W-c (Issue 6) |
|
|
338
|
+
|
|
339
|
+
### Live sandbox evidence for F9 and StreamPay timing
|
|
340
|
+
|
|
341
|
+
Run on 2026-11-21 against the Stream sandbox through the Railway `staging` variables of
|
|
342
|
+
`genie-courses-web`. Every StreamPay call was read-only except the R2 probe, which created one
|
|
343
|
+
test consumer and deleted it.
|
|
344
|
+
|
|
345
|
+
**Event timing.** Real objects compared with the real deliveries recorded in October:
|
|
346
|
+
|
|
347
|
+
| Object | Provider write | Event timestamp | Lag |
|
|
348
|
+
| --- | --- | --- | --- |
|
|
349
|
+
| Subscription `39143aaa` created | `created_at` 14:53:27.100 | `SUBSCRIPTION_CREATED` 14:53:28.316 | 1.2 s |
|
|
350
|
+
| Its first invoice completed | `updated_at` 14:53:27.887 | `INVOICE_COMPLETED` 14:53:28.583 | 0.7 s |
|
|
351
|
+
| Subscription `1e5bca28` canceled | `updated_at` 14:13:50.437 | `SUBSCRIPTION_CANCELED` 14:13:50.814 | 0.4 s |
|
|
352
|
+
|
|
353
|
+
StreamPay delivers a burst concurrently: the plugin started processing `INVOICE_COMPLETED`
|
|
354
|
+
3 ms before `SUBSCRIPTION_CREATED`. One burst is therefore not stale against itself; a later write
|
|
355
|
+
is what makes an event stale.
|
|
356
|
+
|
|
357
|
+
**F9.** `probe-f9-live.mjs` runs each build against sandbox subscription `619e3b9e`. It was
|
|
358
|
+
activated at 09:23:32 and its period-end cancellation was scheduled at 09:26:30, so its
|
|
359
|
+
`updated_at` is the cancellation write. `SUBSCRIPTION_ACTIVATED` is signed with the observed lag
|
|
360
|
+
(09:23:33.3) and delivered twice; the first `onSubscriptionActivated` call throws.
|
|
361
|
+
|
|
362
|
+
| Step | Original `main` | With the fix |
|
|
363
|
+
| --- | --- | --- |
|
|
364
|
+
| First delivery | 500, callback threw, row `active` | same |
|
|
365
|
+
| Retry | 200, callback skipped as stale | 200, callback delivered with `cancelAtPeriodEnd: true` |
|
|
366
|
+
| Inbox | `completed` after 2 attempts | `completed` after 2 attempts |
|
|
367
|
+
| Successful callbacks | 0 | 1 |
|
|
368
|
+
|
|
369
|
+
**F13.** `probe-f13-live.mjs` runs each build against sandbox subscription `a74dcc6a`, which
|
|
370
|
+
StreamPay renewed from cycle 4 to 5 on 2026-11-12. The local row starts at cycle 4. A
|
|
371
|
+
`SUBSCRIPTION_PLAN_UPDATED` is processed first (it writes cycle 5), then `INVOICE_COMPLETED` for
|
|
372
|
+
the real latest invoice (`COMPLETED`, `subscription_id` matching).
|
|
373
|
+
|
|
374
|
+
| Build | `onSubscriptionRenewed` calls | Row after |
|
|
375
|
+
| --- | --- | --- |
|
|
376
|
+
| Original `main` | none | cycle 5 |
|
|
377
|
+
| With the fix | one, for cycle 5 | cycle 5, `renewedCycleNumber` 5 |
|
|
378
|
+
|
|
379
|
+
**StreamPay documentation, checked 2026-11-21.** The [webhook guide](https://docs.streampay.sa/webhooks/)
|
|
380
|
+
confirms the assumptions above: `SUBSCRIPTION_ACTIVATED` covers "initial activation or
|
|
381
|
+
reactivation" (L6, F11), failed deliveries are retried up to 5 times after 5 minutes, 30 minutes,
|
|
382
|
+
2, 6, and 12 hours (the plugin uses the same schedule; the first gap is the F9 window), and
|
|
383
|
+
`SUBSCRIPTION_PLAN_CHANGED` fires when a scheduled change is applied at period end (the F13
|
|
384
|
+
trigger). The guide gives no ordering guarantee and no event ID, so the inbox keys stay
|
|
385
|
+
`event_type:entity_id:timestamp`. It documents renewal as `INVOICE_CREATED`, `PAYMENT_SUCCEEDED`,
|
|
386
|
+
`INVOICE_COMPLETED` and does not place `SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY` in that sequence,
|
|
387
|
+
which is why both are treated as renewal evidence. The [cancel API](https://docs.streampay.sa/api/v2-subscriptions-cancel/)
|
|
388
|
+
confirms `INACTIVE`, `TRIALING`, and `TRIAL_PENDING` are cancelled immediately and `ACTIVE` at
|
|
389
|
+
period end.
|
|
390
|
+
|
|
391
|
+
**F28.** StreamPay bills every cycle through the checkout link: all five invoices of sandbox
|
|
392
|
+
subscription `a74dcc6a` (cycles 1 to 5) carry payment link `5fcf418c`, whose custom metadata holds
|
|
393
|
+
the plugin's plan, reference, and reservation row ID. `probe-r11-live.mjs` gives each build only the
|
|
394
|
+
reservation that owns that link, as if every creation webhook had failed, then delivers the real
|
|
395
|
+
`INVOICE_COMPLETED` for cycle 5.
|
|
396
|
+
|
|
397
|
+
| Build | Inbox | Reservation | `onSubscriptionRenewed` |
|
|
398
|
+
| --- | --- | --- | --- |
|
|
399
|
+
| 3.3.0 | `completed` | still `incomplete`, unlinked | none |
|
|
400
|
+
| With the fix | `completed` | `active`, linked to `a74dcc6a`, cycle 5 | one, for cycle 5 |
|
|
401
|
+
|
|
402
|
+
**F10.** The sandbox exposes `latest_invoice` with `id` and `status` on the subscription, and a
|
|
403
|
+
paid invoice reads `COMPLETED` (subscription `39143aaa`). An invoice's `period_end` does not match
|
|
404
|
+
the subscription's (12 seconds apart), so the fix compares invoice IDs, not periods.
|
|
405
|
+
|
|
406
|
+
**R2, disproved.** Two concurrent `createConsumer` calls with the same email and `external_id`
|
|
407
|
+
returned one consumer and one `DUPLICATE_CONSUMER`. A third call returned `DUPLICATE_CONSUMER`.
|
|
408
|
+
The plugin's duplicate recovery then resolves the same consumer, so concurrent first checkouts
|
|
409
|
+
converge. The test consumer was deleted.
|
|
282
410
|
|
|
283
411
|
### Live sandbox evidence for F1
|
|
284
412
|
|
|
@@ -305,19 +433,47 @@ duplicate as a permanent failure. Map a live slot holder to `SUBSCRIPTION_ALREAD
|
|
|
305
433
|
**Issue 2, P2: Manual replay dead-letters events that StreamPay is still retrying (F5–F7).** Fixed
|
|
306
434
|
by #27.
|
|
307
435
|
|
|
308
|
-
**Issue 3, P3: The cancellation schedule time is lost when events arrive out of order (F8).**
|
|
309
|
-
|
|
310
|
-
|
|
436
|
+
**Issue 3, P3: The cancellation schedule time is lost when events arrive out of order (F8).**
|
|
437
|
+
Folded into Issue 4, which has the same cause.
|
|
438
|
+
|
|
439
|
+
**Issue 4, P1: Stale-event suppression drops effects that StreamPay still confirms (F9, F10, F8).**
|
|
440
|
+
Staleness was measured against the provider's latest `updated_at`, so any later write turned a
|
|
441
|
+
retried or reordered event into a no-op. Judge a stale event against the fresh snapshot instead
|
|
442
|
+
(S8), and let stale renewal evidence clear `past_due` when it settles the latest invoice.
|
|
443
|
+
|
|
444
|
+
**Issue 5, P2: Renewal evidence revives a subscription without its billing slot (F11).** Share the
|
|
445
|
+
slot projection and S4 takeover between the reconcile and renewal paths.
|
|
446
|
+
|
|
447
|
+
**Issue 6, P3: Unreplayable pending events starve the due-event processor (F12).** Park them out of
|
|
448
|
+
the due queue, keep them open to StreamPay redelivery, and store the payload a redelivery carries.
|
|
449
|
+
|
|
450
|
+
**Issue 7, P2: Renewal callbacks are absorbed by other writers (F13).** Track the last handled
|
|
451
|
+
cycle in its own column, advanced only by renewal evidence.
|
|
452
|
+
|
|
453
|
+
**Issue 8, P1: Review findings (F14 to F24).** GPT-6.2 Astra and Gemini 4 Neon (high) reviewed
|
|
454
|
+
the branch independently, then re-reviewed the fixes. Both found F14. The re-reviews found F21's
|
|
455
|
+
first fix incomplete, plus F23 to F27. F14, F16, and F19 were gaps in the new code; the rest
|
|
456
|
+
were pre-existing.
|
|
457
|
+
|
|
458
|
+
Issues 4 to 8 are fixed on `ali/fix-stale-lifecycle-effects`. Regression tests:
|
|
459
|
+
`tests/integration/stale-lifecycle.test.ts` (F8 to F11, plus two guards: a contradicted stale
|
|
460
|
+
cancellation stays suppressed, and a late invoice that is not the latest keeps `past_due`) and
|
|
461
|
+
`tests/integration/due-queue.test.ts` (F12). The `renewal callbacks` tests in the first file cover
|
|
462
|
+
F13 and F14, including a legacy row without the marker; the revival tests cover F17; the due-queue
|
|
463
|
+
file covers F15 and F16; `tests/integration/review-findings.test.ts` covers F18 to F27. Every bug test fails on the code before its fix and passes after it.
|
|
311
464
|
|
|
312
465
|
### Open risks (not confirmed, not changed)
|
|
313
466
|
|
|
314
467
|
| ID | Risk | Why it is not fixed here |
|
|
315
468
|
| --- | --- | --- |
|
|
316
|
-
| R1 |
|
|
317
|
-
| R2 | `persistConsumerId` writes with `updateUser`, not a CAS on a null link.
|
|
469
|
+
| R1 | Confirmed as F10 and fixed. | |
|
|
470
|
+
| R2 | `persistConsumerId` writes with `updateUser`, not a CAS on a null link. | Disproved live: StreamPay rejects a concurrent duplicate email or `external_id`, so both requests link the same consumer. |
|
|
318
471
|
| R3 | An unknown future provider status maps to `incomplete` on a live row. The row keeps its slot but loses access. | Fails closed. Handle new statuses explicitly when StreamPay adds them. |
|
|
319
472
|
| R4 | A dead-lettered renewal callback owner (machine 6) blocks renewal evidence for that subscription until it is replayed or discarded. | Intentional, to avoid a double callback. The operator needs to act. |
|
|
320
473
|
| R5 | Generic handler deliveries always use 5 attempts and ignore `maxWebhookAttempts`. | That option belongs to `subscriptions()`. Changing it is an API decision. |
|
|
321
474
|
| R6 | A callback that runs longer than the 2-minute lease can run concurrently with a redelivery. | Documented. Callbacks must be idempotent. |
|
|
322
|
-
| R7 |
|
|
323
|
-
| R8 |
|
|
475
|
+
| R7 | Fixed with F8 (Issue 4). | |
|
|
476
|
+
| R8 | Confirmed as F12 and fixed. Parked rather than dead-lettered, so StreamPay retries still count (W4). | |
|
|
477
|
+
| R9 | Confirmed as F13 and fixed. | |
|
|
478
|
+
| R10 | Confirmed as F17 and fixed. | |
|
|
479
|
+
| R11 | Confirmed as F28 and fixed. Rows created by a webhook without any reservation (no plugin checkout link) still depend on their creation event. | |
|
package/docs/subscriptions.md
CHANGED
|
@@ -79,6 +79,7 @@ applicable, or has not yet been confirmed upstream.
|
|
|
79
79
|
| `periodStart` | nullable date | Start of the current provider billing period. |
|
|
80
80
|
| `periodEnd` | nullable date | End of the current provider billing period and usual effective time for a deferred change. |
|
|
81
81
|
| `currentCycleNumber` | nullable number | Provider cycle counter; helps identify genuine renewals and avoid duplicate renewal callbacks. |
|
|
82
|
+
| `renewedCycleNumber` | nullable number, server-managed | Last provider cycle whose renewal was handled. Only renewal evidence advances it, so other writers cannot absorb a renewal callback. Null on legacy rows, which fall back to `currentCycleNumber`. |
|
|
82
83
|
| `renewalCallbackEventId` | nullable string, server-managed | Event that owns a pending renewal callback. Saved atomically with cycle advancement and cleared after delivery so replay can recover interrupted callbacks. |
|
|
83
84
|
| `trialStart` | nullable date | Start of a known trial. Also records trial history for one-trial-per-group eligibility. |
|
|
84
85
|
| `trialEnd` | nullable date | Provider trial end. |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "better-auth-streampay",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.3.1",
|
|
4
4
|
"description": "Community Better Auth plugin for StreamPay with consumers, checkout, portal, subscriptions, and signed webhooks. Not affiliated with Stream.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|