better-auth-streampay 1.1.6 → 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/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,43 +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;
531
535
  }
532
- }
533
- async function releaseWebhookEvent(ctx, payload) {
534
- const eventId = extractEventId(payload);
535
- if (!eventId) return;
536
- try {
537
- await ctx.context.adapter.delete({
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 };
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({
538
561
  model: WEBHOOK_EVENT_MODEL,
539
- where: [{ field: "eventId", value: eventId }]
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 }]
540
570
  });
541
- } catch (err) {
542
- const msg = err instanceof Error ? err.message : String(err);
543
- ctx.context.logger.error(
544
- `StreamPay webhook ${payload.event_type} (${eventId}): failed to release dedupe claim after sync error \u2014 retry will be skipped: ${msg}`
545
- );
571
+ return { action: "dead_letter", row: updated2 ?? existing };
546
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
+ });
547
608
  }
548
609
  function extractEventId(payload) {
549
610
  if (!payload.timestamp || !payload.entity_id) return null;
@@ -736,27 +797,42 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
736
797
  return;
737
798
  }
738
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 };
739
804
  if (dedupe) {
740
- const claimed = await claimWebhookEvent(ctx, payload);
741
- if (!claimed) return;
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
+ }
742
813
  }
814
+ const trackedRowId = claim.row?.id ?? null;
743
815
  try {
744
816
  if (payload.event_type === "INVOICE_COMPLETED") {
745
817
  await handleInvoiceCompleted(ctx, payload, client, plans, callbacks);
746
- return;
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
+ }
747
830
  }
748
- const { row, stream } = await reconcileFromStreamPay(ctx, payload, client, plans);
749
- if (!row) return;
750
- const user = await resolveRowUser(ctx, row);
751
- const data = {
752
- subscription: row,
753
- streampaySubscription: stream,
754
- user,
755
- event: payload
756
- };
757
- await dispatchSubscriptionCallback(ctx, payload, data, callbacks);
831
+ if (trackedRowId) await markWebhookEventCompleted(ctx, trackedRowId);
758
832
  } catch (err) {
759
- if (dedupe) await releaseWebhookEvent(ctx, payload);
833
+ if (trackedRowId) {
834
+ await recordWebhookEventFailure(ctx, trackedRowId, rawBody, signatureHeader, err);
835
+ }
760
836
  throw err;
761
837
  }
762
838
  }
@@ -1676,7 +1752,121 @@ function buildPaymentLinksEndpoints(client, adminOptions) {
1676
1752
  )
1677
1753
  };
1678
1754
  }
1679
- 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) => {
1680
1870
  const client = options.client;
1681
1871
  return {
1682
1872
  endpoints: {
@@ -1686,7 +1876,8 @@ var admin = (adminOptions = {}) => (options) => {
1686
1876
  ...buildInvoicesEndpoints(client, adminOptions),
1687
1877
  ...buildProductsEndpoints(client, adminOptions),
1688
1878
  ...buildCouponsEndpoints(client, adminOptions),
1689
- ...buildPaymentLinksEndpoints(client, adminOptions)
1879
+ ...buildPaymentLinksEndpoints(client, adminOptions),
1880
+ ...buildWebhookEventsEndpoints(adminOptions, registry)
1690
1881
  }
1691
1882
  };
1692
1883
  };
@@ -2901,9 +3092,40 @@ var webhookEventTable = {
2901
3092
  type: "string",
2902
3093
  required: true
2903
3094
  },
3095
+ /** Last activity (insert/retry/completion/dead-letter).
3096
+ * For `completed` = finished-at; for `pending` = last attempt. */
2904
3097
  processedAt: {
2905
3098
  type: "date",
2906
- 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
2907
3129
  }
2908
3130
  }
2909
3131
  }
@@ -2920,19 +3142,30 @@ function subscriptions(subsOptions) {
2920
3142
  } else if (typeof subsOptions.plans !== "function") {
2921
3143
  throw new TypeError("subscriptions(): `plans` must be an array or an async factory function.");
2922
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
+ }
2923
3151
  const tableEnabled = subsOptions.enableSubscriptionTable !== false;
2924
3152
  const dedupeEnabled = subsOptions.enableWebhookEventTable !== false;
2925
3153
  return (options, registry) => {
2926
3154
  const resolvePlans = createPlanResolver(subsOptions.plans);
2927
3155
  if (registry && tableEnabled) {
2928
- registry.subscriptionWebhookSync = async (ctx, payload) => {
3156
+ registry.subscriptionWebhookSync = async (ctx, payload, meta) => {
2929
3157
  const syncCtx = {
2930
3158
  context: ctx.context
2931
3159
  };
2932
3160
  const plans = await resolvePlans();
2933
3161
  try {
2934
3162
  await syncWebhookPayload(syncCtx, payload, options.client, plans, subsOptions, {
2935
- 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
+ }
2936
3169
  });
2937
3170
  } catch (err) {
2938
3171
  if (classifyWebhookFailure(err) === "PERMANENT") {
@@ -2945,6 +3178,40 @@ function subscriptions(subsOptions) {
2945
3178
  throw err;
2946
3179
  }
2947
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
+ }
2948
3215
  }
2949
3216
  const schema = {
2950
3217
  ...tableEnabled ? subscriptionTable : {},
@@ -3161,7 +3428,10 @@ var webhooks = (webhooksOptions) => (_options, registry) => {
3161
3428
  const payload = parsed;
3162
3429
  if (registry?.subscriptionWebhookSync) {
3163
3430
  try {
3164
- await registry.subscriptionWebhookSync(ctx, payload);
3431
+ await registry.subscriptionWebhookSync(ctx, payload, {
3432
+ rawBody,
3433
+ signatureHeader
3434
+ });
3165
3435
  } catch (err) {
3166
3436
  const message = err instanceof Error ? err.message : String(err);
3167
3437
  ctx.context.logger.error(`StreamPay subscription sync failed: ${message}`);
@@ -3299,7 +3569,7 @@ var onUserDelete = (options) => async (user, context) => {
3299
3569
 
3300
3570
  // package.json
3301
3571
  var package_default = {
3302
- version: "1.1.6"};
3572
+ version: "1.2.0"};
3303
3573
 
3304
3574
  // src/version.ts
3305
3575
  var version = package_default.version;