better-auth-streampay 3.3.0 → 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.
- package/dist/client.d.cts +2 -2
- package/dist/client.d.ts +2 -2
- package/dist/index.cjs +3682 -3612
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +3682 -3612
- package/dist/index.js.map +1 -1
- package/dist/{streampay-idQUxi7x.d.cts → streampay-CzZfiZvE.d.cts} +192 -124
- package/dist/{streampay-idQUxi7x.d.ts → streampay-CzZfiZvE.d.ts} +192 -124
- package/docs/integration.md +2 -0
- package/docs/staging-validation.md +1 -0
- package/docs/state-machines.md +48 -23
- package/package.json +3 -3
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as better_auth from 'better-auth';
|
|
2
|
-
import {
|
|
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
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
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
|
-
*
|
|
439
|
-
*
|
|
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
|
-
|
|
462
|
-
|
|
463
|
-
|
|
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:
|
|
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:
|
|
7310
|
+
discarded: true;
|
|
7243
7311
|
eventId: string;
|
|
7244
7312
|
}>;
|
|
7245
7313
|
adminListPaymentLinks: better_auth.StrictEndpoint<"/admin/streampay/payment-links", {
|
package/docs/integration.md
CHANGED
|
@@ -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
|
|
@@ -39,6 +39,7 @@ Tests cover the plugin's implemented features, not every feature of the Stream p
|
|
|
39
39
|
| Paid abandoned checkout loses access | Live sandbox payment of a replaced checkout link: the original code dead-lettered the activation and left `/subscription/current` empty; the fix activated it on the first delivery and StreamPay reported the replacement link `INACTIVE`. Replaced links show "Payment link is inactive". See [state machines](state-machines.md#live-sandbox-evidence-for-f1). |
|
|
40
40
|
| A retried webhook skips its lifecycle callback | Live sandbox subscription with a later cancellation write: on the original code a retried `SUBSCRIPTION_ACTIVATED` completed without a successful `onSubscriptionActivated`; with the fix the retry delivered it. See [state machines](state-machines.md#live-sandbox-evidence-for-f9-and-streampay-timing). |
|
|
41
41
|
| A renewal written by another event skips its callback | Live sandbox subscription renewed from cycle 4 to 5: on the original code a plan-update event that wrote cycle 5 first left `INVOICE_COMPLETED` with no `onSubscriptionRenewed`; with the fix it ran once. See [state machines](state-machines.md#live-sandbox-evidence-for-f9-and-streampay-timing). |
|
|
42
|
+
| Renewal evidence for an unlinked checkout is dropped | Live sandbox subscription at cycle 5 with only its checkout reservation: on 3.3.0 the completed renewal invoice left the reservation unlinked with no callback; with the fix it linked the reservation and reported the renewal once. See [state machines](state-machines.md#live-sandbox-evidence-for-f9-and-streampay-timing). |
|
|
42
43
|
| Checkout activates the wrong reservation | Known payment-link and consumer mismatches cannot bind a pending checkout. |
|
|
43
44
|
| Portal client sends the wrong HTTP method | The real Better Auth client sends POST for the documented no-argument session call. |
|
|
44
45
|
| Consumer lookup misses an existing account | Exact identity searches follow pagination; later-page failures and repeated provider pages fail instead of creating a duplicate consumer. |
|
package/docs/state-machines.md
CHANGED
|
@@ -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/
|
|
31
|
-
| 2 | Checkout reservation | Implicit sub-machine of 1 | `status = incomplete*`, `streampayPaymentLinkId`, `createdAt` | `subscriptions/checkout-reservation.ts
|
|
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` | `
|
|
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) | `
|
|
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,17 @@ 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. | `
|
|
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 (`
|
|
75
|
-
| S7 | Every lifecycle write is a CAS on `providerUpdatedAt`, `status`, `billingStatus`, and the correlation IDs. | `
|
|
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
|
|
79
79
|
|
|
80
80
|
| # | Trigger | From | To | Guard and code |
|
|
81
81
|
| --- | --- | --- | --- | --- |
|
|
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`). Takes the slot from an unpaid holder (S4). The `/subscription/success` fallback also confirms, but only for an `incomplete` row that still holds its slot, matched by consumer, product, and link (`isCheckoutSubscriptionCandidate`). |
|
|
82
|
+
| L1 | Paid checkout confirmed by webhook | `incomplete`, `incomplete_expired`, or no row | provider status | Signed metadata row ID, then a payment-link match, then the newest matching reservation (`reconcileFromStreamPay`). Renewal evidence that finds no linked row links a reservation owning the subscription's checkout link the same way, with the link's signed metadata (`linkCheckoutFromRenewalEvidence`, F28). Takes the slot from an unpaid holder (S4). The `/subscription/success` fallback also confirms, but only for an `incomplete` row that still holds its slot, matched by consumer, product, and link (`isCheckoutSubscriptionCandidate`). |
|
|
83
83
|
| L2 | `SUBSCRIPTION_CYCLE_RENEWAL_FAILED`, not stale | `active` | `past_due`, billing `past_due` | `sync.ts` |
|
|
84
84
|
| L3 | `INVOICE_COMPLETED` or `SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY`, not stale, or stale while its invoice is the provider's `COMPLETED` `latest_invoice` | `past_due` | `active`, billing `current` | `handleRenewalEvidence` (`sync.ts`) |
|
|
85
85
|
| L4 | Any other projection while billing is `past_due` | `past_due` | `past_due` | S5 |
|
|
@@ -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. | `
|
|
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 | `
|
|
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,14 +195,15 @@ 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 | `
|
|
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
|
|
202
202
|
evidence for that subscription waits until the lock clears. Only renewal evidence advances
|
|
203
203
|
`renewedCycleNumber`. Every other projection leaves it untouched, or initializes it to the row's
|
|
204
204
|
current cycle when it is still null on a legacy row, so a webhook or endpoint that writes the new
|
|
205
|
-
cycle first cannot absorb the renewal (F13).
|
|
205
|
+
cycle first cannot absorb the renewal (F13). A subscription first linked after it already renewed starts at the
|
|
206
|
+
first cycle, so its next renewal evidence reports the missed renewal once (F28). Every lifecycle CAS includes the marker, so a
|
|
206
207
|
projection prepared before a renewal callback cannot roll it back and let a second renewal event
|
|
207
208
|
deliver the callback again (F14). StreamPay's cycle counter is the renewal identity because period
|
|
208
209
|
boundaries drift: live sandbox subscriptions started in July read cycle 5 in November, and their
|
|
@@ -212,7 +213,9 @@ periods start up to 9 minutes after `started_at`.
|
|
|
212
213
|
|
|
213
214
|
One table serves two scopes. Subscription sync uses
|
|
214
215
|
`<event_type>:<entity_id>:<timestamp>`. Generic handlers (`webhooks({ deduplicate: true })`) use
|
|
215
|
-
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).
|
|
216
219
|
|
|
217
220
|
### States
|
|
218
221
|
|
|
@@ -230,9 +233,9 @@ the same ID with a `handlers:` prefix.
|
|
|
230
233
|
| ID | Invariant | Enforced by |
|
|
231
234
|
| --- | --- | --- |
|
|
232
235
|
| W1 | At most one worker holds a live lease. | `eventId` is unique. Claims are CAS on `status` and `lockedAt`. |
|
|
233
|
-
| W2 | Only the lease owner can complete or fail an event. | `markWebhookEventCompleted` and `recordWebhookEventFailure`
|
|
236
|
+
| W2 | Only the lease owner can complete or fail an event. | `markWebhookEventCompleted` and `recordWebhookEventFailure` require the lease's `lockedBy`. |
|
|
234
237
|
| W3 | Completed and dead-lettered events are never processed by delivery, only by replay. | `claimOrAdvanceWebhookEvent` skips them. |
|
|
235
|
-
| 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. |
|
|
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. |
|
|
236
239
|
|
|
237
240
|
### Transitions
|
|
238
241
|
|
|
@@ -245,10 +248,10 @@ the same ID with a `handlers:` prefix.
|
|
|
245
248
|
| W-e | Processing succeeds | E1 | E3 | `markWebhookEventCompleted(lockedBy)` |
|
|
246
249
|
| W-f | Transient failure, attempts left | E1 | E2 (`nextAttemptAt` set) | `recordWebhookEventFailure` |
|
|
247
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 |
|
|
248
|
-
| 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`, `
|
|
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) |
|
|
249
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. |
|
|
250
|
-
| W-j | Admin discard | any except E1 | E3 | `
|
|
251
|
-
| 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). |
|
|
252
255
|
|
|
253
256
|
E2 events move on a StreamPay redelivery, an admin replay, or a scheduled call to
|
|
254
257
|
`processDueStreampayWebhookEvents`, which selects them by `nextAttemptAt` and expired leases. E2p
|
|
@@ -281,10 +284,10 @@ sync, and the redelivery skips the sync row.
|
|
|
281
284
|
| --- | --- | --- | --- |
|
|
282
285
|
| Sign-up with `createConsumerOnSignUp` | Unlinked | Linked (inside the user insert) | `onBeforeUserCreate`. `onAfterUserCreate` backfills `external_id`. |
|
|
283
286
|
| First checkout or upgrade | Unlinked | Linked | `ensureConsumerForUser`: recover by `external_id`, create, or claim a duplicate |
|
|
284
|
-
| 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 |
|
|
285
288
|
| Provider 404 on profile sync | Linked | Unlinked (CAS) | `onUserUpdate` |
|
|
286
289
|
| Admin deletes the consumer | Linked | Unlinked (CAS) | `adminDeleteConsumer` |
|
|
287
|
-
| 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` |
|
|
288
291
|
| Portal call while unlinked | Unlinked | Unlinked (reads by `external_id`, never writes) | `portal.ts` |
|
|
289
292
|
|
|
290
293
|
Invariants: one consumer per user and one user per consumer (unique column and
|
|
@@ -328,6 +331,7 @@ PostgreSQL 17. Run the end-to-end tests on PostgreSQL with `STREAMPAY_E2E_DB=pos
|
|
|
328
331
|
| F25 | Low | 1 | A row in plan group B still holding group A's slot. | Found by Gemini 4 Neon on re-review. StreamPay moves a subscription to a product in another configured group outside the plugin, and a customer endpoint observes it before any webhook. The endpoint wrote the new group but only moved the slot on a revival. | Upgrades in group A are refused as already active, and group B can hold two live rows. | Endpoints move the slot whenever the desired slot differs |
|
|
329
332
|
| 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 |
|
|
330
333
|
| 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 |
|
|
334
|
+
| 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 |
|
|
331
335
|
| 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 |
|
|
332
336
|
| 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` |
|
|
333
337
|
| 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` |
|
|
@@ -386,6 +390,17 @@ which is why both are treated as renewal evidence. The [cancel API](https://docs
|
|
|
386
390
|
confirms `INACTIVE`, `TRIALING`, and `TRIAL_PENDING` are cancelled immediately and `ACTIVE` at
|
|
387
391
|
period end.
|
|
388
392
|
|
|
393
|
+
**F28.** StreamPay bills every cycle through the checkout link: all five invoices of sandbox
|
|
394
|
+
subscription `a74dcc6a` (cycles 1 to 5) carry payment link `5fcf418c`, whose custom metadata holds
|
|
395
|
+
the plugin's plan, reference, and reservation row ID. `probe-r11-live.mjs` gives each build only the
|
|
396
|
+
reservation that owns that link, as if every creation webhook had failed, then delivers the real
|
|
397
|
+
`INVOICE_COMPLETED` for cycle 5.
|
|
398
|
+
|
|
399
|
+
| Build | Inbox | Reservation | `onSubscriptionRenewed` |
|
|
400
|
+
| --- | --- | --- | --- |
|
|
401
|
+
| 3.3.0 | `completed` | still `incomplete`, unlinked | none |
|
|
402
|
+
| With the fix | `completed` | `active`, linked to `a74dcc6a`, cycle 5 | one, for cycle 5 |
|
|
403
|
+
|
|
389
404
|
**F10.** The sandbox exposes `latest_invoice` with `id` and `status` on the subscription, and a
|
|
390
405
|
paid invoice reads `COMPLETED` (subscription `39143aaa`). An invoice's `period_end` does not match
|
|
391
406
|
the subscription's (12 seconds apart), so the fix compares invoice IDs, not periods.
|
|
@@ -454,13 +469,23 @@ file covers F15 and F16; `tests/integration/review-findings.test.ts` covers F18
|
|
|
454
469
|
| ID | Risk | Why it is not fixed here |
|
|
455
470
|
| --- | --- | --- |
|
|
456
471
|
| R1 | Confirmed as F10 and fixed. | |
|
|
457
|
-
| R2 |
|
|
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. | |
|
|
458
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. |
|
|
459
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. |
|
|
460
|
-
| R5 |
|
|
475
|
+
| R5 | Fixed: `webhooks({ maxWebhookAttempts })` sets the generic handler attempt budget (default 5). | |
|
|
461
476
|
| R6 | A callback that runs longer than the 2-minute lease can run concurrently with a redelivery. | Documented. Callbacks must be idempotent. |
|
|
462
477
|
| R7 | Fixed with F8 (Issue 4). | |
|
|
463
478
|
| R8 | Confirmed as F12 and fixed. Parked rather than dead-lettered, so StreamPay retries still count (W4). | |
|
|
464
479
|
| R9 | Confirmed as F13 and fixed. | |
|
|
465
480
|
| R10 | Confirmed as F17 and fixed. | |
|
|
466
|
-
| R11 |
|
|
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
|
+
"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",
|