better-auth-streampay 3.0.2 → 3.2.0

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.
@@ -327,22 +327,6 @@ declare const REFERENCE_ID_METADATA_KEY = "streampay_plugin_reference_id";
327
327
  declare const REFERENCE_TYPE_METADATA_KEY = "streampay_plugin_reference_type";
328
328
  declare const SUBSCRIPTION_ROW_ID_METADATA_KEY = "streampay_plugin_subscription_row_id";
329
329
 
330
- interface ResolvedPlans {
331
- list: readonly StreamPayPlanLike[];
332
- byName: Map<string, StreamPayPlanLike>;
333
- }
334
- type FeatureKey<P> = P extends {
335
- limits?: infer L;
336
- } ? L extends Record<string, unknown> ? Extract<keyof L, string> : string : string;
337
- declare function hasSubscriptionAccess(subscription: Pick<Subscription, "status" | "catalogMapped">, accessStatuses?: readonly SubscriptionStatus[]): boolean;
338
- declare function hasFeature<P extends StreamPayPlanLike>(subscription: Subscription, plan: P | undefined, feature: FeatureKey<P>, accessStatuses?: readonly SubscriptionStatus[]): boolean;
339
- interface LimitCheckResult {
340
- allowed: boolean;
341
- limit: number;
342
- remaining: number;
343
- }
344
- declare function checkLimit<P extends StreamPayPlanLike>(subscription: Subscription, plan: P | undefined, feature: FeatureKey<P>, requested: number, accessStatuses?: readonly SubscriptionStatus[]): LimitCheckResult;
345
-
346
330
  interface PluginAdapter {
347
331
  create: <T = unknown, D extends object = Record<string, unknown>>(args: {
348
332
  model: string;
@@ -368,6 +352,7 @@ interface PluginAdapter {
368
352
  where?: Array<{
369
353
  field: string;
370
354
  value: unknown;
355
+ operator?: "lt" | "lte";
371
356
  }>;
372
357
  limit?: number;
373
358
  offset?: number;
@@ -392,6 +377,22 @@ interface PluginAdapter {
392
377
  }) => Promise<number>;
393
378
  }
394
379
 
380
+ interface ResolvedPlans {
381
+ list: readonly StreamPayPlanLike[];
382
+ byName: Map<string, StreamPayPlanLike>;
383
+ }
384
+ type FeatureKey<P> = P extends {
385
+ limits?: infer L;
386
+ } ? L extends Record<string, unknown> ? Extract<keyof L, string> : string : string;
387
+ declare function hasSubscriptionAccess(subscription: Pick<Subscription, "status" | "catalogMapped">, accessStatuses?: readonly SubscriptionStatus[]): boolean;
388
+ declare function hasFeature<P extends StreamPayPlanLike>(subscription: Subscription, plan: P | undefined, feature: FeatureKey<P>, accessStatuses?: readonly SubscriptionStatus[]): boolean;
389
+ interface LimitCheckResult {
390
+ allowed: boolean;
391
+ limit: number;
392
+ remaining: number;
393
+ }
394
+ declare function checkLimit<P extends StreamPayPlanLike>(subscription: Subscription, plan: P | undefined, feature: FeatureKey<P>, requested: number, accessStatuses?: readonly SubscriptionStatus[]): LimitCheckResult;
395
+
395
396
  interface SyncContext {
396
397
  context: {
397
398
  adapter: PluginAdapter;
@@ -428,6 +429,10 @@ interface WebhookEventRow {
428
429
  lastError: string | null;
429
430
  lastErrorCode: string | null;
430
431
  }
432
+ interface WebhookReplayOptions {
433
+ /** @deprecated No effect: a failed replay keeps a pending event retryable until its attempts are spent. */
434
+ retryUntilExhausted?: boolean;
435
+ }
431
436
  declare function syncWebhookPayload(ctx: SyncContext, payload: StreamPayWebhookPayload, client: StreamPayClient, plans: ResolvedPlans, callbacks: SubscriptionCallbacks, options?: {
432
437
  dedupe?: boolean;
433
438
  rawBody?: string | null;
@@ -444,7 +449,9 @@ interface StreamPayPluginRegistry {
444
449
  rawBody?: string;
445
450
  signatureHeader?: string | null;
446
451
  }) => Promise<void>;
447
- replayWebhookEvent?: (ctx: GenericEndpointContext, eventId: string) => Promise<{
452
+ replayWebhookEvent?: (ctx: GenericEndpointContext, eventId: string,
453
+ /** @deprecated No effect. */
454
+ options?: WebhookReplayOptions) => Promise<{
448
455
  replayed: true;
449
456
  eventId: string;
450
457
  }>;
@@ -6962,6 +6969,21 @@ declare const webhooks: (webhooksOptions: WebhooksOptions) => (_options: StreamP
6962
6969
  }, {
6963
6970
  received: boolean;
6964
6971
  }>;
6972
+ processDueStreampayWebhookEvents: better_auth.StrictEndpoint<"/streampay/webhooks/process-due", {
6973
+ method: "POST";
6974
+ body: z.ZodOptional<z.ZodObject<{
6975
+ limit: z.ZodOptional<z.ZodNumber>;
6976
+ }, z.core.$strip>>;
6977
+ metadata: {
6978
+ SERVER_ONLY: true;
6979
+ };
6980
+ }, {
6981
+ succeeded: string[];
6982
+ failed: {
6983
+ eventId: string;
6984
+ error: string;
6985
+ }[];
6986
+ }>;
6965
6987
  };
6966
6988
  };
6967
6989
 
@@ -13145,6 +13167,21 @@ declare const streampay: <O extends StreamPayOptions>(options: O) => {
13145
13167
  }, {
13146
13168
  received: boolean;
13147
13169
  }>;
13170
+ processDueStreampayWebhookEvents: better_auth.StrictEndpoint<"/streampay/webhooks/process-due", {
13171
+ method: "POST";
13172
+ body: zod.ZodOptional<zod.ZodObject<{
13173
+ limit: zod.ZodOptional<zod.ZodNumber>;
13174
+ }, zod_v4_core.$strip>>;
13175
+ metadata: {
13176
+ SERVER_ONLY: true;
13177
+ };
13178
+ }, {
13179
+ succeeded: string[];
13180
+ failed: {
13181
+ eventId: string;
13182
+ error: string;
13183
+ }[];
13184
+ }>;
13148
13185
  };
13149
13186
  schema: {
13150
13187
  user: {
@@ -327,22 +327,6 @@ declare const REFERENCE_ID_METADATA_KEY = "streampay_plugin_reference_id";
327
327
  declare const REFERENCE_TYPE_METADATA_KEY = "streampay_plugin_reference_type";
328
328
  declare const SUBSCRIPTION_ROW_ID_METADATA_KEY = "streampay_plugin_subscription_row_id";
329
329
 
330
- interface ResolvedPlans {
331
- list: readonly StreamPayPlanLike[];
332
- byName: Map<string, StreamPayPlanLike>;
333
- }
334
- type FeatureKey<P> = P extends {
335
- limits?: infer L;
336
- } ? L extends Record<string, unknown> ? Extract<keyof L, string> : string : string;
337
- declare function hasSubscriptionAccess(subscription: Pick<Subscription, "status" | "catalogMapped">, accessStatuses?: readonly SubscriptionStatus[]): boolean;
338
- declare function hasFeature<P extends StreamPayPlanLike>(subscription: Subscription, plan: P | undefined, feature: FeatureKey<P>, accessStatuses?: readonly SubscriptionStatus[]): boolean;
339
- interface LimitCheckResult {
340
- allowed: boolean;
341
- limit: number;
342
- remaining: number;
343
- }
344
- declare function checkLimit<P extends StreamPayPlanLike>(subscription: Subscription, plan: P | undefined, feature: FeatureKey<P>, requested: number, accessStatuses?: readonly SubscriptionStatus[]): LimitCheckResult;
345
-
346
330
  interface PluginAdapter {
347
331
  create: <T = unknown, D extends object = Record<string, unknown>>(args: {
348
332
  model: string;
@@ -368,6 +352,7 @@ interface PluginAdapter {
368
352
  where?: Array<{
369
353
  field: string;
370
354
  value: unknown;
355
+ operator?: "lt" | "lte";
371
356
  }>;
372
357
  limit?: number;
373
358
  offset?: number;
@@ -392,6 +377,22 @@ interface PluginAdapter {
392
377
  }) => Promise<number>;
393
378
  }
394
379
 
380
+ interface ResolvedPlans {
381
+ list: readonly StreamPayPlanLike[];
382
+ byName: Map<string, StreamPayPlanLike>;
383
+ }
384
+ type FeatureKey<P> = P extends {
385
+ limits?: infer L;
386
+ } ? L extends Record<string, unknown> ? Extract<keyof L, string> : string : string;
387
+ declare function hasSubscriptionAccess(subscription: Pick<Subscription, "status" | "catalogMapped">, accessStatuses?: readonly SubscriptionStatus[]): boolean;
388
+ declare function hasFeature<P extends StreamPayPlanLike>(subscription: Subscription, plan: P | undefined, feature: FeatureKey<P>, accessStatuses?: readonly SubscriptionStatus[]): boolean;
389
+ interface LimitCheckResult {
390
+ allowed: boolean;
391
+ limit: number;
392
+ remaining: number;
393
+ }
394
+ declare function checkLimit<P extends StreamPayPlanLike>(subscription: Subscription, plan: P | undefined, feature: FeatureKey<P>, requested: number, accessStatuses?: readonly SubscriptionStatus[]): LimitCheckResult;
395
+
395
396
  interface SyncContext {
396
397
  context: {
397
398
  adapter: PluginAdapter;
@@ -428,6 +429,10 @@ interface WebhookEventRow {
428
429
  lastError: string | null;
429
430
  lastErrorCode: string | null;
430
431
  }
432
+ interface WebhookReplayOptions {
433
+ /** @deprecated No effect: a failed replay keeps a pending event retryable until its attempts are spent. */
434
+ retryUntilExhausted?: boolean;
435
+ }
431
436
  declare function syncWebhookPayload(ctx: SyncContext, payload: StreamPayWebhookPayload, client: StreamPayClient, plans: ResolvedPlans, callbacks: SubscriptionCallbacks, options?: {
432
437
  dedupe?: boolean;
433
438
  rawBody?: string | null;
@@ -444,7 +449,9 @@ interface StreamPayPluginRegistry {
444
449
  rawBody?: string;
445
450
  signatureHeader?: string | null;
446
451
  }) => Promise<void>;
447
- replayWebhookEvent?: (ctx: GenericEndpointContext, eventId: string) => Promise<{
452
+ replayWebhookEvent?: (ctx: GenericEndpointContext, eventId: string,
453
+ /** @deprecated No effect. */
454
+ options?: WebhookReplayOptions) => Promise<{
448
455
  replayed: true;
449
456
  eventId: string;
450
457
  }>;
@@ -6962,6 +6969,21 @@ declare const webhooks: (webhooksOptions: WebhooksOptions) => (_options: StreamP
6962
6969
  }, {
6963
6970
  received: boolean;
6964
6971
  }>;
6972
+ processDueStreampayWebhookEvents: better_auth.StrictEndpoint<"/streampay/webhooks/process-due", {
6973
+ method: "POST";
6974
+ body: z.ZodOptional<z.ZodObject<{
6975
+ limit: z.ZodOptional<z.ZodNumber>;
6976
+ }, z.core.$strip>>;
6977
+ metadata: {
6978
+ SERVER_ONLY: true;
6979
+ };
6980
+ }, {
6981
+ succeeded: string[];
6982
+ failed: {
6983
+ eventId: string;
6984
+ error: string;
6985
+ }[];
6986
+ }>;
6965
6987
  };
6966
6988
  };
6967
6989
 
@@ -13145,6 +13167,21 @@ declare const streampay: <O extends StreamPayOptions>(options: O) => {
13145
13167
  }, {
13146
13168
  received: boolean;
13147
13169
  }>;
13170
+ processDueStreampayWebhookEvents: better_auth.StrictEndpoint<"/streampay/webhooks/process-due", {
13171
+ method: "POST";
13172
+ body: zod.ZodOptional<zod.ZodObject<{
13173
+ limit: zod.ZodOptional<zod.ZodNumber>;
13174
+ }, zod_v4_core.$strip>>;
13175
+ metadata: {
13176
+ SERVER_ONLY: true;
13177
+ };
13178
+ }, {
13179
+ succeeded: string[];
13180
+ failed: {
13181
+ eventId: string;
13182
+ error: string;
13183
+ }[];
13184
+ }>;
13148
13185
  };
13149
13186
  schema: {
13150
13187
  user: {
@@ -578,8 +578,25 @@ the `handlers:` event ID prefix and support the existing authenticated admin rep
578
578
  The default is `false` to preserve existing installations that have no inbox table.
579
579
 
580
580
  Verified payloads are persisted when processing is claimed, so an interrupted delivery can be
581
- recovered after its two-minute lease expires. A callback that outlives the lease can run again
582
- when another delivery claims it. Callbacks must still be idempotent: a crash after an external
581
+ recovered after its two-minute lease expires. A delivery that arrives while another worker holds
582
+ the lease gets `503`, so StreamPay redelivers it instead of treating it as handled.
583
+
584
+ StreamPay redelivery is not a retry schedule you control. Run the server-only retry endpoint on a
585
+ schedule (for example every minute) so failed events are retried at `nextAttemptAt` and abandoned
586
+ leases are reclaimed:
587
+
588
+ ```ts
589
+ const { succeeded, failed } = await auth.api.processDueStreampayWebhookEvents({
590
+ body: { limit: 25 },
591
+ });
592
+ ```
593
+
594
+ It processes pending events whose retry time has passed or whose lease expired, keeps failures
595
+ pending with backoff until the attempt budget is spent, and then dead-letters them. The endpoint
596
+ has no HTTP route. Dead-lettered events still need the admin replay endpoint. A failed admin
597
+ replay follows the same rules: a pending event stays pending unless the failure is permanent or
598
+ its attempts are spent, and a dead-lettered event returns to dead letter. A callback that outlives
599
+ the lease can run again when another delivery claims it. Callbacks must still be idempotent: a crash after an external
583
600
  side effect, or failure of a later callback, can repeat earlier work on retry. Inbox deduplication
584
601
  does not provide exactly-once execution of external side effects.
585
602
 
@@ -36,6 +36,7 @@ Tests cover the plugin's implemented features, not every feature of the Stream p
36
36
  | Dynamic catalog stays stale | The upstream 2.2.1 resolver fix is retained and tested. |
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
+ | 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). |
39
40
  | Checkout activates the wrong reservation | Known payment-link and consumer mismatches cannot bind a pending checkout. |
40
41
  | Portal client sends the wrong HTTP method | The real Better Auth client sends POST for the documented no-argument session call. |
41
42
  | 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. |
@@ -0,0 +1,323 @@
1
+ # State machines
2
+
3
+ This document lists every state machine in the plugin, including the ones that exist only as a
4
+ combination of columns. Each section gives the states, the invariants, and a transition table
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 audit, how each one is reachable, and where it
7
+ is fixed.
8
+
9
+ Keep this file in sync with the code. A change to a status value, a slot rule, a lease rule, or a
10
+ compare-and-set `where` clause must update the matching table here and add a regression test.
11
+
12
+ ## Conventions
13
+
14
+ - **CAS** means a conditional `adapter.update` whose `where` clause includes the expected current
15
+ values. A `null` result means another writer changed the row first.
16
+ - **Slot** means `subscription.activeSlotKey`, a unique key derived from
17
+ `(referenceType, referenceId, group)` by `subscriptionSlotKey` in
18
+ `src/plugins/subscriptions/types.ts`.
19
+ - **Provider** means StreamPay. Provider state is fetched again on every webhook. The webhook body
20
+ is only a trigger and a source of signed checkout metadata.
21
+
22
+ ## Inventory
23
+
24
+ | # | Machine | Kind | State lives in | Main code |
25
+ | --- | --- | --- | --- | --- |
26
+ | 1 | Subscription lifecycle | Explicit `status`, plus overlays | `subscription.status`, `billingStatus`, `activeSlotKey` | `subscriptions/sync.ts`, `reconcile.ts`, `endpoints.ts` |
27
+ | 2 | Checkout reservation | Implicit sub-machine of 1 | `status = incomplete*`, `streampayPaymentLinkId`, `createdAt` | `subscriptions/checkout-reservation.ts`, `endpoints.ts` (`upgradeSubscription`) |
28
+ | 3 | Cancellation schedule | Implicit | `cancelAtPeriodEnd`, `cancelAt`, `cancelScheduledAt`, `canceledAt` | `reconcile.ts`, `sync.ts` |
29
+ | 4 | Pending plan/seat change | Implicit | `pendingPlan`, `pendingProductId`, `pendingSeats`, `pending*EffectiveAt` | `reconcile.ts` (`projectPlanFields`), `endpoints.ts` |
30
+ | 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`) |
32
+ | 7 | Webhook inbox event | Explicit `status`, plus lease | `streampayWebhookEvent.status`, `lockedAt`, `lockedBy`, `attemptCount` | `sync.ts`, `webhooks.ts`, `subscriptions/index.ts`, `admin.ts` |
33
+ | 8 | Webhook request pipeline | Implicit ordering | Request scope | `plugins/webhooks.ts` |
34
+ | 9 | Consumer link | Implicit | `user.streampayConsumerId` (unique) | `hooks/consumer.ts`, `utils/ensure-consumer.ts`, `utils/session.ts` |
35
+ | 10 | One-time checkout link | Request-scoped saga | Provider payment link | `plugins/checkout.ts` |
36
+
37
+ ## 1. Subscription lifecycle
38
+
39
+ ### States
40
+
41
+ | Class | Local `status` | Provider status | Slot | Access by default |
42
+ | --- | --- | --- | --- | --- |
43
+ | Reservation | `incomplete` | none yet, or an unknown value | held | no |
44
+ | Released reservation | `incomplete_expired` | none | null | no |
45
+ | Live | `trial_pending` | `TRIAL_PENDING` | held | no |
46
+ | Live | `trialing` | `TRIALING` | held | yes |
47
+ | Live | `active` | `ACTIVE` | held | yes |
48
+ | Live | `frozen` | `FROZEN` | held | yes |
49
+ | Live overlay | `past_due` | `ACTIVE` while `billingStatus = past_due` | held | yes |
50
+ | Terminal | `inactive` | `INACTIVE` | null | no |
51
+ | Terminal | `expired` | `EXPIRED` | null | no |
52
+ | Terminal | `canceled` | `CANCELED` | null | no |
53
+
54
+ `toLocalStatus` (`status.ts`) maps provider values. Any value it does not know maps to
55
+ `incomplete`. `isTerminalSubscriptionStatus` (`status.ts`) defines the terminal class.
56
+ `catalogMapped = false` removes access in every status (`plans.ts`, `hasSubscriptionAccess`).
57
+
58
+ `billingStatus` is a second axis with two values, `current` and `past_due`. It is a local
59
+ overlay: StreamPay keeps reporting `ACTIVE` while a renewal payment is outstanding.
60
+
61
+ ### Invariants
62
+
63
+ | ID | Invariant | Enforced by |
64
+ | --- | --- | --- |
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 backfills a missing slot for live rows. |
66
+ | S2 | At most one row holds a slot. | Database unique constraint on `activeSlotKey`. |
67
+ | 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` runs `takeSlotFromReservation` after its stale-state check (`sync.ts`). |
69
+ | S5 | `billingStatus = past_due` and provider `ACTIVE` imply local `past_due`. | `reconcileProjectionAgainstExisting` (`reconcile.ts`), the renewal stale branch (`sync.ts`). |
70
+ | S6 | `providerUpdatedAt` never moves backwards. | The webhook path throws and retries (`updateReconciledSubscription`). The endpoint path keeps the newer local row (`persistSubscriptionProjection`). |
71
+ | S7 | Every lifecycle write is a CAS on `providerUpdatedAt`, `status`, `billingStatus`, and the correlation IDs. | `updateReconciledSubscription`, `persistSubscriptionProjection`, `handleRenewalEvidence`. |
72
+
73
+ ### Transitions
74
+
75
+ | # | Trigger | From | To | Guard and code |
76
+ | --- | --- | --- | --- | --- |
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`). |
78
+ | 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`) |
80
+ | L4 | Any other projection while billing is `past_due` | `past_due` | `past_due` | S5 |
81
+ | 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. An unpaid holder is released. A live holder raises `SubscriptionCorrelationError`, a permanent failure that dead-letters for manual review. |
83
+ | L7 | Freeze, unfreeze, or freeze cancel | `active` and `frozen` | per provider | `endpoints.ts`, then `syncSubscriptionFromUpstream` |
84
+ | 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
+ | L9 | Unmapped product (`catalogMapped = false`) | any | same status, no access | `projectPlanFields` |
86
+
87
+ Stale events (event timestamp older than `providerUpdatedAt`) still write the freshly fetched
88
+ provider state, but they skip lifecycle callbacks and timestamp stamping.
89
+
90
+ ## 2. Checkout reservation
91
+
92
+ A reservation is the `incomplete` part of machine 1. It holds the slot while the customer is on
93
+ StreamPay's hosted checkout. The idempotency window is
94
+ `UPGRADE_IDEMPOTENCY_WINDOW_MS` (15 minutes).
95
+
96
+ ### States
97
+
98
+ | State | Shape |
99
+ | --- | --- |
100
+ | R0 none | no row for the slot |
101
+ | R1 reserved | `incomplete`, slot held, `streampayPaymentLinkId = null` |
102
+ | R2 linked | `incomplete`, slot held, link ID set |
103
+ | R3 released | `incomplete_expired`, slot null, link inactive or unpayable |
104
+ | R4 confirmed | live status (machine 1) |
105
+
106
+ ### Invariants
107
+
108
+ | ID | Invariant | Enforced by |
109
+ | --- | --- | --- |
110
+ | C1 | A request recovers a reservation only for the same plan and seat count. | `matchesCheckout` in `resumeOrReserveCheckoutSlot` |
111
+ | C2 | A released reservation has no payable link. | `deactivatePaymentLink` (`lifecycle.ts`) runs before every release of a linked reservation. On upgrade, a deactivation failure keeps the reservation and fails the request. On the webhook takeover it is best effort and logged for manual action, so it never blocks the paid subscription. StreamPay still completes a payment already in progress, which S4 covers. |
112
+ | C3 | A checkout URL is returned only while its reservation is still live, or after the customer has already paid it, unless the link persistence write itself fails. | `upgradeSubscription` checks the row returned by the link persistence update (`endpoints.ts`). The takeover's release also matches the holder's link ID, so a link persisted concurrently makes the webhook retry. |
113
+
114
+ ### Transitions
115
+
116
+ | # | Trigger | From | To | Code |
117
+ | --- | --- | --- | --- | --- |
118
+ | C-a | `upgrade` with no holder | R0 | R1 | `adapter.create` with the slot |
119
+ | C-b | `createPaymentLink` succeeds | R1 | R2 | CAS on `id`, `referenceId`, `referenceType`, consumer, `link = null` |
120
+ | C-c | `createPaymentLink` throws | R1 | R0 (row deleted) | `deleteReservedSubscription` |
121
+ | 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` |
124
+ | 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 |
126
+ | C-i | Reservation released while its link was being created | R1 (released) | R3, request gets `SUBSCRIPTION_CHECKOUT_IN_PROGRESS` | New link deactivated |
127
+ | C-j | Paid subscription arrives for another row of the same slot | R1/R2 | R3 | `takeSlotFromReservation` |
128
+ | 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 |
129
+ | C-l | Webhook | R1/R2/R3 | R4 | machine 1, L1 |
130
+ | C-m | `/subscription/success` fallback | R1/R2 | R4 | machine 1, L1 |
131
+
132
+ ## 3. Cancellation schedule
133
+
134
+ | State | `cancelAtPeriodEnd` | `cancelAt` | `cancelScheduledAt` | `canceledAt` |
135
+ | --- | --- | --- | --- | --- |
136
+ | Renewing | false | null | null | null |
137
+ | Scheduled | true | `periodEnd` | first schedule time | null |
138
+ | Canceled | any | any | any | first confirmation time |
139
+
140
+ | Trigger | From | To | Code |
141
+ | --- | --- | --- | --- |
142
+ | `/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 | Not fixed: the later cancel event usually counts as stale and does not stamp (F8, R7) |
144
+ | `/subscription/uncancel` | Scheduled | Renewing | `projectSubscriptionFields` clears `cancelScheduledAt` |
145
+ | Provider `CANCELED` | any | Canceled | `canceledAt` is stamped once |
146
+
147
+ Plan and seat changes are rejected while the subscription is Scheduled.
148
+
149
+ ## 4. Pending plan or seat change
150
+
151
+ States: **None** (all `pending*` null) and **Scheduled** (fields copied from the provider's
152
+ `pending_change.target_items`). The provider is the only source. `projectPlanFields` recomputes
153
+ the fields from every fetched subscription, so a webhook after the effective date clears them.
154
+ `change-plan` and `update-seats` return `reused: true` when the provider already has the same
155
+ target. They reject a different target with `*_ALREADY_SCHEDULED`. Both cancel endpoints are
156
+ idempotent.
157
+
158
+ ## 5. Freeze
159
+
160
+ The plugin does not store a freeze machine of its own. `frozenAt` and `freezeEndAt` are set only
161
+ while the provider status is `FROZEN`. Future (scheduled) freezes exist only at StreamPay.
162
+ `unfreeze` ends the active freeze at "now". `freeze/cancel` treats StreamPay's "Cannot delete
163
+ non-latest freeze entry" 403 response as already canceled.
164
+
165
+ ## 6. Renewal callback ownership
166
+
167
+ `renewalCallbackEventId` is a per-subscription lock that makes `onSubscriptionRenewed` survive
168
+ retries without firing for two events of the same cycle.
169
+
170
+ | From | Trigger | To | Code |
171
+ | --- | --- | --- | --- |
172
+ | null | Fresh renewal evidence advances the period or cycle and a callback is configured | event ID (CAS with the projection) | `handleRenewalEvidence` |
173
+ | event E | Callback succeeds | null (CAS on E) | same |
174
+ | event E | Callback throws with `retryOnCallbackError` | E (event recorded as failed) | same |
175
+ | event E | Redelivery or replay of E | E, then null after success | `pendingCallback === eventId` branch |
176
+ | 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
+ Invariant: while the lock is set, its cycle's callback has not been delivered. Other renewal
180
+ evidence for that subscription waits until the lock clears.
181
+
182
+ ## 7. Webhook inbox event
183
+
184
+ One table serves two scopes. Subscription sync uses
185
+ `<event_type>:<entity_id>:<timestamp>`. Generic handlers (`webhooks({ deduplicate: true })`) use
186
+ the same ID with a `handlers:` prefix.
187
+
188
+ ### States
189
+
190
+ | State | `status` | Lease | Payload |
191
+ | --- | --- | --- | --- |
192
+ | E0 absent | none | none | none |
193
+ | E1 leased | `pending` | `lockedAt` under 2 minutes old, `lockedBy` set | stored |
194
+ | E2 retryable | `pending` | none (failure recorded) or expired (crash) | stored |
195
+ | E3 completed | `completed` | none | cleared |
196
+ | E4 dead letter | `dead_letter` | none | stored |
197
+
198
+ ### Invariants
199
+
200
+ | ID | Invariant | Enforced by |
201
+ | --- | --- | --- |
202
+ | W1 | At most one worker holds a live lease. | `eventId` is unique. Claims are CAS on `status` and `lockedAt`. |
203
+ | W2 | Only the lease owner can complete or fail an event. | `markWebhookEventCompleted` and `recordWebhookEventFailure` filter on `lockedBy`. |
204
+ | W3 | Completed and dead-lettered events are never processed by delivery, only by replay. | `claimOrAdvanceWebhookEvent` skips them. |
205
+ | W4 | A replay failure never takes an event out of provider retry unless the event was already dead-lettered, has exhausted its attempts, or failed permanently. | Replay functions in `subscriptions/index.ts` and `webhooks.ts` (#27). |
206
+
207
+ ### Transitions
208
+
209
+ | # | Trigger | From | To | Code |
210
+ | --- | --- | --- | --- | --- |
211
+ | W-a | First delivery | E0 | E1 | `claimOrAdvanceWebhookEvent` create |
212
+ | 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 `lockedAt` |
214
+ | W-d | Delivery with attempts exhausted | E2 | E4 | same CAS |
215
+ | W-e | Processing succeeds | E1 | E3 | `markWebhookEventCompleted(lockedBy)` |
216
+ | W-f | Transient failure, attempts left | E1 | E2 (`nextAttemptAt` set) | `recordWebhookEventFailure` |
217
+ | 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` |
219
+ | 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 | `adminDiscardWebhookEvent`. Ignores a live lease by design. |
221
+
222
+ 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.
224
+
225
+ ## 8. Webhook request pipeline
226
+
227
+ ```text
228
+ verify signature and tolerance -> parse envelope
229
+ -> subscription sync (own inbox row; in-progress returns 503, permanent failure 200, transient 500)
230
+ -> generic handlers (own `handlers:` inbox row when deduplicate is on)
231
+ -> 200
232
+ ```
233
+
234
+ A sync failure stops the request before the handlers run. StreamPay's redelivery then skips the
235
+ completed sync row and retries the handlers. A handler failure returns 500 after a successful
236
+ sync, and the redelivery skips the sync row.
237
+
238
+ ## 9. Consumer link
239
+
240
+ | State | `user.streampayConsumerId` |
241
+ | --- | --- |
242
+ | Unlinked | null |
243
+ | Linked | StreamPay consumer UUID (unique) |
244
+
245
+ | Trigger | From | To | Code |
246
+ | --- | --- | --- | --- |
247
+ | Sign-up with `createConsumerOnSignUp` | Unlinked | Linked (inside the user insert) | `onBeforeUserCreate`. `onAfterUserCreate` backfills `external_id`. |
248
+ | First checkout or upgrade | Unlinked | Linked | `ensureConsumerForUser`: recover by `external_id`, create, or claim a duplicate |
249
+ | Claim backfill fails | Linked | Unlinked (CAS on the claimed ID) | `ensure-consumer.ts` duplicate branch |
250
+ | Provider 404 on profile sync | Linked | Unlinked (CAS) | `onUserUpdate` |
251
+ | Admin deletes the consumer | Linked | Unlinked (CAS) | `adminDeleteConsumer` |
252
+ | Cached session carries an old ID | n/a | the database value wins | `getCurrentConsumerUser` |
253
+ | Portal call while unlinked | Unlinked | Unlinked (reads by `external_id`, never writes) | `portal.ts` |
254
+
255
+ Invariants: one consumer per user and one user per consumer (unique column and
256
+ `assertConsumerUnclaimed`). Client input never sets the link (`input: false`).
257
+
258
+ ## 10. One-time checkout link
259
+
260
+ `POST /checkout` creates a payment link, then runs `onCheckoutCreated`. If URL resolution or the
261
+ callback fails, the link is deactivated best-effort and the request fails. No local state is
262
+ written.
263
+
264
+ ## Audit findings
265
+
266
+ Severity reflects customer and money impact. Each finding has unit tests and end-to-end tests that
267
+ drive a real Better Auth instance through HTTP with signed webhooks. All of them fail on the code
268
+ before the fix and pass after it. CI runs them on SQLite; they were also run locally on
269
+ PostgreSQL 17. Run the end-to-end tests on PostgreSQL with `STREAMPAY_E2E_DB=postgres` and a database at
270
+ `postgres://user:password@localhost:5432/better_auth` (hardcoded by `better-auth/test`).
271
+
272
+ | ID | Severity | Machine | Invalid state or transition | How it is reached | Before the fix | Fix |
273
+ | --- | --- | --- | --- | --- | --- | --- |
274
+ | F1 | High | 2 → 1 | A paid subscription is never recorded, so the customer has no access. A second payment is also possible. | Checkout A (link L1) is left open for more than 15 minutes. The customer starts checkout B with another plan or seat count. C-h releases A without deactivating L1, and B takes the slot. The customer pays L1. The webhook correlates to A and tries to take the slot from B, which fails the unique constraint on every attempt. | Five deliveries return 500, then the event dead-letters with a raw unique-constraint error. `/subscription/success` does not link it either. `/subscription/current` returns `null`, and L2 stays payable. Reproduced live in the StreamPay sandbox. | C2 and S4, in the PR that adds this document |
275
+ | F2 | Low | 1 | Two live subscriptions compete for one slot, and the failure is retried as if it were transient. | StreamPay reactivates a locally terminal subscription (StreamPay documents `SUBSCRIPTION_ACTIVATED` as "initial activation or reactivation") after a replacement took the slot (L6). | Five deliveries return 500, then the event dead-letters with a misleading code. When the holder is an unpaid reservation, this is F1. | Dead letter on the first attempt as `SubscriptionCorrelationError` |
276
+ | F3 | n/a | 2 | A checkout URL is returned for a reservation that was already released. | Reachable only through the S4 takeover, while an upgrade is creating its link. | n/a | Guard C3, shipped with the F1 fix |
277
+ | F4 | Low | 2 | The raw database unique-constraint error reaches the client. | A webhook activates the user's pending checkout while a second upgrade is between its active-subscription check and its reservation insert (for example during `isTrialEligible`). | HTTP 500 with an empty body. | 409 `SUBSCRIPTION_ALREADY_ACTIVE` (C-k) |
278
+ | 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
+ | 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
+ | 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`. | Not fixed (R7). Relaxing the stamp condition alone let endpoints stamp the time of an unrelated later call. |
282
+
283
+ ### Live sandbox evidence for F1
284
+
285
+ Run on 2026-11-09 in a Stream sandbox organization with a 3DS test-card payment.
286
+
287
+ | Step | Original `main` | With the fix |
288
+ | --- | --- | --- |
289
+ | Replace a checkout reservation older than 15 minutes | StreamPay reports the abandoned link `ACTIVE` | StreamPay reports it `INACTIVE`; its hosted page shows "Payment link is inactive" with no card form |
290
+ | Pay the abandoned link (original build only) | StreamPay creates an `ACTIVE` subscription whose `latest_invoice.payment_link_id` is the abandoned link | n/a: the link refuses payment |
291
+ | Process `SUBSCRIPTION_ACTIVATED` for that subscription | Five HTTP 500 responses, then a dead letter on `activeSlotKey`; `/subscription/current` is `null`; the replacement link stays `ACTIVE` | First delivery returns 200; the paid row is active; the replacement reservation is released and StreamPay reports its link `INACTIVE` |
292
+
293
+ The sandbox API keys cannot register webhooks, so StreamPay's delivery hop was replaced: the event
294
+ was signed locally, and its `data.metadata` is the `custom_metadata` StreamPay stored on the paid
295
+ link. The plugin re-fetched the subscription from StreamPay as usual. The fixed run used a copy of
296
+ the original run's database with the inbox cleared, as if the fix had been deployed first.
297
+
298
+ ### Grouped issues
299
+
300
+ **Issue 1, P1: Released checkout reservations stay payable and block the paid subscription (F1,
301
+ F2, F4, and guard F3).** Deactivate a linked reservation's payment link before releasing it. Let a
302
+ provider-confirmed subscription take its slot from an unpaid reservation. Dead-letter a genuine
303
+ duplicate as a permanent failure. Map a live slot holder to `SUBSCRIPTION_ALREADY_ACTIVE`.
304
+
305
+ **Issue 2, P2: Manual replay dead-letters events that StreamPay is still retrying (F5–F7).** Fixed
306
+ by #27.
307
+
308
+ **Issue 3, P3: The cancellation schedule time is lost when events arrive out of order (F8).** Open.
309
+ A correct fix must stamp from the cancel event even when it is stale against `providerUpdatedAt`,
310
+ without letting endpoint projections stamp unrelated call times.
311
+
312
+ ### Open risks (not confirmed, not changed)
313
+
314
+ | ID | Risk | Why it is not fixed here |
315
+ | --- | --- | --- |
316
+ | R1 | `past_due` can stay set after recovery. If a non-renewal webhook or customer action stores a `providerUpdatedAt` later than the timestamp of the recovering `INVOICE_COMPLETED`, that evidence counts as stale and the stale branch keeps `past_due` (`handleRenewalEvidence`). | Depends on how StreamPay orders `updated_at` against event timestamps. A correct fix needs the failure time stored (a schema change). Access is unaffected by default because `past_due` grants access. |
317
+ | R2 | `persistConsumerId` writes with `updateUser`, not a CAS on a null link. Two concurrent first checkouts can each create a consumer if StreamPay does not reject the duplicate email or `external_id`. | Unconfirmed provider behavior. Recovery by `external_id` covers the common case. |
318
+ | 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
+ | 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
+ | R5 | Generic handler deliveries always use 5 attempts and ignore `maxWebhookAttempts`. | That option belongs to `subscriptions()`. Changing it is an API decision. |
321
+ | R6 | A callback that runs longer than the 2-minute lease can run concurrently with a redelivery. | Documented. Callbacks must be idempotent. |
322
+ | R7 | F8: `cancelScheduledAt` stays `null` when another webhook records the scheduled cancellation before the cancel event. | See Issue 3. The column is informational; access and slots are unaffected. |
323
+ | R8 | A pending inbox row that fails before it is claimed for replay (no stored payload, or a payload that is no longer valid) is never retried or dead-lettered. `processDueStreampayWebhookEvents` selects it oldest first on every run, so enough such rows fill every batch. | Pre-existing. Needs its own fix: dead-letter unreplayable rows when the processor finds them. |
@@ -124,7 +124,7 @@ processing idempotent and observable.
124
124
  | `eventType` | string, required | StreamPay event such as `SUBSCRIPTION_PLAN_UPDATED`. Useful for routing, debugging, and operations. |
125
125
  | `receivedAt` | date, required, indexed | First receipt time. |
126
126
  | `lastAttemptAt` | nullable date, indexed | Most recent processing/replay attempt. |
127
- | `nextAttemptAt` | nullable date, indexed | Earliest automatic retry time after transient failure. |
127
+ | `nextAttemptAt` | nullable date, indexed | Earliest time `processDueStreampayWebhookEvents` retries the event after a transient failure. |
128
128
  | `completedAt` | nullable date, indexed | Successful completion time. Completed events no longer retain replay payload/signature data. |
129
129
  | `deadLetteredAt` | nullable date, indexed | Time a permanent failure or exhausted retry budget moved the event to manual review. |
130
130
  | `lockedAt` | nullable date, indexed | Start time of the current processing lease. Stale leases can be safely reclaimed. |
@@ -215,7 +215,10 @@ updateSeats(newSeats)
215
215
 
216
216
  The upgrade reservation is idempotent by plan **and** seat count. A second request for a different
217
217
  quantity cannot accidentally recover an earlier checkout URL; it returns a conflict until that
218
- reservation expires.
218
+ reservation expires. Replacing an expired reservation first deactivates its StreamPay payment
219
+ link. If a customer still completes an older checkout, the paid subscription takes the slot from any
220
+ unpaid reservation. Two paid subscriptions in one slot are dead-lettered for manual review.
221
+ [State machines](state-machines.md) lists every reservation and lifecycle transition.
219
222
 
220
223
  ## Migration
221
224
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "better-auth-streampay",
3
- "version": "3.0.2",
3
+ "version": "3.2.0",
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",