better-auth-streampay 3.3.1 → 3.5.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.
@@ -27,15 +27,15 @@ compare-and-set `where` clause must update the matching table here and add a reg
27
27
 
28
28
  | # | Machine | Kind | State lives in | Main code |
29
29
  | --- | --- | --- | --- | --- |
30
- | 1 | Subscription lifecycle | Explicit `status`, plus overlays | `subscription.status`, `billingStatus`, `activeSlotKey` | `subscriptions/sync.ts`, `reconcile.ts`, `endpoints.ts` |
31
- | 2 | Checkout reservation | Implicit sub-machine of 1 | `status = incomplete*`, `streampayPaymentLinkId`, `createdAt` | `subscriptions/checkout-reservation.ts`, `endpoints.ts` (`upgradeSubscription`) |
30
+ | 1 | Subscription lifecycle | Explicit `status`, plus overlays | `subscription.status`, `billingStatus`, `activeSlotKey` | `subscriptions/reconcile.ts` (all row writes), `sync.ts`, `endpoints.ts` |
31
+ | 2 | Checkout reservation | Implicit sub-machine of 1 | `status = incomplete*`, `streampayPaymentLinkId`, `createdAt` | `subscriptions/checkout-reservation.ts` (every R-state move) |
32
32
  | 3 | Cancellation schedule | Implicit | `cancelAtPeriodEnd`, `cancelAt`, `cancelScheduledAt`, `canceledAt` | `reconcile.ts`, `sync.ts` |
33
33
  | 4 | Pending plan/seat change | Implicit | `pendingPlan`, `pendingProductId`, `pendingSeats`, `pending*EffectiveAt` | `reconcile.ts` (`projectPlanFields`), `endpoints.ts` |
34
34
  | 5 | Freeze | Provider-driven projection | `status = frozen`, `frozenAt`, `freezeEndAt` | `endpoints.ts`, `lifecycle.ts` |
35
35
  | 6 | Renewal callback ownership | Implicit lock plus cycle marker | `subscription.renewalCallbackEventId`, `renewedCycleNumber` | `sync.ts` (`handleRenewalEvidence`) |
36
- | 7 | Webhook inbox event | Explicit `status`, plus lease | `streampayWebhookEvent.status`, `lockedAt`, `lockedBy`, `attemptCount` | `sync.ts`, `webhooks.ts`, `subscriptions/index.ts`, `admin.ts` |
36
+ | 7 | Webhook inbox event | Explicit `status`, plus lease | `streampayWebhookEvent.status`, `lockedAt`, `lockedBy`, `attemptCount` | `webhooks/inbox.ts`; scopes in `subscriptions/sync.ts` and `plugins/webhooks.ts` |
37
37
  | 8 | Webhook request pipeline | Implicit ordering | Request scope | `plugins/webhooks.ts` |
38
- | 9 | Consumer link | Implicit | `user.streampayConsumerId` (unique) | `hooks/consumer.ts`, `utils/ensure-consumer.ts`, `utils/session.ts` |
38
+ | 9 | Consumer link | Implicit | `user.streampayConsumerId` (unique) | `utils/consumer-link.ts` (every link write and read), `utils/ensure-consumer.ts`, `hooks/consumer.ts` |
39
39
  | 10 | One-time checkout link | Request-scoped saga | Provider payment link | `plugins/checkout.ts` |
40
40
 
41
41
  ## 1. Subscription lifecycle
@@ -69,17 +69,18 @@ overlay: StreamPay keeps reporting `ACTIVE` while a renewal payment is outstandi
69
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). |
70
70
  | S2 | At most one row holds a slot. | Database unique constraint on `activeSlotKey`. |
71
71
  | S3 | A provider subscription maps to at most one row. A payment link maps to at most one row. | Unique `streampaySubscriptionId` and `streampayPaymentLinkId`. |
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`). |
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. | `persistReconciledProjection` and `handleRenewalEvidence` run `yieldReservationToPaidSubscription` after their stale-state checks (`sync.ts`). |
73
73
  | S5 | `billingStatus = past_due` and provider `ACTIVE` imply local `past_due`. | `reconcileProjectionAgainstExisting` (`reconcile.ts`), the renewal stale branch (`sync.ts`). |
74
- | S6 | `providerUpdatedAt` never moves backwards. | The webhook path throws and retries (`updateReconciledSubscription`). The endpoint path keeps the newer local row (`persistSubscriptionProjection`). |
75
- | S7 | Every lifecycle write is a CAS on `providerUpdatedAt`, `status`, `billingStatus`, and the correlation IDs. | `updateReconciledSubscription`, `persistSubscriptionProjection`, `handleRenewalEvidence`. |
74
+ | S6 | `providerUpdatedAt` never moves backwards. | `isOlderProviderState` (`reconcile.ts`). The webhook path throws and retries (`persistReconciledProjection`). The endpoint path keeps the newer local row (`persistSubscriptionProjection`). |
75
+ | S7 | Every lifecycle write is a CAS on `providerUpdatedAt`, `status`, `billingStatus`, and the correlation IDs. | `lifecycleWriteGuard` (`reconcile.ts`, includes `renewedCycleNumber`), used by `persistReconciledProjection`, `persistSubscriptionProjection`, and `handleRenewalEvidence`, which adds the period, cycle, and callback owner (F31). |
76
+ | S9 | A checkout link stamped with another `appId` never links, through any path. Otherwise a subscription with no row ID or payment-link match is linked only with ownership evidence: StreamPay bills a configured plan product, and a `user` reference exists with a compatible consumer, an organization or custom reference passes `resolveSubscriptionReference`, or the app's `resolveUnlinkedSubscription` (only for subscriptions without any plugin metadata) or an admin chose the reference. An admin link never displaces another slot holder. | `verifyUnlinkedOwnership`, `resolveUnlinkedCorrelation`, `linkSubscriptionToReference` (`sync.ts`). `SUBSCRIPTION_CREATED` and `SUBSCRIPTION_ACTIVATED` keep linking unverified organization and custom references with a warning (3.x compatibility). |
76
77
  | 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`). |
77
78
 
78
79
  ### Transitions
79
80
 
80
81
  | # | Trigger | From | To | Guard and code |
81
82
  | --- | --- | --- | --- | --- |
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`). |
83
+ | 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). The row that owns the payment link, in any status, comes before the newest-reservation fallback; with no local row, S9 decides. 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`). |
83
84
  | L2 | `SUBSCRIPTION_CYCLE_RENEWAL_FAILED`, not stale | `active` | `past_due`, billing `past_due` | `sync.ts` |
84
85
  | 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`) |
85
86
  | L4 | Any other projection while billing is `past_due` | `past_due` | `past_due` | S5 |
@@ -128,7 +129,7 @@ StreamPay's hosted checkout. The idempotency window is
128
129
  | ID | Invariant | Enforced by |
129
130
  | --- | --- | --- |
130
131
  | C1 | A request recovers a reservation only for the same plan and seat count. | `matchesCheckout` in `resumeOrReserveCheckoutSlot` |
131
- | 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. |
132
+ | C2 | A released reservation has no payable link. | `releaseReservation` (`checkout-reservation.ts`) runs `deactivatePaymentLink` before every release of a linked reservation, except when the link is already gone or inactive. 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. |
132
133
  | 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. |
133
134
 
134
135
  ### Transitions
@@ -144,7 +145,7 @@ StreamPay's hosted checkout. The idempotency window is
144
145
  | C-g | Different plan or seats within the window | R1/R2 | R1/R2, request gets `SUBSCRIPTION_CHECKOUT_IN_PROGRESS` | by design |
145
146
  | 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. |
146
147
  | C-i | Reservation released while its link was being created | R1 (released) | R3, request gets `SUBSCRIPTION_CHECKOUT_IN_PROGRESS` | New link deactivated |
147
- | C-j | Paid subscription arrives for another row of the same slot | R1/R2 | R3 | `takeSlotFromReservation` |
148
+ | C-j | Paid subscription arrives for another row of the same slot | R1/R2 | R3 | `yieldReservationToPaidSubscription` |
148
149
  | 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 |
149
150
  | C-l | Webhook | R1/R2/R3 | R4 | machine 1, L1 |
150
151
  | C-m | `/subscription/success` fallback | R1/R2 | R4 | machine 1, L1 |
@@ -195,7 +196,7 @@ retries without firing for two events of the same cycle.
195
196
  | event E | Callback throws with `retryOnCallbackError` | E (event recorded as failed) | same |
196
197
  | event E | Redelivery or replay of E | E, then null after success | `pendingCallback === eventId` branch |
197
198
  | event E | Renewal evidence for another event | E (other event fails and retries) | `pendingCallback !== eventId` |
198
- | event E | Admin discards E | null | `adminDiscardWebhookEvent`, after the event is completed |
199
+ | event E | Admin discards E | null | the subscription scope's `onDiscard` (`releaseRenewalCallbackOwner`), after the event is completed |
199
200
  | 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
 
201
202
  Invariants: while the lock is set, its cycle's callback has not been delivered, and other renewal
@@ -213,7 +214,9 @@ periods start up to 9 minutes after `started_at`.
213
214
 
214
215
  One table serves two scopes. Subscription sync uses
215
216
  `<event_type>:<entity_id>:<timestamp>`. Generic handlers (`webhooks({ deduplicate: true })`) use
216
- the same ID with a `handlers:` prefix.
217
+ the same ID with a `handlers:` prefix. Both scopes run in the inbox module (`webhooks/inbox.ts`),
218
+ which routes replay by that prefix: a `handlers:` row is never replayed through subscription sync,
219
+ even when generic deduplication is off (F29).
217
220
 
218
221
  ### States
219
222
 
@@ -231,9 +234,9 @@ the same ID with a `handlers:` prefix.
231
234
  | ID | Invariant | Enforced by |
232
235
  | --- | --- | --- |
233
236
  | W1 | At most one worker holds a live lease. | `eventId` is unique. Claims are CAS on `status` and `lockedAt`. |
234
- | W2 | Only the lease owner can complete or fail an event. | `markWebhookEventCompleted` and `recordWebhookEventFailure` filter on `lockedBy`. |
237
+ | W2 | Only the lease owner can complete or fail an event. | `markWebhookEventCompleted` and `recordWebhookEventFailure` require the lease's `lockedBy`. |
235
238
  | W3 | Completed and dead-lettered events are never processed by delivery, only by replay. | `claimOrAdvanceWebhookEvent` skips them. |
236
- | 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). |
239
+ | 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. | `runClaimedEvent` (`webhooks/inbox.ts`), shared by delivery, replay, and the due queue. |
237
240
 
238
241
  ### Transitions
239
242
 
@@ -246,10 +249,10 @@ the same ID with a `handlers:` prefix.
246
249
  | W-e | Processing succeeds | E1 | E3 | `markWebhookEventCompleted(lockedBy)` |
247
250
  | W-f | Transient failure, attempts left | E1 | E2 (`nextAttemptAt` set) | `recordWebhookEventFailure` |
248
251
  | 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 |
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) |
252
+ | 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`, `isStillDue` (`webhooks/inbox.ts`) (F15) |
250
253
  | 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. |
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). |
254
+ | W-j | Admin discard | any except E1 | E3 | `WebhookInbox.discard`, 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). |
255
+ | W-k | Replay or due-event processing finds no replayable payload, or the event's scope is disabled (`lastErrorCode = WEBHOOK_INBOX_SCOPE_DISABLED`) | 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). |
253
256
 
254
257
  E2 events move on a StreamPay redelivery, an admin replay, or a scheduled call to
255
258
  `processDueStreampayWebhookEvents`, which selects them by `nextAttemptAt` and expired leases. E2p
@@ -282,10 +285,10 @@ sync, and the redelivery skips the sync row.
282
285
  | --- | --- | --- | --- |
283
286
  | Sign-up with `createConsumerOnSignUp` | Unlinked | Linked (inside the user insert) | `onBeforeUserCreate`. `onAfterUserCreate` backfills `external_id`. |
284
287
  | First checkout or upgrade | Unlinked | Linked | `ensureConsumerForUser`: recover by `external_id`, create, or claim a duplicate |
285
- | Claim backfill fails | Linked | Unlinked (CAS on the claimed ID) | `ensure-consumer.ts` duplicate branch |
288
+ | Claim backfill fails | Linked | Unlinked (CAS on the claimed ID) | `unlinkConsumer`, from the `ensure-consumer.ts` duplicate branch, only by the request that stored the link |
286
289
  | Provider 404 on profile sync | Linked | Unlinked (CAS) | `onUserUpdate` |
287
290
  | Admin deletes the consumer | Linked | Unlinked (CAS) | `adminDeleteConsumer` |
288
- | Cached session carries an old ID | n/a | the database value wins | `getCurrentConsumerUser` |
291
+ | Cached session carries an old ID, or none | n/a | the database value wins | `getCurrentConsumerUser` |
289
292
  | Portal call while unlinked | Unlinked | Unlinked (reads by `external_id`, never writes) | `portal.ts` |
290
293
 
291
294
  Invariants: one consumer per user and one user per consumer (unique column and
@@ -330,6 +333,8 @@ PostgreSQL 17. Run the end-to-end tests on PostgreSQL with `STREAMPAY_E2E_DB=pos
330
333
  | 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
334
  | 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
335
  | 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 |
336
+ | F32 | Medium | 1 | A row for a reference this app does not have, or a paid checkout that fails to link on every delivery. | Pre-existing, raised in the design consultation. A creation webhook without a reservation created a row from metadata alone, so in a StreamPay organization shared by two apps, the other app's checkout created rows here and could release a local unpaid reservation in the same slot. When a released reservation (`incomplete_expired`) owned the payment link and the metadata had no row ID, the insert failed on the unique link ID. | Junk rows and slot interference across apps; a dead-lettered activation. | S9, and the link owner is linked before any insert |
337
+ | F33 | Medium | 1, 6 | A paid subscription that is never linked: a dashboard or API subscription, or a plugin checkout whose reservation row is gone. Every renewal completes without effect. | The rest of R11. Nothing tied the subscription to a local row except data the plugin did not check. | No access and no `onSubscriptionRenewed`, silently. | `resolveUnlinkedSubscription` (opt-in), recovery under S9 on renewal and creation events, and `adminLinkSubscription` for manual repair. GPT-6.2 Astra's implementation review found six bypasses and races (a foreign `appId` through row-ID or link-owner paths, the creation exception on other events, admin races, resolver plan and error handling); all fixed with regression tests. Reproduced live; see below |
333
338
  | 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
339
  | 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
340
  | 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` |
@@ -399,6 +404,16 @@ reservation that owns that link, as if every creation webhook had failed, then d
399
404
  | 3.3.0 | `completed` | still `incomplete`, unlinked | none |
400
405
  | With the fix | `completed` | `active`, linked to `a74dcc6a`, cycle 5 | one, for cycle 5 |
401
406
 
407
+ **F33.** `probe-unlinked-live.mjs` runs 3.3.1 and this change against real sandbox objects. All
408
+ StreamPay calls were read-only except one subscription created through the API (`7695025f`),
409
+ canceled afterwards.
410
+
411
+ | Case | Real object | 3.3.1 | With the fix |
412
+ | --- | --- | --- | --- |
413
+ | Plugin checkout whose reservation row is gone; the local user exists with the same consumer; real cycle-4 `INVOICE_COMPLETED` | `068838a9` | no row, no callback | linked, `active`, slot held, `onSubscriptionRenewed` once (cycle 4) |
414
+ | Subscription created through the StreamPay API (no link, no metadata); `SUBSCRIPTION_CREATED` | `7695025f` | no row | `resolveUnlinkedSubscription` called once; linked (`inactive`, no slot); `onSubscriptionCreated` once |
415
+ | Admin link of an `ACTIVE` cycle-5 subscription | `a74dcc6a` | endpoint 404 | 200, linked, `active`, slot held, no lifecycle callback |
416
+
402
417
  **F10.** The sandbox exposes `latest_invoice` with `id` and `status` on the subscription, and a
403
418
  paid invoice reads `COMPLETED` (subscription `39143aaa`). An invoice's `period_end` does not match
404
419
  the subscription's (12 seconds apart), so the fix compares invoice IDs, not periods.
@@ -467,13 +482,23 @@ file covers F15 and F16; `tests/integration/review-findings.test.ts` covers F18
467
482
  | ID | Risk | Why it is not fixed here |
468
483
  | --- | --- | --- |
469
484
  | 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. |
485
+ | R2 | Disproved live: StreamPay rejects a concurrent duplicate email or `external_id`, so both requests link the same consumer. The link is still claimed with a CAS on a null link (`linkConsumer`), so a request that loses never overwrites the stored link or rolls it back. | |
471
486
  | 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. |
472
487
  | 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. |
473
- | R5 | Generic handler deliveries always use 5 attempts and ignore `maxWebhookAttempts`. | That option belongs to `subscriptions()`. Changing it is an API decision. |
488
+ | R5 | Fixed: `webhooks({ maxWebhookAttempts })` sets the generic handler attempt budget (default 5). | |
474
489
  | R6 | A callback that runs longer than the 2-minute lease can run concurrently with a redelivery. | Documented. Callbacks must be idempotent. |
475
490
  | R7 | Fixed with F8 (Issue 4). | |
476
491
  | R8 | Confirmed as F12 and fixed. Parked rather than dead-lettered, so StreamPay retries still count (W4). | |
477
492
  | R9 | Confirmed as F13 and fixed. | |
478
493
  | 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. | |
494
+ | R11 | Fixed: F28, F32, and F33. A subscription that no rule links stays unlinked by design; `adminLinkSubscription` repairs it. | |
495
+
496
+ ### Module consolidation findings
497
+
498
+ Found while consolidating each machine into one module (3.4.0).
499
+
500
+ | ID | Severity | Machine | Invalid state or transition | Before | Fix |
501
+ | --- | --- | --- | --- | --- | --- |
502
+ | F29 | Medium | 7 | A leftover `handlers:` row is marked completed without running any handler. | With `subscriptions()` deduplicating and `webhooks({ deduplicate })` off, replay fell through to subscription sync, which ignored the event and completed the row. | Prefix routing in the inbox; the row is parked (W-k). |
503
+ | F30 | Low | 4 | `pending*` and `catalogMapped` stay stale after cancel, uncancel, freeze, unfreeze, freeze cancel, and admin subscription changes. | Those paths projected status fields only. | Every endpoint projection includes the plan catalog; admin writes go through `registry.refreshSubscriptionProjection`. A snapshot without `items` leaves plan fields unchanged. |
504
+ | F31 | Low | 1, 6 | A renewal write could apply to a row whose consumer or subscription binding changed concurrently. | Its CAS omitted the correlation IDs that S7 lists. | `lifecycleWriteGuard` in the renewal CAS. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "better-auth-streampay",
3
- "version": "3.3.1",
3
+ "version": "3.5.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",
@@ -69,8 +69,8 @@
69
69
  "demo:exercise": "node --env-file=examples/demo/.env.local examples/demo/exercise.mjs",
70
70
  "demo:cleanup": "node --env-file=examples/demo/.env.local examples/demo/cleanup.mjs",
71
71
  "test": "vitest run --exclude tests/live/**/*.test.ts",
72
- "test:live": "STREAMPAY_LIVE=1 vitest run tests/live",
73
- "test:live:write": "STREAMPAY_LIVE=1 STREAMPAY_LIVE_WRITE=1 vitest run tests/live",
72
+ "test:live": "STREAMPAY_LIVE=1 vitest run tests/live --no-file-parallelism",
73
+ "test:live:write": "STREAMPAY_LIVE=1 STREAMPAY_LIVE_WRITE=1 vitest run tests/live --no-file-parallelism",
74
74
  "test:watch": "vitest --exclude tests/live/**/*.test.ts",
75
75
  "test:coverage": "vitest run --coverage --exclude tests/live/**/*.test.ts",
76
76
  "typecheck": "tsc --noEmit",