better-auth-streampay 2.0.0 → 2.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/index.cjs CHANGED
@@ -22,6 +22,8 @@ var $ERROR_CODES = defineErrorCodes({
22
22
  FORBIDDEN: "You do not have permission to perform this action.",
23
23
  NOT_FOUND: "The requested resource was not found.",
24
24
  CONSUMER_DUPLICATE: "A consumer with one of the provided identifiers already exists.",
25
+ STREAMPAY_CONSUMER_LINK_CONFLICT: "This StreamPay consumer is already linked to another account.",
26
+ STREAMPAY_CONSUMER_LINK_WRITE_FAILED: "The StreamPay consumer link could not be saved.",
25
27
  CONSUMER_HAS_ONGOING_ACTIVITY: "The consumer has ongoing invoices or active subscriptions and cannot be modified.",
26
28
  INVOICE_INVALID_STATE: "The invoice is in a state that forbids this action.",
27
29
  PAYMENT_DUPLICATE: "A payment with the same information already exists.",
@@ -33,6 +35,7 @@ var $ERROR_CODES = defineErrorCodes({
33
35
  PAYMENT_METHOD_INVALID: "The supplied payment method is invalid for this flow.",
34
36
  PRODUCT_LOCKED: "The product is referenced by a finalized invoice and cannot be modified.",
35
37
  COUPON_LOCKED: "The coupon is referenced by a finalized invoice and cannot be modified.",
38
+ CHECKOUT_CLIENT_FIELDS_FORBIDDEN: "Checkout fields must be resolved by the server.",
36
39
  SUBSCRIPTION_NOT_FOUND: "The subscription does not exist.",
37
40
  SUBSCRIPTION_PLAN_NOT_FOUND: "The requested subscription plan is not configured.",
38
41
  SUBSCRIPTION_ALREADY_ACTIVE: "An active subscription already exists for this plan group.",
@@ -344,12 +347,17 @@ async function ensureConsumerForUser(options, ctx, user) {
344
347
  if (isDuplicateConsumerError(err)) {
345
348
  const reusedId = await resolveDuplicateConsumer(options, payload, ctx);
346
349
  if (reusedId) {
350
+ await assertConsumerUnclaimed(ctx, reusedId, user.id);
347
351
  try {
348
352
  await options.client.updateConsumer(reusedId, { external_id: user.id });
349
353
  } catch (backfillErr) {
350
354
  getLogger(ctx).error(
351
355
  `consumer external_id backfill failed for user=${user.id} consumer=${reusedId}: ${formatStreamPayError(backfillErr)}`
352
356
  );
357
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
358
+ code: "STREAMPAY_CONSUMER_LINK_WRITE_FAILED",
359
+ message: "StreamPay consumer linking failed. Please try again."
360
+ });
353
361
  }
354
362
  await persistConsumerId(ctx, user.id, reusedId);
355
363
  return { consumerId: reusedId, created: false };
@@ -363,7 +371,40 @@ async function ensureConsumerForUser(options, ctx, user) {
363
371
  });
364
372
  }
365
373
  }
374
+ function consumerLinkUnavailable() {
375
+ return new api.APIError("INTERNAL_SERVER_ERROR", {
376
+ code: "STREAMPAY_CONSUMER_LINK_WRITE_FAILED",
377
+ message: "StreamPay consumer linking failed. Please try again."
378
+ });
379
+ }
380
+ async function findConsumerOwner(ctx, consumerId) {
381
+ try {
382
+ return await ctx.context.adapter.findOne({
383
+ model: "user",
384
+ where: [{ field: "streampayConsumerId", value: consumerId }]
385
+ });
386
+ } catch (err) {
387
+ getLogger(ctx).error(
388
+ `consumer ownership check failed for consumer=${consumerId}: ${formatStreamPayError(err)}`
389
+ );
390
+ throw consumerLinkUnavailable();
391
+ }
392
+ }
393
+ async function assertConsumerUnclaimed(ctx, consumerId, userId) {
394
+ const owner = await findConsumerOwner(ctx, consumerId);
395
+ if (!owner) return;
396
+ if (typeof owner.id !== "string") {
397
+ getLogger(ctx).error(`consumer ownership check returned a user without an id: ${consumerId}`);
398
+ throw consumerLinkUnavailable();
399
+ }
400
+ if (owner.id === userId) return;
401
+ throw new api.APIError("CONFLICT", {
402
+ code: "STREAMPAY_CONSUMER_LINK_CONFLICT",
403
+ message: "This StreamPay consumer is already linked to another account."
404
+ });
405
+ }
366
406
  async function persistConsumerId(ctx, userId, consumerId) {
407
+ await assertConsumerUnclaimed(ctx, consumerId, userId);
367
408
  try {
368
409
  await ctx.context.internalAdapter.updateUser(userId, {
369
410
  streampayConsumerId: consumerId
@@ -372,6 +413,8 @@ async function persistConsumerId(ctx, userId, consumerId) {
372
413
  getLogger(ctx).error(
373
414
  `consumer link write failed for user=${userId}: ${formatStreamPayError(err)}`
374
415
  );
416
+ await assertConsumerUnclaimed(ctx, consumerId, userId);
417
+ throw consumerLinkUnavailable();
375
418
  }
376
419
  }
377
420
 
@@ -2359,15 +2402,15 @@ var admin = (adminOptions = {}) => (options, registry) => {
2359
2402
  var RelativeOrAbsoluteUrl = zod.z.string().refine((val) => val.startsWith("/") || URL.canParse(val), {
2360
2403
  message: "Must be a valid URL or a relative path starting with /"
2361
2404
  });
2362
- var CheckoutBody = zod.z.object({
2405
+ var CheckoutRequestBody = zod.z.object({
2363
2406
  products: zod.z.union([
2364
2407
  zod.z.array(
2365
2408
  zod.z.object({
2366
2409
  productId: zod.z.string().uuid(),
2367
2410
  quantity: zod.z.number().int().positive().optional()
2368
2411
  })
2369
- ).nonempty("`products` must contain at least one item."),
2370
- zod.z.array(zod.z.string().uuid()).nonempty("`products` must contain at least one item."),
2412
+ ).min(1, "`products` must contain at least one item."),
2413
+ zod.z.array(zod.z.string().uuid()).min(1, "`products` must contain at least one item."),
2371
2414
  zod.z.string().uuid()
2372
2415
  ]).optional(),
2373
2416
  slug: zod.z.string().optional(),
@@ -2381,10 +2424,26 @@ var CheckoutBody = zod.z.object({
2381
2424
  validUntil: zod.z.string().datetime().optional(),
2382
2425
  couponIds: zod.z.array(zod.z.string().uuid()).optional(),
2383
2426
  redirect: zod.z.coerce.boolean().optional()
2384
- }).refine((data) => data.slug !== void 0 || data.products !== void 0, {
2385
- message: "Either `slug` or `products` is required.",
2386
- path: ["products"]
2387
2427
  });
2428
+ var CheckoutBody = CheckoutRequestBody.refine(
2429
+ (data) => data.slug !== void 0 || data.products !== void 0,
2430
+ {
2431
+ message: "Either `slug` or `products` is required.",
2432
+ path: ["products"]
2433
+ }
2434
+ );
2435
+ var SERVER_ONLY_CHECKOUT_FIELDS = [
2436
+ "products",
2437
+ "slug",
2438
+ "name",
2439
+ "description",
2440
+ "metadata",
2441
+ "successUrl",
2442
+ "failureUrl",
2443
+ "maxNumberOfPayments",
2444
+ "validUntil",
2445
+ "couponIds"
2446
+ ];
2388
2447
  function buildItem(productId, quantity) {
2389
2448
  return {
2390
2449
  product_id: productId,
@@ -2409,6 +2468,69 @@ async function resolveProducts(body, options) {
2409
2468
  (entry) => typeof entry === "string" ? buildItem(entry, 1) : buildItem(entry.productId, entry.quantity ?? 1)
2410
2469
  );
2411
2470
  }
2471
+ function rejectUntrustedClientFields(body) {
2472
+ const supplied = SERVER_ONLY_CHECKOUT_FIELDS.filter(
2473
+ (field) => Object.hasOwn(body, field) && body[field] !== void 0
2474
+ );
2475
+ if (supplied.length === 0) return;
2476
+ throw new api.APIError("BAD_REQUEST", {
2477
+ code: "CHECKOUT_CLIENT_FIELDS_FORBIDDEN",
2478
+ message: "Checkout product and payment fields must be resolved by the server."
2479
+ });
2480
+ }
2481
+ function mergeCheckoutOverrides(body, overrides) {
2482
+ const effective = { ...body };
2483
+ if (overrides.products !== void 0) {
2484
+ effective.products = overrides.products;
2485
+ delete effective.slug;
2486
+ }
2487
+ if (overrides.name !== void 0) effective.name = overrides.name;
2488
+ if (overrides.description !== void 0) effective.description = overrides.description;
2489
+ if (overrides.successUrl !== void 0) effective.successUrl = overrides.successUrl;
2490
+ if (overrides.failureUrl !== void 0) effective.failureUrl = overrides.failureUrl;
2491
+ if (overrides.maxNumberOfPayments !== void 0) {
2492
+ effective.maxNumberOfPayments = overrides.maxNumberOfPayments;
2493
+ }
2494
+ if (overrides.validUntil !== void 0) effective.validUntil = overrides.validUntil;
2495
+ if (overrides.couponIds !== void 0) effective.couponIds = overrides.couponIds;
2496
+ if (overrides.referenceId !== void 0) effective.referenceId = overrides.referenceId;
2497
+ if (overrides.metadata !== void 0) {
2498
+ effective.metadata = { ...body.metadata ?? {}, ...overrides.metadata };
2499
+ }
2500
+ return effective;
2501
+ }
2502
+ function validateEffectiveCheckout(body, logger2) {
2503
+ const parsed = CheckoutBody.safeParse(body);
2504
+ if (parsed.success) return parsed.data;
2505
+ const invalidPaths = [
2506
+ ...new Set(
2507
+ parsed.error.issues.map((issue) => issue.path.length > 0 ? issue.path.join(".") : "<root>")
2508
+ )
2509
+ ].join(", ");
2510
+ logger2.error(`resolved checkout validation failed at: ${invalidPaths}`);
2511
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
2512
+ message: "Checkout resolution produced invalid parameters."
2513
+ });
2514
+ }
2515
+ function checkoutUser(rawUser, user) {
2516
+ if (!user || rawUser === null || typeof rawUser !== "object") return null;
2517
+ return { ...rawUser, ...user };
2518
+ }
2519
+ async function deactivatePaymentLinkBestEffort(client, paymentLinkId, logger2) {
2520
+ if (!client.updatePaymentLinkStatus) {
2521
+ logger2.error(
2522
+ `checkout compensation unavailable for payment_link=${paymentLinkId}: client does not implement updatePaymentLinkStatus`
2523
+ );
2524
+ return;
2525
+ }
2526
+ try {
2527
+ await client.updatePaymentLinkStatus(paymentLinkId, { status: "INACTIVE" });
2528
+ } catch (err) {
2529
+ logger2.error(
2530
+ `checkout compensation failed for payment_link=${paymentLinkId}: ${formatStreamPayError(err)}`
2531
+ );
2532
+ }
2533
+ }
2412
2534
  function resolveRedirectUrl(urlOrPath, request, baseURL) {
2413
2535
  if (!urlOrPath) return void 0;
2414
2536
  return new URL(urlOrPath, request?.url ?? baseURL).toString();
@@ -2418,99 +2540,157 @@ async function resolveConsumerId(options, ctx, user) {
2418
2540
  const { consumerId } = await ensureConsumerForUser(options, ctx, user);
2419
2541
  return consumerId;
2420
2542
  }
2421
- var checkout = (checkoutOptions = {}) => (options) => {
2422
- const client = options.client;
2423
- return {
2424
- endpoints: {
2425
- checkout: api.createAuthEndpoint(
2426
- "/checkout",
2427
- {
2428
- method: "POST",
2429
- body: CheckoutBody
2430
- },
2431
- async (ctx) => {
2432
- const session = await api.getSessionFromCtx(ctx);
2433
- const sessionUser = asSessionUser(session?.user);
2434
- if (checkoutOptions.authenticatedUsersOnly) {
2435
- if (!sessionUser) {
2436
- throw new api.APIError("UNAUTHORIZED", {
2437
- message: "You must be logged in to checkout."
2438
- });
2543
+ var checkout = (checkoutOptions = {}) => {
2544
+ return (options) => {
2545
+ const client = options.client;
2546
+ return {
2547
+ endpoints: {
2548
+ checkout: api.createAuthEndpoint(
2549
+ "/checkout",
2550
+ {
2551
+ method: "POST",
2552
+ body: checkoutOptions.resolveCheckout ? CheckoutRequestBody : CheckoutBody
2553
+ },
2554
+ async (ctx) => {
2555
+ const session = await api.getSessionFromCtx(ctx);
2556
+ const sessionUser = asSessionUser(session?.user);
2557
+ const user = checkoutUser(session?.user, sessionUser);
2558
+ if (checkoutOptions.authenticatedUsersOnly) {
2559
+ if (!sessionUser) {
2560
+ throw new api.APIError("UNAUTHORIZED", {
2561
+ message: "You must be logged in to checkout."
2562
+ });
2563
+ }
2564
+ if (sessionUser.isAnonymous) {
2565
+ throw new api.APIError("UNAUTHORIZED", {
2566
+ message: "Anonymous users cannot checkout."
2567
+ });
2568
+ }
2439
2569
  }
2440
- if (sessionUser.isAnonymous) {
2441
- throw new api.APIError("UNAUTHORIZED", {
2442
- message: "Anonymous users cannot checkout."
2443
- });
2570
+ if (checkoutOptions.resolveCheckout) {
2571
+ rejectUntrustedClientFields(ctx.body);
2444
2572
  }
2445
- }
2446
- const items = await resolveProducts(ctx.body, checkoutOptions);
2447
- const consumerId = await resolveConsumerId(options, ctx, sessionUser);
2448
- const successUrl = resolveRedirectUrl(
2449
- ctx.body.successUrl ?? checkoutOptions.successUrl,
2450
- ctx.request,
2451
- ctx.context.baseURL
2452
- );
2453
- const failureUrl = resolveRedirectUrl(
2454
- ctx.body.failureUrl ?? checkoutOptions.failureUrl,
2455
- ctx.request,
2456
- ctx.context.baseURL
2457
- );
2458
- const customMetadata = (() => {
2459
- const base = ctx.body.metadata ?? {};
2460
- const merged = ctx.body.referenceId ? { referenceId: ctx.body.referenceId, ...base } : base;
2461
- return Object.keys(merged).length > 0 ? merged : null;
2462
- })();
2463
- const payload = {
2464
- name: ctx.body.name ?? `Checkout ${(/* @__PURE__ */ new Date()).toISOString()}`,
2465
- description: ctx.body.description ?? null,
2466
- currency: checkoutOptions.currency ?? "SAR",
2467
- items
2468
- };
2469
- if (consumerId !== null) payload.organization_consumer_id = consumerId;
2470
- if (successUrl) payload.success_redirect_url = successUrl;
2471
- if (failureUrl) payload.failure_redirect_url = failureUrl;
2472
- if (ctx.body.maxNumberOfPayments !== void 0) {
2473
- payload.max_number_of_payments = ctx.body.maxNumberOfPayments;
2474
- }
2475
- if (ctx.body.validUntil !== void 0) {
2476
- payload.valid_until = ctx.body.validUntil;
2477
- }
2478
- if (ctx.body.couponIds && ctx.body.couponIds.length > 0) {
2479
- payload.coupons = ctx.body.couponIds;
2480
- }
2481
- if (customMetadata !== null) payload.custom_metadata = customMetadata;
2482
- if (checkoutOptions.customFields) {
2483
- payload.custom_fields = checkoutOptions.customFields;
2484
- }
2485
- if (checkoutOptions.contactInformationType) {
2486
- payload.contact_information_type = checkoutOptions.contactInformationType;
2487
- }
2488
- try {
2489
- const link = await client.createPaymentLink(payload);
2490
- const url = client.getPaymentUrl(link);
2491
- if (!url) {
2492
- throw new api.APIError("INTERNAL_SERVER_ERROR", {
2493
- message: "StreamPay payment link created but no URL was returned."
2494
- });
2573
+ let effective = ctx.body;
2574
+ if (checkoutOptions.resolveCheckout) {
2575
+ let overrides;
2576
+ try {
2577
+ overrides = await checkoutOptions.resolveCheckout({ user, body: ctx.body }, ctx);
2578
+ } catch (err) {
2579
+ if (err instanceof api.APIError) throw err;
2580
+ getLogger(ctx).error(`resolveCheckout failed: ${formatStreamPayError(err)}`);
2581
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
2582
+ message: "Checkout resolution failed."
2583
+ });
2584
+ }
2585
+ effective = mergeCheckoutOverrides(ctx.body, overrides);
2495
2586
  }
2496
- return ctx.json({
2497
- url,
2498
- id: link.id ?? null,
2499
- redirect: ctx.body.redirect ?? true
2500
- });
2501
- } catch (err) {
2502
- toAPIError(
2503
- {
2504
- logPrefix: "checkout creation failed:",
2505
- userMessage: "StreamPay checkout creation failed."
2506
- },
2507
- err,
2508
- getLogger(ctx)
2587
+ effective = validateEffectiveCheckout(effective, getLogger(ctx));
2588
+ const items = await resolveProducts(effective, checkoutOptions);
2589
+ const consumerId = await resolveConsumerId(options, ctx, sessionUser);
2590
+ const successUrl = resolveRedirectUrl(
2591
+ effective.successUrl ?? checkoutOptions.successUrl,
2592
+ ctx.request,
2593
+ ctx.context.baseURL
2509
2594
  );
2595
+ const failureUrl = resolveRedirectUrl(
2596
+ effective.failureUrl ?? checkoutOptions.failureUrl,
2597
+ ctx.request,
2598
+ ctx.context.baseURL
2599
+ );
2600
+ const customMetadata = (() => {
2601
+ const merged = { ...effective.metadata ?? {} };
2602
+ if (effective.referenceId !== void 0) {
2603
+ merged.referenceId = effective.referenceId;
2604
+ }
2605
+ return Object.keys(merged).length > 0 ? merged : null;
2606
+ })();
2607
+ const payload = {
2608
+ name: effective.name ?? `Checkout ${(/* @__PURE__ */ new Date()).toISOString()}`,
2609
+ description: effective.description ?? null,
2610
+ currency: checkoutOptions.currency ?? "SAR",
2611
+ items
2612
+ };
2613
+ if (consumerId !== null) payload.organization_consumer_id = consumerId;
2614
+ if (successUrl) payload.success_redirect_url = successUrl;
2615
+ if (failureUrl) payload.failure_redirect_url = failureUrl;
2616
+ if (effective.maxNumberOfPayments !== void 0) {
2617
+ payload.max_number_of_payments = effective.maxNumberOfPayments;
2618
+ }
2619
+ if (effective.validUntil !== void 0) {
2620
+ payload.valid_until = effective.validUntil;
2621
+ }
2622
+ if (effective.couponIds && effective.couponIds.length > 0) {
2623
+ payload.coupons = effective.couponIds;
2624
+ }
2625
+ if (customMetadata !== null) payload.custom_metadata = customMetadata;
2626
+ if (checkoutOptions.customFields) {
2627
+ payload.custom_fields = checkoutOptions.customFields;
2628
+ }
2629
+ if (checkoutOptions.contactInformationType) {
2630
+ payload.contact_information_type = checkoutOptions.contactInformationType;
2631
+ }
2632
+ try {
2633
+ const link = await client.createPaymentLink(payload);
2634
+ const paymentLinkId = typeof link.id === "string" && link.id.length > 0 ? link.id : null;
2635
+ let url;
2636
+ try {
2637
+ const resolvedUrl = client.getPaymentUrl(link);
2638
+ if (!resolvedUrl) {
2639
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
2640
+ message: "StreamPay payment link created but no URL was returned."
2641
+ });
2642
+ }
2643
+ url = resolvedUrl;
2644
+ if (checkoutOptions.onCheckoutCreated) {
2645
+ if (!paymentLinkId) {
2646
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
2647
+ message: "StreamPay payment link created but no id was returned."
2648
+ });
2649
+ }
2650
+ try {
2651
+ const callbackData = {
2652
+ user,
2653
+ paymentLinkId,
2654
+ url,
2655
+ payload
2656
+ };
2657
+ if (effective.referenceId !== void 0) {
2658
+ callbackData.referenceId = effective.referenceId;
2659
+ }
2660
+ await checkoutOptions.onCheckoutCreated(callbackData, ctx);
2661
+ } catch (err) {
2662
+ if (err instanceof api.APIError) throw err;
2663
+ getLogger(ctx).error(`onCheckoutCreated failed: ${formatStreamPayError(err)}`);
2664
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
2665
+ message: "Checkout persistence failed."
2666
+ });
2667
+ }
2668
+ }
2669
+ } catch (err) {
2670
+ if (paymentLinkId) {
2671
+ await deactivatePaymentLinkBestEffort(client, paymentLinkId, getLogger(ctx));
2672
+ }
2673
+ throw err;
2674
+ }
2675
+ return ctx.json({
2676
+ url,
2677
+ id: paymentLinkId,
2678
+ redirect: ctx.body.redirect ?? true
2679
+ });
2680
+ } catch (err) {
2681
+ toAPIError(
2682
+ {
2683
+ logPrefix: "checkout creation failed:",
2684
+ userMessage: "StreamPay checkout creation failed."
2685
+ },
2686
+ err,
2687
+ getLogger(ctx)
2688
+ );
2689
+ }
2510
2690
  }
2511
- }
2512
- )
2513
- }
2691
+ )
2692
+ }
2693
+ };
2514
2694
  };
2515
2695
  };
2516
2696
  var DEFAULT_PAGE_SIZE = 100;
@@ -4613,7 +4793,7 @@ var onUserDelete = (options) => async (user, context) => {
4613
4793
 
4614
4794
  // package.json
4615
4795
  var package_default = {
4616
- version: "2.0.0"};
4796
+ version: "2.1.0"};
4617
4797
 
4618
4798
  // src/version.ts
4619
4799
  var version = package_default.version;
@@ -4640,7 +4820,8 @@ var streampay = (options) => {
4640
4820
  streampayConsumerId: {
4641
4821
  type: "string",
4642
4822
  required: false,
4643
- input: false
4823
+ input: false,
4824
+ unique: true
4644
4825
  }
4645
4826
  }
4646
4827
  },