@zendfi/sdk 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,37 @@
1
+ import { W as WebhookHandlerConfig, a as WebhookHandlers } from './webhook-handler-BIze3Qop.js';
2
+
3
+ /**
4
+ * Next.js Webhook Handler for App Router
5
+ *
6
+ * @example
7
+ * ```typescript
8
+ * // app/api/webhooks/zendfi/route.ts
9
+ * import { createNextWebhookHandler } from '@zendfi/sdk/nextjs';
10
+ *
11
+ * export const POST = createNextWebhookHandler({
12
+ * secret: process.env.ZENDFI_WEBHOOK_SECRET!,
13
+ * handlers: {
14
+ * 'payment.confirmed': async (payment) => {
15
+ * await db.orders.update({
16
+ * where: { id: payment.metadata.orderId },
17
+ * data: { status: 'paid' },
18
+ * });
19
+ * },
20
+ * 'payment.failed': async (payment) => {
21
+ * await sendFailureEmail(payment);
22
+ * },
23
+ * },
24
+ * });
25
+ * ```
26
+ */
27
+
28
+ type NextRequest = any;
29
+ interface NextWebhookHandlerConfig extends WebhookHandlerConfig {
30
+ handlers: WebhookHandlers;
31
+ }
32
+ /**
33
+ * Create a Next.js App Router webhook handler
34
+ */
35
+ declare function createNextWebhookHandler(config: NextWebhookHandlerConfig): (request: NextRequest) => Promise<Response>;
36
+
37
+ export { type NextWebhookHandlerConfig, createNextWebhookHandler };
package/dist/nextjs.js ADDED
@@ -0,0 +1,227 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/nextjs.ts
21
+ var nextjs_exports = {};
22
+ __export(nextjs_exports, {
23
+ createNextWebhookHandler: () => createNextWebhookHandler
24
+ });
25
+ module.exports = __toCommonJS(nextjs_exports);
26
+ var import_crypto2 = require("crypto");
27
+
28
+ // src/webhook-handler.ts
29
+ var import_crypto = require("crypto");
30
+ var processedWebhooks = /* @__PURE__ */ new Set();
31
+ var defaultIsProcessed = async (webhookId) => {
32
+ return processedWebhooks.has(webhookId);
33
+ };
34
+ var defaultOnProcessed = async (webhookId) => {
35
+ processedWebhooks.add(webhookId);
36
+ if (processedWebhooks.size > 1e4) {
37
+ const iterator = processedWebhooks.values();
38
+ for (let i = 0; i < 1e3; i++) {
39
+ const { value } = iterator.next();
40
+ if (value) processedWebhooks.delete(value);
41
+ }
42
+ }
43
+ };
44
+ function generateWebhookId(payload) {
45
+ return `${payload.merchant_id}:${payload.event}:${payload.timestamp}`;
46
+ }
47
+ async function processPayload(payload, handlers, config) {
48
+ try {
49
+ const webhookId = generateWebhookId(payload);
50
+ const isProcessed = config.isProcessed || config.checkDuplicate || defaultIsProcessed;
51
+ const onProcessed = config.onProcessed || config.markProcessed || defaultOnProcessed;
52
+ const dedupEnabled = !!(config.enableDeduplication || config.isProcessed || config.checkDuplicate);
53
+ if (dedupEnabled && await isProcessed(webhookId)) {
54
+ return {
55
+ success: false,
56
+ processed: false,
57
+ event: payload.event,
58
+ error: "Duplicate webhook",
59
+ statusCode: 409
60
+ };
61
+ }
62
+ const handler = handlers[payload.event];
63
+ if (!handler) {
64
+ return {
65
+ success: true,
66
+ processed: false,
67
+ event: payload.event,
68
+ statusCode: 200
69
+ };
70
+ }
71
+ await handler(payload.data, payload);
72
+ await onProcessed(webhookId);
73
+ return {
74
+ success: true,
75
+ processed: true,
76
+ event: payload.event
77
+ };
78
+ } catch (error) {
79
+ const err = error;
80
+ if (config?.onError) {
81
+ await config.onError(err, error?.event);
82
+ }
83
+ return {
84
+ success: false,
85
+ processed: false,
86
+ error: err.message,
87
+ event: error?.event,
88
+ statusCode: 500
89
+ };
90
+ }
91
+ }
92
+ async function processWebhook(a, b, c) {
93
+ if (a && typeof a === "object" && a.event && b && c) {
94
+ return processPayload(a, b, c);
95
+ }
96
+ const opts = a;
97
+ if (!opts || !opts.signature && !opts.body && !opts.handlers) {
98
+ return {
99
+ success: false,
100
+ processed: false,
101
+ error: "Invalid arguments to processWebhook",
102
+ statusCode: 400
103
+ };
104
+ }
105
+ const signature = opts.signature;
106
+ const body = opts.body;
107
+ const handlers = opts.handlers || {};
108
+ const cfg = opts.config || {};
109
+ const secret = cfg.webhookSecret || cfg.secret;
110
+ if (!secret) {
111
+ return {
112
+ success: false,
113
+ processed: false,
114
+ error: "Webhook secret not provided",
115
+ statusCode: 400
116
+ };
117
+ }
118
+ if (!signature || !body) {
119
+ return {
120
+ success: false,
121
+ processed: false,
122
+ error: "Missing signature or body",
123
+ statusCode: 400
124
+ };
125
+ }
126
+ try {
127
+ const sig = typeof signature === "string" && signature.startsWith("sha256=") ? signature.slice("sha256=".length) : String(signature);
128
+ const hmac = (0, import_crypto.createHmac)("sha256", secret).update(body, "utf8").digest("hex");
129
+ let ok = false;
130
+ try {
131
+ const sigBuf = Buffer.from(sig, "hex");
132
+ const hmacBuf = Buffer.from(hmac, "hex");
133
+ if (sigBuf.length === hmacBuf.length) {
134
+ ok = (0, import_crypto.timingSafeEqual)(sigBuf, hmacBuf);
135
+ }
136
+ } catch (e) {
137
+ ok = (0, import_crypto.timingSafeEqual)(Buffer.from(String(sig), "utf8"), Buffer.from(hmac, "utf8"));
138
+ }
139
+ if (!ok) {
140
+ return {
141
+ success: false,
142
+ processed: false,
143
+ error: "Invalid signature",
144
+ statusCode: 401
145
+ };
146
+ }
147
+ const payload = JSON.parse(body);
148
+ const fullConfig = {
149
+ secret,
150
+ isProcessed: cfg.isProcessed,
151
+ onProcessed: cfg.onProcessed,
152
+ onError: cfg.onError,
153
+ // Forward compatibility for alternate names and flags
154
+ enableDeduplication: cfg.enableDeduplication,
155
+ checkDuplicate: cfg.checkDuplicate,
156
+ markProcessed: cfg.markProcessed
157
+ };
158
+ return await processPayload(payload, handlers, fullConfig);
159
+ } catch (err) {
160
+ return {
161
+ success: false,
162
+ processed: false,
163
+ error: err.message,
164
+ statusCode: 500
165
+ };
166
+ }
167
+ }
168
+
169
+ // src/nextjs.ts
170
+ function createNextWebhookHandler(config) {
171
+ return async (request) => {
172
+ try {
173
+ const signature = request.headers.get("x-zendfi-signature");
174
+ if (!signature) {
175
+ return new Response(
176
+ JSON.stringify({ error: "Missing signature" }),
177
+ { status: 401, headers: { "Content-Type": "application/json" } }
178
+ );
179
+ }
180
+ const body = await request.text();
181
+ const computedSignature = (0, import_crypto2.createHmac)("sha256", config.secret).update(body, "utf8").digest("hex");
182
+ const sigBuffer = Buffer.from(signature, "utf8");
183
+ const compBuffer = Buffer.from(computedSignature, "utf8");
184
+ if (sigBuffer.length !== compBuffer.length || !(0, import_crypto2.timingSafeEqual)(sigBuffer, compBuffer)) {
185
+ return new Response(
186
+ JSON.stringify({ error: "Invalid signature" }),
187
+ { status: 401, headers: { "Content-Type": "application/json" } }
188
+ );
189
+ }
190
+ let payload;
191
+ try {
192
+ payload = JSON.parse(body);
193
+ } catch {
194
+ return new Response(
195
+ JSON.stringify({ error: "Invalid JSON" }),
196
+ { status: 400, headers: { "Content-Type": "application/json" } }
197
+ );
198
+ }
199
+ const result = await processWebhook(payload, config.handlers, config);
200
+ if (!result.success) {
201
+ return new Response(
202
+ JSON.stringify({ error: result.error || "Webhook processing failed" }),
203
+ { status: 500, headers: { "Content-Type": "application/json" } }
204
+ );
205
+ }
206
+ return new Response(
207
+ JSON.stringify({
208
+ received: true,
209
+ processed: result.processed,
210
+ event: result.event
211
+ }),
212
+ { status: 200, headers: { "Content-Type": "application/json" } }
213
+ );
214
+ } catch (error) {
215
+ const err = error;
216
+ console.error("Webhook handler error:", err);
217
+ return new Response(
218
+ JSON.stringify({ error: "Internal server error" }),
219
+ { status: 500, headers: { "Content-Type": "application/json" } }
220
+ );
221
+ }
222
+ };
223
+ }
224
+ // Annotate the CommonJS export names for ESM import in node:
225
+ 0 && (module.exports = {
226
+ createNextWebhookHandler
227
+ });
@@ -0,0 +1,63 @@
1
+ import {
2
+ processWebhook
3
+ } from "./chunk-YFOBPGQE.mjs";
4
+
5
+ // src/nextjs.ts
6
+ import { createHmac, timingSafeEqual } from "crypto";
7
+ function createNextWebhookHandler(config) {
8
+ return async (request) => {
9
+ try {
10
+ const signature = request.headers.get("x-zendfi-signature");
11
+ if (!signature) {
12
+ return new Response(
13
+ JSON.stringify({ error: "Missing signature" }),
14
+ { status: 401, headers: { "Content-Type": "application/json" } }
15
+ );
16
+ }
17
+ const body = await request.text();
18
+ const computedSignature = createHmac("sha256", config.secret).update(body, "utf8").digest("hex");
19
+ const sigBuffer = Buffer.from(signature, "utf8");
20
+ const compBuffer = Buffer.from(computedSignature, "utf8");
21
+ if (sigBuffer.length !== compBuffer.length || !timingSafeEqual(sigBuffer, compBuffer)) {
22
+ return new Response(
23
+ JSON.stringify({ error: "Invalid signature" }),
24
+ { status: 401, headers: { "Content-Type": "application/json" } }
25
+ );
26
+ }
27
+ let payload;
28
+ try {
29
+ payload = JSON.parse(body);
30
+ } catch {
31
+ return new Response(
32
+ JSON.stringify({ error: "Invalid JSON" }),
33
+ { status: 400, headers: { "Content-Type": "application/json" } }
34
+ );
35
+ }
36
+ const result = await processWebhook(payload, config.handlers, config);
37
+ if (!result.success) {
38
+ return new Response(
39
+ JSON.stringify({ error: result.error || "Webhook processing failed" }),
40
+ { status: 500, headers: { "Content-Type": "application/json" } }
41
+ );
42
+ }
43
+ return new Response(
44
+ JSON.stringify({
45
+ received: true,
46
+ processed: result.processed,
47
+ event: result.event
48
+ }),
49
+ { status: 200, headers: { "Content-Type": "application/json" } }
50
+ );
51
+ } catch (error) {
52
+ const err = error;
53
+ console.error("Webhook handler error:", err);
54
+ return new Response(
55
+ JSON.stringify({ error: "Internal server error" }),
56
+ { status: 500, headers: { "Content-Type": "application/json" } }
57
+ );
58
+ }
59
+ };
60
+ }
61
+ export {
62
+ createNextWebhookHandler
63
+ };