better-auth-streampay 1.1.5 → 1.2.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/README.md CHANGED
@@ -23,6 +23,15 @@ pnpm add better-auth-streampay @streamsdk/typescript better-auth zod
23
23
 
24
24
  Peers: `better-auth ^1.4`, `@streamsdk/typescript ^1.0.6`, `zod ^3.24 || ^4`.
25
25
 
26
+ ### Preview releases
27
+
28
+ Every push to `main` and every PR is published as an installable tarball
29
+ via [pkg.pr.new](https://github.com/stackblitz-labs/pkg.pr.new):
30
+
31
+ ```bash
32
+ pnpm add https://pkg.pr.new/better-auth-streampay@<sha-or-pr-number>
33
+ ```
34
+
26
35
  ## Env
27
36
 
28
37
  ```bash
package/dist/client.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { s as streampay, E as ErrorCodeEntry } from './streampay-a7EIioZY.cjs';
2
- export { $ as $ERROR_CODES, S as StreamPayErrorCode } from './streampay-a7EIioZY.cjs';
1
+ import { s as streampay, E as ErrorCodeEntry } from './streampay-DWXCWh1U.cjs';
2
+ export { $ as $ERROR_CODES, S as StreamPayErrorCode } from './streampay-DWXCWh1U.cjs';
3
3
  import '@streamsdk/typescript';
4
4
  import 'better-auth';
5
5
  import 'zod/v4/core';
package/dist/client.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { s as streampay, E as ErrorCodeEntry } from './streampay-a7EIioZY.js';
2
- export { $ as $ERROR_CODES, S as StreamPayErrorCode } from './streampay-a7EIioZY.js';
1
+ import { s as streampay, E as ErrorCodeEntry } from './streampay-DWXCWh1U.js';
2
+ export { $ as $ERROR_CODES, S as StreamPayErrorCode } from './streampay-DWXCWh1U.js';
3
3
  import '@streamsdk/typescript';
4
4
  import 'better-auth';
5
5
  import 'zod/v4/core';
package/dist/index.cjs CHANGED
@@ -500,6 +500,7 @@ var REFERENCE_ID_METADATA_KEY = "streampay_plugin_reference_id";
500
500
  // src/plugins/subscriptions/sync.ts
501
501
  var SUBSCRIPTION_MODEL = "subscription";
502
502
  var WEBHOOK_EVENT_MODEL = "streampayWebhookEvent";
503
+ var DEFAULT_MAX_WEBHOOK_ATTEMPTS = 10;
503
504
  function isUniqueConstraintError(err) {
504
505
  if (!err || typeof err !== "object") return false;
505
506
  const message = "message" in err && typeof err.message === "string" ? err.message : "";
@@ -507,28 +508,103 @@ function isUniqueConstraintError(err) {
507
508
  const code = "code" in err && typeof err.code === "string" ? err.code : "";
508
509
  return code === "P2002" || code === "23505" || code === "SQLITE_CONSTRAINT_UNIQUE";
509
510
  }
510
- async function claimWebhookEvent(ctx, payload) {
511
+ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts) {
511
512
  const eventId = extractEventId(payload);
512
- if (!eventId) return true;
513
+ if (!eventId) {
514
+ ctx.context.logger.warn(
515
+ `StreamPay webhook ${payload.event_type}: missing entity_id/timestamp \u2014 processing without dedupe.`
516
+ );
517
+ return { action: "process", row: null };
518
+ }
519
+ const now = /* @__PURE__ */ new Date();
513
520
  try {
514
- await ctx.context.adapter.create({
521
+ const inserted = await ctx.context.adapter.create({
515
522
  model: WEBHOOK_EVENT_MODEL,
516
523
  data: {
517
524
  eventId,
518
525
  eventType: payload.event_type,
519
- processedAt: /* @__PURE__ */ new Date()
526
+ status: "pending",
527
+ attemptCount: 1,
528
+ processedAt: now,
529
+ firstSeenAt: now
520
530
  }
521
531
  });
522
- return true;
532
+ return { action: "process", row: inserted };
523
533
  } catch (err) {
524
- if (isUniqueConstraintError(err)) {
525
- ctx.context.logger.info(
526
- `StreamPay webhook ${payload.event_type} (${eventId}) already processed \u2014 skipping.`
527
- );
528
- return false;
529
- }
530
- throw err;
534
+ if (!isUniqueConstraintError(err)) throw err;
535
+ }
536
+ const existing = await ctx.context.adapter.findOne({
537
+ model: WEBHOOK_EVENT_MODEL,
538
+ where: [{ field: "eventId", value: eventId }]
539
+ });
540
+ if (!existing) {
541
+ ctx.context.logger.warn(
542
+ `StreamPay webhook ${payload.event_type} (${eventId}): unique conflict but row missing, processing without tracking.`
543
+ );
544
+ return { action: "process", row: null };
531
545
  }
546
+ if (existing.status === "completed") {
547
+ ctx.context.logger.info(
548
+ `StreamPay webhook ${payload.event_type} (${eventId}) already completed \u2014 skipping.`
549
+ );
550
+ return { action: "skip", reason: "completed" };
551
+ }
552
+ if (existing.status === "dead_letter") {
553
+ ctx.context.logger.warn(
554
+ `StreamPay webhook ${payload.event_type} (${eventId}) already dead-lettered \u2014 skipping (replay manually).`
555
+ );
556
+ return { action: "skip", reason: "dead_letter" };
557
+ }
558
+ const nextAttempt = (existing.attemptCount ?? 0) + 1;
559
+ if (nextAttempt > maxAttempts) {
560
+ const updated2 = await ctx.context.adapter.update({
561
+ model: WEBHOOK_EVENT_MODEL,
562
+ update: {
563
+ status: "dead_letter",
564
+ attemptCount: nextAttempt,
565
+ processedAt: now,
566
+ rawPayload: rawBody,
567
+ signatureHeader
568
+ },
569
+ where: [{ field: "id", value: existing.id }]
570
+ });
571
+ return { action: "dead_letter", row: updated2 ?? existing };
572
+ }
573
+ const updated = await ctx.context.adapter.update({
574
+ model: WEBHOOK_EVENT_MODEL,
575
+ update: {
576
+ attemptCount: nextAttempt,
577
+ processedAt: now
578
+ },
579
+ where: [{ field: "id", value: existing.id }]
580
+ });
581
+ return { action: "process", row: updated ?? existing };
582
+ }
583
+ async function markWebhookEventCompleted(ctx, rowId) {
584
+ await ctx.context.adapter.update({
585
+ model: WEBHOOK_EVENT_MODEL,
586
+ update: {
587
+ status: "completed",
588
+ processedAt: /* @__PURE__ */ new Date(),
589
+ rawPayload: null,
590
+ signatureHeader: null,
591
+ lastError: null
592
+ },
593
+ where: [{ field: "id", value: rowId }]
594
+ });
595
+ }
596
+ async function recordWebhookEventFailure(ctx, rowId, rawBody, signatureHeader, err) {
597
+ const lastError = err instanceof Error ? err.message : String(err);
598
+ await ctx.context.adapter.update({
599
+ model: WEBHOOK_EVENT_MODEL,
600
+ update: {
601
+ processedAt: /* @__PURE__ */ new Date(),
602
+ lastError,
603
+ ...rawBody !== null ? { rawPayload: rawBody } : {},
604
+ ...signatureHeader !== null ? { signatureHeader } : {}
605
+ },
606
+ where: [{ field: "id", value: rowId }]
607
+ });
532
608
  }
533
609
  function extractEventId(payload) {
534
610
  if (!payload.timestamp || !payload.entity_id) return null;
@@ -720,24 +796,45 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
720
796
  if (payload.entity_type !== "SUBSCRIPTION" && payload.event_type !== "INVOICE_COMPLETED") {
721
797
  return;
722
798
  }
723
- if (options.dedupe !== false) {
724
- const claimed = await claimWebhookEvent(ctx, payload);
725
- if (!claimed) return;
799
+ const dedupe = options.dedupe !== false;
800
+ const rawBody = options.rawBody ?? null;
801
+ const signatureHeader = options.signatureHeader ?? null;
802
+ const maxAttempts = Math.max(1, options.maxAttempts ?? DEFAULT_MAX_WEBHOOK_ATTEMPTS);
803
+ let claim = { action: "process", row: null };
804
+ if (dedupe) {
805
+ claim = await claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts);
806
+ if (claim.action === "skip") return;
807
+ if (claim.action === "dead_letter") {
808
+ ctx.context.logger.warn(
809
+ `StreamPay webhook ${payload.event_type} (${claim.row.eventId}) dead-lettered after ${claim.row.attemptCount} attempts. Replay manually.`
810
+ );
811
+ return;
812
+ }
726
813
  }
727
- if (payload.event_type === "INVOICE_COMPLETED") {
728
- await handleInvoiceCompleted(ctx, payload, client, plans, callbacks);
729
- return;
814
+ const trackedRowId = claim.row?.id ?? null;
815
+ try {
816
+ if (payload.event_type === "INVOICE_COMPLETED") {
817
+ await handleInvoiceCompleted(ctx, payload, client, plans, callbacks);
818
+ } else {
819
+ const { row, stream } = await reconcileFromStreamPay(ctx, payload, client, plans);
820
+ if (row) {
821
+ const user = await resolveRowUser(ctx, row);
822
+ const data = {
823
+ subscription: row,
824
+ streampaySubscription: stream,
825
+ user,
826
+ event: payload
827
+ };
828
+ await dispatchSubscriptionCallback(ctx, payload, data, callbacks);
829
+ }
830
+ }
831
+ if (trackedRowId) await markWebhookEventCompleted(ctx, trackedRowId);
832
+ } catch (err) {
833
+ if (trackedRowId) {
834
+ await recordWebhookEventFailure(ctx, trackedRowId, rawBody, signatureHeader, err);
835
+ }
836
+ throw err;
730
837
  }
731
- const { row, stream } = await reconcileFromStreamPay(ctx, payload, client, plans);
732
- if (!row) return;
733
- const user = await resolveRowUser(ctx, row);
734
- const data = {
735
- subscription: row,
736
- streampaySubscription: stream,
737
- user,
738
- event: payload
739
- };
740
- await dispatchSubscriptionCallback(ctx, payload, data, callbacks);
741
838
  }
742
839
  async function handleInvoiceCompleted(ctx, payload, client, _plans, callbacks) {
743
840
  const invoiceId = payload.data?.invoice?.id ?? payload.entity_id;
@@ -1655,7 +1752,121 @@ function buildPaymentLinksEndpoints(client, adminOptions) {
1655
1752
  )
1656
1753
  };
1657
1754
  }
1658
- var admin = (adminOptions = {}) => (options) => {
1755
+ var WebhookEventsListQuery = zod.z.object({
1756
+ status: zod.z.enum(["pending", "completed", "dead_letter"]).optional(),
1757
+ eventType: zod.z.string().optional(),
1758
+ page: zod.z.coerce.number().int().positive().optional(),
1759
+ size: zod.z.coerce.number().int().positive().max(100).optional()
1760
+ }).passthrough();
1761
+ function buildWebhookEventsEndpoints(adminOptions, registry) {
1762
+ return {
1763
+ adminListWebhookEvents: api.createAuthEndpoint(
1764
+ "/admin/streampay/webhook-events",
1765
+ {
1766
+ method: "GET",
1767
+ query: WebhookEventsListQuery,
1768
+ use: [api.sessionMiddleware]
1769
+ },
1770
+ async (ctx) => {
1771
+ await requireAdmin(ctx, adminOptions);
1772
+ const adapter = getAdapter(ctx);
1773
+ const where = [];
1774
+ if (ctx.query.status) where.push({ field: "status", value: ctx.query.status });
1775
+ if (ctx.query.eventType) where.push({ field: "eventType", value: ctx.query.eventType });
1776
+ const page = ctx.query.page ?? 1;
1777
+ const size = ctx.query.size ?? 50;
1778
+ const [items, total] = await Promise.all([
1779
+ adapter.findMany({
1780
+ model: WEBHOOK_EVENT_MODEL,
1781
+ ...where.length > 0 ? { where } : {},
1782
+ limit: size,
1783
+ offset: (page - 1) * size,
1784
+ sortBy: { field: "processedAt", direction: "desc" }
1785
+ }),
1786
+ adapter.count({
1787
+ model: WEBHOOK_EVENT_MODEL,
1788
+ ...where.length > 0 ? { where } : {}
1789
+ })
1790
+ ]);
1791
+ return ctx.json({ items, total, page, size });
1792
+ }
1793
+ ),
1794
+ adminGetWebhookEvent: api.createAuthEndpoint(
1795
+ "/admin/streampay/webhook-events/:eventId",
1796
+ {
1797
+ method: "GET",
1798
+ use: [api.sessionMiddleware]
1799
+ },
1800
+ async (ctx) => {
1801
+ await requireAdmin(ctx, adminOptions);
1802
+ const adapter = getAdapter(ctx);
1803
+ const row = await adapter.findOne({
1804
+ model: WEBHOOK_EVENT_MODEL,
1805
+ where: [{ field: "eventId", value: ctx.params.eventId }]
1806
+ });
1807
+ if (!row) {
1808
+ throw new api.APIError("NOT_FOUND", {
1809
+ code: $ERROR_CODES.NOT_FOUND.code,
1810
+ message: `Webhook event ${ctx.params.eventId} not found.`
1811
+ });
1812
+ }
1813
+ return ctx.json(row);
1814
+ }
1815
+ ),
1816
+ adminReplayWebhookEvent: api.createAuthEndpoint(
1817
+ "/admin/streampay/webhook-events/:eventId/replay",
1818
+ {
1819
+ method: "POST",
1820
+ disableBody: true,
1821
+ use: [api.sessionMiddleware]
1822
+ },
1823
+ async (ctx) => {
1824
+ await requireAdmin(ctx, adminOptions);
1825
+ if (!registry?.replayWebhookEvent) {
1826
+ throw new api.APIError("BAD_REQUEST", {
1827
+ message: "Replay unavailable \u2014 `subscriptions()` plugin must be in `use` and `enableWebhookEventTable` left enabled."
1828
+ });
1829
+ }
1830
+ try {
1831
+ const result = await registry.replayWebhookEvent(ctx, ctx.params.eventId);
1832
+ return ctx.json(result);
1833
+ } catch (err) {
1834
+ if (err instanceof api.APIError) throw err;
1835
+ toAPIError(
1836
+ `StreamPay replayWebhookEvent failed for event=${ctx.params.eventId}:`,
1837
+ err,
1838
+ ctx.context.logger
1839
+ );
1840
+ }
1841
+ }
1842
+ ),
1843
+ adminDiscardWebhookEvent: api.createAuthEndpoint(
1844
+ "/admin/streampay/webhook-events/:eventId",
1845
+ {
1846
+ method: "DELETE",
1847
+ disableBody: true,
1848
+ use: [api.sessionMiddleware]
1849
+ },
1850
+ async (ctx) => {
1851
+ await requireAdmin(ctx, adminOptions);
1852
+ const adapter = getAdapter(ctx);
1853
+ const row = await adapter.findOne({
1854
+ model: WEBHOOK_EVENT_MODEL,
1855
+ where: [{ field: "eventId", value: ctx.params.eventId }]
1856
+ });
1857
+ if (!row) {
1858
+ throw new api.APIError("NOT_FOUND", {
1859
+ code: $ERROR_CODES.NOT_FOUND.code,
1860
+ message: `Webhook event ${ctx.params.eventId} not found.`
1861
+ });
1862
+ }
1863
+ await markWebhookEventCompleted({ context: { adapter } }, row.id);
1864
+ return ctx.json({ discarded: true, eventId: ctx.params.eventId });
1865
+ }
1866
+ )
1867
+ };
1868
+ }
1869
+ var admin = (adminOptions = {}) => (options, registry) => {
1659
1870
  const client = options.client;
1660
1871
  return {
1661
1872
  endpoints: {
@@ -1665,7 +1876,8 @@ var admin = (adminOptions = {}) => (options) => {
1665
1876
  ...buildInvoicesEndpoints(client, adminOptions),
1666
1877
  ...buildProductsEndpoints(client, adminOptions),
1667
1878
  ...buildCouponsEndpoints(client, adminOptions),
1668
- ...buildPaymentLinksEndpoints(client, adminOptions)
1879
+ ...buildPaymentLinksEndpoints(client, adminOptions),
1880
+ ...buildWebhookEventsEndpoints(adminOptions, registry)
1669
1881
  }
1670
1882
  };
1671
1883
  };
@@ -2880,9 +3092,40 @@ var webhookEventTable = {
2880
3092
  type: "string",
2881
3093
  required: true
2882
3094
  },
3095
+ /** Last activity (insert/retry/completion/dead-letter).
3096
+ * For `completed` = finished-at; for `pending` = last attempt. */
2883
3097
  processedAt: {
2884
3098
  type: "date",
2885
- required: true
3099
+ required: true,
3100
+ index: true
3101
+ },
3102
+ /** Defaults to `completed` so pre-state-machine rows still dedupe. */
3103
+ status: {
3104
+ type: "string",
3105
+ required: false,
3106
+ defaultValue: "completed",
3107
+ index: true
3108
+ },
3109
+ attemptCount: {
3110
+ type: "number",
3111
+ required: false,
3112
+ defaultValue: 1
3113
+ },
3114
+ firstSeenAt: {
3115
+ type: "date",
3116
+ required: false
3117
+ },
3118
+ rawPayload: {
3119
+ type: "string",
3120
+ required: false
3121
+ },
3122
+ signatureHeader: {
3123
+ type: "string",
3124
+ required: false
3125
+ },
3126
+ lastError: {
3127
+ type: "string",
3128
+ required: false
2886
3129
  }
2887
3130
  }
2888
3131
  }
@@ -2899,19 +3142,30 @@ function subscriptions(subsOptions) {
2899
3142
  } else if (typeof subsOptions.plans !== "function") {
2900
3143
  throw new TypeError("subscriptions(): `plans` must be an array or an async factory function.");
2901
3144
  }
3145
+ const flags = subsOptions;
3146
+ if (flags.enableSubscriptionTable === false && flags.enableWebhookEventTable === true) {
3147
+ throw new TypeError(
3148
+ "subscriptions(): `enableWebhookEventTable: true` requires `enableSubscriptionTable: true` \u2014 the event lifecycle table is part of the subscription sync pipeline."
3149
+ );
3150
+ }
2902
3151
  const tableEnabled = subsOptions.enableSubscriptionTable !== false;
2903
3152
  const dedupeEnabled = subsOptions.enableWebhookEventTable !== false;
2904
3153
  return (options, registry) => {
2905
3154
  const resolvePlans = createPlanResolver(subsOptions.plans);
2906
3155
  if (registry && tableEnabled) {
2907
- registry.subscriptionWebhookSync = async (ctx, payload) => {
3156
+ registry.subscriptionWebhookSync = async (ctx, payload, meta) => {
2908
3157
  const syncCtx = {
2909
3158
  context: ctx.context
2910
3159
  };
2911
3160
  const plans = await resolvePlans();
2912
3161
  try {
2913
3162
  await syncWebhookPayload(syncCtx, payload, options.client, plans, subsOptions, {
2914
- dedupe: dedupeEnabled
3163
+ dedupe: dedupeEnabled,
3164
+ rawBody: meta?.rawBody ?? null,
3165
+ signatureHeader: meta?.signatureHeader ?? null,
3166
+ ...subsOptions.maxWebhookAttempts !== void 0 && {
3167
+ maxAttempts: subsOptions.maxWebhookAttempts
3168
+ }
2915
3169
  });
2916
3170
  } catch (err) {
2917
3171
  if (classifyWebhookFailure(err) === "PERMANENT") {
@@ -2924,6 +3178,40 @@ function subscriptions(subsOptions) {
2924
3178
  throw err;
2925
3179
  }
2926
3180
  };
3181
+ if (dedupeEnabled) {
3182
+ registry.replayWebhookEvent = async (ctx, eventId) => {
3183
+ const syncCtx = {
3184
+ context: ctx.context
3185
+ };
3186
+ const row = await syncCtx.context.adapter.findOne({
3187
+ model: WEBHOOK_EVENT_MODEL,
3188
+ where: [{ field: "eventId", value: eventId }]
3189
+ });
3190
+ if (!row) {
3191
+ throw new api.APIError("NOT_FOUND", {
3192
+ code: $ERROR_CODES.NOT_FOUND.code,
3193
+ message: `Webhook event ${eventId} not found.`
3194
+ });
3195
+ }
3196
+ if (!row.rawPayload) {
3197
+ throw new api.APIError("BAD_REQUEST", {
3198
+ message: `Webhook event ${eventId} has no rawPayload \u2014 nothing to replay (already completed cleanly?).`
3199
+ });
3200
+ }
3201
+ const payload = JSON.parse(row.rawPayload);
3202
+ const plans = await resolvePlans();
3203
+ try {
3204
+ await syncWebhookPayload(syncCtx, payload, options.client, plans, subsOptions, {
3205
+ dedupe: false
3206
+ });
3207
+ await markWebhookEventCompleted(syncCtx, row.id);
3208
+ return { replayed: true, eventId };
3209
+ } catch (err) {
3210
+ await recordWebhookEventFailure(syncCtx, row.id, null, null, err);
3211
+ throw err;
3212
+ }
3213
+ };
3214
+ }
2927
3215
  }
2928
3216
  const schema = {
2929
3217
  ...tableEnabled ? subscriptionTable : {},
@@ -3140,7 +3428,10 @@ var webhooks = (webhooksOptions) => (_options, registry) => {
3140
3428
  const payload = parsed;
3141
3429
  if (registry?.subscriptionWebhookSync) {
3142
3430
  try {
3143
- await registry.subscriptionWebhookSync(ctx, payload);
3431
+ await registry.subscriptionWebhookSync(ctx, payload, {
3432
+ rawBody,
3433
+ signatureHeader
3434
+ });
3144
3435
  } catch (err) {
3145
3436
  const message = err instanceof Error ? err.message : String(err);
3146
3437
  ctx.context.logger.error(`StreamPay subscription sync failed: ${message}`);
@@ -3278,7 +3569,7 @@ var onUserDelete = (options) => async (user, context) => {
3278
3569
 
3279
3570
  // package.json
3280
3571
  var package_default = {
3281
- version: "1.1.5"};
3572
+ version: "1.2.0"};
3282
3573
 
3283
3574
  // src/version.ts
3284
3575
  var version = package_default.version;