better-auth-streampay 3.3.1 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,31 +55,10 @@ 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
- }
58
+ declare const SUBSCRIPTION_STATUSES: readonly ["incomplete", "incomplete_expired", "trial_pending", "trialing", "active", "inactive", "expired", "canceled", "frozen", "past_due"];
59
+ type SubscriptionStatus = (typeof SUBSCRIPTION_STATUSES)[number];
60
+ type StreamPaySubscriptionStatus = NonNullable<SubscriptionDetailed["status"]>;
61
+ declare const DEFAULT_ACCESS_STATUSES: readonly ["active", "trialing", "frozen", "past_due"];
83
62
 
84
63
  interface StreamPaySessionUser {
85
64
  id: string;
@@ -89,11 +68,6 @@ interface StreamPaySessionUser {
89
68
  streampayConsumerId?: string | null;
90
69
  }
91
70
 
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"];
96
-
97
71
  type StreamPayEntityType = "PAYMENT" | "INVOICE" | "SUBSCRIPTION" | "PAYMENT_LINK";
98
72
  declare const STREAMPAY_EVENT_ENTITY_TYPES: {
99
73
  readonly PAYMENT_SUCCEEDED: "PAYMENT";
@@ -304,6 +278,29 @@ interface TrialEligibilityContext {
304
278
  /** False after a trial is recorded for the same reference and plan group. */
305
279
  defaultEligible: boolean;
306
280
  }
281
+ /** Organization or custom reference recovered from checkout metadata without a local reservation. */
282
+ interface SubscriptionReferenceContext {
283
+ referenceType: "organization" | "custom";
284
+ referenceId: string;
285
+ plan: StreamPayPlanLike;
286
+ subscription: SubscriptionDetailed;
287
+ }
288
+ /** A StreamPay subscription with no plugin checkout metadata, for example one created in the dashboard. */
289
+ interface UnlinkedSubscriptionContext {
290
+ subscription: SubscriptionDetailed;
291
+ /** Local user whose StreamPay consumer matches. A lookup hint, not proof that this app sold it. */
292
+ consumerUser: StreamPaySessionUser | null;
293
+ /** Custom metadata of the subscription's checkout link, when it has one. */
294
+ linkMetadata: Record<string, unknown> | null;
295
+ /** Configured plan whose product StreamPay bills, or null when no configured product matches. */
296
+ inferredPlan: StreamPayPlanLike | null;
297
+ }
298
+ interface UnlinkedSubscriptionResolution {
299
+ referenceType: SubscriptionReferenceType;
300
+ referenceId: string;
301
+ /** Defaults to the inferred plan. Must match the product StreamPay bills. */
302
+ plan?: string;
303
+ }
307
304
  declare function subscriptionSlotKey(referenceType: SubscriptionReferenceType, referenceId: string, group: string | null | undefined): string;
308
305
  interface SubscriptionsOptionsBase extends SubscriptionCallbacks {
309
306
  plans: PlansInput;
@@ -322,12 +319,30 @@ interface SubscriptionsOptionsBase extends SubscriptionCallbacks {
322
319
  accessStatuses?: readonly SubscriptionStatus[];
323
320
  /** Disabling this removes persisted webhook deduplication and replay. */
324
321
  enableWebhookEventTable?: boolean;
322
+ /**
323
+ * Identifies this deployment on checkout links. Give each deployment its own value when several
324
+ * apps or environments share one StreamPay organization: recovery never adopts a checkout link
325
+ * stamped with another value.
326
+ */
327
+ appId?: string;
328
+ /**
329
+ * Confirms that an organization or custom reference recovered from checkout metadata, without a
330
+ * local reservation, belongs to this app. Without it, renewal recovery skips those references.
331
+ */
332
+ resolveSubscriptionReference?: (data: SubscriptionReferenceContext) => boolean | Promise<boolean>;
333
+ /**
334
+ * Maps a subscription without plugin checkout metadata to a local reference, or returns null to
335
+ * leave it unlinked. Called for each such creation and renewal event, so it must be idempotent.
336
+ * A thrown error is retried.
337
+ */
338
+ resolveUnlinkedSubscription?: (data: UnlinkedSubscriptionContext) => UnlinkedSubscriptionResolution | null | Promise<UnlinkedSubscriptionResolution | null>;
325
339
  }
326
340
  type SubscriptionsOptions = SubscriptionsOptionsBase;
327
341
  declare const PLAN_NAME_METADATA_KEY = "streampay_plugin_plan_name";
328
342
  declare const REFERENCE_ID_METADATA_KEY = "streampay_plugin_reference_id";
329
343
  declare const REFERENCE_TYPE_METADATA_KEY = "streampay_plugin_reference_type";
330
344
  declare const SUBSCRIPTION_ROW_ID_METADATA_KEY = "streampay_plugin_subscription_row_id";
345
+ declare const APP_ID_METADATA_KEY = "streampay_plugin_app_id";
331
346
 
332
347
  interface PluginAdapter {
333
348
  create: <T = unknown, D extends object = Record<string, unknown>>(args: {
@@ -378,23 +393,6 @@ interface PluginAdapter {
378
393
  }>;
379
394
  }) => Promise<number>;
380
395
  }
381
-
382
- interface ResolvedPlans {
383
- list: readonly StreamPayPlanLike[];
384
- byName: Map<string, StreamPayPlanLike>;
385
- }
386
- type FeatureKey<P> = P extends {
387
- limits?: infer L;
388
- } ? L extends Record<string, unknown> ? Extract<keyof L, string> : string : string;
389
- declare function hasSubscriptionAccess(subscription: Pick<Subscription, "status" | "catalogMapped">, accessStatuses?: readonly SubscriptionStatus[]): boolean;
390
- declare function hasFeature<P extends StreamPayPlanLike>(subscription: Subscription, plan: P | undefined, feature: FeatureKey<P>, accessStatuses?: readonly SubscriptionStatus[]): boolean;
391
- interface LimitCheckResult {
392
- allowed: boolean;
393
- limit: number;
394
- remaining: number;
395
- }
396
- declare function checkLimit<P extends StreamPayPlanLike>(subscription: Subscription, plan: P | undefined, feature: FeatureKey<P>, requested: number, accessStatuses?: readonly SubscriptionStatus[]): LimitCheckResult;
397
-
398
396
  interface SyncContext {
399
397
  context: {
400
398
  adapter: PluginAdapter;
@@ -412,6 +410,7 @@ interface SyncContext {
412
410
  };
413
411
  };
414
412
  }
413
+
415
414
  type WebhookEventStatus = "pending" | "completed" | "dead_letter";
416
415
  interface WebhookEventRow {
417
416
  id: string;
@@ -431,16 +430,87 @@ interface WebhookEventRow {
431
430
  lastError: string | null;
432
431
  lastErrorCode: string | null;
433
432
  }
433
+ /** What a scope learns about the attempt it is running. */
434
+ interface WebhookInboxAttempt {
435
+ previousError: string | null;
436
+ previousErrorCode: string | null;
437
+ }
438
+ type WebhookEventRunner = (ctx: SyncContext, attempt: WebhookInboxAttempt) => Promise<void>;
439
+ /**
440
+ * One kind of work the inbox runs for a StreamPay event. Subscription sync and generic handlers are
441
+ * the two scopes; each keeps its own inbox row per event, distinguished by `eventIdPrefix`.
442
+ */
443
+ interface WebhookInboxScope {
444
+ /** `null` keeps the unprefixed event IDs that subscription sync has always stored. */
445
+ eventIdPrefix: string | null;
446
+ maxAttempts: number;
447
+ /** Returns the work for an event this scope handles, or `null` to leave the event alone. */
448
+ prepare: (payload: StreamPayWebhookEnvelope) => WebhookEventRunner | null;
449
+ isPermanentFailure: (err: unknown) => boolean;
450
+ /** Releases scope-owned state that waits on the event before an operator discards it. */
451
+ onDiscard?: (ctx: SyncContext, row: WebhookEventRow) => Promise<void>;
452
+ }
453
+ interface ProcessDueWebhookEventsResult {
454
+ succeeded: string[];
455
+ failed: Array<{
456
+ eventId: string;
457
+ error: string;
458
+ }>;
459
+ }
460
+ interface WebhookInbox {
461
+ /**
462
+ * Adds a scope. A scope that is not `replayable` keeps its discard hook for rows it stored
463
+ * earlier, but its events are neither replayed nor retried.
464
+ *
465
+ * @throws TypeError for a prefix other than `null` or `HANDLERS_EVENT_ID_PREFIX`, which replay
466
+ * could not route.
467
+ */
468
+ register: (scope: WebhookInboxScope, options?: {
469
+ replayable?: boolean;
470
+ }) => void;
471
+ isEnabled: () => boolean;
472
+ /** With `dueAttemptCount`, replays only while the event is still that pending, due attempt. */
473
+ replay: (ctx: SyncContext, eventId: string, options?: {
474
+ dueAttemptCount?: number;
475
+ }) => Promise<{
476
+ replayed: true;
477
+ eventId: string;
478
+ }>;
479
+ /** @throws APIError `CONFLICT` while a worker holds the event or claims it during the discard. */
480
+ discard: (ctx: SyncContext, eventId: string) => Promise<{
481
+ discarded: true;
482
+ eventId: string;
483
+ }>;
484
+ processDue: (ctx: SyncContext, limit: number) => Promise<ProcessDueWebhookEventsResult>;
485
+ }
486
+
487
+ interface ResolvedPlans {
488
+ list: readonly StreamPayPlanLike[];
489
+ byName: Map<string, StreamPayPlanLike>;
490
+ }
491
+ type FeatureKey<P> = P extends {
492
+ limits?: infer L;
493
+ } ? L extends Record<string, unknown> ? Extract<keyof L, string> : string : string;
494
+ declare function hasSubscriptionAccess(subscription: Pick<Subscription, "status" | "catalogMapped">, accessStatuses?: readonly SubscriptionStatus[]): boolean;
495
+ declare function hasFeature<P extends StreamPayPlanLike>(subscription: Subscription, plan: P | undefined, feature: FeatureKey<P>, accessStatuses?: readonly SubscriptionStatus[]): boolean;
496
+ interface LimitCheckResult {
497
+ allowed: boolean;
498
+ limit: number;
499
+ remaining: number;
500
+ }
501
+ declare function checkLimit<P extends StreamPayPlanLike>(subscription: Subscription, plan: P | undefined, feature: FeatureKey<P>, requested: number, accessStatuses?: readonly SubscriptionStatus[]): LimitCheckResult;
502
+
434
503
  interface WebhookReplayOptions {
435
504
  /** @deprecated No effect: a failed replay keeps a pending event retryable until its attempts are spent. */
436
505
  retryUntilExhausted?: boolean;
437
506
  /**
438
- * Set by `processDueStreampayWebhookEvents`: replay only if the event is still pending at this
439
- * attempt and due. Otherwise the replay fails with `CONFLICT`.
507
+ * Replay only if the event is still pending at this attempt and due. Otherwise the replay fails
508
+ * with `CONFLICT`. `processDueStreampayWebhookEvents` applies this check itself.
440
509
  */
441
510
  dueAttemptCount?: number;
442
511
  }
443
- declare function syncWebhookPayload(ctx: SyncContext, payload: StreamPayWebhookPayload, client: StreamPayClient, plans: ResolvedPlans, callbacks: SubscriptionCallbacks, options?: {
512
+ type LinkOptions = Pick<SubscriptionsOptions, "appId" | "resolveSubscriptionReference" | "resolveUnlinkedSubscription">;
513
+ declare function syncWebhookPayload(ctx: SyncContext, payload: StreamPayWebhookPayload, client: StreamPayClient, plans: ResolvedPlans, callbacks: SubscriptionCallbacks & LinkOptions, options?: {
444
514
  dedupe?: boolean;
445
515
  rawBody?: string | null;
446
516
  signatureHeader?: string | null;
@@ -450,6 +520,13 @@ declare function syncWebhookPayload(ctx: SyncContext, payload: StreamPayWebhookP
450
520
  /** The inbox table exists. Defaults to `dedupe`; replay processes without dedupe but has an inbox. */
451
521
  inboxEnabled?: boolean;
452
522
  }): Promise<void>;
523
+ interface SubscriptionLinkRequest {
524
+ streampaySubscriptionId: string;
525
+ referenceType: SubscriptionReferenceType;
526
+ referenceId: string;
527
+ /** Defaults to the configured plan whose product StreamPay bills. */
528
+ plan?: string;
529
+ }
453
530
  type WebhookSyncFailure = "PERMANENT" | "TRANSIENT";
454
531
  declare function classifyWebhookFailure(err: unknown): WebhookSyncFailure;
455
532
 
@@ -458,13 +535,28 @@ interface StreamPayPluginRegistry {
458
535
  rawBody?: string;
459
536
  signatureHeader?: string | null;
460
537
  }) => Promise<void>;
461
- replayWebhookEvent?: (ctx: GenericEndpointContext, eventId: string,
462
- /** @deprecated No effect. */
463
- options?: WebhookReplayOptions) => Promise<{
538
+ /** Shared by every plugin that stores events in the webhook inbox table. */
539
+ webhookInbox?: WebhookInbox;
540
+ /**
541
+ * Re-projects a local subscription row from StreamPay after an out-of-band provider change,
542
+ * using the configured plan catalog. Never throws: a failed projection reconciles on the next
543
+ * webhook.
544
+ */
545
+ refreshSubscriptionProjection?: (ctx: GenericEndpointContext, subscription: {
546
+ streampaySubscriptionId: string;
547
+ } | {
548
+ snapshot: SubscriptionDetailed;
549
+ }, source: string) => Promise<void>;
550
+ replayWebhookEvent?: (ctx: GenericEndpointContext, eventId: string, options?: WebhookReplayOptions) => Promise<{
464
551
  replayed: true;
465
552
  eventId: string;
466
553
  }>;
554
+ /** @deprecated Use `replayWebhookEvent`; both replay any inbox event. */
467
555
  replayWebhookHandler?: NonNullable<StreamPayPluginRegistry["replayWebhookEvent"]>;
556
+ linkSubscription?: (ctx: GenericEndpointContext, request: SubscriptionLinkRequest) => Promise<{
557
+ row: Subscription;
558
+ reused: boolean;
559
+ }>;
468
560
  }
469
561
  declare function subscriptions(subsOptions: SubscriptionsOptions): (options: StreamPayOptions, registry?: StreamPayPluginRegistry) => {
470
562
  endpoints: {
@@ -475,9 +567,9 @@ declare function subscriptions(subsOptions: SubscriptionsOptions): (options: Str
475
567
  seats: zod.ZodOptional<zod.ZodNumber>;
476
568
  referenceId: zod.ZodOptional<zod.ZodString>;
477
569
  referenceType: zod.ZodOptional<zod.ZodEnum<{
478
- custom: "custom";
479
570
  user: "user";
480
571
  organization: "organization";
572
+ custom: "custom";
481
573
  }>>;
482
574
  successUrl: zod.ZodOptional<zod.ZodString>;
483
575
  failureUrl: zod.ZodOptional<zod.ZodString>;
@@ -2327,9 +2419,9 @@ declare function subscriptions(subsOptions: SubscriptionsOptions): (options: Str
2327
2419
  query: zod.ZodOptional<zod.ZodObject<{
2328
2420
  referenceId: zod.ZodOptional<zod.ZodString>;
2329
2421
  referenceType: zod.ZodOptional<zod.ZodEnum<{
2330
- custom: "custom";
2331
2422
  user: "user";
2332
2423
  organization: "organization";
2424
+ custom: "custom";
2333
2425
  }>>;
2334
2426
  }, zod_v4_core.$strip>>;
2335
2427
  use: better_auth.Middleware<better_auth.MiddlewareOptions, (inputContext: better_auth.MiddlewareInputContext<better_auth.MiddlewareOptions>) => Promise<{
@@ -2407,9 +2499,9 @@ declare function subscriptions(subsOptions: SubscriptionsOptions): (options: Str
2407
2499
  group: zod.ZodOptional<zod.ZodString>;
2408
2500
  referenceId: zod.ZodOptional<zod.ZodString>;
2409
2501
  referenceType: zod.ZodOptional<zod.ZodEnum<{
2410
- custom: "custom";
2411
2502
  user: "user";
2412
2503
  organization: "organization";
2504
+ custom: "custom";
2413
2505
  }>>;
2414
2506
  }, zod_v4_core.$strip>>;
2415
2507
  use: better_auth.Middleware<better_auth.MiddlewareOptions, (inputContext: better_auth.MiddlewareInputContext<better_auth.MiddlewareOptions>) => Promise<{
@@ -2488,9 +2580,9 @@ declare function subscriptions(subsOptions: SubscriptionsOptions): (options: Str
2488
2580
  group: zod.ZodOptional<zod.ZodString>;
2489
2581
  referenceId: zod.ZodOptional<zod.ZodString>;
2490
2582
  referenceType: zod.ZodOptional<zod.ZodEnum<{
2491
- custom: "custom";
2492
2583
  user: "user";
2493
2584
  organization: "organization";
2585
+ custom: "custom";
2494
2586
  }>>;
2495
2587
  }, zod_v4_core.$strip>;
2496
2588
  use: better_auth.Middleware<better_auth.MiddlewareOptions, (inputContext: better_auth.MiddlewareInputContext<better_auth.MiddlewareOptions>) => Promise<{
@@ -2527,9 +2619,9 @@ declare function subscriptions(subsOptions: SubscriptionsOptions): (options: Str
2527
2619
  group: zod.ZodOptional<zod.ZodString>;
2528
2620
  referenceId: zod.ZodOptional<zod.ZodString>;
2529
2621
  referenceType: zod.ZodOptional<zod.ZodEnum<{
2530
- custom: "custom";
2531
2622
  user: "user";
2532
2623
  organization: "organization";
2624
+ custom: "custom";
2533
2625
  }>>;
2534
2626
  }, zod_v4_core.$strip>;
2535
2627
  use: better_auth.Middleware<better_auth.MiddlewareOptions, (inputContext: better_auth.MiddlewareInputContext<better_auth.MiddlewareOptions>) => Promise<{
@@ -2864,6 +2956,45 @@ interface AdminOptions {
2864
2956
  }
2865
2957
  declare const admin: (adminOptions?: AdminOptions) => (options: StreamPayOptions, registry?: StreamPayPluginRegistry) => {
2866
2958
  endpoints: {
2959
+ adminLinkSubscription: better_auth.StrictEndpoint<"/admin/streampay/subscriptions/:id/link", {
2960
+ method: "POST";
2961
+ body: z.ZodObject<{
2962
+ referenceType: z.ZodEnum<{
2963
+ user: "user";
2964
+ organization: "organization";
2965
+ custom: "custom";
2966
+ }>;
2967
+ referenceId: z.ZodString;
2968
+ plan: z.ZodOptional<z.ZodString>;
2969
+ }, z.core.$strict>;
2970
+ use: better_auth.Middleware<better_auth.MiddlewareOptions, (inputContext: better_auth.MiddlewareInputContext<better_auth.MiddlewareOptions>) => Promise<{
2971
+ session: {
2972
+ session: Record<string, any> & {
2973
+ id: string;
2974
+ createdAt: Date;
2975
+ updatedAt: Date;
2976
+ userId: string;
2977
+ expiresAt: Date;
2978
+ token: string;
2979
+ ipAddress?: string | null | undefined;
2980
+ userAgent?: string | null | undefined;
2981
+ };
2982
+ user: Record<string, any> & {
2983
+ id: string;
2984
+ createdAt: Date;
2985
+ updatedAt: Date;
2986
+ email: string;
2987
+ emailVerified: boolean;
2988
+ name: string;
2989
+ image?: string | null | undefined;
2990
+ };
2991
+ };
2992
+ }>>[];
2993
+ }, {
2994
+ linked: boolean;
2995
+ reused: boolean;
2996
+ subscription: Subscription;
2997
+ }>;
2867
2998
  adminListWebhookEvents: better_auth.StrictEndpoint<"/admin/streampay/webhook-events", {
2868
2999
  method: "GET";
2869
3000
  query: z.ZodObject<{
@@ -2988,7 +3119,7 @@ declare const admin: (adminOptions?: AdminOptions) => (options: StreamPayOptions
2988
3119
  };
2989
3120
  }>>[];
2990
3121
  }, {
2991
- discarded: boolean;
3122
+ discarded: true;
2992
3123
  eventId: string;
2993
3124
  }>;
2994
3125
  adminListPaymentLinks: better_auth.StrictEndpoint<"/admin/streampay/payment-links", {
@@ -6972,6 +7103,8 @@ interface WebhooksOptions extends WebhookHandlers {
6972
7103
  toleranceSeconds?: number;
6973
7104
  /** Persist and deduplicate callback deliveries. Requires the webhook inbox migration. */
6974
7105
  deduplicate?: boolean;
7106
+ /** Deliveries of a deduplicated callback event before it is dead-lettered. Defaults to 5. */
7107
+ maxWebhookAttempts?: number;
6975
7108
  }
6976
7109
  declare const webhooks: (webhooksOptions: WebhooksOptions) => (_options: StreamPayOptions, registry?: StreamPayPluginRegistry) => {
6977
7110
  schema: {};
@@ -7109,12 +7242,78 @@ interface StreamPayOptions {
7109
7242
  use: StreamPayPlugins;
7110
7243
  }
7111
7244
 
7245
+ interface UserLinkStore {
7246
+ findOne: <T = unknown>(input: {
7247
+ model: string;
7248
+ where: Where[];
7249
+ }) => Promise<T | null>;
7250
+ update?: (input: {
7251
+ model: string;
7252
+ update: Record<string, unknown>;
7253
+ where: Where[];
7254
+ }) => Promise<unknown>;
7255
+ }
7256
+ interface StreamPayLoggerContext {
7257
+ context: {
7258
+ adapter?: UserLinkStore;
7259
+ internalAdapter?: {
7260
+ updateUser?: (userId: string, data: Record<string, unknown>) => Promise<unknown>;
7261
+ listUsers?: (limit: number, offset: number, sortBy: undefined, where: Where[]) => Promise<Record<string, unknown>[]>;
7262
+ };
7263
+ logger: {
7264
+ error: (message: string) => void;
7265
+ warn: (message: string) => void;
7266
+ info: (message: string) => void;
7267
+ debug: (message: string) => void;
7268
+ };
7269
+ };
7270
+ }
7271
+
7112
7272
  type StreamPayHookContext = StreamPayLoggerContext;
7113
7273
 
7114
7274
  declare const streampay: <O extends StreamPayOptions>(options: O) => {
7115
7275
  id: "streampay";
7116
7276
  version: string;
7117
7277
  endpoints: {
7278
+ adminLinkSubscription: better_auth.StrictEndpoint<"/admin/streampay/subscriptions/:id/link", {
7279
+ method: "POST";
7280
+ body: zod.ZodObject<{
7281
+ referenceType: zod.ZodEnum<{
7282
+ user: "user";
7283
+ organization: "organization";
7284
+ custom: "custom";
7285
+ }>;
7286
+ referenceId: zod.ZodString;
7287
+ plan: zod.ZodOptional<zod.ZodString>;
7288
+ }, zod_v4_core.$strict>;
7289
+ use: better_auth.Middleware<better_auth.MiddlewareOptions, (inputContext: better_auth.MiddlewareInputContext<better_auth.MiddlewareOptions>) => Promise<{
7290
+ session: {
7291
+ session: Record<string, any> & {
7292
+ id: string;
7293
+ createdAt: Date;
7294
+ updatedAt: Date;
7295
+ userId: string;
7296
+ expiresAt: Date;
7297
+ token: string;
7298
+ ipAddress?: string | null | undefined;
7299
+ userAgent?: string | null | undefined;
7300
+ };
7301
+ user: Record<string, any> & {
7302
+ id: string;
7303
+ createdAt: Date;
7304
+ updatedAt: Date;
7305
+ email: string;
7306
+ emailVerified: boolean;
7307
+ name: string;
7308
+ image?: string | null | undefined;
7309
+ };
7310
+ };
7311
+ }>>[];
7312
+ }, {
7313
+ linked: boolean;
7314
+ reused: boolean;
7315
+ subscription: Subscription;
7316
+ }>;
7118
7317
  adminListWebhookEvents: better_auth.StrictEndpoint<"/admin/streampay/webhook-events", {
7119
7318
  method: "GET";
7120
7319
  query: zod.ZodObject<{
@@ -7239,7 +7438,7 @@ declare const streampay: <O extends StreamPayOptions>(options: O) => {
7239
7438
  };
7240
7439
  }>>[];
7241
7440
  }, {
7242
- discarded: boolean;
7441
+ discarded: true;
7243
7442
  eventId: string;
7244
7443
  }>;
7245
7444
  adminListPaymentLinks: better_auth.StrictEndpoint<"/admin/streampay/payment-links", {
@@ -11090,9 +11289,9 @@ declare const streampay: <O extends StreamPayOptions>(options: O) => {
11090
11289
  seats: zod.ZodOptional<zod.ZodNumber>;
11091
11290
  referenceId: zod.ZodOptional<zod.ZodString>;
11092
11291
  referenceType: zod.ZodOptional<zod.ZodEnum<{
11093
- custom: "custom";
11094
11292
  user: "user";
11095
11293
  organization: "organization";
11294
+ custom: "custom";
11096
11295
  }>>;
11097
11296
  successUrl: zod.ZodOptional<zod.ZodString>;
11098
11297
  failureUrl: zod.ZodOptional<zod.ZodString>;
@@ -12942,9 +13141,9 @@ declare const streampay: <O extends StreamPayOptions>(options: O) => {
12942
13141
  query: zod.ZodOptional<zod.ZodObject<{
12943
13142
  referenceId: zod.ZodOptional<zod.ZodString>;
12944
13143
  referenceType: zod.ZodOptional<zod.ZodEnum<{
12945
- custom: "custom";
12946
13144
  user: "user";
12947
13145
  organization: "organization";
13146
+ custom: "custom";
12948
13147
  }>>;
12949
13148
  }, zod_v4_core.$strip>>;
12950
13149
  use: better_auth.Middleware<better_auth.MiddlewareOptions, (inputContext: better_auth.MiddlewareInputContext<better_auth.MiddlewareOptions>) => Promise<{
@@ -13022,9 +13221,9 @@ declare const streampay: <O extends StreamPayOptions>(options: O) => {
13022
13221
  group: zod.ZodOptional<zod.ZodString>;
13023
13222
  referenceId: zod.ZodOptional<zod.ZodString>;
13024
13223
  referenceType: zod.ZodOptional<zod.ZodEnum<{
13025
- custom: "custom";
13026
13224
  user: "user";
13027
13225
  organization: "organization";
13226
+ custom: "custom";
13028
13227
  }>>;
13029
13228
  }, zod_v4_core.$strip>>;
13030
13229
  use: better_auth.Middleware<better_auth.MiddlewareOptions, (inputContext: better_auth.MiddlewareInputContext<better_auth.MiddlewareOptions>) => Promise<{
@@ -13103,9 +13302,9 @@ declare const streampay: <O extends StreamPayOptions>(options: O) => {
13103
13302
  group: zod.ZodOptional<zod.ZodString>;
13104
13303
  referenceId: zod.ZodOptional<zod.ZodString>;
13105
13304
  referenceType: zod.ZodOptional<zod.ZodEnum<{
13106
- custom: "custom";
13107
13305
  user: "user";
13108
13306
  organization: "organization";
13307
+ custom: "custom";
13109
13308
  }>>;
13110
13309
  }, zod_v4_core.$strip>;
13111
13310
  use: better_auth.Middleware<better_auth.MiddlewareOptions, (inputContext: better_auth.MiddlewareInputContext<better_auth.MiddlewareOptions>) => Promise<{
@@ -13142,9 +13341,9 @@ declare const streampay: <O extends StreamPayOptions>(options: O) => {
13142
13341
  group: zod.ZodOptional<zod.ZodString>;
13143
13342
  referenceId: zod.ZodOptional<zod.ZodString>;
13144
13343
  referenceType: zod.ZodOptional<zod.ZodEnum<{
13145
- custom: "custom";
13146
13344
  user: "user";
13147
13345
  organization: "organization";
13346
+ custom: "custom";
13148
13347
  }>>;
13149
13348
  }, zod_v4_core.$strip>;
13150
13349
  use: better_auth.Middleware<better_auth.MiddlewareOptions, (inputContext: better_auth.MiddlewareInputContext<better_auth.MiddlewareOptions>) => Promise<{
@@ -13237,4 +13436,4 @@ declare const streampay: <O extends StreamPayOptions>(options: O) => {
13237
13436
  };
13238
13437
  };
13239
13438
 
13240
- export { $ERROR_CODES as $, type AdminOptions as A, type StreamPayHookContext as B, CheckoutBody as C, DEFAULT_ACCESS_STATUSES as D, type ErrorCodeEntry as E, type FeatureKey as F, type StreamPayInvoiceEventType as G, type StreamPayOptions as H, type StreamPayPaymentEventType as I, type StreamPayPaymentLinkEventType as J, type StreamPayPlan as K, type LimitCheckResult as L, type StreamPayPlanLike as M, type StreamPayPlugin as N, type StreamPayPluginRegistry as O, PLAN_NAME_METADATA_KEY as P, type StreamPayPlugins as Q, REFERENCE_ID_METADATA_KEY as R, type StreamPayErrorCode as S, type StreamPayProduct as T, type StreamPaySeatBilling as U, type StreamPaySubscriptionEventType as V, type StreamPayWebhookData as W, type StreamPayWebhookEnvelope as X, type StreamPayWebhookPayload as Y, type Subscription as Z, type SubscriptionBillingStatus as _, type StreamPayClient as a, type SubscriptionCallback as a0, type SubscriptionCallbackData as a1, type SubscriptionCallbacks as a2, type SubscriptionReferenceType as a3, type SubscriptionStatus as a4, type SubscriptionsOptions as a5, type SyncContext as a6, type TrialEligibilityContext as a7, type WebhookEnvelopeHandler as a8, type WebhookHandler as a9, type WebhookHandlers as aa, type WebhookSyncFailure as ab, type WebhooksOptions as ac, admin as ad, checkLimit as ae, checkout as af, classifyWebhookFailure as ag, dispatchWebhook as ah, hasFeature as ai, hasSubscriptionAccess as aj, isKnownStreamPayWebhookPayload as ak, isStreamPayWebhookEnvelope as al, mapToErrorCode as am, portal as an, subscriptionSlotKey as ao, subscriptions as ap, syncWebhookPayload as aq, webhooks as ar, type AuthorizeReferenceContext as b, type CheckoutCreatedContext as c, type CheckoutOptions as d, type CheckoutOverrides as e, type CheckoutParams as f, type CheckoutResolutionContext as g, type ClaimExistingConsumerBy as h, type ClaimExistingConsumerIdentifier as i, type ConsumerCreateOverrides as j, type PluginAdapter as k, type PortalOptions as l, REFERENCE_TYPE_METADATA_KEY as m, type ResolvedPlans as n, STREAMPAY_EVENT_TYPES as o, STREAMPAY_INVOICE_EVENT_TYPES as p, STREAMPAY_PAYMENT_EVENT_TYPES as q, STREAMPAY_PAYMENT_LINK_EVENT_TYPES as r, streampay as s, STREAMPAY_SUBSCRIPTION_EVENT_TYPES as t, SUBSCRIPTION_ROW_ID_METADATA_KEY as u, type StreamPayCustomFieldDefinition as v, type StreamPayCustomFieldsSchema as w, type StreamPayEndpoints as x, type StreamPayEntityType as y, type StreamPayEventType as z };
13439
+ export { $ERROR_CODES as $, APP_ID_METADATA_KEY as A, type StreamPayEventType as B, CheckoutBody as C, DEFAULT_ACCESS_STATUSES as D, type ErrorCodeEntry as E, type FeatureKey as F, type StreamPayHookContext as G, type StreamPayInvoiceEventType as H, type StreamPayOptions as I, type StreamPayPaymentEventType as J, type StreamPayPaymentLinkEventType as K, type LimitCheckResult as L, type StreamPayPlan as M, type StreamPayPlanLike as N, type StreamPayPlugin as O, PLAN_NAME_METADATA_KEY as P, type StreamPayPluginRegistry as Q, REFERENCE_ID_METADATA_KEY as R, type StreamPayErrorCode as S, type StreamPayPlugins as T, type StreamPayProduct as U, type StreamPaySeatBilling as V, type StreamPaySubscriptionEventType as W, type StreamPayWebhookData as X, type StreamPayWebhookEnvelope as Y, type StreamPayWebhookPayload as Z, type Subscription as _, type StreamPayClient as a, type SubscriptionBillingStatus as a0, type SubscriptionCallback as a1, type SubscriptionCallbackData as a2, type SubscriptionCallbacks as a3, type SubscriptionReferenceContext as a4, type SubscriptionReferenceType as a5, type SubscriptionStatus as a6, type SubscriptionsOptions as a7, type SyncContext as a8, type TrialEligibilityContext as a9, type UnlinkedSubscriptionContext as aa, type UnlinkedSubscriptionResolution as ab, type WebhookEnvelopeHandler as ac, type WebhookHandler as ad, type WebhookHandlers as ae, type WebhookSyncFailure as af, type WebhooksOptions as ag, admin as ah, checkLimit as ai, checkout as aj, classifyWebhookFailure as ak, dispatchWebhook as al, hasFeature as am, hasSubscriptionAccess as an, isKnownStreamPayWebhookPayload as ao, isStreamPayWebhookEnvelope as ap, mapToErrorCode as aq, portal as ar, subscriptionSlotKey as as, subscriptions as at, syncWebhookPayload as au, webhooks as av, type AdminOptions as b, type AuthorizeReferenceContext as c, type CheckoutCreatedContext as d, type CheckoutOptions as e, type CheckoutOverrides as f, type CheckoutParams as g, type CheckoutResolutionContext as h, type ClaimExistingConsumerBy as i, type ClaimExistingConsumerIdentifier as j, type ConsumerCreateOverrides as k, type PluginAdapter as l, type PortalOptions as m, REFERENCE_TYPE_METADATA_KEY as n, type ResolvedPlans as o, STREAMPAY_EVENT_TYPES as p, STREAMPAY_INVOICE_EVENT_TYPES as q, STREAMPAY_PAYMENT_EVENT_TYPES as r, streampay as s, STREAMPAY_PAYMENT_LINK_EVENT_TYPES as t, STREAMPAY_SUBSCRIPTION_EVENT_TYPES as u, SUBSCRIPTION_ROW_ID_METADATA_KEY as v, type StreamPayCustomFieldDefinition as w, type StreamPayCustomFieldsSchema as x, type StreamPayEndpoints as y, type StreamPayEntityType as z };
@@ -517,6 +517,56 @@ subscriptions({
517
517
 
518
518
  Without this callback, cross-account actions return `FORBIDDEN`.
519
519
 
520
+ ## Subscriptions without a local reservation
521
+
522
+ A plugin checkout normally links its StreamPay subscription to the reservation the upgrade
523
+ created. When that row is gone (deleted, or from an older plugin version), or the subscription was
524
+ created in the StreamPay dashboard or API, the plugin links it only with ownership evidence. One
525
+ StreamPay organization can serve several apps or environments, so metadata alone is not proof.
526
+
527
+ ```ts
528
+ subscriptions({
529
+ plans,
530
+ // A different value per deployment that shares the StreamPay organization. Keep it stable:
531
+ // links stamped with an earlier value are treated as another app's.
532
+ appId: process.env.STREAMPAY_APP_ID,
533
+ // Confirms organization and custom references recovered from checkout metadata.
534
+ resolveSubscriptionReference: async ({ referenceType, referenceId }) =>
535
+ organizationExists(referenceType, referenceId),
536
+ // Maps subscriptions that carry no plugin metadata. Return null to leave them unlinked.
537
+ resolveUnlinkedSubscription: async ({ consumerUser, inferredPlan }) =>
538
+ consumerUser && inferredPlan ? { referenceType: "user", referenceId: consumerUser.id } : null,
539
+ });
540
+ ```
541
+
542
+ | Case | Linked when |
543
+ | --- | --- |
544
+ | Checkout link stamped with another `appId` | never, not even through a reservation row ID it names (a cloned database can hold another app's rows) |
545
+ | Plugin metadata, `user` reference | StreamPay bills a configured plan product, the user exists, and its StreamPay consumer is unset or matches |
546
+ | Plugin metadata, organization or custom reference | the same product check, and `resolveSubscriptionReference` returns `true`. Without that callback, `SUBSCRIPTION_CREATED` and `SUBSCRIPTION_ACTIVATED` still link it with a warning, as before (3.x compatibility); every other event skips it |
547
+ | No plugin metadata at all | `resolveUnlinkedSubscription` returns a reference. `consumerUser` is only a hint; return `null` unless your app sold the subscription. Errors it throws are retried, whatever their status; a returned plan that StreamPay does not bill dead-letters the event |
548
+
549
+ Both creation webhooks and renewal events (`INVOICE_COMPLETED`,
550
+ `SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY`) apply these rules, so a subscription whose creation
551
+ webhooks failed is linked by its next renewal, and that renewal is reported once. The plugin never
552
+ looks up the checkout link of a subscription whose product is not a configured plan.
553
+
554
+ To link one by hand, use the admin endpoint:
555
+
556
+ ```ts
557
+ await auth.api.adminLinkSubscription({
558
+ params: { id: streampaySubscriptionId },
559
+ body: { referenceType: "user", referenceId: user.id },
560
+ headers,
561
+ });
562
+ ```
563
+
564
+ It projects StreamPay's state without firing lifecycle callbacks, returns `reused: true` for the
565
+ same reference, and returns `409` when the subscription is linked elsewhere or any other row holds
566
+ the reference's billing slot, including an open checkout; it never takes over a checkout other than
567
+ the one that owns the subscription's payment link. Its next renewal event reports one catch-up
568
+ renewal.
569
+
520
570
  ## Admin
521
571
 
522
572
  `admin()` adds billing actions for payments, subscriptions, freezes, consumers, invoices,
@@ -537,6 +587,7 @@ Calls use names such as:
537
587
  - `auth.api.adminGetSubscription`
538
588
  - `auth.api.adminCreateProduct`
539
589
  - `auth.api.adminReplayWebhookEvent`
590
+ - `auth.api.adminLinkSubscription`
540
591
 
541
592
  The IDE shows the body, query, and response types for every action.
542
593
 
@@ -577,6 +628,8 @@ The plugin:
577
628
  unknown event envelopes. Apply the inbox table migration before enabling it. Handler receipts use
578
629
  the `handlers:` event ID prefix and support the existing authenticated admin replay endpoint.
579
630
  The default is `false` to preserve existing installations that have no inbox table.
631
+ A handler event that keeps failing is dead-lettered after `maxWebhookAttempts` deliveries
632
+ (default 5), the same budget `subscriptions({ maxWebhookAttempts })` sets for subscription sync.
580
633
 
581
634
  Verified payloads are persisted when processing is claimed, so an interrupted delivery can be
582
635
  recovered after its two-minute lease expires. A delivery that arrives while another worker holds
@@ -40,6 +40,7 @@ Tests cover the plugin's implemented features, not every feature of the Stream p
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
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). |
43
+ | A subscription without a local reservation is never linked | Live sandbox: a plugin checkout whose reservation row is gone was linked by its real renewal event, an API-created subscription was linked through `resolveUnlinkedSubscription`, and the admin link endpoint linked an active subscription without callbacks. On 3.3.1 none were linked. See [state machines](state-machines.md#live-sandbox-evidence-for-f9-and-streampay-timing). |
43
44
  | Checkout activates the wrong reservation | Known payment-link and consumer mismatches cannot bind a pending checkout. |
44
45
  | Portal client sends the wrong HTTP method | The real Better Auth client sends POST for the documented no-argument session call. |
45
46
  | 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. |