better-auth-streampay 3.0.0 → 3.0.2

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.
@@ -0,0 +1,159 @@
1
+ # Staging validation
2
+
3
+ Validated on 2026-10-10 against Stream sandbox, SDK 1.1.3 and Better Auth 1.7.7.
4
+ The minimum supported Better Auth version is 1.6.0; Zod 3.24 and Zod 4 are supported.
5
+ Tests cover the plugin's implemented features, not every feature of the Stream platform.
6
+
7
+ ## Live coverage
8
+
9
+ | Feature | Evidence | Boundary |
10
+ | --- | --- | --- |
11
+ | Consumers | Authenticated creation and lookup; admin PATCH, read and delete passed. | Concurrent relinking and untrusted external IDs are covered by database regressions. |
12
+ | Hosted portal | A server-created session opened the dedicated consumer's portal in a browser. | Portal settings and catalog mappings control available self-service actions. |
13
+ | Recurring checkout | Declined and successful cards passed through sandbox 3DS; real events activated the local reservation. | No synthetic correlation was needed for activation. |
14
+ | One-off checkout | Server-resolved checkout, quantity two, required custom field, reference, metadata and 10% coupon produced a paid 1.80 SAR invoice. | Empty custom field blocked payment; the link allowed one payment. |
15
+ | Multi-product checkout | Two SAR products, quantity handling and a fixed coupon produced 3.80 SAR through the plugin and real API. | Quote/link validation only; this link was deactivated without payment. |
16
+ | Refunds | Partial refund, separate full refunds, admin refund and repeated-refund rejection passed. | This organization rejected a second refund after a partial refund; see discrepancy below. |
17
+ | Subscription cancellation | Cancel at period end, uncancel and repeated requests passed. | Stream does not immediately cancel an active subscription. |
18
+ | Seats and plans | Seat bounds, unchanged seats, scheduled seat increase, plan switch and cancellation of pending changes passed. | Changes were accepted for the next period; the future billing boundary was not observed. |
19
+ | Freezes | Scheduled freeze, cancel, repeated cancel, immediate freeze and unfreeze passed. | Same-calendar-day start/end was rejected by Stream, despite distinct timestamps. |
20
+ | Admin | Unauthenticated and ordinary users were rejected; all seven lists respected size=1; product/coupon CRUD and consumer update/delete passed. | Mutations used dedicated fixtures, which were deleted afterward. |
21
+ | Webhooks | Registration through the API accepted all 31 supported event types; real payment, invoice, subscription and refund deliveries reached the tunnel. | Registration does not prove all 31 event types were emitted in real flows. |
22
+ | Demo redirects | Success/failure query parameters are accepted by the local home route. | The tunnel exposes only the webhook route; interactive testing uses localhost. |
23
+
24
+ ## Regression coverage
25
+
26
+ | Risk | Regression or staging proof |
27
+ | --- | --- |
28
+ | Unknown product retains old access | Plan projection and authenticated SQLite tests deny access while retaining billing diagnostics. |
29
+ | Generic callbacks run twice | SQLite integration overlaps deliveries; PostgreSQL gives one of eight contenders the claim. Admin replay works with either plugin order. |
30
+ | Crash loses payload | Initial claim retains payload/signature; PostgreSQL recovers an expired lease and fences stale completion/failure writes. |
31
+ | Inbox conflict loses tracking | A unique conflict with no visible row raises a retryable failure instead of running untracked callbacks. |
32
+ | Exhausted generic callback stays pending | The fifth failed delivery is durably dead-lettered immediately; later delivery does not run the callback again. |
33
+ | Invalid usage count grants access | Invalid numeric counts fail closed; live HTTP rejects negative, fractional, non-finite, and unsafe counts. |
34
+ | Hosted portal opens another consumer | Caller IDs are ignored; sessions require authentication, HTTPS, and no-store. Real portal opened as the dedicated consumer. |
35
+ | Portal hides later pages | Authenticated page 2 preserves ownership and returns provider pagination; invalid live page/size requests return 400. |
36
+ | Dynamic catalog stays stale | The upstream 2.2.1 resolver fix is retained and tested. |
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
+ | Crash skips a renewal callback | SQLite simulates a lost update response and an interrupted worker; replay uses the durable callback owner. |
39
+ | Checkout activates the wrong reservation | Known payment-link and consumer mismatches cannot bind a pending checkout. |
40
+ | Portal client sends the wrong HTTP method | The real Better Auth client sends POST for the documented no-argument session call. |
41
+ | 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. |
42
+ | Checkout cleanup overwrites activation | Conditional expiry/deletion preserves a reservation activated while a provider request is in flight. |
43
+ | Older response restores canceled access | A provider timestamp check and conditional projection prevent older activation writes from overwriting newer cancellation state. |
44
+ | Missing refund/renewal handlers | Dispatcher regressions cover both events; real partial/full-refund events reached the inbox. |
45
+ | Forged webhooks mutate billing | Missing, invalid, expired, or tampered signatures and malformed JSON were rejected through the public tunnel without adding inbox rows. |
46
+
47
+ The browser exercised a declined card through sandbox 3DS, then successful recurring checkout.
48
+ Repeated subscription upgrade reused its checkout link. Provider-created subscription, invoice,
49
+ payment, and activation events reconciled the local reservation into an active subscription without
50
+ synthetic correlation. A 1 SAR partial refund of the 80 SAR test payment returned
51
+ `PARTIALLY_REFUNDED`; a separate 1 SAR payment was fully refunded and returned `REFUNDED`.
52
+ Both invoices remained completed, as documented. Generic refund callbacks do not automatically
53
+ cancel a subscription; applications own their refund/access policy.
54
+
55
+ Provider discrepancy: refunding the remaining 79 SAR after the partial refund returned HTTP 400
56
+ `PAYMENT_REFUNDED_ALREADY`, both with an explicit amount and with the amount omitted. Stream's
57
+ current [webhook guide](https://docs.streampay.sa/webhooks/) describes cumulative refunds, but
58
+ this staging organization did not permit them. Do not assume multiple-refund support without
59
+ confirming it with Stream.
60
+
61
+ The paid subscription was scheduled to cancel at period end; Stream does not support immediate
62
+ cancellation of active subscriptions. Both checkout links completed their single allowed payment.
63
+
64
+ A same-price product switch was accepted and deferred to the next billing period; its pending
65
+ change was removed afterward. The earlier trial switch was blocked because it was scheduled to
66
+ cancel. Immediate transitions to an unmapped product are proven by deterministic tests, not by
67
+ waiting for a live billing boundary. General live write tests remain skipped to protect shared
68
+ fixtures. Long-duration renewal scheduling, real process termination during external side effects,
69
+ and all supported third-party database adapters remain outside this validation. Callbacks must
70
+ remain idempotent; these checks do not establish zero bugs.
71
+
72
+
73
+ ## Remaining limits
74
+
75
+ SDK 1.1.3 does not expose pagination arguments for subscription freeze history. The plugin now
76
+ accepts a server-side `subscriptions({ listSubscriptionFreezes })` REST adapter to traverse pages
77
+ for cancellation and unfreeze. The demo configures it. Without the adapter, SDK-only integrations
78
+ retain the authoritative latest-freeze fallback and 409 when later pages cannot be resolved safely.
79
+ Live isolated plugin/API testing with one item per page canceled the scheduled freeze on page 5,
80
+ returned reused success on repeat, and unfroze the active freeze on page 6. The fixture returned
81
+ to ACTIVE with cancellation scheduled at period end.
82
+
83
+ Traversal rejects malformed/nonadvancing pages and stops after 100 pages; it never reports
84
+ absence after a partial or failed read.
85
+
86
+ | Freeze pagination risk | Protection |
87
+ | --- | --- |
88
+ | Later-page freeze is missed | Cancellation and unfreeze regressions find a target on page two. |
89
+ | Missing target falsely reported canceled after failed read | Later-page failures reject both actions without provider mutation. |
90
+ | Repeated or malformed pages | Invalid metadata/data, empty advancing pages and repeated IDs return 409. |
91
+ | Unbounded history traversal | A 100-page ceiling rejects continued history without mutation. |
92
+ | Foreign subscription leaks to REST callback | Ownership denial happens before the callback. |
93
+
94
+ Natural renewals, future scheduled transitions, every hosted-portal permission combination,
95
+ every payment method/currency, and every third-party database adapter have not been verified
96
+ end to end. Fixed-coupon application passed for SAR; the paid coupon flow used a percentage coupon.
97
+ USD product creation returned HTTP 400 in this organization, so USD checkout is not verified.
98
+ KWD product creation encountered an upstream HTTP 502; KWD checkout remains unverified.
99
+ Deterministic tests cover provider failures, ownership boundaries, duplicate/reordered events,
100
+ trial history, stale endpoint responses and database races. These checks cannot establish zero bugs.
101
+
102
+ Sources: [customer portal](https://docs.streampay.sa/customer-portal/),
103
+ [webhooks](https://docs.streampay.sa/webhooks/), and the current public API reference.
104
+
105
+ ## Repeat audit of 3.0.0
106
+
107
+ Three Luna agents reviewed billing, portal/API contracts, and webhook reliability. The main
108
+ checkout passed the complete local check, including PostgreSQL. The npm 3.0.0 package was also
109
+ checked for ESM and CommonJS exports, its reported version, and accidental credential files.
110
+ Registry checks still returned Better Auth 1.7.7 and Stream SDK 1.1.3 on October 10, 2026.
111
+
112
+ The repeat staging checks passed:
113
+
114
+ - Eight read-only live tests. Eleven generic write tests stayed disabled.
115
+ - A new unpaid hosted checkout retained quantity two, the 10% coupon, metadata, custom fields,
116
+ and redirects, producing 180 halalas. Its link was deactivated and temporary catalog entries
117
+ were deleted after validation.
118
+ - Admin authentication and authorization, pagination across seven resources, product/coupon CRUD,
119
+ and updates/deletion of a dedicated consumer. Previously refunded payments were read; a new
120
+ refund was not submitted in this repeat.
121
+ - Scheduled freeze cancellation on page 7, repeated cancellation, and active unfreeze on page 8.
122
+ - Seat validation, unchanged quantity reuse, a scheduled quantity change, pending-change
123
+ cancellation and reuse, and a same-price plan switch. Temporary changes were removed.
124
+ - Local-demo freeze/unfreeze reconciled both provider and SQLite state. Cancellation at period
125
+ end was restored afterward.
126
+ - The browser opened the authenticated hosted portal. Real subscription events reached the
127
+ public webhook tunnel and completed in the inbox. An unsigned webhook returned 401 without
128
+ adding an inbox row; public diagnostics returned 404.
129
+ - An eager duplicate signup against an existing sandbox identity returned 409
130
+ `STREAMPAY_CONSUMER_LINK_CONFLICT`, preserving the provider's original external ID and the
131
+ existing local owner. Sandbox rules prohibit arbitrary customer emails and phone numbers, so
132
+ this live test seeded local ownership before attempting the duplicate signup.
133
+
134
+ Real Better Auth/SQLite regressions also cover unclaimed duplicate signup recovery and cleanup
135
+ of an old missing consumer while another request replaces its local link. Ownership reads inside
136
+ signup use Better Auth's transaction-aware internal adapter; reading through the outer adapter
137
+ can deadlock on SQLite. Cleanup compares the stored link with the failed link before clearing it.
138
+
139
+ The database unique constraint still decides the winner when two eager signups simultaneously
140
+ claim an initially unclaimed consumer. A losing signup may receive a database validation error
141
+ instead of the explicit ownership conflict. Webhook callbacks must finish within their processing
142
+ lease or tolerate replay; deduplication cannot make external side effects exactly once. These
143
+ limits and the earlier untested provider scenarios remain part of the coverage boundary.
144
+
145
+ The repeat audit found and fixed four consumer-link defects: eager recovery returned a database
146
+ validation error for an established owner; stale 404 cleanup could clear a concurrent replacement;
147
+ lazy recovery changed the provider external ID before winning the local claim; and session caches
148
+ could keep using a link after database rollback. Nine real Better Auth/SQLite regressions cover
149
+ these paths, including recovery after failed backfill, preserving a replacement during rollback,
150
+ and rejecting a cached linked account after deletion or a failed database read. Linked billing
151
+ requests now read the current database link before using a cached consumer ID. This adds one
152
+ database read to the linked checkout, subscription-creation, and portal paths.
153
+
154
+ Final local validation passed 568 tests across 35 files on Node 22 and Node 24, including
155
+ PostgreSQL. The minimum-peer run passed the same 568 tests with Better Auth 1.6.0, Zod 3.24.0,
156
+ and SDK 1.1.3. Node 20 passed 511 tests in its supported subset; four cases and SQLite integration
157
+ were excluded or skipped because that runtime lacks the SQLite features used by the test harness.
158
+ ESM and CommonJS imports passed on Node 20. The package archive includes the three documentation
159
+ guides and contains no local credentials or fixture data.
@@ -0,0 +1,271 @@
1
+ # Subscription data model and seat billing
2
+
3
+ This document explains why the subscription tables exist, what every plugin-owned column means,
4
+ how seats map to StreamPay quantity, and which system is authoritative at each point in the
5
+ lifecycle.
6
+
7
+ The short version: StreamPay owns money and billing state; your database owns application
8
+ references, access-friendly projections, webhook processing state, and recovery metadata. The
9
+ local subscription row is deliberately a projection, not a second billing engine.
10
+
11
+ ## Why local tables exist
12
+
13
+ Calling StreamPay for every authorization check would make application access depend on a remote
14
+ network request, add latency, and make webhook retries difficult to reason about. The plugin keeps
15
+ three pieces of local state:
16
+
17
+ | Model | Purpose | Why it cannot live only at StreamPay |
18
+ | --- | --- | --- |
19
+ | Better Auth `user` extension | Links one app user to one StreamPay consumer. | StreamPay does not know the Better Auth user primary key or session. |
20
+ | `subscription` | Projects the subscription into app-owned references, current/pending plan and seats, access status, periods, and correlation IDs. | The application needs fast authorization reads, organization/custom ownership, checkout recovery, and a stable local ID. |
21
+ | `streampayWebhookEvent` | Deduplicates signed deliveries and records retry/dead-letter state. | HTTP delivery is at-least-once; application callbacks and database writes must be recoverable and observable. |
22
+
23
+ ## Data authority
24
+
25
+ | Data | Authority | Local behavior |
26
+ | --- | --- | --- |
27
+ | Product price, discounts, invoice totals, currency | StreamPay | Copied from subscription responses/webhooks. The configured price is only the pre-checkout quote. |
28
+ | Current item quantity | StreamPay `subscription.items[].quantity` | Stored as `seats` after success reconciliation or a webhook. |
29
+ | Scheduled item quantity | StreamPay `pending_change.target_items[].quantity` | Stored as `pendingSeats` until applied or canceled. |
30
+ | Subscription status and billing periods | StreamPay | Normalized for access checks while retaining the raw provider status. |
31
+ | User/organization/custom ownership | Your application | Stored in `referenceId` and `referenceType`; cross-reference actions require authorization. |
32
+ | Plan name, version, group, entitlements | Plugin configuration | Correlated to the provider product ID and snapshotted/projected locally. |
33
+ | Webhook attempt state | Your database | Controlled by the plugin's lease, retry, completion, and dead-letter state machine. |
34
+
35
+ Never use the local amount as a payment ledger and never overwrite provider-confirmed quantities
36
+ with an optimistic browser value. StreamPay's [subscription update API](https://docs.streampay.sa/api/v2-subscriptions-update/)
37
+ and [webhooks](https://docs.streampay.sa/webhooks/) are the billing source of truth.
38
+
39
+ ## Better Auth user extension
40
+
41
+ Better Auth owns the normal user columns. The StreamPay plugin adds one field:
42
+
43
+ | Column | Shape | Meaning |
44
+ | --- | --- | --- |
45
+ | `streampayConsumerId` | nullable string, server-managed | StreamPay organization-consumer UUID linked to this user. It is created lazily by default, cleared when a confirmed upstream 404 makes the link stale, and never accepted from client input. |
46
+
47
+ This belongs on the user because it is an identity link. It is repeated on subscription rows as a
48
+ historical/correlation snapshot because a subscription can also belong to an organization or
49
+ custom application reference.
50
+
51
+ ## `subscription` table
52
+
53
+ Better Auth supplies the string `id` primary key. "Nullable" means the value is unknown, not
54
+ applicable, or has not yet been confirmed upstream.
55
+
56
+ | Column | Shape / default | What it means and why it exists |
57
+ | --- | --- | --- |
58
+ | `id` | string, primary key | Stable application-side identifier generated through the Better Auth adapter. Client mutation APIs accept this ID (and ownership is always rechecked). |
59
+ | `referenceId` | string, required, indexed | App-owned subject receiving the subscription: a user ID, organization ID, or custom ID. This is the main ownership key. |
60
+ | `referenceType` | string, default `user` | Interprets `referenceId` as `user`, `organization`, or `custom`; prevents IDs from different namespaces colliding. |
61
+ | `activeSlotKey` | nullable string, unique, server-managed | SHA-256 key of reference type + ID + plan group. Enforces one live/in-progress subscription per billing slot and makes concurrent checkout safe. Cleared for terminal rows. |
62
+ | `streampaySubscriptionId` | nullable string, unique, server-managed | Provider subscription UUID. Null while hosted checkout has not produced a subscription. Used for lifecycle API calls and webhook lookup. |
63
+ | `streampayConsumerId` | nullable string, indexed, server-managed | Provider consumer UUID used for checkout and fallback reconciliation. Kept on the row even for non-user references. |
64
+ | `streampayPaymentLinkId` | nullable string, unique, server-managed | Hosted-checkout correlation/recovery ID. Lets an idempotent upgrade return the existing URL and helps verify success reconciliation. |
65
+ | `plan` | string, required | Stable application-facing plan name. Code should use this instead of a raw provider product ID. |
66
+ | `catalogMapped` | nullable boolean, default `true`, server-managed | False when effective provider products cannot be mapped to the catalog; access is denied while billing diagnostics remain available. Backfill existing rows to true during migration. |
67
+ | `planVersion` | nullable string | Optional catalog/config version snapshot for auditing which plan definition was active. |
68
+ | `productId` | nullable string, indexed | Current configured StreamPay product UUID. Webhooks use it to infer `plan`; it may remain populated even if the plan is later removed from configuration. |
69
+ | `group` | nullable string, indexed | Mutually exclusive plan family such as `main` or `workspace`. Combined with the reference to form the active slot. |
70
+ | `seats` | number, default `1` | Current provider-confirmed quantity for the configured plan product. This is billed quantity, not an entitlement limit. |
71
+ | `amountInSmallestUnit` | nullable number | Current full subscription amount after discounts, in halalas/cents/etc. It can include seats and add-ons; do not treat it as unit price. |
72
+ | `originalAmountInSmallestUnit` | nullable number | Current full amount before discounts, also in the smallest currency unit. |
73
+ | `currency` | nullable string, default `SAR` | ISO currency from the provider/plan. Amount columns are meaningless without it. |
74
+ | `billingInterval` | nullable string | Provider recurrence (`WEEK`, `MONTH`, `QUARTER`, or `YEAR`). |
75
+ | `billingIntervalCount` | nullable number, default `1` | Multiplier for the recurrence, for example every 3 months. |
76
+ | `status` | string, default `incomplete`, indexed | Normalized application status: `incomplete`, `incomplete_expired`, `trial_pending`, `trialing`, `active`, `inactive`, `expired`, `canceled`, `frozen`, or `past_due`. |
77
+ | `providerStatus` | nullable string | Raw StreamPay subscription status. Retained so normalization does not discard provider detail. |
78
+ | `billingStatus` | string, default `current`, indexed | Payment health overlay: `current` or `past_due`. A renewal failure can deny/limit access without inventing a provider lifecycle status. |
79
+ | `periodStart` | nullable date | Start of the current provider billing period. |
80
+ | `periodEnd` | nullable date | End of the current provider billing period and usual effective time for a deferred change. |
81
+ | `currentCycleNumber` | nullable number | Provider cycle counter; helps identify genuine renewals and avoid duplicate renewal callbacks. |
82
+ | `renewalCallbackEventId` | nullable string, server-managed | Event that owns a pending renewal callback. Saved atomically with cycle advancement and cleared after delivery so replay can recover interrupted callbacks. |
83
+ | `trialStart` | nullable date | Start of a known trial. Also records trial history for one-trial-per-group eligibility. |
84
+ | `trialEnd` | nullable date | Provider trial end. |
85
+ | `cancelAtPeriodEnd` | boolean, default `false` | Whether renewal is scheduled to stop after the current period. |
86
+ | `cancelAt` | nullable date | Expected cancellation effective time, normally `periodEnd`. |
87
+ | `cancelScheduledAt` | nullable date | When the plugin first observed the cancellation schedule. Useful for audit/UI wording. |
88
+ | `canceledAt` | nullable date | When final canceled state was first confirmed. |
89
+ | `pendingPlan` | nullable string | Target application plan for a real product/plan change. Remains null for quantity-only changes. |
90
+ | `pendingProductId` | nullable string, indexed | Target provider product UUID for a real plan change. Remains null for quantity-only changes. |
91
+ | `pendingPlanEffectiveAt` | nullable date | Provider effective time for the pending plan/product change. |
92
+ | `pendingSeats` | nullable number | Quantity of the configured target plan item after the pending change. May accompany a plan change or exist alone. |
93
+ | `pendingSeatsEffectiveAt` | nullable date | Provider effective time for `pendingSeats`. Kept explicit so the UI need not infer it from a plan-only field. |
94
+ | `endedAt` | nullable date | Provider end timestamp for a terminal subscription. |
95
+ | `frozenAt` | nullable date | Start of the active provider freeze, when status is frozen. |
96
+ | `freezeEndAt` | nullable date | Scheduled end of the active freeze, or null for open-ended freezes. |
97
+ | `providerUpdatedAt` | nullable date | Provider update timestamp used to reject stale lifecycle effects from older webhook deliveries. |
98
+ | `syncedAt` | nullable date, indexed | Last time the plugin successfully projected a provider subscription response. Useful for freshness monitoring. |
99
+ | `createdAt` | nullable date, server-managed | Local row creation time. Also bounds checkout fallback correlation and idempotency. |
100
+ | `updatedAt` | nullable date, indexed, server-managed | Last local projection/mutation time. |
101
+
102
+ ### Why current and pending fields are separate
103
+
104
+ StreamPay documents item, quantity, coupon, and interval updates as deferred to the current period
105
+ end. Replacing `seats` immediately would grant the new number of licenses before the provider says
106
+ the quantity is active. The two-state representation makes the UI and access policy explicit:
107
+
108
+ ```text
109
+ seats=5, pendingSeats=12, pendingSeatsEffectiveAt=2026-08-01
110
+ ```
111
+
112
+ The application should enforce five seats until a provider response/webhook changes `seats` to 12.
113
+ Canceling the pending change clears the pending fields but leaves the current fields untouched.
114
+
115
+ ## `streampayWebhookEvent` table
116
+
117
+ StreamPay signs deliveries, but signatures do not make delivery exactly-once. This table makes
118
+ processing idempotent and observable.
119
+
120
+ | Column | Shape / default | What it means and why it exists |
121
+ | --- | --- | --- |
122
+ | `id` | string, primary key | Internal Better Auth adapter row identifier. `eventId`, not this value, is the delivery deduplication key. |
123
+ | `eventId` | string, required, unique | Deterministic identity for deduplication. A completed delivery with the same ID is skipped. |
124
+ | `eventType` | string, required | StreamPay event such as `SUBSCRIPTION_PLAN_UPDATED`. Useful for routing, debugging, and operations. |
125
+ | `receivedAt` | date, required, indexed | First receipt time. |
126
+ | `lastAttemptAt` | nullable date, indexed | Most recent processing/replay attempt. |
127
+ | `nextAttemptAt` | nullable date, indexed | Earliest automatic retry time after transient failure. |
128
+ | `completedAt` | nullable date, indexed | Successful completion time. Completed events no longer retain replay payload/signature data. |
129
+ | `deadLetteredAt` | nullable date, indexed | Time a permanent failure or exhausted retry budget moved the event to manual review. |
130
+ | `lockedAt` | nullable date, indexed | Start time of the current processing lease. Stale leases can be safely reclaimed. |
131
+ | `lockedBy` | nullable string | Unique lease owner token. Prevents an old worker from completing a lease reclaimed by another worker. |
132
+ | `status` | string, default `pending`, indexed | `pending`, `completed`, or `dead_letter`. |
133
+ | `attemptCount` | number, default `1` | Number of processing claims, including manual replay. |
134
+ | `rawPayload` | nullable string | Exact stored JSON for retry/replay after failure. Cleared after clean completion to reduce sensitive retention. |
135
+ | `signatureHeader` | nullable string | Original signature header retained only with a failed payload for forensic replay. |
136
+ | `lastError` | nullable string | Last failure message for operators. |
137
+ | `lastErrorCode` | nullable string, indexed | Stable/classified error code for filtering and alerting. |
138
+
139
+ Set `enableWebhookEventTable: false` only if another durable queue/inbox provides equivalent
140
+ deduplication, leasing, retry, and dead-letter behavior. Application lifecycle callbacks should
141
+ still be idempotent.
142
+
143
+ ## Seat API
144
+
145
+ Configure plan bounds separately from feature limits:
146
+
147
+ ```ts
148
+ subscriptions({
149
+ plans: [{
150
+ name: "team-monthly",
151
+ productId: process.env.STREAMPAY_TEAM_PRODUCT_ID!,
152
+ priceInSmallestUnit: 4_900, // price for one seat
153
+ currency: "SAR",
154
+ billingInterval: "MONTH",
155
+ group: "workspace",
156
+ seatBilling: {
157
+ default: 5,
158
+ minimum: 2,
159
+ maximum: 100,
160
+ customerEditable: false,
161
+ },
162
+ limits: { reports: true },
163
+ }],
164
+ });
165
+ ```
166
+
167
+ `customerEditable: true` maps to StreamPay payment-link `allow_custom_quantity` and sends the
168
+ inclusive `min_quantity`/`max_quantity` bounds documented by the
169
+ [payment-link API](https://docs.streampay.sa/api/v2-payment-links-create/). Server-selected seats
170
+ work regardless of that flag.
171
+
172
+ ```ts
173
+ await authClient.subscription.upgrade({ plan: "team-monthly", seats: 8 });
174
+
175
+ await authClient.subscription.updateSeats({ subscriptionId, seats: 12 });
176
+
177
+ await authClient.subscription.changePlan({
178
+ subscriptionId,
179
+ plan: "team-yearly",
180
+ seats: 20,
181
+ });
182
+
183
+ await authClient.subscription.pendingChange.cancel({ subscriptionId });
184
+ ```
185
+
186
+ Plan changes preserve the current quantity when `seats` is omitted. Both plan and seat updates
187
+ send the complete current StreamPay item list and subscription coupon list because the provider's
188
+ update contract replaces them. Unrelated add-ons stay in place. Coupon IDs visible in the
189
+ provider's calculation metadata are retained; if StreamPay does not expose historical item-level
190
+ coupon identity in a response, no client can perfectly reconstruct that hidden state.
191
+
192
+ The provider response remains authoritative if its accepted current or pending quantity differs
193
+ from the request. A subscription containing more than one configured plan product is rejected as
194
+ ambiguous instead of guessing which item is billed as the plan. Canceling a pending change is
195
+ idempotent: if StreamPay already cleared it, the endpoint reconciles local state and succeeds with
196
+ `reused: true`.
197
+
198
+ ## Checkout and webhook sequence
199
+
200
+ ```text
201
+ upgrade(seats)
202
+ -> validate plan/bounds and reserve unique local slot
203
+ -> create StreamPay payment link with item.quantity
204
+ -> customer pays (and may edit quantity only when explicitly enabled)
205
+ -> signed webhook or success fallback fetches the subscription
206
+ -> provider items[].quantity overwrites local seats
207
+
208
+ updateSeats(newSeats)
209
+ -> fetch provider subscription
210
+ -> preserve every item/coupon and replace configured item quantity
211
+ -> StreamPay returns pending_change (or an immediate authoritative state)
212
+ -> persist current seats + pendingSeats separately
213
+ -> later webhook fetches provider state and applies/clears pending seats
214
+ ```
215
+
216
+ The upgrade reservation is idempotent by plan **and** seat count. A second request for a different
217
+ quantity cannot accidentally recover an earlier checkout URL; it returns a conflict until that
218
+ reservation expires.
219
+
220
+ ## Migration
221
+
222
+ Adding seat support adds three subscription columns:
223
+
224
+ ```text
225
+ seats number, default 1
226
+ pendingSeats nullable number
227
+ pendingSeatsEffectiveAt nullable date
228
+ ```
229
+
230
+ Generate/apply the normal Better Auth migration:
231
+
232
+ ```bash
233
+ npx auth@latest migrate --config path/to/auth.ts
234
+ ```
235
+
236
+ For an existing application, prefer `npx auth@latest generate --config path/to/auth.ts`, review the
237
+ generated schema, and create the equivalent application migration through your ORM. This is
238
+ required for Drizzle and Prisma and is safer for SQLite upgrades because SQLite cannot express
239
+ every constraint change with `ALTER TABLE`.
240
+
241
+ The application migration must add the three columns and explicitly backfill existing rows:
242
+
243
+ ```sql
244
+ UPDATE subscription SET seats = 1 WHERE seats IS NULL;
245
+ ```
246
+
247
+ Better Auth's plugin-level `defaultValue: 1` protects new writes but its generated SQL currently
248
+ creates `seats` as a nullable integer without a database default. Keep the backfill in the same
249
+ reviewed migration as the new columns, and deploy that migration before code that reads `seats`.
250
+
251
+ This follows Better Auth's plugin contract: this package declares the complete schema and release
252
+ notes, while the consuming application controls database credentials, rollout order, backups, and
253
+ the actual migration. The plugin never performs DDL automatically during startup or a request.
254
+
255
+ ## Industry-standard comparison
256
+
257
+ | Practice | This plugin | Common billing practice |
258
+ | --- | --- | --- |
259
+ | Quantity is attached to a subscription item | Yes; public `seats` maps to StreamPay item `quantity`. | Stripe also models quantities on subscription items ([quantities guide](https://docs.stripe.com/billing/subscriptions/quantities)). |
260
+ | Hosted customer quantity editing is opt-in and bounded | Yes; `customerEditable` plus required min/max. | Stripe Checkout similarly uses opt-in adjustable quantity and min/max ([adjustable quantity](https://docs.stripe.com/payments/checkout/adjustable-quantity)). |
261
+ | App stores a provider projection | Yes. | Standard webhook-driven SaaS design; avoids remote calls on every authorization. |
262
+ | Current and scheduled state are distinct | Yes. | Required whenever provider changes are deferred/prorated/scheduled. |
263
+ | Full-replacement update preserves unrelated items | Yes. | Required by StreamPay's documented update contract. |
264
+ | Webhooks are deduplicated with durable retry state | Yes, by default. | Standard inbox/idempotent-consumer pattern for at-least-once webhooks. |
265
+ | Billed seats and entitlement limits are separate | Yes: `seats` versus `limits`. | Prevents silently multiplying every limit when only licensed members should scale. |
266
+ | Better Auth Stripe-style `seats` request vocabulary | Yes. | Matches the Better Auth [Stripe plugin](https://www.better-auth.com/docs/plugins/stripe) while retaining StreamPay semantics. |
267
+
268
+ No local model can make a remote payment provider transactional with your application database.
269
+ The industry-standard answer is what this plugin implements: protected metadata, unique local
270
+ reservations, provider-authoritative reconciliation, signed idempotent webhooks, retry/dead-letter
271
+ state, and explicit UI for pending changes.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "better-auth-streampay",
3
- "version": "3.0.0",
3
+ "version": "3.0.2",
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",
@@ -35,6 +35,7 @@
35
35
  },
36
36
  "files": [
37
37
  "dist",
38
+ "docs",
38
39
  "README.md",
39
40
  "LICENSE"
40
41
  ],