better-auth-streampay 3.3.1 → 3.4.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.
@@ -1,5 +1,5 @@
1
1
  import * as better_auth from 'better-auth';
2
- import { Where, GenericEndpointContext, User, UnionToIntersection } from 'better-auth';
2
+ import { GenericEndpointContext, User, UnionToIntersection, Where } from 'better-auth';
3
3
  import * as _streamsdk_typescript from '@streamsdk/typescript';
4
4
  import { SubscriptionDetailed, CurrencyCode, CreatePaymentLinkDto, FreezeListResponse, PaymentRefundRequest, SubscriptionUpdate, ConsumerCreate, ConsumerResponse, PaginationParams, ConsumerListResponse, ConsumerUpdate, PaymentLinkDetailed, PaymentLinkListResponse, UpdatePaymentLinkStatusDto, ProductCreate, ProductDto, ProductListResponse, ProductUpdate, CouponCreate, CouponDetailed, CouponListResponse, CouponUpdate, SubscriptionCreate, SubscriptionListResponse, SubscriptionCancel, FreezeSubscriptionCreateRequest, FreezeSubscriptionBase, FreezeSubscriptionUpdateRequest, InvoiceListResponse, InvoiceDetailed, PaymentListResponse, PaymentResponse } from '@streamsdk/typescript';
5
5
  import * as zod from 'zod';
@@ -55,32 +55,6 @@ declare const $ERROR_CODES: {
55
55
  type StreamPayErrorCode = keyof typeof $ERROR_CODES;
56
56
  declare function mapToErrorCode(rawCode: string | undefined, status: number | undefined): StreamPayErrorCode;
57
57
 
58
- interface StreamPayLoggerContext {
59
- context: {
60
- adapter?: {
61
- findOne: <T = unknown>(input: {
62
- model: string;
63
- where: Where[];
64
- }) => Promise<T | null>;
65
- update?: (input: {
66
- model: string;
67
- update: Record<string, unknown>;
68
- where: Where[];
69
- }) => Promise<unknown>;
70
- };
71
- internalAdapter?: {
72
- updateUser?: (userId: string, data: Record<string, unknown>) => Promise<unknown>;
73
- listUsers?: (limit: number, offset: number, sortBy: undefined, where: Where[]) => Promise<Record<string, unknown>[]>;
74
- };
75
- logger: {
76
- error: (message: string) => void;
77
- warn: (message: string) => void;
78
- info: (message: string) => void;
79
- debug: (message: string) => void;
80
- };
81
- };
82
- }
83
-
84
58
  interface StreamPaySessionUser {
85
59
  id: string;
86
60
  email?: string;
@@ -89,10 +63,72 @@ interface StreamPaySessionUser {
89
63
  streampayConsumerId?: string | null;
90
64
  }
91
65
 
92
- declare const SUBSCRIPTION_STATUSES: readonly ["incomplete", "incomplete_expired", "trial_pending", "trialing", "active", "inactive", "expired", "canceled", "frozen", "past_due"];
93
- type SubscriptionStatus = (typeof SUBSCRIPTION_STATUSES)[number];
94
- type StreamPaySubscriptionStatus = NonNullable<SubscriptionDetailed["status"]>;
95
- declare const DEFAULT_ACCESS_STATUSES: readonly ["active", "trialing", "frozen", "past_due"];
66
+ interface PluginAdapter {
67
+ create: <T = unknown, D extends object = Record<string, unknown>>(args: {
68
+ model: string;
69
+ data: D;
70
+ }) => Promise<T>;
71
+ update: <T = unknown, D extends object = Record<string, unknown>>(args: {
72
+ model: string;
73
+ update: D;
74
+ where: Array<{
75
+ field: string;
76
+ value: unknown;
77
+ }>;
78
+ }) => Promise<T | null>;
79
+ findOne: <T = unknown>(args: {
80
+ model: string;
81
+ where: Array<{
82
+ field: string;
83
+ value: unknown;
84
+ }>;
85
+ }) => Promise<T | null>;
86
+ findMany: <T = unknown>(args: {
87
+ model: string;
88
+ where?: Array<{
89
+ field: string;
90
+ value: unknown;
91
+ operator?: "lt" | "lte";
92
+ }>;
93
+ limit?: number;
94
+ offset?: number;
95
+ sortBy?: {
96
+ field: string;
97
+ direction: "asc" | "desc";
98
+ };
99
+ }) => Promise<T[]>;
100
+ delete: (args: {
101
+ model: string;
102
+ where: Array<{
103
+ field: string;
104
+ value: unknown;
105
+ }>;
106
+ }) => Promise<void>;
107
+ count: (args: {
108
+ model: string;
109
+ where?: Array<{
110
+ field: string;
111
+ value: unknown;
112
+ }>;
113
+ }) => Promise<number>;
114
+ }
115
+ interface SyncContext {
116
+ context: {
117
+ adapter: PluginAdapter;
118
+ logger: {
119
+ error: (msg: string) => void;
120
+ warn: (msg: string) => void;
121
+ info: (msg: string) => void;
122
+ debug: (msg: string) => void;
123
+ };
124
+ session?: {
125
+ user?: unknown;
126
+ };
127
+ internalAdapter?: {
128
+ findUserById?: (userId: string) => Promise<unknown>;
129
+ };
130
+ };
131
+ }
96
132
 
97
133
  type StreamPayEntityType = "PAYMENT" | "INVOICE" | "SUBSCRIPTION" | "PAYMENT_LINK";
98
134
  declare const STREAMPAY_EVENT_ENTITY_TYPES: {
@@ -182,6 +218,84 @@ type StreamPayWebhookPayload<TEvent extends StreamPayEventType = StreamPayEventT
182
218
  entity_type: TEntity;
183
219
  }>;
184
220
 
221
+ type WebhookEventStatus = "pending" | "completed" | "dead_letter";
222
+ interface WebhookEventRow {
223
+ id: string;
224
+ eventId: string;
225
+ eventType: string;
226
+ status: WebhookEventStatus;
227
+ attemptCount: number;
228
+ receivedAt: Date;
229
+ lastAttemptAt: Date | null;
230
+ nextAttemptAt: Date | null;
231
+ completedAt: Date | null;
232
+ deadLetteredAt: Date | null;
233
+ lockedAt: Date | null;
234
+ lockedBy: string | null;
235
+ rawPayload: string | null;
236
+ signatureHeader: string | null;
237
+ lastError: string | null;
238
+ lastErrorCode: string | null;
239
+ }
240
+ /** What a scope learns about the attempt it is running. */
241
+ interface WebhookInboxAttempt {
242
+ previousError: string | null;
243
+ previousErrorCode: string | null;
244
+ }
245
+ type WebhookEventRunner = (ctx: SyncContext, attempt: WebhookInboxAttempt) => Promise<void>;
246
+ /**
247
+ * One kind of work the inbox runs for a StreamPay event. Subscription sync and generic handlers are
248
+ * the two scopes; each keeps its own inbox row per event, distinguished by `eventIdPrefix`.
249
+ */
250
+ interface WebhookInboxScope {
251
+ /** `null` keeps the unprefixed event IDs that subscription sync has always stored. */
252
+ eventIdPrefix: string | null;
253
+ maxAttempts: number;
254
+ /** Returns the work for an event this scope handles, or `null` to leave the event alone. */
255
+ prepare: (payload: StreamPayWebhookEnvelope) => WebhookEventRunner | null;
256
+ isPermanentFailure: (err: unknown) => boolean;
257
+ /** Releases scope-owned state that waits on the event before an operator discards it. */
258
+ onDiscard?: (ctx: SyncContext, row: WebhookEventRow) => Promise<void>;
259
+ }
260
+ interface ProcessDueWebhookEventsResult {
261
+ succeeded: string[];
262
+ failed: Array<{
263
+ eventId: string;
264
+ error: string;
265
+ }>;
266
+ }
267
+ interface WebhookInbox {
268
+ /**
269
+ * Adds a scope. A scope that is not `replayable` keeps its discard hook for rows it stored
270
+ * earlier, but its events are neither replayed nor retried.
271
+ *
272
+ * @throws TypeError for a prefix other than `null` or `HANDLERS_EVENT_ID_PREFIX`, which replay
273
+ * could not route.
274
+ */
275
+ register: (scope: WebhookInboxScope, options?: {
276
+ replayable?: boolean;
277
+ }) => void;
278
+ isEnabled: () => boolean;
279
+ /** With `dueAttemptCount`, replays only while the event is still that pending, due attempt. */
280
+ replay: (ctx: SyncContext, eventId: string, options?: {
281
+ dueAttemptCount?: number;
282
+ }) => Promise<{
283
+ replayed: true;
284
+ eventId: string;
285
+ }>;
286
+ /** @throws APIError `CONFLICT` while a worker holds the event or claims it during the discard. */
287
+ discard: (ctx: SyncContext, eventId: string) => Promise<{
288
+ discarded: true;
289
+ eventId: string;
290
+ }>;
291
+ processDue: (ctx: SyncContext, limit: number) => Promise<ProcessDueWebhookEventsResult>;
292
+ }
293
+
294
+ declare const SUBSCRIPTION_STATUSES: readonly ["incomplete", "incomplete_expired", "trial_pending", "trialing", "active", "inactive", "expired", "canceled", "frozen", "past_due"];
295
+ type SubscriptionStatus = (typeof SUBSCRIPTION_STATUSES)[number];
296
+ type StreamPaySubscriptionStatus = NonNullable<SubscriptionDetailed["status"]>;
297
+ declare const DEFAULT_ACCESS_STATUSES: readonly ["active", "trialing", "frozen", "past_due"];
298
+
185
299
  type SubscriptionRecurringInterval = NonNullable<SubscriptionDetailed["recurring_interval"]>;
186
300
  type SubscriptionBillingStatus = "current" | "past_due";
187
301
  type SubscriptionReferenceType = "user" | "organization" | "custom";
@@ -329,56 +443,6 @@ declare const REFERENCE_ID_METADATA_KEY = "streampay_plugin_reference_id";
329
443
  declare const REFERENCE_TYPE_METADATA_KEY = "streampay_plugin_reference_type";
330
444
  declare const SUBSCRIPTION_ROW_ID_METADATA_KEY = "streampay_plugin_subscription_row_id";
331
445
 
332
- interface PluginAdapter {
333
- create: <T = unknown, D extends object = Record<string, unknown>>(args: {
334
- model: string;
335
- data: D;
336
- }) => Promise<T>;
337
- update: <T = unknown, D extends object = Record<string, unknown>>(args: {
338
- model: string;
339
- update: D;
340
- where: Array<{
341
- field: string;
342
- value: unknown;
343
- }>;
344
- }) => Promise<T | null>;
345
- findOne: <T = unknown>(args: {
346
- model: string;
347
- where: Array<{
348
- field: string;
349
- value: unknown;
350
- }>;
351
- }) => Promise<T | null>;
352
- findMany: <T = unknown>(args: {
353
- model: string;
354
- where?: Array<{
355
- field: string;
356
- value: unknown;
357
- operator?: "lt" | "lte";
358
- }>;
359
- limit?: number;
360
- offset?: number;
361
- sortBy?: {
362
- field: string;
363
- direction: "asc" | "desc";
364
- };
365
- }) => Promise<T[]>;
366
- delete: (args: {
367
- model: string;
368
- where: Array<{
369
- field: string;
370
- value: unknown;
371
- }>;
372
- }) => Promise<void>;
373
- count: (args: {
374
- model: string;
375
- where?: Array<{
376
- field: string;
377
- value: unknown;
378
- }>;
379
- }) => Promise<number>;
380
- }
381
-
382
446
  interface ResolvedPlans {
383
447
  list: readonly StreamPayPlanLike[];
384
448
  byName: Map<string, StreamPayPlanLike>;
@@ -395,48 +459,12 @@ interface LimitCheckResult {
395
459
  }
396
460
  declare function checkLimit<P extends StreamPayPlanLike>(subscription: Subscription, plan: P | undefined, feature: FeatureKey<P>, requested: number, accessStatuses?: readonly SubscriptionStatus[]): LimitCheckResult;
397
461
 
398
- interface SyncContext {
399
- context: {
400
- adapter: PluginAdapter;
401
- logger: {
402
- error: (msg: string) => void;
403
- warn: (msg: string) => void;
404
- info: (msg: string) => void;
405
- debug: (msg: string) => void;
406
- };
407
- session?: {
408
- user?: unknown;
409
- };
410
- internalAdapter?: {
411
- findUserById?: (userId: string) => Promise<unknown>;
412
- };
413
- };
414
- }
415
- type WebhookEventStatus = "pending" | "completed" | "dead_letter";
416
- interface WebhookEventRow {
417
- id: string;
418
- eventId: string;
419
- eventType: string;
420
- status: WebhookEventStatus;
421
- attemptCount: number;
422
- receivedAt: Date;
423
- lastAttemptAt: Date | null;
424
- nextAttemptAt: Date | null;
425
- completedAt: Date | null;
426
- deadLetteredAt: Date | null;
427
- lockedAt: Date | null;
428
- lockedBy: string | null;
429
- rawPayload: string | null;
430
- signatureHeader: string | null;
431
- lastError: string | null;
432
- lastErrorCode: string | null;
433
- }
434
462
  interface WebhookReplayOptions {
435
463
  /** @deprecated No effect: a failed replay keeps a pending event retryable until its attempts are spent. */
436
464
  retryUntilExhausted?: boolean;
437
465
  /**
438
- * Set by `processDueStreampayWebhookEvents`: replay only if the event is still pending at this
439
- * attempt and due. Otherwise the replay fails with `CONFLICT`.
466
+ * Replay only if the event is still pending at this attempt and due. Otherwise the replay fails
467
+ * with `CONFLICT`. `processDueStreampayWebhookEvents` applies this check itself.
440
468
  */
441
469
  dueAttemptCount?: number;
442
470
  }
@@ -458,12 +486,23 @@ interface StreamPayPluginRegistry {
458
486
  rawBody?: string;
459
487
  signatureHeader?: string | null;
460
488
  }) => Promise<void>;
461
- replayWebhookEvent?: (ctx: GenericEndpointContext, eventId: string,
462
- /** @deprecated No effect. */
463
- options?: WebhookReplayOptions) => Promise<{
489
+ /** Shared by every plugin that stores events in the webhook inbox table. */
490
+ webhookInbox?: WebhookInbox;
491
+ /**
492
+ * Re-projects a local subscription row from StreamPay after an out-of-band provider change,
493
+ * using the configured plan catalog. Never throws: a failed projection reconciles on the next
494
+ * webhook.
495
+ */
496
+ refreshSubscriptionProjection?: (ctx: GenericEndpointContext, subscription: {
497
+ streampaySubscriptionId: string;
498
+ } | {
499
+ snapshot: SubscriptionDetailed;
500
+ }, source: string) => Promise<void>;
501
+ replayWebhookEvent?: (ctx: GenericEndpointContext, eventId: string, options?: WebhookReplayOptions) => Promise<{
464
502
  replayed: true;
465
503
  eventId: string;
466
504
  }>;
505
+ /** @deprecated Use `replayWebhookEvent`; both replay any inbox event. */
467
506
  replayWebhookHandler?: NonNullable<StreamPayPluginRegistry["replayWebhookEvent"]>;
468
507
  }
469
508
  declare function subscriptions(subsOptions: SubscriptionsOptions): (options: StreamPayOptions, registry?: StreamPayPluginRegistry) => {
@@ -2988,7 +3027,7 @@ declare const admin: (adminOptions?: AdminOptions) => (options: StreamPayOptions
2988
3027
  };
2989
3028
  }>>[];
2990
3029
  }, {
2991
- discarded: boolean;
3030
+ discarded: true;
2992
3031
  eventId: string;
2993
3032
  }>;
2994
3033
  adminListPaymentLinks: better_auth.StrictEndpoint<"/admin/streampay/payment-links", {
@@ -6972,6 +7011,8 @@ interface WebhooksOptions extends WebhookHandlers {
6972
7011
  toleranceSeconds?: number;
6973
7012
  /** Persist and deduplicate callback deliveries. Requires the webhook inbox migration. */
6974
7013
  deduplicate?: boolean;
7014
+ /** Deliveries of a deduplicated callback event before it is dead-lettered. Defaults to 5. */
7015
+ maxWebhookAttempts?: number;
6975
7016
  }
6976
7017
  declare const webhooks: (webhooksOptions: WebhooksOptions) => (_options: StreamPayOptions, registry?: StreamPayPluginRegistry) => {
6977
7018
  schema: {};
@@ -7109,6 +7150,33 @@ interface StreamPayOptions {
7109
7150
  use: StreamPayPlugins;
7110
7151
  }
7111
7152
 
7153
+ interface UserLinkStore {
7154
+ findOne: <T = unknown>(input: {
7155
+ model: string;
7156
+ where: Where[];
7157
+ }) => Promise<T | null>;
7158
+ update?: (input: {
7159
+ model: string;
7160
+ update: Record<string, unknown>;
7161
+ where: Where[];
7162
+ }) => Promise<unknown>;
7163
+ }
7164
+ interface StreamPayLoggerContext {
7165
+ context: {
7166
+ adapter?: UserLinkStore;
7167
+ internalAdapter?: {
7168
+ updateUser?: (userId: string, data: Record<string, unknown>) => Promise<unknown>;
7169
+ listUsers?: (limit: number, offset: number, sortBy: undefined, where: Where[]) => Promise<Record<string, unknown>[]>;
7170
+ };
7171
+ logger: {
7172
+ error: (message: string) => void;
7173
+ warn: (message: string) => void;
7174
+ info: (message: string) => void;
7175
+ debug: (message: string) => void;
7176
+ };
7177
+ };
7178
+ }
7179
+
7112
7180
  type StreamPayHookContext = StreamPayLoggerContext;
7113
7181
 
7114
7182
  declare const streampay: <O extends StreamPayOptions>(options: O) => {
@@ -7239,7 +7307,7 @@ declare const streampay: <O extends StreamPayOptions>(options: O) => {
7239
7307
  };
7240
7308
  }>>[];
7241
7309
  }, {
7242
- discarded: boolean;
7310
+ discarded: true;
7243
7311
  eventId: string;
7244
7312
  }>;
7245
7313
  adminListPaymentLinks: better_auth.StrictEndpoint<"/admin/streampay/payment-links", {
@@ -577,6 +577,8 @@ The plugin:
577
577
  unknown event envelopes. Apply the inbox table migration before enabling it. Handler receipts use
578
578
  the `handlers:` event ID prefix and support the existing authenticated admin replay endpoint.
579
579
  The default is `false` to preserve existing installations that have no inbox table.
580
+ A handler event that keeps failing is dead-lettered after `maxWebhookAttempts` deliveries
581
+ (default 5), the same budget `subscriptions({ maxWebhookAttempts })` sets for subscription sync.
580
582
 
581
583
  Verified payloads are persisted when processing is claimed, so an interrupted delivery can be
582
584
  recovered after its two-minute lease expires. A delivery that arrives while another worker holds
@@ -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,10 +69,10 @@ 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
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`). |
77
77
 
78
78
  ### Transitions
@@ -128,7 +128,7 @@ StreamPay's hosted checkout. The idempotency window is
128
128
  | ID | Invariant | Enforced by |
129
129
  | --- | --- | --- |
130
130
  | 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. |
131
+ | 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
132
  | 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
133
 
134
134
  ### Transitions
@@ -144,7 +144,7 @@ StreamPay's hosted checkout. The idempotency window is
144
144
  | C-g | Different plan or seats within the window | R1/R2 | R1/R2, request gets `SUBSCRIPTION_CHECKOUT_IN_PROGRESS` | by design |
145
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. |
146
146
  | 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` |
147
+ | C-j | Paid subscription arrives for another row of the same slot | R1/R2 | R3 | `yieldReservationToPaidSubscription` |
148
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 |
149
149
  | C-l | Webhook | R1/R2/R3 | R4 | machine 1, L1 |
150
150
  | C-m | `/subscription/success` fallback | R1/R2 | R4 | machine 1, L1 |
@@ -195,7 +195,7 @@ retries without firing for two events of the same cycle.
195
195
  | event E | Callback throws with `retryOnCallbackError` | E (event recorded as failed) | same |
196
196
  | event E | Redelivery or replay of E | E, then null after success | `pendingCallback === eventId` branch |
197
197
  | 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 |
198
+ | event E | Admin discards E | null | the subscription scope's `onDiscard` (`releaseRenewalCallbackOwner`), after the event is completed |
199
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
200
 
201
201
  Invariants: while the lock is set, its cycle's callback has not been delivered, and other renewal
@@ -213,7 +213,9 @@ periods start up to 9 minutes after `started_at`.
213
213
 
214
214
  One table serves two scopes. Subscription sync uses
215
215
  `<event_type>:<entity_id>:<timestamp>`. Generic handlers (`webhooks({ deduplicate: true })`) use
216
- the same ID with a `handlers:` prefix.
216
+ the same ID with a `handlers:` prefix. Both scopes run in the inbox module (`webhooks/inbox.ts`),
217
+ which routes replay by that prefix: a `handlers:` row is never replayed through subscription sync,
218
+ even when generic deduplication is off (F29).
217
219
 
218
220
  ### States
219
221
 
@@ -231,9 +233,9 @@ the same ID with a `handlers:` prefix.
231
233
  | ID | Invariant | Enforced by |
232
234
  | --- | --- | --- |
233
235
  | 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`. |
236
+ | W2 | Only the lease owner can complete or fail an event. | `markWebhookEventCompleted` and `recordWebhookEventFailure` require the lease's `lockedBy`. |
235
237
  | 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). |
238
+ | 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
239
 
238
240
  ### Transitions
239
241
 
@@ -246,10 +248,10 @@ the same ID with a `handlers:` prefix.
246
248
  | W-e | Processing succeeds | E1 | E3 | `markWebhookEventCompleted(lockedBy)` |
247
249
  | W-f | Transient failure, attempts left | E1 | E2 (`nextAttemptAt` set) | `recordWebhookEventFailure` |
248
250
  | 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) |
251
+ | 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
252
  | 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). |
253
+ | 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). |
254
+ | 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
255
 
254
256
  E2 events move on a StreamPay redelivery, an admin replay, or a scheduled call to
255
257
  `processDueStreampayWebhookEvents`, which selects them by `nextAttemptAt` and expired leases. E2p
@@ -282,10 +284,10 @@ sync, and the redelivery skips the sync row.
282
284
  | --- | --- | --- | --- |
283
285
  | Sign-up with `createConsumerOnSignUp` | Unlinked | Linked (inside the user insert) | `onBeforeUserCreate`. `onAfterUserCreate` backfills `external_id`. |
284
286
  | 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 |
287
+ | 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
288
  | Provider 404 on profile sync | Linked | Unlinked (CAS) | `onUserUpdate` |
287
289
  | Admin deletes the consumer | Linked | Unlinked (CAS) | `adminDeleteConsumer` |
288
- | Cached session carries an old ID | n/a | the database value wins | `getCurrentConsumerUser` |
290
+ | Cached session carries an old ID, or none | n/a | the database value wins | `getCurrentConsumerUser` |
289
291
  | Portal call while unlinked | Unlinked | Unlinked (reads by `external_id`, never writes) | `portal.ts` |
290
292
 
291
293
  Invariants: one consumer per user and one user per consumer (unique column and
@@ -467,13 +469,23 @@ file covers F15 and F16; `tests/integration/review-findings.test.ts` covers F18
467
469
  | ID | Risk | Why it is not fixed here |
468
470
  | --- | --- | --- |
469
471
  | 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. |
472
+ | 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
473
  | 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
474
  | 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. |
475
+ | R5 | Fixed: `webhooks({ maxWebhookAttempts })` sets the generic handler attempt budget (default 5). | |
474
476
  | R6 | A callback that runs longer than the 2-minute lease can run concurrently with a redelivery. | Documented. Callbacks must be idempotent. |
475
477
  | R7 | Fixed with F8 (Issue 4). | |
476
478
  | R8 | Confirmed as F12 and fixed. Parked rather than dead-lettered, so StreamPay retries still count (W4). | |
477
479
  | R9 | Confirmed as F13 and fixed. | |
478
480
  | R10 | Confirmed as F17 and fixed. | |
479
481
  | R11 | Confirmed as F28 and fixed. Rows created by a webhook without any reservation (no plugin checkout link) still depend on their creation event. | |
482
+
483
+ ### Module consolidation findings
484
+
485
+ Found while consolidating each machine into one module (3.4.0).
486
+
487
+ | ID | Severity | Machine | Invalid state or transition | Before | Fix |
488
+ | --- | --- | --- | --- | --- | --- |
489
+ | 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). |
490
+ | 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. |
491
+ | 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.4.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",