better-auth-paystack 3.5.6 → 4.0.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.mjs CHANGED
@@ -1,14 +1,14 @@
1
- import { a as getMetadataBoolean, c as hasPaystackMetadata, i as createRenewalMetadata, l as parsePaystackMetadata, n as createCheckoutMetadata, o as getMetadataNumber, r as createProrationMetadata, s as getMetadataString, t as PACKAGE_VERSION, u as stringifyPaystackMetadata } from "./version-ClvErcin.mjs";
1
+ import { a as getMetadataBoolean, c as hasPaystackMetadata, i as createRenewalMetadata, l as parsePaystackMetadata, n as createCheckoutMetadata, o as getMetadataNumber, r as createProrationMetadata, s as getMetadataString, t as PACKAGE_VERSION, u as stringifyPaystackMetadata } from "./version-BW3EZXTR.mjs";
2
2
  import { HIDE_METADATA, defineErrorCodes } from "better-auth";
3
3
  import { APIError, createAuthEndpoint, createAuthMiddleware, getSessionFromCtx, originCheckMiddleware, sessionMiddleware } from "better-auth/api";
4
4
  import { defu } from "defu";
5
5
  import { PaystackError, PaystackResponse } from "@alexasomba/paystack-node";
6
- import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID } from "node:crypto";
6
+ import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
7
7
  import { z } from "zod";
8
8
  import { Buffer } from "node:buffer";
9
9
  import * as z$1 from "zod/v4";
10
10
  import { mergeSchema } from "better-auth/db";
11
- //#region src/models.ts
11
+ // src/models.ts
12
12
  /** Provider-owned Better Auth model names. Keep these centralized so a provider
13
13
  * model cannot accidentally fall back to Better Auth's generic billing tables. */
14
14
  const PAYSTACK_MODELS = {
@@ -21,8 +21,7 @@ const PAYSTACK_MODELS = {
21
21
  webhookEvent: "paystackWebhookEvent"
22
22
  };
23
23
  const LEGACY_PAYSTACK_MODELS = { subscription: "subscription" };
24
- //#endregion
25
- //#region src/billing-store.ts
24
+ // src/billing-store.ts
26
25
  function sortSubscriptionsForCurrent(subscriptions) {
27
26
  const statusRank = /* @__PURE__ */ new Map([
28
27
  ["active", 0],
@@ -305,8 +304,7 @@ function createBillingStoreFromAdapter(adapter) {
305
304
  }
306
305
  };
307
306
  }
308
- //#endregion
309
- //#region src/paystack-sdk.ts
307
+ // src/paystack-sdk.ts
310
308
  /**
311
309
  * Interface for checking if a result is a PaystackResponse from the SDK v1.9.1+
312
310
  */
@@ -397,8 +395,7 @@ function createPaystackAdapter(client) {
397
395
  }
398
396
  };
399
397
  }
400
- //#endregion
401
- //#region src/customer.ts
398
+ // src/customer.ts
402
399
  function isNotFound(error) {
403
400
  if (error === null || typeof error !== "object") return false;
404
401
  const candidate = error;
@@ -492,8 +489,7 @@ async function resolvePaystackCustomer(input) {
492
489
  created: true
493
490
  };
494
491
  }
495
- //#endregion
496
- //#region src/utils.ts
492
+ // src/utils.ts
497
493
  function getPlanSeatAmount(plan) {
498
494
  if (plan.seatAmount !== void 0) {
499
495
  if (typeof plan.seatAmount === "number" && Number.isFinite(plan.seatAmount)) return plan.seatAmount;
@@ -631,8 +627,7 @@ async function syncSubscriptionSeats(ctx, organizationId, options) {
631
627
  }
632
628
  }
633
629
  }
634
- //#endregion
635
- //#region src/limits.ts
630
+ // src/limits.ts
636
631
  const getOrganizationSubscription = async (ctx, organizationId, groupId) => {
637
632
  return createBillingStore(ctx).findCurrentSubscription(organizationId, groupId);
638
633
  };
@@ -662,8 +657,7 @@ const checkTeamLimit = async (ctx, organizationId, maxTeams) => {
662
657
  if ((await createBillingStore(ctx).listTeams(organizationId)).length >= maxTeams) throw new APIError("FORBIDDEN", { message: `Organization team limit reached. Max teams: ${maxTeams}` });
663
658
  return true;
664
659
  };
665
- //#endregion
666
- //#region src/credential-crypto.ts
660
+ // src/credential-crypto.ts
667
661
  const ALGORITHM = "aes-256-gcm";
668
662
  const VERSION = "v1";
669
663
  const IV_LENGTH = 12;
@@ -701,8 +695,7 @@ function resolveCredentialEncryptionKey(options) {
701
695
  if (typeof key !== "string" || key.trim() === "") throw new Error("credentialEncryptionKey or secretKey must be a non-empty string");
702
696
  return key;
703
697
  }
704
- //#endregion
705
- //#region src/payment-credentials.ts
698
+ // src/payment-credentials.ts
706
699
  async function readPaystackPaymentCredentials(adapter, options, subscriptionId) {
707
700
  let row;
708
701
  try {
@@ -766,8 +759,7 @@ async function savePaystackPaymentCredentials(adapter, options, subscriptionId,
766
759
  }
767
760
  });
768
761
  }
769
- //#endregion
770
- //#region src/reference-access.ts
762
+ // src/reference-access.ts
771
763
  const DEFAULT_BILLING_ORG_ROLES = ["owner", "admin"];
772
764
  function normalizeBillingRoles(roles) {
773
765
  return new Set(roles.map((value) => value.trim()).filter((value) => value !== ""));
@@ -813,8 +805,7 @@ async function authorizeBillingReference(ctx, options, data) {
813
805
  }
814
806
  throw new APIError("UNAUTHORIZED");
815
807
  }
816
- //#endregion
817
- //#region src/subscription-fulfillment.ts
808
+ // src/subscription-fulfillment.ts
818
809
  const progressSchema = z$1.object({
819
810
  version: z$1.literal(1),
820
811
  completed: z$1.array(z$1.enum([
@@ -965,8 +956,7 @@ async function releaseSubscriptionFulfillment(ctx, claim) {
965
956
  }
966
957
  });
967
958
  }
968
- //#endregion
969
- //#region src/reconciliation.ts
959
+ // src/reconciliation.ts
970
960
  function getAllowedSubscriptionChannels$1(options) {
971
961
  const channels = options.subscription?.allowedPaymentChannels;
972
962
  return Array.isArray(channels) && channels.length > 0 ? channels : void 0;
@@ -1343,8 +1333,7 @@ async function reconcilePaystackTransaction(ctx, options, input) {
1343
1333
  throw error;
1344
1334
  }
1345
1335
  }
1346
- //#endregion
1347
- //#region src/reference-middleware.ts
1336
+ // src/reference-middleware.ts
1348
1337
  const referenceMiddleware = (options, action) => createAuthMiddleware(async (ctx) => {
1349
1338
  const session = ctx.context.session;
1350
1339
  if (session === null || session === void 0) throw new APIError("UNAUTHORIZED");
@@ -1365,8 +1354,7 @@ const referenceMiddleware = (options, action) => createAuthMiddleware(async (ctx
1365
1354
  referenceId
1366
1355
  } };
1367
1356
  });
1368
- //#endregion
1369
- //#region src/route-modules/callback-url.ts
1357
+ // src/route-modules/callback-url.ts
1370
1358
  /** Accept only absolute HTTP(S) URLs or root-relative paths on the Better Auth origin. */
1371
1359
  function hasControlCharacters(value) {
1372
1360
  for (const character of value) {
@@ -1386,8 +1374,7 @@ function isTrustedCallbackURL(callbackURL, baseURL) {
1386
1374
  return false;
1387
1375
  }
1388
1376
  }
1389
- //#endregion
1390
- //#region src/route-modules/catalog.ts
1377
+ // src/route-modules/catalog.ts
1391
1378
  async function listStoredProducts(ctx) {
1392
1379
  return createBillingStore(ctx).listProducts();
1393
1380
  }
@@ -1400,8 +1387,7 @@ async function getConfiguredCatalog(options) {
1400
1387
  products: await getProducts(options.products)
1401
1388
  };
1402
1389
  }
1403
- //#endregion
1404
- //#region src/route-modules/checkout.ts
1390
+ // src/route-modules/checkout.ts
1405
1391
  const initializeTransactionBodySchema = z.object({
1406
1392
  plan: z.string().optional(),
1407
1393
  product: z.string().optional(),
@@ -1418,9 +1404,8 @@ const initializeTransactionBodySchema = z.object({
1418
1404
  prorateAndCharge: z.boolean().optional(),
1419
1405
  confirmTrialTokenizationCharge: z.boolean().optional()
1420
1406
  });
1421
- //#endregion
1422
- //#region src/route-modules/shared.ts
1423
- const PAYSTACK_ERROR_CODES = defineErrorCodes({
1407
+ // src/route-modules/shared.ts
1408
+ const PAYSTACK_ERROR_MESSAGES = {
1424
1409
  SUBSCRIPTION_NOT_FOUND: "Subscription not found",
1425
1410
  SUBSCRIPTION_PLAN_NOT_FOUND: "Subscription plan not found",
1426
1411
  UNABLE_TO_CREATE_CUSTOMER: "Unable to create customer",
@@ -1430,30 +1415,13 @@ const PAYSTACK_ERROR_CODES = defineErrorCodes({
1430
1415
  FAILED_TO_ENABLE_SUBSCRIPTION: "Failed to enable subscription",
1431
1416
  EMAIL_VERIFICATION_REQUIRED: "Email verification is required before you can subscribe to a plan",
1432
1417
  SUBSCRIPTION_PAYMENT_CHANNEL_NOT_ALLOWED: "This subscription only supports specific payment channels"
1433
- });
1418
+ };
1419
+ const PAYSTACK_ERROR_CODES = defineErrorCodes(PAYSTACK_ERROR_MESSAGES);
1434
1420
  function getAllowedSubscriptionChannels(options) {
1435
1421
  const channels = options.subscription?.allowedPaymentChannels;
1436
1422
  return Array.isArray(channels) && channels.length > 0 ? channels : void 0;
1437
1423
  }
1438
- async function hmacSha512Hex(secret, message) {
1439
- const encoder = new TextEncoder();
1440
- const keyData = encoder.encode(secret);
1441
- const msgData = encoder.encode(message);
1442
- const crypto = globalThis.crypto;
1443
- if (crypto !== void 0 && crypto !== null && "subtle" in crypto) {
1444
- const subtle = crypto.subtle;
1445
- const key = await subtle.importKey("raw", keyData, {
1446
- name: "HMAC",
1447
- hash: "SHA-512"
1448
- }, false, ["sign"]);
1449
- const signature = await subtle.sign("HMAC", key, msgData);
1450
- return Array.from(new Uint8Array(signature)).map((b) => b.toString(16).padStart(2, "0")).join("");
1451
- }
1452
- const { createHmac } = await import("node:crypto");
1453
- return createHmac("sha512", secret).update(message).digest("hex");
1454
- }
1455
- //#endregion
1456
- //#region src/route-modules/subscriptions.ts
1424
+ // src/route-modules/subscriptions.ts
1457
1425
  const enableDisableBodySchema = z.object({
1458
1426
  referenceId: z.string().optional(),
1459
1427
  subscriptionCode: z.string(),
@@ -1481,8 +1449,7 @@ function tryGetEmailTokenFromSubscriptionManageLink(link) {
1481
1449
  return;
1482
1450
  }
1483
1451
  }
1484
- //#endregion
1485
- //#region src/route-modules/webhook.ts
1452
+ // src/route-modules/webhook.ts
1486
1453
  function getWebhookRequest(ctx) {
1487
1454
  return ctx.requestClone ?? ctx.request;
1488
1455
  }
@@ -1492,8 +1459,7 @@ function getWebhookHeaders(ctx) {
1492
1459
  function getWebhookClientIP(ctx, headers) {
1493
1460
  return headers?.get("x-forwarded-for")?.split(",")[0]?.trim() ?? headers?.get("x-real-ip") ?? ctx.request.ip;
1494
1461
  }
1495
- //#endregion
1496
- //#region src/subscription-lifecycle.ts
1462
+ // src/subscription-lifecycle.ts
1497
1463
  /** Keep reservation context invocation-local, including concurrent requests through one plugin. */
1498
1464
  async function runSubscriptionOperation(ctx, options, operation, run) {
1499
1465
  const hooks = options?.subscription?.operationHooks;
@@ -1809,8 +1775,7 @@ async function handleProratedUpgrade(ctx, options, input) {
1809
1775
  };
1810
1776
  });
1811
1777
  }
1812
- //#endregion
1813
- //#region src/routes.ts
1778
+ // src/routes.ts
1814
1779
  const paystackWebhook = (options, path = "/webhook") => {
1815
1780
  return createAuthEndpoint(path, {
1816
1781
  method: "POST",
@@ -1823,7 +1788,8 @@ const paystackWebhook = (options, path = "/webhook") => {
1823
1788
  }, async (ctx) => {
1824
1789
  const request = getWebhookRequest(ctx);
1825
1790
  if (request === void 0 || request === null) throw new APIError("BAD_REQUEST", { message: "Request object is missing from context" });
1826
- const payload = await request.text();
1791
+ const rawBody = new Uint8Array(await request.arrayBuffer());
1792
+ const payload = new TextDecoder().decode(rawBody);
1827
1793
  const headers = getWebhookHeaders(ctx);
1828
1794
  const signature = headers?.get("x-paystack-signature");
1829
1795
  if (options.webhook?.verifyIP === true) {
@@ -1838,19 +1804,39 @@ const paystackWebhook = (options, path = "/webhook") => {
1838
1804
  status: 401
1839
1805
  });
1840
1806
  }
1841
- if (signature === void 0 || signature === null || signature === "") throw new APIError("UNAUTHORIZED", {
1842
- message: "Missing x-paystack-signature header",
1843
- status: 401
1844
- });
1845
- if (await hmacSha512Hex(options.secretKey, payload) !== signature) throw new APIError("UNAUTHORIZED", {
1846
- message: "Invalid Paystack webhook signature",
1807
+ const modernSignature = headers?.get("paystack-signature");
1808
+ const signingKeys = options.webhook?.signingKeys ?? {};
1809
+ const matches = (digest, candidate) => {
1810
+ if (!/^[0-9a-f]{128}$/.test(candidate)) return false;
1811
+ const bytes = /* @__PURE__ */ new Uint8Array(64);
1812
+ for (let i = 0; i < bytes.length; i++) bytes[i] = Number.parseInt(candidate.slice(i * 2, i * 2 + 2), 16);
1813
+ return timingSafeEqual(digest, bytes);
1814
+ };
1815
+ if (modernSignature != null) {
1816
+ const fields = modernSignature.split(",").map((field) => field.trim());
1817
+ const timestamps = fields.filter((field) => field.startsWith("t="));
1818
+ const timestamp = timestamps[0]?.slice(2);
1819
+ const validTimestamp = timestamps.length === 1 && typeof timestamp === "string" && /^[0-9]+$/.test(timestamp) && Math.abs(Date.now() / 1e3 - Number(timestamp)) <= 300;
1820
+ let verified = false;
1821
+ if (validTimestamp) for (const field of fields) {
1822
+ const entry = /^v1=(whk_[a-zA-Z0-9]+):([0-9a-f]{128})$/.exec(field);
1823
+ if (!entry) continue;
1824
+ const [, keyId, candidate] = entry;
1825
+ if (!keyId || !candidate || !Object.hasOwn(signingKeys, keyId)) continue;
1826
+ const secret = signingKeys[keyId];
1827
+ if (secret === void 0 || secret === "") continue;
1828
+ if (matches(createHmac("sha512", secret).update(timestamp + ".").update(rawBody).digest(), candidate)) verified = true;
1829
+ }
1830
+ if (!verified) throw new APIError("UNAUTHORIZED", { message: "Invalid Paystack webhook signature" });
1831
+ } else if (signature == null || signature === "" || !matches(createHmac("sha512", options.secretKey).update(rawBody).digest(), signature)) throw new APIError("UNAUTHORIZED", {
1832
+ message: signature != null && signature !== "" ? "Invalid Paystack webhook signature" : "Missing x-paystack-signature header",
1847
1833
  status: 401
1848
1834
  });
1849
1835
  const event = JSON.parse(payload);
1850
1836
  const eventName = event.event;
1851
1837
  const data = event.data;
1852
1838
  const reference = data?.reference;
1853
- const eventId = createHash("sha256").update(payload).digest("hex");
1839
+ const eventId = createHash("sha256").update(rawBody).digest("hex");
1854
1840
  const store = createBillingStore(ctx);
1855
1841
  let claimStatus;
1856
1842
  try {
@@ -2328,7 +2314,7 @@ const initializeTransaction = (options, path = "/initialize-transaction") => {
2328
2314
  const user = session.user;
2329
2315
  if (subscriptionOptions?.enabled === true && subscriptionOptions.requireEmailVerification === true && user.emailVerified !== true) throw new APIError("BAD_REQUEST", {
2330
2316
  code: "EMAIL_VERIFICATION_REQUIRED",
2331
- message: PAYSTACK_ERROR_CODES.EMAIL_VERIFICATION_REQUIRED.message
2317
+ message: PAYSTACK_ERROR_MESSAGES.EMAIL_VERIFICATION_REQUIRED
2332
2318
  });
2333
2319
  let plan;
2334
2320
  let product;
@@ -2356,7 +2342,7 @@ const initializeTransaction = (options, path = "/initialize-transaction") => {
2356
2342
  }
2357
2343
  if (plan === void 0 || plan === null) throw new APIError("BAD_REQUEST", {
2358
2344
  code: "SUBSCRIPTION_PLAN_NOT_FOUND",
2359
- message: PAYSTACK_ERROR_CODES.SUBSCRIPTION_PLAN_NOT_FOUND.message,
2345
+ message: PAYSTACK_ERROR_MESSAGES.SUBSCRIPTION_PLAN_NOT_FOUND,
2360
2346
  status: 400
2361
2347
  });
2362
2348
  } else if (productName !== void 0 && productName !== null && productName !== "") {
@@ -2433,7 +2419,7 @@ const initializeTransaction = (options, path = "/initialize-transaction") => {
2433
2419
  ctx.context.logger.error("Failed to initialize Paystack transaction", error);
2434
2420
  return new APIError("BAD_REQUEST", {
2435
2421
  code: "FAILED_TO_INITIALIZE_TRANSACTION",
2436
- message: error instanceof Error ? error.message : PAYSTACK_ERROR_CODES.FAILED_TO_INITIALIZE_TRANSACTION.message
2422
+ message: error instanceof Error ? error.message : PAYSTACK_ERROR_MESSAGES.FAILED_TO_INITIALIZE_TRANSACTION
2437
2423
  });
2438
2424
  };
2439
2425
  const prepared = await (async () => {
@@ -2666,7 +2652,7 @@ const verifyTransaction = (options, path = "/verify-transaction") => {
2666
2652
  });
2667
2653
  if (!result.ok || result.data === null) throw new APIError("BAD_REQUEST", {
2668
2654
  code: result.error?.code ?? "FAILED_TO_VERIFY_TRANSACTION",
2669
- message: result.error?.message ?? PAYSTACK_ERROR_CODES.FAILED_TO_VERIFY_TRANSACTION.message,
2655
+ message: result.error?.message ?? PAYSTACK_ERROR_MESSAGES.FAILED_TO_VERIFY_TRANSACTION,
2670
2656
  status: result.error?.status
2671
2657
  });
2672
2658
  return ctx.json({
@@ -2832,7 +2818,7 @@ const disablePaystackSubscription = (options, path = "/disable-subscription") =>
2832
2818
  return ctx.json({ status: "success" });
2833
2819
  } catch (error) {
2834
2820
  ctx.context.logger.error("Failed to disable subscription", error);
2835
- const errorMessage = error instanceof Error ? error.message : PAYSTACK_ERROR_CODES.FAILED_TO_DISABLE_SUBSCRIPTION.message;
2821
+ const errorMessage = error instanceof Error ? error.message : PAYSTACK_ERROR_MESSAGES.FAILED_TO_DISABLE_SUBSCRIPTION;
2836
2822
  throw new APIError("BAD_REQUEST", {
2837
2823
  code: "FAILED_TO_DISABLE_SUBSCRIPTION",
2838
2824
  message: errorMessage
@@ -2889,7 +2875,7 @@ const enablePaystackSubscription = (options, path = "/enable-subscription") => {
2889
2875
  return ctx.json({ status: "success" });
2890
2876
  } catch (error) {
2891
2877
  ctx.context.logger.error("Failed to enable subscription", error);
2892
- const errorMessage = error instanceof Error ? error.message : PAYSTACK_ERROR_CODES.FAILED_TO_ENABLE_SUBSCRIPTION.message;
2878
+ const errorMessage = error instanceof Error ? error.message : PAYSTACK_ERROR_MESSAGES.FAILED_TO_ENABLE_SUBSCRIPTION;
2893
2879
  throw new APIError("BAD_REQUEST", {
2894
2880
  code: "FAILED_TO_ENABLE_SUBSCRIPTION",
2895
2881
  message: errorMessage
@@ -3351,8 +3337,7 @@ const getSchema = (options) => {
3351
3337
  }
3352
3338
  return mergeSchema(baseSchema, optionSchema);
3353
3339
  };
3354
- //#endregion
3355
- //#region src/operations.ts
3340
+ // src/operations.ts
3356
3341
  async function syncPaystackProducts(ctx, options) {
3357
3342
  const paystack = createPaystackAdapter(options.paystackClient);
3358
3343
  const store = createBillingStore(ctx);
@@ -3507,8 +3492,7 @@ async function chargeSubscriptionRenewal(ctx, options, input) {
3507
3492
  data: typedChargeData
3508
3493
  };
3509
3494
  }
3510
- //#endregion
3511
- //#region src/migrations.ts
3495
+ // src/migrations.ts
3512
3496
  function asString(value) {
3513
3497
  return typeof value === "string" && value !== "" ? value : void 0;
3514
3498
  }
@@ -3698,9 +3682,7 @@ async function migratePaystackSubscriptionSchema(ctx, options) {
3698
3682
  report.status = report.failures.length > 0 ? "partial" : "complete";
3699
3683
  return report;
3700
3684
  }
3701
- //#endregion
3702
- //#region src/index.ts
3703
- const INTERNAL_ERROR_CODES = defineErrorCodes(Object.fromEntries(Object.entries(PAYSTACK_ERROR_CODES).map(([key, value]) => [key, typeof value === "string" ? value : value.message])));
3685
+ // src/index.ts
3704
3686
  const createPaystackPlugin = (options) => {
3705
3687
  const routeOptions = {
3706
3688
  ...options,
@@ -3729,7 +3711,7 @@ const createPaystackPlugin = (options) => {
3729
3711
  },
3730
3712
  schema: getSchema(options),
3731
3713
  init: ((ctx) => {
3732
- const organizationPluginAvailable = ctx.hasPlugin("organization");
3714
+ const organizationPluginAvailable = ctx.options.plugins?.some((plugin) => plugin.id === "organization") === true;
3733
3715
  if (options.organization?.enabled === true && !organizationPluginAvailable) ctx.logger.error("Paystack organization billing is enabled, but the Better Auth organization plugin was not found. Organization billing hooks will be skipped.");
3734
3716
  return { options: { databaseHooks: {
3735
3717
  user: {
@@ -3874,12 +3856,11 @@ const createPaystackPlugin = (options) => {
3874
3856
  } } } : void 0
3875
3857
  } } };
3876
3858
  }),
3877
- $ERROR_CODES: INTERNAL_ERROR_CODES,
3859
+ $ERROR_CODES: PAYSTACK_ERROR_CODES,
3878
3860
  options
3879
3861
  };
3880
3862
  };
3881
3863
  const paystack = createPaystackPlugin;
3882
- //#endregion
3883
3864
  export { chargeSubscriptionRenewal, createCheckoutMetadata, createProrationMetadata, createRenewalMetadata, getMetadataBoolean, getMetadataNumber, getMetadataString, getOrganizationEntitlements, hasPaystackMetadata, migratePaystackSubscriptionSchema, parsePaystackMetadata, paystack, reconcilePaystackTransaction, stringifyPaystackMetadata, syncPaystackPlans, syncPaystackProducts };
3884
3865
 
3885
3866
  //# sourceMappingURL=index.mjs.map