better-auth-streampay 3.0.1 → 3.1.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-uhs67tYl.cjs';
2
- export { $ as $ERROR_CODES, S as StreamPayErrorCode } from './streampay-uhs67tYl.cjs';
1
+ import { s as streampay, E as ErrorCodeEntry } from './streampay-Bij1FvXa.cjs';
2
+ export { $ as $ERROR_CODES, S as StreamPayErrorCode } from './streampay-Bij1FvXa.cjs';
3
3
  import 'better-auth';
4
4
  import '@streamsdk/typescript';
5
5
  import 'zod';
package/dist/client.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { s as streampay, E as ErrorCodeEntry } from './streampay-uhs67tYl.js';
2
- export { $ as $ERROR_CODES, S as StreamPayErrorCode } from './streampay-uhs67tYl.js';
1
+ import { s as streampay, E as ErrorCodeEntry } from './streampay-Bij1FvXa.js';
2
+ export { $ as $ERROR_CODES, S as StreamPayErrorCode } from './streampay-Bij1FvXa.js';
3
3
  import 'better-auth';
4
4
  import '@streamsdk/typescript';
5
5
  import 'zod';
package/dist/index.cjs CHANGED
@@ -249,6 +249,82 @@ function readValidationDetails(body) {
249
249
  return entries;
250
250
  }
251
251
 
252
+ // src/utils/parse-error.ts
253
+ function parseStreamPayError(err) {
254
+ const { status, requestId, body, message: fallbackMessage } = readSdkErrorFields(err);
255
+ const envelope = readEnvelope(body);
256
+ if (envelope && (envelope.code !== void 0 || envelope.message !== void 0)) {
257
+ return {
258
+ status,
259
+ code: envelope.code,
260
+ requestId,
261
+ message: envelope.message ?? fallbackMessage,
262
+ additionalInfo: envelope.additionalInfo,
263
+ validationErrors: []
264
+ };
265
+ }
266
+ const validationErrors = readValidationDetails(body).map((entry) => ({
267
+ loc: entry.loc,
268
+ message: entry.msg,
269
+ type: entry.type
270
+ }));
271
+ return {
272
+ status,
273
+ code: void 0,
274
+ requestId,
275
+ message: fallbackMessage,
276
+ additionalInfo: void 0,
277
+ validationErrors
278
+ };
279
+ }
280
+
281
+ // src/utils/errors.ts
282
+ function statusToAPIErrorStatus(status) {
283
+ switch (status) {
284
+ case 400:
285
+ return "BAD_REQUEST";
286
+ case 401:
287
+ return "UNAUTHORIZED";
288
+ case 403:
289
+ return "FORBIDDEN";
290
+ case 404:
291
+ return "NOT_FOUND";
292
+ case 409:
293
+ return "CONFLICT";
294
+ case 422:
295
+ return "UNPROCESSABLE_ENTITY";
296
+ case 429:
297
+ return "TOO_MANY_REQUESTS";
298
+ default:
299
+ return "INTERNAL_SERVER_ERROR";
300
+ }
301
+ }
302
+ function toAPIError(messageOrConfig, err, logger2) {
303
+ if (err instanceof api.APIError) throw err;
304
+ const { logPrefix, userMessage } = typeof messageOrConfig === "string" ? { logPrefix: messageOrConfig, userMessage: messageOrConfig } : messageOrConfig;
305
+ const parsed = parseStreamPayError(err);
306
+ const tail = [
307
+ parsed.status !== void 0 ? `status=${parsed.status}` : void 0,
308
+ parsed.code ? `code=${parsed.code}` : void 0,
309
+ parsed.requestId ? `request_id=${parsed.requestId}` : void 0
310
+ ].filter((segment) => segment !== void 0);
311
+ const validationSummary = parsed.validationErrors.length > 0 ? ` validation=${parsed.validationErrors.map((issue) => `${issue.loc.join(".")}: ${issue.message}`).join(" | ")}` : "";
312
+ const logDetail = (tail.length > 0 ? `${parsed.message} [${tail.join(" ")}]` : parsed.message) + validationSummary;
313
+ logger2.error(`${logPrefix} ${logDetail}`);
314
+ throw new api.APIError(statusToAPIErrorStatus(parsed.status), {
315
+ code: mapToErrorCode(parsed.code, parsed.status),
316
+ message: userMessage
317
+ });
318
+ }
319
+ function rejectUnauthorized(user, anonymousMessage) {
320
+ if (!user) {
321
+ throw new api.APIError("UNAUTHORIZED", { message: "Session user is missing." });
322
+ }
323
+ if (user.isAnonymous) {
324
+ throw new api.APIError("UNAUTHORIZED", { message: anonymousMessage });
325
+ }
326
+ }
327
+
252
328
  // src/utils/format-error.ts
253
329
  function formatStreamPayError(err) {
254
330
  const { body, message: fallback } = readSdkErrorFields(err);
@@ -440,12 +516,31 @@ async function ensureConsumerForUser(options, ctx, user) {
440
516
  return { consumerId: reusedId, created: false };
441
517
  }
442
518
  }
443
- getLogger(ctx).error(
444
- `consumer creation failed for user=${user.id}: ${formatStreamPayError(err)}`
519
+ const { status } = readSdkErrorFields(err);
520
+ const transient = status !== void 0 && status >= 500 || status === void 0 && err instanceof TypeError;
521
+ let recoveredId = null;
522
+ if (transient) {
523
+ try {
524
+ recoveredId = await findConsumerByExternalId(options.client, { externalId: user.id });
525
+ } catch (searchErr) {
526
+ getLogger(ctx).warn(
527
+ `consumer recovery search failed for user=${user.id}: ${formatStreamPayError(searchErr)}`
528
+ );
529
+ }
530
+ }
531
+ if (recoveredId) {
532
+ await persistConsumerId(ctx, user.id, recoveredId);
533
+ getLogger(ctx).warn(`consumer recovered after failed creation for user=${user.id}`);
534
+ return { consumerId: recoveredId, created: false };
535
+ }
536
+ toAPIError(
537
+ {
538
+ logPrefix: `consumer creation failed for user=${user.id}:`,
539
+ userMessage: "StreamPay consumer provisioning failed. Please try again."
540
+ },
541
+ err,
542
+ getLogger(ctx)
445
543
  );
446
- throw new api.APIError("INTERNAL_SERVER_ERROR", {
447
- message: "StreamPay consumer provisioning failed. Please try again."
448
- });
449
544
  }
450
545
  }
451
546
  function consumerLinkUnavailable() {
@@ -501,82 +596,6 @@ async function persistConsumerId(ctx, userId, consumerId) {
501
596
  }
502
597
  }
503
598
 
504
- // src/utils/parse-error.ts
505
- function parseStreamPayError(err) {
506
- const { status, requestId, body, message: fallbackMessage } = readSdkErrorFields(err);
507
- const envelope = readEnvelope(body);
508
- if (envelope && (envelope.code !== void 0 || envelope.message !== void 0)) {
509
- return {
510
- status,
511
- code: envelope.code,
512
- requestId,
513
- message: envelope.message ?? fallbackMessage,
514
- additionalInfo: envelope.additionalInfo,
515
- validationErrors: []
516
- };
517
- }
518
- const validationErrors = readValidationDetails(body).map((entry) => ({
519
- loc: entry.loc,
520
- message: entry.msg,
521
- type: entry.type
522
- }));
523
- return {
524
- status,
525
- code: void 0,
526
- requestId,
527
- message: fallbackMessage,
528
- additionalInfo: void 0,
529
- validationErrors
530
- };
531
- }
532
-
533
- // src/utils/errors.ts
534
- function statusToAPIErrorStatus(status) {
535
- switch (status) {
536
- case 400:
537
- return "BAD_REQUEST";
538
- case 401:
539
- return "UNAUTHORIZED";
540
- case 403:
541
- return "FORBIDDEN";
542
- case 404:
543
- return "NOT_FOUND";
544
- case 409:
545
- return "CONFLICT";
546
- case 422:
547
- return "UNPROCESSABLE_ENTITY";
548
- case 429:
549
- return "TOO_MANY_REQUESTS";
550
- default:
551
- return "INTERNAL_SERVER_ERROR";
552
- }
553
- }
554
- function toAPIError(messageOrConfig, err, logger2) {
555
- if (err instanceof api.APIError) throw err;
556
- const { logPrefix, userMessage } = typeof messageOrConfig === "string" ? { logPrefix: messageOrConfig, userMessage: messageOrConfig } : messageOrConfig;
557
- const parsed = parseStreamPayError(err);
558
- const tail = [
559
- parsed.status !== void 0 ? `status=${parsed.status}` : void 0,
560
- parsed.code ? `code=${parsed.code}` : void 0,
561
- parsed.requestId ? `request_id=${parsed.requestId}` : void 0
562
- ].filter((segment) => segment !== void 0);
563
- const validationSummary = parsed.validationErrors.length > 0 ? ` validation=${parsed.validationErrors.map((issue) => `${issue.loc.join(".")}: ${issue.message}`).join(" | ")}` : "";
564
- const logDetail = (tail.length > 0 ? `${parsed.message} [${tail.join(" ")}]` : parsed.message) + validationSummary;
565
- logger2.error(`${logPrefix} ${logDetail}`);
566
- throw new api.APIError(statusToAPIErrorStatus(parsed.status), {
567
- code: mapToErrorCode(parsed.code, parsed.status),
568
- message: userMessage
569
- });
570
- }
571
- function rejectUnauthorized(user, anonymousMessage) {
572
- if (!user) {
573
- throw new api.APIError("UNAUTHORIZED", { message: "Session user is missing." });
574
- }
575
- if (user.isAnonymous) {
576
- throw new api.APIError("UNAUTHORIZED", { message: anonymousMessage });
577
- }
578
- }
579
-
580
599
  // src/plugins/subscriptions/status.ts
581
600
  var SUBSCRIPTION_STATUSES = [
582
601
  "incomplete",
@@ -896,6 +915,40 @@ function isUniqueConstraintError(err) {
896
915
  }
897
916
  var WEBHOOK_PROCESSING_LEASE_MS = 2 * 60 * 1e3;
898
917
  var WEBHOOK_RETRY_DELAYS_MS = [5, 30, 120, 360, 720].map((minutes) => minutes * 60 * 1e3);
918
+ var WebhookEventInProgressError = class extends Error {
919
+ constructor(eventType) {
920
+ super(`Webhook ${eventType} is already being processed; retry later.`);
921
+ this.name = "WebhookEventInProgressError";
922
+ }
923
+ };
924
+ async function findDueWebhookEvents(ctx, now, limit) {
925
+ const [retryDue, abandoned] = await Promise.all([
926
+ ctx.context.adapter.findMany({
927
+ model: WEBHOOK_EVENT_MODEL,
928
+ where: [
929
+ { field: "status", value: "pending" },
930
+ { field: "nextAttemptAt", operator: "lte", value: now }
931
+ ],
932
+ limit,
933
+ sortBy: { field: "nextAttemptAt", direction: "asc" }
934
+ }),
935
+ ctx.context.adapter.findMany({
936
+ model: WEBHOOK_EVENT_MODEL,
937
+ where: [
938
+ { field: "status", value: "pending" },
939
+ {
940
+ field: "lockedAt",
941
+ operator: "lt",
942
+ value: new Date(now.getTime() - WEBHOOK_PROCESSING_LEASE_MS)
943
+ }
944
+ ],
945
+ limit,
946
+ sortBy: { field: "lockedAt", direction: "asc" }
947
+ })
948
+ ]);
949
+ const byId = new Map([...retryDue, ...abandoned].map((row) => [row.id, row]));
950
+ return [...byId.values()].slice(0, limit);
951
+ }
899
952
  async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts, scope) {
900
953
  const sourceEventId = extractEventId(payload);
901
954
  const eventId = sourceEventId && (scope ? `${scope}:${sourceEventId}` : sourceEventId);
@@ -1361,6 +1414,9 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
1361
1414
  let claim = { action: "process", row: null };
1362
1415
  if (dedupe) {
1363
1416
  claim = await claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts);
1417
+ if (claim.action === "skip" && claim.reason === "in_progress") {
1418
+ throw new WebhookEventInProgressError(payload.event_type);
1419
+ }
1364
1420
  if (claim.action === "skip") return;
1365
1421
  if (claim.action === "dead_letter") {
1366
1422
  logger(ctx).warn(
@@ -5049,9 +5105,9 @@ function subscriptions(subsOptions) {
5049
5105
  }
5050
5106
  };
5051
5107
  if (dedupeEnabled) {
5052
- registry.replayWebhookEvent = async (ctx, eventId) => {
5108
+ registry.replayWebhookEvent = async (ctx, eventId, replayOptions) => {
5053
5109
  if (eventId.startsWith("handlers:") && registry.replayWebhookHandler) {
5054
- return registry.replayWebhookHandler(ctx, eventId);
5110
+ return registry.replayWebhookHandler(ctx, eventId, replayOptions);
5055
5111
  }
5056
5112
  const syncCtx = {
5057
5113
  context: ctx.context
@@ -5103,6 +5159,7 @@ function subscriptions(subsOptions) {
5103
5159
  await markWebhookEventCompleted(syncCtx, claimed.id, claimed.lockedBy);
5104
5160
  return { replayed: true, eventId };
5105
5161
  } catch (err) {
5162
+ const maxAttempts = subsOptions.maxWebhookAttempts ?? DEFAULT_MAX_WEBHOOK_ATTEMPTS;
5106
5163
  await recordWebhookEventFailure(
5107
5164
  syncCtx,
5108
5165
  claimed.id,
@@ -5110,7 +5167,7 @@ function subscriptions(subsOptions) {
5110
5167
  null,
5111
5168
  err,
5112
5169
  claimed.lockedBy,
5113
- true
5170
+ !replayOptions?.retryUntilExhausted || classifyWebhookFailure(err) === "PERMANENT" || claimed.attemptCount >= maxAttempts
5114
5171
  );
5115
5172
  throw err;
5116
5173
  }
@@ -5289,6 +5346,13 @@ function verifyWebhookOrThrow(input) {
5289
5346
  }
5290
5347
 
5291
5348
  // src/plugins/webhooks.ts
5349
+ var DEFAULT_DUE_WEBHOOK_BATCH = 25;
5350
+ var ProcessDueWebhookEventsBody = zod.z.object({ limit: zod.z.number().int().min(1).max(100).optional() }).optional();
5351
+ function inProgressError() {
5352
+ return new api.APIError("SERVICE_UNAVAILABLE", {
5353
+ message: "Webhook event is already being processed. Retry later."
5354
+ });
5355
+ }
5292
5356
  function toErrorCode(reason) {
5293
5357
  return reason === "MISSING_HEADER" || reason === "INVALID_SIGNATURE" || reason === "EXPIRED" ? "UNAUTHORIZED" : "BAD_REQUEST";
5294
5358
  }
@@ -5303,7 +5367,7 @@ var webhooks = (webhooksOptions) => {
5303
5367
  return (_options, registry) => {
5304
5368
  const { secret, toleranceSeconds, deduplicate = false, ...handlers } = webhooksOptions;
5305
5369
  if (deduplicate && registry) {
5306
- registry.replayWebhookHandler = async (ctx, eventId) => {
5370
+ registry.replayWebhookHandler = async (ctx, eventId, replayOptions) => {
5307
5371
  const syncContext = { context: ctx.context };
5308
5372
  const row = await syncContext.context.adapter.findOne({
5309
5373
  model: WEBHOOK_EVENT_MODEL,
@@ -5341,7 +5405,7 @@ var webhooks = (webhooksOptions) => {
5341
5405
  row.signatureHeader,
5342
5406
  err,
5343
5407
  claimed.lockedBy,
5344
- true
5408
+ !replayOptions?.retryUntilExhausted || claimed.attemptCount >= DEFAULT_MAX_WEBHOOK_ATTEMPTS
5345
5409
  );
5346
5410
  throw err;
5347
5411
  }
@@ -5403,6 +5467,7 @@ var webhooks = (webhooksOptions) => {
5403
5467
  signatureHeader
5404
5468
  });
5405
5469
  } catch (err) {
5470
+ if (err instanceof WebhookEventInProgressError) throw inProgressError();
5406
5471
  const message = err instanceof Error ? err.message : String(err);
5407
5472
  logger2.error(`subscription sync failed: ${message}`);
5408
5473
  throw new api.APIError("INTERNAL_SERVER_ERROR", {
@@ -5419,6 +5484,7 @@ var webhooks = (webhooksOptions) => {
5419
5484
  DEFAULT_MAX_WEBHOOK_ATTEMPTS,
5420
5485
  "handlers"
5421
5486
  ) : null;
5487
+ if (claim?.action === "skip" && claim.reason === "in_progress") throw inProgressError();
5422
5488
  if (claim && claim.action !== "process") return ctx.json({ received: true });
5423
5489
  const row = claim?.action === "process" ? claim.row : null;
5424
5490
  try {
@@ -5444,6 +5510,48 @@ var webhooks = (webhooksOptions) => {
5444
5510
  }
5445
5511
  return ctx.json({ received: true });
5446
5512
  }
5513
+ ),
5514
+ processDueStreampayWebhookEvents: api.createAuthEndpoint(
5515
+ "/streampay/webhooks/process-due",
5516
+ {
5517
+ method: "POST",
5518
+ body: ProcessDueWebhookEventsBody,
5519
+ metadata: { SERVER_ONLY: true }
5520
+ },
5521
+ async (ctx) => {
5522
+ const replay = registry?.replayWebhookEvent;
5523
+ if (!replay) {
5524
+ throw new api.APIError("BAD_REQUEST", {
5525
+ message: "Retry processing requires the webhook inbox: enable subscriptions or webhooks({ deduplicate: true })."
5526
+ });
5527
+ }
5528
+ const syncContext = { context: ctx.context };
5529
+ const due = await findDueWebhookEvents(
5530
+ syncContext,
5531
+ /* @__PURE__ */ new Date(),
5532
+ ctx.body?.limit ?? DEFAULT_DUE_WEBHOOK_BATCH
5533
+ );
5534
+ const succeeded = [];
5535
+ const failed = [];
5536
+ for (const row of due) {
5537
+ try {
5538
+ await replay(ctx, row.eventId, { retryUntilExhausted: true });
5539
+ succeeded.push(row.eventId);
5540
+ } catch (err) {
5541
+ if (err instanceof api.APIError && err.status === "CONFLICT") continue;
5542
+ failed.push({
5543
+ eventId: row.eventId,
5544
+ error: err instanceof Error ? err.message : String(err)
5545
+ });
5546
+ }
5547
+ }
5548
+ if (failed.length > 0) {
5549
+ getLogger(ctx).error(
5550
+ `webhook retry: ${failed.length} of ${due.length} due events failed again`
5551
+ );
5552
+ }
5553
+ return ctx.json({ succeeded, failed });
5554
+ }
5447
5555
  )
5448
5556
  }
5449
5557
  };
@@ -5568,7 +5676,7 @@ var onUserDelete = (options) => async (user, context) => {
5568
5676
 
5569
5677
  // package.json
5570
5678
  var package_default = {
5571
- version: "3.0.1"};
5679
+ version: "3.1.0"};
5572
5680
 
5573
5681
  // src/version.ts
5574
5682
  var version = package_default.version;