@alexasomba/better-auth-paystack 0.0.4

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 ADDED
@@ -0,0 +1,896 @@
1
+ import { defu } from "defu";
2
+ import { createEndpoint, createMiddleware } from "better-call";
3
+ import { HIDE_METADATA, logger } from "better-auth";
4
+ import { APIError, getSessionFromCtx, originCheck, sessionMiddleware } from "better-auth/api";
5
+ import * as z from "zod/v4";
6
+ import { mergeSchema } from "better-auth/db";
7
+
8
+ //#region node_modules/.pnpm/@better-auth+core@1.4.7_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call_3563929c6579aa89e38f28ea99bd09aa/node_modules/@better-auth/core/dist/env-DbssmzoK.mjs
9
+ const _envShim = Object.create(null);
10
+ const _getEnv = (useShim) => globalThis.process?.env || globalThis.Deno?.env.toObject() || globalThis.__env__ || (useShim ? _envShim : globalThis);
11
+ const env = new Proxy(_envShim, {
12
+ get(_, prop) {
13
+ return _getEnv()[prop] ?? _envShim[prop];
14
+ },
15
+ has(_, prop) {
16
+ return prop in _getEnv() || prop in _envShim;
17
+ },
18
+ set(_, prop, value) {
19
+ const env$1 = _getEnv(true);
20
+ env$1[prop] = value;
21
+ return true;
22
+ },
23
+ deleteProperty(_, prop) {
24
+ if (!prop) return false;
25
+ const env$1 = _getEnv(true);
26
+ delete env$1[prop];
27
+ return true;
28
+ },
29
+ ownKeys() {
30
+ const env$1 = _getEnv(true);
31
+ return Object.keys(env$1);
32
+ }
33
+ });
34
+ const nodeENV = typeof process !== "undefined" && process.env && process.env.NODE_ENV || "";
35
+ /**
36
+ * Get environment variable with fallback
37
+ */
38
+ function getEnvVar(key, fallback) {
39
+ if (typeof process !== "undefined" && process.env) return process.env[key] ?? fallback;
40
+ if (typeof Deno !== "undefined") return Deno.env.get(key) ?? fallback;
41
+ if (typeof Bun !== "undefined") return Bun.env[key] ?? fallback;
42
+ return fallback;
43
+ }
44
+ /**
45
+ * Common environment variables used in Better Auth
46
+ */
47
+ const ENV = Object.freeze({
48
+ get BETTER_AUTH_SECRET() {
49
+ return getEnvVar("BETTER_AUTH_SECRET");
50
+ },
51
+ get AUTH_SECRET() {
52
+ return getEnvVar("AUTH_SECRET");
53
+ },
54
+ get BETTER_AUTH_TELEMETRY() {
55
+ return getEnvVar("BETTER_AUTH_TELEMETRY");
56
+ },
57
+ get BETTER_AUTH_TELEMETRY_ID() {
58
+ return getEnvVar("BETTER_AUTH_TELEMETRY_ID");
59
+ },
60
+ get NODE_ENV() {
61
+ return getEnvVar("NODE_ENV", "development");
62
+ },
63
+ get PACKAGE_VERSION() {
64
+ return getEnvVar("PACKAGE_VERSION", "0.0.0");
65
+ },
66
+ get BETTER_AUTH_TELEMETRY_ENDPOINT() {
67
+ return getEnvVar("BETTER_AUTH_TELEMETRY_ENDPOINT", "https://telemetry.better-auth.com/v1/track");
68
+ }
69
+ });
70
+ const COLORS_2 = 1;
71
+ const COLORS_16 = 4;
72
+ const COLORS_256 = 8;
73
+ const COLORS_16m = 24;
74
+ const TERM_ENVS = {
75
+ eterm: COLORS_16,
76
+ cons25: COLORS_16,
77
+ console: COLORS_16,
78
+ cygwin: COLORS_16,
79
+ dtterm: COLORS_16,
80
+ gnome: COLORS_16,
81
+ hurd: COLORS_16,
82
+ jfbterm: COLORS_16,
83
+ konsole: COLORS_16,
84
+ kterm: COLORS_16,
85
+ mlterm: COLORS_16,
86
+ mosh: COLORS_16m,
87
+ putty: COLORS_16,
88
+ st: COLORS_16,
89
+ "rxvt-unicode-24bit": COLORS_16m,
90
+ terminator: COLORS_16m,
91
+ "xterm-kitty": COLORS_16m
92
+ };
93
+ const CI_ENVS_MAP = new Map(Object.entries({
94
+ APPVEYOR: COLORS_256,
95
+ BUILDKITE: COLORS_256,
96
+ CIRCLECI: COLORS_16m,
97
+ DRONE: COLORS_256,
98
+ GITEA_ACTIONS: COLORS_16m,
99
+ GITHUB_ACTIONS: COLORS_16m,
100
+ GITLAB_CI: COLORS_256,
101
+ TRAVIS: COLORS_256
102
+ }));
103
+ const TERM_ENVS_REG_EXP = [
104
+ /ansi/,
105
+ /color/,
106
+ /linux/,
107
+ /direct/,
108
+ /^con[0-9]*x[0-9]/,
109
+ /^rxvt/,
110
+ /^screen/,
111
+ /^xterm/,
112
+ /^vt100/,
113
+ /^vt220/
114
+ ];
115
+ function getColorDepth() {
116
+ if (getEnvVar("FORCE_COLOR") !== void 0) switch (getEnvVar("FORCE_COLOR")) {
117
+ case "":
118
+ case "1":
119
+ case "true": return COLORS_16;
120
+ case "2": return COLORS_256;
121
+ case "3": return COLORS_16m;
122
+ default: return COLORS_2;
123
+ }
124
+ if (getEnvVar("NODE_DISABLE_COLORS") !== void 0 && getEnvVar("NODE_DISABLE_COLORS") !== "" || getEnvVar("NO_COLOR") !== void 0 && getEnvVar("NO_COLOR") !== "" || getEnvVar("TERM") === "dumb") return COLORS_2;
125
+ if (getEnvVar("TMUX")) return COLORS_16m;
126
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) return COLORS_16;
127
+ if ("CI" in env) {
128
+ for (const { 0: envName, 1: colors } of CI_ENVS_MAP) if (envName in env) return colors;
129
+ if (getEnvVar("CI_NAME") === "codeship") return COLORS_256;
130
+ return COLORS_2;
131
+ }
132
+ if ("TEAMCITY_VERSION" in env) return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.exec(getEnvVar("TEAMCITY_VERSION")) !== null ? COLORS_16 : COLORS_2;
133
+ switch (getEnvVar("TERM_PROGRAM")) {
134
+ case "iTerm.app":
135
+ if (!getEnvVar("TERM_PROGRAM_VERSION") || /^[0-2]\./.exec(getEnvVar("TERM_PROGRAM_VERSION")) !== null) return COLORS_256;
136
+ return COLORS_16m;
137
+ case "HyperTerm":
138
+ case "MacTerm": return COLORS_16m;
139
+ case "Apple_Terminal": return COLORS_256;
140
+ }
141
+ if (getEnvVar("COLORTERM") === "truecolor" || getEnvVar("COLORTERM") === "24bit") return COLORS_16m;
142
+ if (getEnvVar("TERM")) {
143
+ if (/truecolor/.exec(getEnvVar("TERM")) !== null) return COLORS_16m;
144
+ if (/^xterm-256/.exec(getEnvVar("TERM")) !== null) return COLORS_256;
145
+ const termEnv = getEnvVar("TERM").toLowerCase();
146
+ if (TERM_ENVS[termEnv]) return TERM_ENVS[termEnv];
147
+ if (TERM_ENVS_REG_EXP.some((term) => term.exec(termEnv) !== null)) return COLORS_16;
148
+ }
149
+ if (getEnvVar("COLORTERM")) return COLORS_16;
150
+ return COLORS_2;
151
+ }
152
+ const TTY_COLORS = {
153
+ reset: "\x1B[0m",
154
+ bright: "\x1B[1m",
155
+ dim: "\x1B[2m",
156
+ undim: "\x1B[22m",
157
+ underscore: "\x1B[4m",
158
+ blink: "\x1B[5m",
159
+ reverse: "\x1B[7m",
160
+ hidden: "\x1B[8m",
161
+ fg: {
162
+ black: "\x1B[30m",
163
+ red: "\x1B[31m",
164
+ green: "\x1B[32m",
165
+ yellow: "\x1B[33m",
166
+ blue: "\x1B[34m",
167
+ magenta: "\x1B[35m",
168
+ cyan: "\x1B[36m",
169
+ white: "\x1B[37m"
170
+ },
171
+ bg: {
172
+ black: "\x1B[40m",
173
+ red: "\x1B[41m",
174
+ green: "\x1B[42m",
175
+ yellow: "\x1B[43m",
176
+ blue: "\x1B[44m",
177
+ magenta: "\x1B[45m",
178
+ cyan: "\x1B[46m",
179
+ white: "\x1B[47m"
180
+ }
181
+ };
182
+ const levels = [
183
+ "debug",
184
+ "info",
185
+ "success",
186
+ "warn",
187
+ "error"
188
+ ];
189
+ function shouldPublishLog(currentLogLevel, logLevel) {
190
+ return levels.indexOf(logLevel) >= levels.indexOf(currentLogLevel);
191
+ }
192
+ const levelColors = {
193
+ info: TTY_COLORS.fg.blue,
194
+ success: TTY_COLORS.fg.green,
195
+ warn: TTY_COLORS.fg.yellow,
196
+ error: TTY_COLORS.fg.red,
197
+ debug: TTY_COLORS.fg.magenta
198
+ };
199
+ const formatMessage = (level, message, colorsEnabled) => {
200
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
201
+ if (colorsEnabled) return `${TTY_COLORS.dim}${timestamp}${TTY_COLORS.reset} ${levelColors[level]}${level.toUpperCase()}${TTY_COLORS.reset} ${TTY_COLORS.bright}[Better Auth]:${TTY_COLORS.reset} ${message}`;
202
+ return `${timestamp} ${level.toUpperCase()} [Better Auth]: ${message}`;
203
+ };
204
+ const createLogger = (options) => {
205
+ const enabled = options?.disabled !== true;
206
+ const logLevel = options?.level ?? "error";
207
+ const colorsEnabled = options?.disableColors !== void 0 ? !options.disableColors : getColorDepth() !== 1;
208
+ const LogFunc = (level, message, args = []) => {
209
+ if (!enabled || !shouldPublishLog(logLevel, level)) return;
210
+ const formattedMessage = formatMessage(level, message, colorsEnabled);
211
+ if (!options || typeof options.log !== "function") {
212
+ if (level === "error") console.error(formattedMessage, ...args);
213
+ else if (level === "warn") console.warn(formattedMessage, ...args);
214
+ else console.log(formattedMessage, ...args);
215
+ return;
216
+ }
217
+ options.log(level === "success" ? "info" : level, message, ...args);
218
+ };
219
+ return {
220
+ ...Object.fromEntries(levels.map((level) => [level, (...[message, ...args]) => LogFunc(level, message, args)])),
221
+ get level() {
222
+ return logLevel;
223
+ }
224
+ };
225
+ };
226
+ const logger$1 = createLogger();
227
+
228
+ //#endregion
229
+ //#region node_modules/.pnpm/@better-auth+core@1.4.7_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call_3563929c6579aa89e38f28ea99bd09aa/node_modules/@better-auth/core/dist/utils-NloIXYE0.mjs
230
+ function defineErrorCodes(codes) {
231
+ return codes;
232
+ }
233
+
234
+ //#endregion
235
+ //#region node_modules/.pnpm/@better-auth+core@1.4.7_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call_3563929c6579aa89e38f28ea99bd09aa/node_modules/@better-auth/core/dist/async_hooks/index.mjs
236
+ const AsyncLocalStoragePromise = import(
237
+ /* @vite-ignore */
238
+ /* webpackIgnore: true */
239
+ "node:async_hooks"
240
+ ).then((mod) => mod.AsyncLocalStorage).catch((err) => {
241
+ if ("AsyncLocalStorage" in globalThis) return globalThis.AsyncLocalStorage;
242
+ if (typeof window !== "undefined") return null;
243
+ console.warn("[better-auth] Warning: AsyncLocalStorage is not available in this environment. Some features may not work as expected.");
244
+ console.warn("[better-auth] Please read more about this warning at https://better-auth.com/docs/installation#mount-handler");
245
+ console.warn("[better-auth] If you are using Cloudflare Workers, please see: https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag");
246
+ throw err;
247
+ });
248
+ async function getAsyncLocalStorage() {
249
+ const mod = await AsyncLocalStoragePromise;
250
+ if (mod === null) throw new Error("getAsyncLocalStorage is only available in server code");
251
+ else return mod;
252
+ }
253
+
254
+ //#endregion
255
+ //#region node_modules/.pnpm/@better-auth+core@1.4.7_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call_3563929c6579aa89e38f28ea99bd09aa/node_modules/@better-auth/core/dist/context-DblZrIwO.mjs
256
+ let currentContextAsyncStorage = null;
257
+ const ensureAsyncStorage$2 = async () => {
258
+ if (!currentContextAsyncStorage) currentContextAsyncStorage = new (await (getAsyncLocalStorage()))();
259
+ return currentContextAsyncStorage;
260
+ };
261
+ async function runWithEndpointContext(context, fn) {
262
+ return (await ensureAsyncStorage$2()).run(context, fn);
263
+ }
264
+
265
+ //#endregion
266
+ //#region node_modules/.pnpm/@better-auth+core@1.4.7_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call_3563929c6579aa89e38f28ea99bd09aa/node_modules/@better-auth/core/dist/api/index.mjs
267
+ const optionsMiddleware = createMiddleware(async () => {
268
+ /**
269
+ * This will be passed on the instance of
270
+ * the context. Used to infer the type
271
+ * here.
272
+ */
273
+ return {};
274
+ });
275
+ const createAuthMiddleware = createMiddleware.create({ use: [optionsMiddleware, createMiddleware(async () => {
276
+ return {};
277
+ })] });
278
+ const use = [optionsMiddleware];
279
+ function createAuthEndpoint(pathOrOptions, handlerOrOptions, handlerOrNever) {
280
+ const path = typeof pathOrOptions === "string" ? pathOrOptions : void 0;
281
+ const options = typeof handlerOrOptions === "object" ? handlerOrOptions : pathOrOptions;
282
+ const handler = typeof handlerOrOptions === "function" ? handlerOrOptions : handlerOrNever;
283
+ if (path) return createEndpoint(path, {
284
+ ...options,
285
+ use: [...options?.use || [], ...use]
286
+ }, async (ctx) => runWithEndpointContext(ctx, () => handler(ctx)));
287
+ return createEndpoint({
288
+ ...options,
289
+ use: [...options?.use || [], ...use]
290
+ }, async (ctx) => runWithEndpointContext(ctx, () => handler(ctx)));
291
+ }
292
+
293
+ //#endregion
294
+ //#region src/utils.ts
295
+ async function getPlans(subscriptionOptions) {
296
+ if (subscriptionOptions?.enabled) return typeof subscriptionOptions.plans === "function" ? await subscriptionOptions.plans() : subscriptionOptions.plans;
297
+ throw new Error("Subscriptions are not enabled in the Paystack options.");
298
+ }
299
+ async function getPlanByName(options, name) {
300
+ return await getPlans(options.subscription).then((plans) => plans?.find((plan) => plan.name.toLowerCase() === name.toLowerCase()));
301
+ }
302
+
303
+ //#endregion
304
+ //#region src/middleware.ts
305
+ const referenceMiddleware = (subscriptionOptions, action) => createAuthMiddleware(async (ctx) => {
306
+ const session = ctx.context.session;
307
+ if (!session) throw new APIError("UNAUTHORIZED");
308
+ const referenceId = ctx.body?.referenceId || ctx.query?.referenceId || session.user.id;
309
+ if (referenceId !== session.user.id && !subscriptionOptions.authorizeReference) {
310
+ logger.error(`Passing referenceId into a subscription action isn't allowed if subscription.authorizeReference isn't defined in your paystack plugin config.`);
311
+ throw new APIError("BAD_REQUEST", { message: "Passing referenceId isn't allowed without subscription.authorizeReference." });
312
+ }
313
+ if (referenceId !== session.user.id && subscriptionOptions.authorizeReference) {
314
+ if (!await subscriptionOptions.authorizeReference({
315
+ user: session.user,
316
+ session,
317
+ referenceId,
318
+ action
319
+ }, ctx)) throw new APIError("UNAUTHORIZED");
320
+ }
321
+ return { context: { referenceId } };
322
+ });
323
+
324
+ //#endregion
325
+ //#region src/paystack-sdk.ts
326
+ function isOpenApiFetchResponse(value) {
327
+ return value && typeof value === "object" && ("data" in value || "error" in value || "response" in value);
328
+ }
329
+ function unwrapSdkResult(result) {
330
+ if (isOpenApiFetchResponse(result)) {
331
+ if (result.error) throw result.error;
332
+ return result.data;
333
+ }
334
+ return result?.data ?? result;
335
+ }
336
+ function getPaystackOps(paystackClient) {
337
+ return {
338
+ customerCreate: async (params) => {
339
+ if (paystackClient?.customer_create) return paystackClient.customer_create({ body: params });
340
+ return paystackClient?.customer?.create?.(params);
341
+ },
342
+ transactionInitialize: async (body) => {
343
+ if (paystackClient?.transaction_initialize) return paystackClient.transaction_initialize({ body });
344
+ return paystackClient?.transaction?.initialize?.(body);
345
+ },
346
+ transactionVerify: async (reference) => {
347
+ if (paystackClient?.transaction_verify) return paystackClient.transaction_verify({ params: { path: { reference } } });
348
+ return paystackClient?.transaction?.verify?.(reference);
349
+ },
350
+ subscriptionDisable: async (body) => {
351
+ if (paystackClient?.subscription_disable) return paystackClient.subscription_disable({ body });
352
+ return paystackClient?.subscription?.disable?.(body);
353
+ },
354
+ subscriptionEnable: async (body) => {
355
+ if (paystackClient?.subscription_enable) return paystackClient.subscription_enable({ body });
356
+ return paystackClient?.subscription?.enable?.(body);
357
+ },
358
+ subscriptionFetch: async (idOrCode) => {
359
+ if (paystackClient?.subscription_fetch) try {
360
+ return await paystackClient.subscription_fetch({ params: { path: { code: idOrCode } } });
361
+ } catch {
362
+ return paystackClient.subscription_fetch({ params: { path: { id_or_code: idOrCode } } });
363
+ }
364
+ return paystackClient?.subscription?.fetch?.(idOrCode);
365
+ },
366
+ subscriptionManageLink: async (code) => {
367
+ if (paystackClient?.subscription_manage_link) return paystackClient.subscription_manage_link({ params: { path: { code } } });
368
+ return paystackClient?.subscription?.manage?.link?.(code);
369
+ }
370
+ };
371
+ }
372
+
373
+ //#endregion
374
+ //#region src/routes.ts
375
+ const PAYSTACK_ERROR_CODES = defineErrorCodes({
376
+ SUBSCRIPTION_NOT_FOUND: "Subscription not found",
377
+ SUBSCRIPTION_PLAN_NOT_FOUND: "Subscription plan not found",
378
+ UNABLE_TO_CREATE_CUSTOMER: "Unable to create customer",
379
+ FAILED_TO_INITIALIZE_TRANSACTION: "Failed to initialize transaction",
380
+ FAILED_TO_VERIFY_TRANSACTION: "Failed to verify transaction",
381
+ FAILED_TO_DISABLE_SUBSCRIPTION: "Failed to disable subscription",
382
+ FAILED_TO_ENABLE_SUBSCRIPTION: "Failed to enable subscription",
383
+ EMAIL_VERIFICATION_REQUIRED: "Email verification is required before you can subscribe to a plan"
384
+ });
385
+ async function hmacSha512Hex(secret, message) {
386
+ const encoder = new TextEncoder();
387
+ const keyData = encoder.encode(secret);
388
+ const msgData = encoder.encode(message);
389
+ const subtle = globalThis.crypto?.subtle;
390
+ if (subtle) {
391
+ const key = await subtle.importKey("raw", keyData, {
392
+ name: "HMAC",
393
+ hash: "SHA-512"
394
+ }, false, ["sign"]);
395
+ const signature = await subtle.sign("HMAC", key, msgData);
396
+ return Array.from(new Uint8Array(signature)).map((b) => b.toString(16).padStart(2, "0")).join("");
397
+ }
398
+ const { createHmac } = await import("node:crypto");
399
+ return createHmac("sha512", secret).update(message).digest("hex");
400
+ }
401
+ const paystackWebhook = (options) => {
402
+ return createAuthEndpoint("/paystack/webhook", {
403
+ method: "POST",
404
+ metadata: {
405
+ ...HIDE_METADATA,
406
+ openapi: { operationId: "handlePaystackWebhook" }
407
+ },
408
+ cloneRequest: true,
409
+ disableBody: true
410
+ }, async (ctx) => {
411
+ const payload = await (ctx.requestClone ?? ctx.request).text();
412
+ const signature = (ctx.headers ?? ctx.request?.headers)?.get("x-paystack-signature");
413
+ if (!signature) throw new APIError("UNAUTHORIZED", {
414
+ message: "Missing x-paystack-signature header",
415
+ status: 401
416
+ });
417
+ if (await hmacSha512Hex(options.paystackWebhookSecret, payload) !== signature) throw new APIError("UNAUTHORIZED", {
418
+ message: "Invalid Paystack webhook signature",
419
+ status: 401
420
+ });
421
+ const event = JSON.parse(payload);
422
+ if (options.subscription?.enabled) {
423
+ const eventName = String(event?.event ?? "");
424
+ const data = event?.data;
425
+ try {
426
+ if (eventName === "subscription.create") {
427
+ const subscriptionCode = data?.subscription_code ?? data?.subscription?.subscription_code ?? data?.code;
428
+ const customerCode = data?.customer?.customer_code ?? data?.customer_code ?? data?.customer?.code;
429
+ const planCode = data?.plan?.plan_code ?? data?.plan_code ?? data?.plan;
430
+ let metadata = data?.metadata;
431
+ if (typeof metadata === "string") try {
432
+ metadata = JSON.parse(metadata);
433
+ } catch {}
434
+ const referenceIdFromMetadata = typeof metadata === "object" && metadata ? metadata.referenceId : void 0;
435
+ let planNameFromMetadata = typeof metadata === "object" && metadata ? metadata.plan : void 0;
436
+ if (typeof planNameFromMetadata === "string") planNameFromMetadata = planNameFromMetadata.toLowerCase();
437
+ const plans = await getPlans(options.subscription);
438
+ const planFromCode = planCode ? plans.find((p) => p.planCode && p.planCode === planCode) : void 0;
439
+ const planName = (planFromCode?.name ?? planNameFromMetadata)?.toLowerCase();
440
+ if (subscriptionCode) {
441
+ const where = [];
442
+ if (referenceIdFromMetadata) where.push({
443
+ field: "referenceId",
444
+ value: referenceIdFromMetadata
445
+ });
446
+ else if (customerCode) where.push({
447
+ field: "paystackCustomerCode",
448
+ value: customerCode
449
+ });
450
+ if (planName) where.push({
451
+ field: "plan",
452
+ value: planName
453
+ });
454
+ if (where.length > 0) {
455
+ const subscription = (await ctx.context.adapter.findMany({
456
+ model: "subscription",
457
+ where
458
+ }))?.[0];
459
+ if (subscription) {
460
+ await ctx.context.adapter.update({
461
+ model: "subscription",
462
+ update: {
463
+ paystackSubscriptionCode: subscriptionCode,
464
+ status: "active",
465
+ updatedAt: /* @__PURE__ */ new Date()
466
+ },
467
+ where: [{
468
+ field: "id",
469
+ value: subscription.id
470
+ }]
471
+ });
472
+ const plan = planFromCode ?? (planName ? await getPlanByName(options, planName) : void 0);
473
+ if (plan) await options.subscription.onSubscriptionComplete?.({
474
+ event,
475
+ subscription: {
476
+ ...subscription,
477
+ paystackSubscriptionCode: subscriptionCode,
478
+ status: "active"
479
+ },
480
+ plan
481
+ }, ctx);
482
+ }
483
+ }
484
+ }
485
+ }
486
+ if (eventName === "subscription.disable" || eventName === "subscription.not_renew") {
487
+ const subscriptionCode = data?.subscription_code ?? data?.subscription?.subscription_code ?? data?.code;
488
+ if (subscriptionCode) await ctx.context.adapter.update({
489
+ model: "subscription",
490
+ update: {
491
+ status: "canceled",
492
+ updatedAt: /* @__PURE__ */ new Date()
493
+ },
494
+ where: [{
495
+ field: "paystackSubscriptionCode",
496
+ value: subscriptionCode
497
+ }]
498
+ });
499
+ }
500
+ } catch (e) {
501
+ ctx.context.logger.error("Failed to sync Paystack webhook event", e);
502
+ }
503
+ }
504
+ await options.onEvent?.(event);
505
+ return ctx.json({ received: true });
506
+ });
507
+ };
508
+ const initializeTransactionBodySchema = z.object({
509
+ plan: z.string(),
510
+ referenceId: z.string().optional(),
511
+ callbackURL: z.string().optional()
512
+ });
513
+ const initializeTransaction = (options) => {
514
+ const subscriptionOptions = options.subscription;
515
+ return createAuthEndpoint("/paystack/transaction/initialize", {
516
+ method: "POST",
517
+ body: initializeTransactionBodySchema,
518
+ use: subscriptionOptions?.enabled ? [
519
+ sessionMiddleware,
520
+ originCheck,
521
+ referenceMiddleware(subscriptionOptions, "initialize-transaction")
522
+ ] : [sessionMiddleware, originCheck]
523
+ }, async (ctx) => {
524
+ const paystack$1 = getPaystackOps(options.paystackClient);
525
+ if (!subscriptionOptions?.enabled) throw new APIError("BAD_REQUEST", { message: "Subscriptions are not enabled in the Paystack options." });
526
+ const session = await getSessionFromCtx(ctx);
527
+ if (!session) throw new APIError("UNAUTHORIZED");
528
+ const user$1 = session.user;
529
+ const referenceIdFromCtx = ctx.context.referenceId;
530
+ const referenceId = ctx.body.referenceId || referenceIdFromCtx || session.user.id;
531
+ if (subscriptionOptions.requireEmailVerification && !user$1.emailVerified) throw new APIError("BAD_REQUEST", {
532
+ code: PAYSTACK_ERROR_CODES.EMAIL_VERIFICATION_REQUIRED,
533
+ message: PAYSTACK_ERROR_CODES.EMAIL_VERIFICATION_REQUIRED
534
+ });
535
+ const plan = await getPlanByName(options, ctx.body.plan);
536
+ if (!plan) throw new APIError("BAD_REQUEST", {
537
+ code: PAYSTACK_ERROR_CODES.SUBSCRIPTION_PLAN_NOT_FOUND,
538
+ message: PAYSTACK_ERROR_CODES.SUBSCRIPTION_PLAN_NOT_FOUND
539
+ });
540
+ if (!plan.planCode && !plan.amount) throw new APIError("BAD_REQUEST", { message: "Paystack transaction initialization requires either plan.planCode (Paystack plan code) or plan.amount (smallest unit)." });
541
+ let url;
542
+ let reference;
543
+ let accessCode;
544
+ try {
545
+ const metadata = JSON.stringify({
546
+ referenceId,
547
+ userId: user$1.id,
548
+ plan: plan.name.toLowerCase()
549
+ });
550
+ const initBody = {
551
+ email: user$1.email,
552
+ callback_url: ctx.body.callbackURL,
553
+ currency: plan.currency,
554
+ plan: plan.planCode,
555
+ invoice_limit: plan.invoiceLimit,
556
+ metadata
557
+ };
558
+ if (!plan.planCode && plan.amount) initBody.amount = String(plan.amount);
559
+ const initRes = unwrapSdkResult(await paystack$1.transactionInitialize(initBody));
560
+ const data = initRes && typeof initRes === "object" && "status" in initRes && "data" in initRes ? initRes.data : initRes?.data ?? initRes;
561
+ url = data?.authorization_url;
562
+ reference = data?.reference;
563
+ accessCode = data?.access_code;
564
+ } catch (error) {
565
+ ctx.context.logger.error("Failed to initialize Paystack transaction", error);
566
+ throw new APIError("BAD_REQUEST", {
567
+ code: PAYSTACK_ERROR_CODES.FAILED_TO_INITIALIZE_TRANSACTION,
568
+ message: error?.message || PAYSTACK_ERROR_CODES.FAILED_TO_INITIALIZE_TRANSACTION
569
+ });
570
+ }
571
+ const paystackCustomerCode = user$1.paystackCustomerCode;
572
+ await ctx.context.adapter.create({
573
+ model: "subscription",
574
+ data: {
575
+ plan: plan.name.toLowerCase(),
576
+ referenceId,
577
+ paystackCustomerCode,
578
+ paystackTransactionReference: reference,
579
+ status: "incomplete"
580
+ }
581
+ });
582
+ return ctx.json({
583
+ url,
584
+ reference,
585
+ accessCode,
586
+ redirect: true
587
+ });
588
+ });
589
+ };
590
+ const verifyTransaction = (options) => {
591
+ const verifyQuerySchema = z.object({ reference: z.string() });
592
+ const subscriptionOptions = options.subscription;
593
+ return createAuthEndpoint("/paystack/transaction/verify", {
594
+ method: "GET",
595
+ query: verifyQuerySchema,
596
+ use: subscriptionOptions?.enabled ? [
597
+ sessionMiddleware,
598
+ originCheck,
599
+ referenceMiddleware(subscriptionOptions, "verify-transaction")
600
+ ] : [sessionMiddleware, originCheck]
601
+ }, async (ctx) => {
602
+ const paystack$1 = getPaystackOps(options.paystackClient);
603
+ let verifyRes;
604
+ try {
605
+ verifyRes = unwrapSdkResult(await paystack$1.transactionVerify(ctx.query.reference));
606
+ } catch (error) {
607
+ ctx.context.logger.error("Failed to verify Paystack transaction", error);
608
+ throw new APIError("BAD_REQUEST", {
609
+ code: PAYSTACK_ERROR_CODES.FAILED_TO_VERIFY_TRANSACTION,
610
+ message: error?.message || PAYSTACK_ERROR_CODES.FAILED_TO_VERIFY_TRANSACTION
611
+ });
612
+ }
613
+ const data = verifyRes && typeof verifyRes === "object" && "status" in verifyRes && "data" in verifyRes ? verifyRes.data : verifyRes?.data ?? verifyRes;
614
+ const status = data?.status;
615
+ const reference = data?.reference ?? ctx.query.reference;
616
+ if (status === "success") try {
617
+ await ctx.context.adapter.update({
618
+ model: "subscription",
619
+ update: {
620
+ status: "active",
621
+ periodStart: /* @__PURE__ */ new Date(),
622
+ updatedAt: /* @__PURE__ */ new Date()
623
+ },
624
+ where: [{
625
+ field: "paystackTransactionReference",
626
+ value: reference
627
+ }]
628
+ });
629
+ } catch (e) {
630
+ ctx.context.logger.error("Failed to update subscription after transaction verification", e);
631
+ }
632
+ return ctx.json({
633
+ status,
634
+ reference,
635
+ data
636
+ });
637
+ });
638
+ };
639
+ const listSubscriptions = (options) => {
640
+ const listQuerySchema = z.object({ referenceId: z.string().optional() });
641
+ const subscriptionOptions = options.subscription;
642
+ return createAuthEndpoint("/paystack/subscription/list-local", {
643
+ method: "GET",
644
+ query: listQuerySchema,
645
+ use: subscriptionOptions?.enabled ? [
646
+ sessionMiddleware,
647
+ originCheck,
648
+ referenceMiddleware(subscriptionOptions, "list-subscriptions")
649
+ ] : [sessionMiddleware, originCheck]
650
+ }, async (ctx) => {
651
+ if (!subscriptionOptions?.enabled) throw new APIError("BAD_REQUEST", { message: "Subscriptions are not enabled in the Paystack options." });
652
+ const session = await getSessionFromCtx(ctx);
653
+ if (!session) throw new APIError("UNAUTHORIZED");
654
+ const referenceId = ctx.context.referenceId ?? ctx.query?.referenceId ?? session.user.id;
655
+ const res = await ctx.context.adapter.findMany({
656
+ model: "subscription",
657
+ where: [{
658
+ field: "referenceId",
659
+ value: referenceId
660
+ }]
661
+ });
662
+ return ctx.json({ subscriptions: res });
663
+ });
664
+ };
665
+ const enableDisableBodySchema = z.object({
666
+ referenceId: z.string().optional(),
667
+ subscriptionCode: z.string(),
668
+ emailToken: z.string().optional()
669
+ });
670
+ function decodeBase64UrlToString(value) {
671
+ const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
672
+ const padded = normalized + "===".slice((normalized.length + 3) % 4);
673
+ if (typeof globalThis.atob === "function") return globalThis.atob(padded);
674
+ return Buffer.from(padded, "base64").toString("utf8");
675
+ }
676
+ function tryGetEmailTokenFromSubscriptionManageLink(link) {
677
+ try {
678
+ const subscriptionToken = new URL(link).searchParams.get("subscription_token");
679
+ if (!subscriptionToken) return void 0;
680
+ const parts = subscriptionToken.split(".");
681
+ if (parts.length < 2) return void 0;
682
+ const payloadJson = decodeBase64UrlToString(parts[1]);
683
+ const payload = JSON.parse(payloadJson);
684
+ return typeof payload?.email_token === "string" ? payload.email_token : void 0;
685
+ } catch {
686
+ return;
687
+ }
688
+ }
689
+ const disablePaystackSubscription = (options) => {
690
+ const subscriptionOptions = options.subscription;
691
+ return createAuthEndpoint("/paystack/subscription/disable", {
692
+ method: "POST",
693
+ body: enableDisableBodySchema,
694
+ use: subscriptionOptions?.enabled ? [
695
+ sessionMiddleware,
696
+ originCheck,
697
+ referenceMiddleware(subscriptionOptions, "disable-subscription")
698
+ ] : [sessionMiddleware, originCheck]
699
+ }, async (ctx) => {
700
+ const { subscriptionCode } = ctx.body;
701
+ const paystack$1 = getPaystackOps(options.paystackClient);
702
+ try {
703
+ let emailToken = ctx.body.emailToken;
704
+ if (!emailToken) try {
705
+ const fetchRes = unwrapSdkResult(await paystack$1.subscriptionFetch(subscriptionCode));
706
+ emailToken = (fetchRes && typeof fetchRes === "object" && "status" in fetchRes && "data" in fetchRes ? fetchRes.data : fetchRes?.data ?? fetchRes)?.email_token;
707
+ } catch {}
708
+ if (!emailToken) try {
709
+ const linkRes = unwrapSdkResult(await paystack$1.subscriptionManageLink(subscriptionCode));
710
+ const link = (linkRes && typeof linkRes === "object" && "status" in linkRes && "data" in linkRes ? linkRes.data : linkRes?.data ?? linkRes)?.link;
711
+ if (typeof link === "string") emailToken = tryGetEmailTokenFromSubscriptionManageLink(link);
712
+ } catch {}
713
+ if (!emailToken) throw new APIError("BAD_REQUEST", { message: "Missing emailToken. Provide it explicitly or ensure your server can fetch it from Paystack using the subscription code." });
714
+ const result = unwrapSdkResult(await paystack$1.subscriptionDisable({
715
+ code: subscriptionCode,
716
+ token: emailToken
717
+ }));
718
+ return ctx.json({ result });
719
+ } catch (error) {
720
+ ctx.context.logger.error("Failed to disable Paystack subscription", error);
721
+ throw new APIError("BAD_REQUEST", {
722
+ code: PAYSTACK_ERROR_CODES.FAILED_TO_DISABLE_SUBSCRIPTION,
723
+ message: error?.message || PAYSTACK_ERROR_CODES.FAILED_TO_DISABLE_SUBSCRIPTION
724
+ });
725
+ }
726
+ });
727
+ };
728
+ const enablePaystackSubscription = (options) => {
729
+ const subscriptionOptions = options.subscription;
730
+ return createAuthEndpoint("/paystack/subscription/enable", {
731
+ method: "POST",
732
+ body: enableDisableBodySchema,
733
+ use: subscriptionOptions?.enabled ? [
734
+ sessionMiddleware,
735
+ originCheck,
736
+ referenceMiddleware(subscriptionOptions, "enable-subscription")
737
+ ] : [sessionMiddleware, originCheck]
738
+ }, async (ctx) => {
739
+ const { subscriptionCode } = ctx.body;
740
+ const paystack$1 = getPaystackOps(options.paystackClient);
741
+ try {
742
+ let emailToken = ctx.body.emailToken;
743
+ if (!emailToken) try {
744
+ const fetchRes = unwrapSdkResult(await paystack$1.subscriptionFetch(subscriptionCode));
745
+ emailToken = (fetchRes && typeof fetchRes === "object" && "status" in fetchRes && "data" in fetchRes ? fetchRes.data : fetchRes?.data ?? fetchRes)?.email_token;
746
+ } catch {}
747
+ if (!emailToken) try {
748
+ const linkRes = unwrapSdkResult(await paystack$1.subscriptionManageLink(subscriptionCode));
749
+ const link = (linkRes && typeof linkRes === "object" && "status" in linkRes && "data" in linkRes ? linkRes.data : linkRes?.data ?? linkRes)?.link;
750
+ if (typeof link === "string") emailToken = tryGetEmailTokenFromSubscriptionManageLink(link);
751
+ } catch {}
752
+ if (!emailToken) throw new APIError("BAD_REQUEST", { message: "Missing emailToken. Provide it explicitly or ensure your server can fetch it from Paystack using the subscription code." });
753
+ const result = unwrapSdkResult(await paystack$1.subscriptionEnable({
754
+ code: subscriptionCode,
755
+ token: emailToken
756
+ }));
757
+ return ctx.json({ result });
758
+ } catch (error) {
759
+ ctx.context.logger.error("Failed to enable Paystack subscription", error);
760
+ throw new APIError("BAD_REQUEST", {
761
+ code: PAYSTACK_ERROR_CODES.FAILED_TO_ENABLE_SUBSCRIPTION,
762
+ message: error?.message || PAYSTACK_ERROR_CODES.FAILED_TO_ENABLE_SUBSCRIPTION
763
+ });
764
+ }
765
+ });
766
+ };
767
+
768
+ //#endregion
769
+ //#region src/schema.ts
770
+ const subscriptions = { subscription: { fields: {
771
+ plan: {
772
+ type: "string",
773
+ required: true
774
+ },
775
+ referenceId: {
776
+ type: "string",
777
+ required: true
778
+ },
779
+ paystackCustomerCode: {
780
+ type: "string",
781
+ required: false
782
+ },
783
+ paystackSubscriptionCode: {
784
+ type: "string",
785
+ required: false
786
+ },
787
+ paystackTransactionReference: {
788
+ type: "string",
789
+ required: false
790
+ },
791
+ status: {
792
+ type: "string",
793
+ defaultValue: "incomplete"
794
+ },
795
+ periodStart: {
796
+ type: "date",
797
+ required: false
798
+ },
799
+ periodEnd: {
800
+ type: "date",
801
+ required: false
802
+ },
803
+ trialStart: {
804
+ type: "date",
805
+ required: false
806
+ },
807
+ trialEnd: {
808
+ type: "date",
809
+ required: false
810
+ },
811
+ cancelAtPeriodEnd: {
812
+ type: "boolean",
813
+ required: false,
814
+ defaultValue: false
815
+ },
816
+ groupId: {
817
+ type: "string",
818
+ required: false
819
+ },
820
+ seats: {
821
+ type: "number",
822
+ required: false
823
+ }
824
+ } } };
825
+ const user = { user: { fields: { paystackCustomerCode: {
826
+ type: "string",
827
+ required: false
828
+ } } } };
829
+ const getSchema = (options) => {
830
+ let baseSchema;
831
+ if (options.subscription?.enabled) baseSchema = {
832
+ ...subscriptions,
833
+ ...user
834
+ };
835
+ else baseSchema = { ...user };
836
+ if (options.schema && !options.subscription?.enabled && "subscription" in options.schema) {
837
+ const { subscription: _subscription, ...restSchema } = options.schema;
838
+ return mergeSchema(baseSchema, restSchema);
839
+ }
840
+ return mergeSchema(baseSchema, options.schema);
841
+ };
842
+
843
+ //#endregion
844
+ //#region src/index.ts
845
+ const INTERNAL_ERROR_CODES = defineErrorCodes({ ...PAYSTACK_ERROR_CODES });
846
+ const paystack = (options) => {
847
+ const baseEndpoints = { paystackWebhook: paystackWebhook(options) };
848
+ const subscriptionEnabledEndpoints = {
849
+ ...baseEndpoints,
850
+ initializeTransaction: initializeTransaction(options),
851
+ verifyTransaction: verifyTransaction(options),
852
+ listSubscriptions: listSubscriptions(options),
853
+ disablePaystackSubscription: disablePaystackSubscription(options),
854
+ enablePaystackSubscription: enablePaystackSubscription(options)
855
+ };
856
+ return {
857
+ id: "paystack",
858
+ endpoints: options.subscription?.enabled ? subscriptionEnabledEndpoints : baseEndpoints,
859
+ init(ctx) {
860
+ return { options: { databaseHooks: { user: { create: { async after(user$1, hookCtx) {
861
+ if (!hookCtx || !options.createCustomerOnSignUp) return;
862
+ try {
863
+ const firstName = user$1.name?.split(" ")[0];
864
+ const lastName = user$1.name?.split(" ").slice(1).join(" ") || void 0;
865
+ const extraCreateParams = options.getCustomerCreateParams ? await options.getCustomerCreateParams(user$1, hookCtx) : {};
866
+ const params = defu({
867
+ email: user$1.email,
868
+ first_name: firstName,
869
+ last_name: lastName,
870
+ metadata: { userId: user$1.id }
871
+ }, extraCreateParams);
872
+ const res = unwrapSdkResult(await getPaystackOps(options.paystackClient).customerCreate(params));
873
+ const paystackCustomer = res && typeof res === "object" && "status" in res && "data" in res ? res.data : res?.data ?? res;
874
+ const customerCode = paystackCustomer?.customer_code;
875
+ if (!customerCode) return;
876
+ await hookCtx.context.internalAdapter.updateUser(user$1.id, { paystackCustomerCode: customerCode });
877
+ await options.onCustomerCreate?.({
878
+ paystackCustomer,
879
+ user: {
880
+ ...user$1,
881
+ paystackCustomerCode: customerCode
882
+ }
883
+ }, hookCtx);
884
+ } catch (e) {
885
+ hookCtx.context.logger.error(`Failed to create Paystack customer: ${e?.message || "Unknown error"}`, e);
886
+ }
887
+ } } } } } };
888
+ },
889
+ schema: getSchema(options),
890
+ $ERROR_CODES: INTERNAL_ERROR_CODES
891
+ };
892
+ };
893
+
894
+ //#endregion
895
+ export { paystack };
896
+ //# sourceMappingURL=index.mjs.map