@whatalo/plugin-sdk 1.2.0 → 1.2.2
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/adapters/express.cjs +106 -10
- package/dist/adapters/express.cjs.map +1 -1
- package/dist/adapters/express.d.cts +9 -7
- package/dist/adapters/express.d.ts +9 -7
- package/dist/adapters/express.mjs +109 -10
- package/dist/adapters/express.mjs.map +1 -1
- package/dist/adapters/hono.cjs +99 -7
- package/dist/adapters/hono.cjs.map +1 -1
- package/dist/adapters/hono.d.cts +4 -3
- package/dist/adapters/hono.d.ts +4 -3
- package/dist/adapters/hono.mjs +102 -7
- package/dist/adapters/hono.mjs.map +1 -1
- package/dist/adapters/nextjs.cjs +99 -7
- package/dist/adapters/nextjs.cjs.map +1 -1
- package/dist/adapters/nextjs.d.cts +4 -3
- package/dist/adapters/nextjs.d.ts +4 -3
- package/dist/adapters/nextjs.mjs +102 -7
- package/dist/adapters/nextjs.mjs.map +1 -1
- package/dist/bridge/index.cjs +60 -5
- package/dist/bridge/index.cjs.map +1 -1
- package/dist/bridge/index.d.cts +17 -5
- package/dist/bridge/index.d.ts +17 -5
- package/dist/bridge/index.mjs +60 -5
- package/dist/bridge/index.mjs.map +1 -1
- package/dist/client/index.cjs +33 -2
- package/dist/client/index.cjs.map +1 -1
- package/dist/client/index.d.cts +29 -1
- package/dist/client/index.d.ts +29 -1
- package/dist/client/index.mjs +33 -2
- package/dist/client/index.mjs.map +1 -1
- package/dist/index.cjs +179 -28
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -4
- package/dist/index.d.ts +7 -4
- package/dist/index.mjs +179 -28
- package/dist/index.mjs.map +1 -1
- package/dist/manifest/index.cjs +2 -17
- package/dist/manifest/index.cjs.map +1 -1
- package/dist/manifest/index.d.cts +10 -4
- package/dist/manifest/index.d.ts +10 -4
- package/dist/manifest/index.mjs +2 -17
- package/dist/manifest/index.mjs.map +1 -1
- package/dist/{types-DcmArIC2.d.ts → types-B8BAV362.d.cts} +24 -1
- package/dist/{types-DcmArIC2.d.cts → types-B8BAV362.d.ts} +24 -1
- package/dist/types-Bzee9Hvr.d.ts +25 -0
- package/dist/types-CDKGAQ3o.d.ts +155 -0
- package/dist/types-CPnSzOfX.d.cts +155 -0
- package/dist/types-CqyAhbXM.d.cts +25 -0
- package/dist/webhooks/index.cjs +83 -3
- package/dist/webhooks/index.cjs.map +1 -1
- package/dist/webhooks/index.d.cts +11 -4
- package/dist/webhooks/index.d.ts +11 -4
- package/dist/webhooks/index.mjs +83 -3
- package/dist/webhooks/index.mjs.map +1 -1
- package/package.json +4 -1
- package/dist/types-C9mg4aQg.d.ts +0 -19
- package/dist/types-DMuHSL_a.d.cts +0 -19
- package/dist/types-DTjA3FHe.d.ts +0 -68
- package/dist/types-tHUO9u-c.d.cts +0 -68
|
@@ -26,14 +26,26 @@ module.exports = __toCommonJS(express_exports);
|
|
|
26
26
|
|
|
27
27
|
// src/webhooks/verify.ts
|
|
28
28
|
var import_node_crypto = require("crypto");
|
|
29
|
+
var DEFAULT_TOLERANCE_SECONDS = 300;
|
|
29
30
|
function verifyWebhook({
|
|
30
31
|
payload,
|
|
31
32
|
signature,
|
|
32
|
-
|
|
33
|
+
timestamp,
|
|
34
|
+
secret,
|
|
35
|
+
toleranceSeconds = DEFAULT_TOLERANCE_SECONDS,
|
|
36
|
+
currentTime = Math.floor(Date.now() / 1e3)
|
|
33
37
|
}) {
|
|
34
|
-
if (!payload || !signature || !secret) return false;
|
|
35
|
-
const
|
|
38
|
+
if (!payload || !signature || !secret || timestamp === "") return false;
|
|
39
|
+
const timestampString = String(timestamp);
|
|
40
|
+
const timestampValue = typeof timestamp === "number" ? timestamp : Number(timestamp);
|
|
41
|
+
if (!Number.isInteger(timestampValue)) return false;
|
|
42
|
+
if (!Number.isFinite(toleranceSeconds) || toleranceSeconds < 0) return false;
|
|
43
|
+
if (!Number.isFinite(currentTime)) return false;
|
|
44
|
+
const ageSeconds = Math.abs(currentTime - timestampValue);
|
|
45
|
+
if (ageSeconds > toleranceSeconds) return false;
|
|
46
|
+
const expected = (0, import_node_crypto.createHmac)("sha256", secret).update(`${timestampString}.${payload}`, "utf8").digest("hex");
|
|
36
47
|
if (expected.length !== signature.length) return false;
|
|
48
|
+
if (!/^[a-f0-9]+$/i.test(signature)) return false;
|
|
37
49
|
try {
|
|
38
50
|
return (0, import_node_crypto.timingSafeEqual)(
|
|
39
51
|
Buffer.from(expected, "hex"),
|
|
@@ -44,9 +56,71 @@ function verifyWebhook({
|
|
|
44
56
|
}
|
|
45
57
|
}
|
|
46
58
|
|
|
59
|
+
// src/webhooks/types.ts
|
|
60
|
+
var import_events = require("@whatalo/protocol/events");
|
|
61
|
+
var WEBHOOK_EVENTS = import_events.PUBLIC_WEBHOOK_EVENTS;
|
|
62
|
+
function isWebhookEvent(value) {
|
|
63
|
+
return (0, import_events.isPublicWebhookEvent)(value);
|
|
64
|
+
}
|
|
65
|
+
function isRecord(value) {
|
|
66
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
67
|
+
}
|
|
68
|
+
function hasStringId(value) {
|
|
69
|
+
return isRecord(value) && typeof value.id === "string";
|
|
70
|
+
}
|
|
71
|
+
function isOptionalString(value, key) {
|
|
72
|
+
return value[key] === void 0 || typeof value[key] === "string";
|
|
73
|
+
}
|
|
74
|
+
function isRuntimeWebhookStore(value) {
|
|
75
|
+
return isRecord(value) && typeof value.id === "string" && typeof value.timezone === "string" && (value.name === void 0 || typeof value.name === "string");
|
|
76
|
+
}
|
|
77
|
+
function hasValidBasePayloadFields(value) {
|
|
78
|
+
if (!isOptionalString(value, "event_id")) return false;
|
|
79
|
+
if (!isOptionalString(value, "occurred_at")) return false;
|
|
80
|
+
return isRuntimeWebhookStore(value.store);
|
|
81
|
+
}
|
|
82
|
+
function isRuntimeOrderWebhookPayload(value) {
|
|
83
|
+
return hasValidBasePayloadFields(value) && hasStringId(value.order) && (value.customer === void 0 || hasStringId(value.customer));
|
|
84
|
+
}
|
|
85
|
+
function isRuntimeProductWebhookPayload(value) {
|
|
86
|
+
return hasValidBasePayloadFields(value) && hasStringId(value.product);
|
|
87
|
+
}
|
|
88
|
+
function isRuntimeCustomerWebhookPayload(value) {
|
|
89
|
+
return hasValidBasePayloadFields(value) && hasStringId(value.customer);
|
|
90
|
+
}
|
|
91
|
+
function isRuntimeCheckoutCompletedWebhookPayload(value) {
|
|
92
|
+
return hasValidBasePayloadFields(value) && hasStringId(value.order) && hasStringId(value.customer) && isRuntimeWebhookStore(value.store);
|
|
93
|
+
}
|
|
94
|
+
function isRuntimeCheckoutAbandonedWebhookPayload(value) {
|
|
95
|
+
return hasValidBasePayloadFields(value) && hasStringId(value.checkout) && isRuntimeWebhookStore(value.store);
|
|
96
|
+
}
|
|
97
|
+
function isRuntimeWebhookPayload(value, event) {
|
|
98
|
+
if (!isRecord(value)) return false;
|
|
99
|
+
switch (event) {
|
|
100
|
+
case WEBHOOK_EVENTS.ORDER_CREATED:
|
|
101
|
+
case WEBHOOK_EVENTS.ORDER_UPDATED:
|
|
102
|
+
case WEBHOOK_EVENTS.ORDER_CANCELLED:
|
|
103
|
+
case WEBHOOK_EVENTS.ORDER_COMPLETED:
|
|
104
|
+
return isRuntimeOrderWebhookPayload(value);
|
|
105
|
+
case WEBHOOK_EVENTS.PRODUCT_CREATED:
|
|
106
|
+
case WEBHOOK_EVENTS.PRODUCT_UPDATED:
|
|
107
|
+
case WEBHOOK_EVENTS.PRODUCT_DELETED:
|
|
108
|
+
return isRuntimeProductWebhookPayload(value);
|
|
109
|
+
case WEBHOOK_EVENTS.CUSTOMER_CREATED:
|
|
110
|
+
case WEBHOOK_EVENTS.CUSTOMER_UPDATED:
|
|
111
|
+
return isRuntimeCustomerWebhookPayload(value);
|
|
112
|
+
case WEBHOOK_EVENTS.CHECKOUT_COMPLETED:
|
|
113
|
+
return isRuntimeCheckoutCompletedWebhookPayload(value);
|
|
114
|
+
case WEBHOOK_EVENTS.CHECKOUT_ABANDONED:
|
|
115
|
+
return isRuntimeCheckoutAbandonedWebhookPayload(value);
|
|
116
|
+
default:
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
47
121
|
// src/adapters/express.ts
|
|
48
|
-
function
|
|
49
|
-
const value = headers[
|
|
122
|
+
function getHeader(name, headers) {
|
|
123
|
+
const value = headers[name];
|
|
50
124
|
if (Array.isArray(value)) {
|
|
51
125
|
return value[0] ?? "";
|
|
52
126
|
}
|
|
@@ -56,23 +130,45 @@ function createWebhookHandler(options) {
|
|
|
56
130
|
return async function webhookHandler(req, res) {
|
|
57
131
|
try {
|
|
58
132
|
const rawPayload = typeof req.body === "string" ? req.body : req.body.toString("utf8");
|
|
59
|
-
const signature =
|
|
133
|
+
const signature = getHeader("x-webhook-signature", req.headers);
|
|
134
|
+
const timestamp = getHeader("x-webhook-timestamp", req.headers);
|
|
135
|
+
const event = getHeader("x-webhook-event", req.headers);
|
|
136
|
+
const deliveryId = getHeader("x-webhook-id", req.headers);
|
|
60
137
|
const isValid = verifyWebhook({
|
|
61
138
|
payload: rawPayload,
|
|
62
139
|
signature,
|
|
140
|
+
timestamp,
|
|
63
141
|
secret: options.secret
|
|
64
142
|
});
|
|
65
143
|
if (!isValid) {
|
|
66
144
|
res.status(401).json({ error: "Invalid signature" });
|
|
67
145
|
return;
|
|
68
146
|
}
|
|
69
|
-
|
|
70
|
-
|
|
147
|
+
if (!event) {
|
|
148
|
+
res.status(400).json({ error: "Missing event header" });
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
if (!isWebhookEvent(event)) {
|
|
152
|
+
res.status(400).json({ error: "Invalid event header" });
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
let parsedPayload;
|
|
156
|
+
try {
|
|
157
|
+
parsedPayload = JSON.parse(rawPayload);
|
|
158
|
+
} catch {
|
|
159
|
+
res.status(400).json({ error: "Invalid JSON" });
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
if (!isRuntimeWebhookPayload(parsedPayload, event)) {
|
|
163
|
+
res.status(400).json({ error: "Invalid payload" });
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
const context = { deliveryId, event, timestamp };
|
|
71
167
|
const handler = options.handlers[event];
|
|
72
168
|
if (handler) {
|
|
73
|
-
await handler(
|
|
169
|
+
await handler(parsedPayload, context);
|
|
74
170
|
} else if (options.onUnhandledEvent) {
|
|
75
|
-
await options.onUnhandledEvent(event,
|
|
171
|
+
await options.onUnhandledEvent(event, parsedPayload, context);
|
|
76
172
|
}
|
|
77
173
|
res.status(200).send("OK");
|
|
78
174
|
} catch {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/adapters/express.ts","../../src/webhooks/verify.ts"],"sourcesContent":["import { verifyWebhook } from \"../webhooks/verify.js\";\nimport type { WebhookPayload } from \"../webhooks/types.js\";\nimport type { WebhookEventHandler, WebhookHandlerOptions } from \"./types.js\";\n\ntype ExpressLikeRequest = {\n body: Buffer | string;\n headers: Record<string, string | string[] | undefined>;\n};\n\ntype ExpressLikeResponse = {\n status: (code: number) => {\n json: (body: unknown) => void;\n send: (body: string) => void;\n };\n};\n\nfunction getSignature(\n headers: Record<string, string | string[] | undefined>\n): string {\n const value = headers[\"x-webhook-signature\"];\n\n if (Array.isArray(value)) {\n return value[0] ?? \"\";\n }\n\n return value ?? \"\";\n}\n\nexport function createWebhookHandler(\n options: WebhookHandlerOptions\n): (req: ExpressLikeRequest, res: ExpressLikeResponse) => Promise<void> {\n return async function webhookHandler(\n req: ExpressLikeRequest,\n res: ExpressLikeResponse\n ): Promise<void> {\n try {\n const rawPayload =\n typeof req.body === \"string\" ? req.body : req.body.toString(\"utf8\");\n const signature = getSignature(req.headers);\n\n const isValid = verifyWebhook({\n payload: rawPayload,\n signature,\n secret: options.secret,\n });\n\n if (!isValid) {\n res.status(401).json({ error: \"Invalid signature\" });\n return;\n }\n\n const payload = JSON.parse(rawPayload) as WebhookPayload;\n const event = payload.event;\n const handler = options.handlers[event] as\n | WebhookEventHandler<typeof event>\n | undefined;\n\n if (handler) {\n await handler(payload);\n } else if (options.onUnhandledEvent) {\n await options.onUnhandledEvent(event, payload);\n }\n\n res.status(200).send(\"OK\");\n } catch {\n res.status(500).json({ error: \"Internal error\" });\n }\n };\n}\n","import { createHmac, timingSafeEqual } from \"node:crypto\";\n\nexport interface VerifyWebhookParams {\n /** Raw request body as a string (NOT parsed JSON) */\n payload: string;\n /** Value of the X-Webhook-Signature header */\n signature: string;\n /** App's webhook secret (provided during app installation) */\n secret: string;\n}\n\n/**\n * Verify webhook signature using HMAC-SHA256.\n * Uses timing-safe comparison to prevent timing attacks.\n */\nexport function verifyWebhook({\n payload,\n signature,\n secret,\n}: VerifyWebhookParams): boolean {\n if (!payload || !signature || !secret) return false;\n\n const expected = createHmac(\"sha256\", secret)\n .update(payload, \"utf8\")\n .digest(\"hex\");\n\n if (expected.length !== signature.length) return false;\n\n try {\n return timingSafeEqual(\n Buffer.from(expected, \"hex\"),\n Buffer.from(signature, \"hex\")\n );\n } catch {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,yBAA4C;AAerC,SAAS,cAAc;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AACF,GAAiC;AAC/B,MAAI,CAAC,WAAW,CAAC,aAAa,CAAC,OAAQ,QAAO;AAE9C,QAAM,eAAW,+BAAW,UAAU,MAAM,EACzC,OAAO,SAAS,MAAM,EACtB,OAAO,KAAK;AAEf,MAAI,SAAS,WAAW,UAAU,OAAQ,QAAO;AAEjD,MAAI;AACF,eAAO;AAAA,MACL,OAAO,KAAK,UAAU,KAAK;AAAA,MAC3B,OAAO,KAAK,WAAW,KAAK;AAAA,IAC9B;AAAA,EACF,QAAQ;AACN,WAAO;AAAA,EACT;AACF;;;ADpBA,SAAS,aACP,SACQ;AACR,QAAM,QAAQ,QAAQ,qBAAqB;AAE3C,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,WAAO,MAAM,CAAC,KAAK;AAAA,EACrB;AAEA,SAAO,SAAS;AAClB;AAEO,SAAS,qBACd,SACsE;AACtE,SAAO,eAAe,eACpB,KACA,KACe;AACf,QAAI;AACF,YAAM,aACJ,OAAO,IAAI,SAAS,WAAW,IAAI,OAAO,IAAI,KAAK,SAAS,MAAM;AACpE,YAAM,YAAY,aAAa,IAAI,OAAO;AAE1C,YAAM,UAAU,cAAc;AAAA,QAC5B,SAAS;AAAA,QACT;AAAA,QACA,QAAQ,QAAQ;AAAA,MAClB,CAAC;AAED,UAAI,CAAC,SAAS;AACZ,YAAI,OAAO,GAAG,EAAE,KAAK,EAAE,OAAO,oBAAoB,CAAC;AACnD;AAAA,MACF;AAEA,YAAM,UAAU,KAAK,MAAM,UAAU;AACrC,YAAM,QAAQ,QAAQ;AACtB,YAAM,UAAU,QAAQ,SAAS,KAAK;AAItC,UAAI,SAAS;AACX,cAAM,QAAQ,OAAO;AAAA,MACvB,WAAW,QAAQ,kBAAkB;AACnC,cAAM,QAAQ,iBAAiB,OAAO,OAAO;AAAA,MAC/C;AAEA,UAAI,OAAO,GAAG,EAAE,KAAK,IAAI;AAAA,IAC3B,QAAQ;AACN,UAAI,OAAO,GAAG,EAAE,KAAK,EAAE,OAAO,iBAAiB,CAAC;AAAA,IAClD;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/express.ts","../../src/webhooks/verify.ts","../../src/webhooks/types.ts"],"sourcesContent":["import { verifyWebhook } from \"../webhooks/verify.js\";\nimport { isRuntimeWebhookPayload, isWebhookEvent } from \"../webhooks/types.js\";\nimport type { WebhookEventHandler, WebhookHandlerOptions } from \"./types.js\";\n\ntype ExpressLikeRequest = {\n body: Buffer | string;\n headers: Record<string, string | string[] | undefined>;\n};\n\ntype ExpressLikeStatusResponse = {\n json: (body: unknown) => void;\n send: (body: string) => void;\n};\n\ntype ExpressLikeResponse = {\n status: (code: number) => ExpressLikeStatusResponse;\n};\n\nfunction getHeader(\n name: string,\n headers: Record<string, string | string[] | undefined>\n): string {\n const value = headers[name];\n\n if (Array.isArray(value)) {\n return value[0] ?? \"\";\n }\n\n return value ?? \"\";\n}\n\nexport function createWebhookHandler(\n options: WebhookHandlerOptions\n): (req: ExpressLikeRequest, res: ExpressLikeResponse) => Promise<void> {\n return async function webhookHandler(\n req: ExpressLikeRequest,\n res: ExpressLikeResponse\n ): Promise<void> {\n try {\n const rawPayload =\n typeof req.body === \"string\" ? req.body : req.body.toString(\"utf8\");\n const signature = getHeader(\"x-webhook-signature\", req.headers);\n const timestamp = getHeader(\"x-webhook-timestamp\", req.headers);\n const event = getHeader(\"x-webhook-event\", req.headers);\n const deliveryId = getHeader(\"x-webhook-id\", req.headers);\n\n const isValid = verifyWebhook({\n payload: rawPayload,\n signature,\n timestamp,\n secret: options.secret,\n });\n\n if (!isValid) {\n res.status(401).json({ error: \"Invalid signature\" });\n return;\n }\n\n if (!event) {\n res.status(400).json({ error: \"Missing event header\" });\n return;\n }\n\n if (!isWebhookEvent(event)) {\n res.status(400).json({ error: \"Invalid event header\" });\n return;\n }\n\n let parsedPayload: unknown;\n try {\n parsedPayload = JSON.parse(rawPayload) as unknown;\n } catch {\n res.status(400).json({ error: \"Invalid JSON\" });\n return;\n }\n\n if (!isRuntimeWebhookPayload(parsedPayload, event)) {\n res.status(400).json({ error: \"Invalid payload\" });\n return;\n }\n\n const context = { deliveryId, event, timestamp };\n const handler = options.handlers[event] as\n | WebhookEventHandler<typeof event>\n | undefined;\n\n if (handler) {\n await handler(parsedPayload, context);\n } else if (options.onUnhandledEvent) {\n await options.onUnhandledEvent(event, parsedPayload, context);\n }\n\n res.status(200).send(\"OK\");\n } catch {\n res.status(500).json({ error: \"Internal error\" });\n }\n };\n}\n","import { createHmac, timingSafeEqual } from \"node:crypto\";\n\nconst DEFAULT_TOLERANCE_SECONDS = 300;\n\nexport interface VerifyWebhookParams {\n /** Raw request body as a string (NOT parsed JSON) */\n payload: string;\n /** Value of the X-Webhook-Signature header */\n signature: string;\n /** Value of the X-Webhook-Timestamp header (Unix epoch in seconds) */\n timestamp: string | number;\n /** App's webhook secret (provided during app installation) */\n secret: string;\n /** Maximum timestamp drift allowed in seconds. Defaults to 300 seconds. */\n toleranceSeconds?: number;\n /** Current Unix epoch time in seconds. Intended for tests. */\n currentTime?: number;\n}\n\n/**\n * Verify webhook signature using HMAC-SHA256 over `${timestamp}.${payload}`.\n * Uses timing-safe comparison to prevent timing attacks.\n */\nexport function verifyWebhook({\n payload,\n signature,\n timestamp,\n secret,\n toleranceSeconds = DEFAULT_TOLERANCE_SECONDS,\n currentTime = Math.floor(Date.now() / 1000),\n}: VerifyWebhookParams): boolean {\n if (!payload || !signature || !secret || timestamp === \"\") return false;\n\n const timestampString = String(timestamp);\n const timestampValue =\n typeof timestamp === \"number\" ? timestamp : Number(timestamp);\n\n if (!Number.isInteger(timestampValue)) return false;\n if (!Number.isFinite(toleranceSeconds) || toleranceSeconds < 0) return false;\n if (!Number.isFinite(currentTime)) return false;\n\n const ageSeconds = Math.abs(currentTime - timestampValue);\n if (ageSeconds > toleranceSeconds) return false;\n\n const expected = createHmac(\"sha256\", secret)\n .update(`${timestampString}.${payload}`, \"utf8\")\n .digest(\"hex\");\n\n if (expected.length !== signature.length) return false;\n if (!/^[a-f0-9]+$/i.test(signature)) return false;\n\n try {\n return timingSafeEqual(\n Buffer.from(expected, \"hex\"),\n Buffer.from(signature, \"hex\")\n );\n } catch {\n return false;\n }\n}\n","import {\n PUBLIC_WEBHOOK_EVENTS,\n isPublicWebhookEvent,\n type PublicWebhookEvent,\n} from \"@whatalo/protocol/events\";\nimport type { Product, Order, Customer } from \"../client/types.js\";\n\nexport const WEBHOOK_EVENTS = PUBLIC_WEBHOOK_EVENTS;\n\n/** All supported webhook event types */\nexport type WebhookEvent = PublicWebhookEvent;\n\n/** Validate an event header against the public runtime webhook event set. */\nexport function isWebhookEvent(value: string): value is WebhookEvent {\n return isPublicWebhookEvent(value);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction hasStringId(value: unknown): value is { id: string } {\n return isRecord(value) && typeof value.id === \"string\";\n}\n\nfunction isOptionalString(\n value: Record<string, unknown>,\n key: string\n): boolean {\n return value[key] === undefined || typeof value[key] === \"string\";\n}\n\nfunction isRuntimeWebhookStore(value: unknown): value is RuntimeWebhookStore {\n return (\n isRecord(value) &&\n typeof value.id === \"string\" &&\n typeof value.timezone === \"string\" &&\n (value.name === undefined || typeof value.name === \"string\")\n );\n}\n\nfunction hasValidBasePayloadFields(value: Record<string, unknown>): boolean {\n if (!isOptionalString(value, \"event_id\")) return false;\n if (!isOptionalString(value, \"occurred_at\")) return false;\n\n return isRuntimeWebhookStore(value.store);\n}\n\nfunction isRuntimeOrderWebhookPayload(value: Record<string, unknown>): boolean {\n return (\n hasValidBasePayloadFields(value) &&\n hasStringId(value.order) &&\n (value.customer === undefined || hasStringId(value.customer))\n );\n}\n\nfunction isRuntimeProductWebhookPayload(value: Record<string, unknown>): boolean {\n return hasValidBasePayloadFields(value) && hasStringId(value.product);\n}\n\nfunction isRuntimeCustomerWebhookPayload(value: Record<string, unknown>): boolean {\n return hasValidBasePayloadFields(value) && hasStringId(value.customer);\n}\n\nfunction isRuntimeCheckoutCompletedWebhookPayload(\n value: Record<string, unknown>\n): boolean {\n return (\n hasValidBasePayloadFields(value) &&\n hasStringId(value.order) &&\n hasStringId(value.customer) &&\n isRuntimeWebhookStore(value.store)\n );\n}\n\nfunction isRuntimeCheckoutAbandonedWebhookPayload(\n value: Record<string, unknown>\n): boolean {\n // An abandoned draft is pre-customer, so `customer` carries no `id` and is not required.\n return (\n hasValidBasePayloadFields(value) &&\n hasStringId(value.checkout) &&\n isRuntimeWebhookStore(value.store)\n );\n}\n\nexport interface OrderCreatedWebhookData {\n order: Order;\n}\n\nexport interface OrderUpdatedWebhookData {\n order: Order;\n changes: string[];\n}\n\nexport interface OrderCancelledWebhookData {\n orderId: string;\n reason?: string;\n}\n\nexport interface OrderCompletedWebhookData {\n order: Order;\n}\n\nexport interface ProductCreatedWebhookData {\n product: Product;\n}\n\nexport interface ProductUpdatedWebhookData {\n product: Product;\n changes: string[];\n}\n\nexport interface ProductDeletedWebhookProduct {\n id: string;\n}\n\nexport interface ProductDeletedWebhookData {\n product: ProductDeletedWebhookProduct;\n}\n\nexport interface CustomerCreatedWebhookData {\n customer: Customer;\n}\n\nexport interface CustomerUpdatedWebhookData {\n customer: Customer;\n changes: string[];\n}\n\nexport interface CheckoutCompletedWebhookData {\n order: RuntimeWebhookOrder;\n customer: RuntimeWebhookCustomer;\n store: RuntimeWebhookStore;\n}\n\n/** Contact captured on an abandoned draft. No `id` — the draft is pre-customer. */\nexport interface CheckoutAbandonedWebhookCustomer {\n name: string | null;\n email: string | null;\n phone: string | null;\n}\n\nexport interface CheckoutAbandonedWebhookData {\n checkout: RuntimeWebhookCheckout;\n customer: CheckoutAbandonedWebhookCustomer;\n store: RuntimeWebhookStore;\n}\n\n/** Map of webhook events to their payload data shapes */\nexport interface WebhookEventData {\n \"order.created\": OrderCreatedWebhookData;\n \"order.updated\": OrderUpdatedWebhookData;\n \"order.cancelled\": OrderCancelledWebhookData;\n \"order.completed\": OrderCompletedWebhookData;\n \"product.created\": ProductCreatedWebhookData;\n \"product.updated\": ProductUpdatedWebhookData;\n \"product.deleted\": ProductDeletedWebhookData;\n \"customer.created\": CustomerCreatedWebhookData;\n \"customer.updated\": CustomerUpdatedWebhookData;\n \"checkout.completed\": CheckoutCompletedWebhookData;\n \"checkout.abandoned\": CheckoutAbandonedWebhookData;\n}\n\n/** Legacy envelope payload. Runtime webhook deliveries do not include the event field in the body. */\nexport interface WebhookPayload<E extends WebhookEvent = WebhookEvent> {\n event: E;\n timestamp: string;\n storeId: string;\n data: WebhookEventData[E];\n}\n\nexport interface RuntimeWebhookStore {\n id: string;\n name?: string;\n timezone: string;\n}\n\nexport interface RuntimeWebhookBasePayload {\n event_id?: string;\n occurred_at?: string;\n store: RuntimeWebhookStore;\n}\n\nexport interface RuntimeWebhookOrder {\n id: string;\n [key: string]: unknown;\n}\n\nexport interface RuntimeWebhookProduct {\n id: string;\n [key: string]: unknown;\n}\n\nexport interface RuntimeWebhookCustomer {\n id: string;\n [key: string]: unknown;\n}\n\nexport interface RuntimeWebhookCheckout {\n id: string;\n [key: string]: unknown;\n}\n\nexport interface RuntimeOrderWebhookPayload extends RuntimeWebhookBasePayload {\n order: RuntimeWebhookOrder;\n customer?: RuntimeWebhookCustomer;\n}\n\nexport interface RuntimeProductWebhookPayload extends RuntimeWebhookBasePayload {\n product: RuntimeWebhookProduct;\n}\n\nexport interface RuntimeCustomerWebhookPayload extends RuntimeWebhookBasePayload {\n customer: RuntimeWebhookCustomer;\n}\n\nexport interface RuntimeCheckoutCompletedWebhookPayload\n extends RuntimeWebhookBasePayload {\n order: RuntimeWebhookOrder;\n customer: RuntimeWebhookCustomer;\n store: RuntimeWebhookStore;\n}\n\nexport interface RuntimeCheckoutAbandonedWebhookPayload\n extends RuntimeWebhookBasePayload {\n checkout: RuntimeWebhookCheckout;\n // Pre-customer draft: contact fields only, no customer id.\n customer?: CheckoutAbandonedWebhookCustomer;\n}\n\nexport interface RuntimeWebhookEventData {\n \"order.created\": RuntimeOrderWebhookPayload;\n \"order.updated\": RuntimeOrderWebhookPayload;\n \"order.cancelled\": RuntimeOrderWebhookPayload;\n \"order.completed\": RuntimeOrderWebhookPayload;\n \"product.created\": RuntimeProductWebhookPayload;\n \"product.updated\": RuntimeProductWebhookPayload;\n \"product.deleted\": RuntimeProductWebhookPayload;\n \"customer.created\": RuntimeCustomerWebhookPayload;\n \"customer.updated\": RuntimeCustomerWebhookPayload;\n \"checkout.completed\": RuntimeCheckoutCompletedWebhookPayload;\n \"checkout.abandoned\": RuntimeCheckoutAbandonedWebhookPayload;\n}\n\n/** Runtime body delivered to subscriber endpoints. The event comes from X-Webhook-Event. */\nexport type RuntimeWebhookPayload<E extends WebhookEvent = WebhookEvent> =\n RuntimeWebhookEventData[E];\n\n/** Validate the minimum runtime payload shape before invoking typed handlers. */\nexport function isRuntimeWebhookPayload<E extends WebhookEvent>(\n value: unknown,\n event: E\n): value is RuntimeWebhookPayload<E> {\n if (!isRecord(value)) return false;\n\n switch (event) {\n case WEBHOOK_EVENTS.ORDER_CREATED:\n case WEBHOOK_EVENTS.ORDER_UPDATED:\n case WEBHOOK_EVENTS.ORDER_CANCELLED:\n case WEBHOOK_EVENTS.ORDER_COMPLETED:\n return isRuntimeOrderWebhookPayload(value);\n case WEBHOOK_EVENTS.PRODUCT_CREATED:\n case WEBHOOK_EVENTS.PRODUCT_UPDATED:\n case WEBHOOK_EVENTS.PRODUCT_DELETED:\n return isRuntimeProductWebhookPayload(value);\n case WEBHOOK_EVENTS.CUSTOMER_CREATED:\n case WEBHOOK_EVENTS.CUSTOMER_UPDATED:\n return isRuntimeCustomerWebhookPayload(value);\n case WEBHOOK_EVENTS.CHECKOUT_COMPLETED:\n return isRuntimeCheckoutCompletedWebhookPayload(value);\n case WEBHOOK_EVENTS.CHECKOUT_ABANDONED:\n return isRuntimeCheckoutAbandonedWebhookPayload(value);\n default:\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,yBAA4C;AAE5C,IAAM,4BAA4B;AAqB3B,SAAS,cAAc;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,mBAAmB;AAAA,EACnB,cAAc,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AAC5C,GAAiC;AAC/B,MAAI,CAAC,WAAW,CAAC,aAAa,CAAC,UAAU,cAAc,GAAI,QAAO;AAElE,QAAM,kBAAkB,OAAO,SAAS;AACxC,QAAM,iBACJ,OAAO,cAAc,WAAW,YAAY,OAAO,SAAS;AAE9D,MAAI,CAAC,OAAO,UAAU,cAAc,EAAG,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,OAAO,eAAe,OAAO;AAAA,MAC9D;AAEA,UAAI,OAAO,GAAG,EAAE,KAAK,IAAI;AAAA,IAC3B,QAAQ;AACN,UAAI,OAAO,GAAG,EAAE,KAAK,EAAE,OAAO,iBAAiB,CAAC;AAAA,IAClD;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1,16 +1,18 @@
|
|
|
1
|
-
import { W as WebhookHandlerOptions } from '../types-
|
|
2
|
-
import '../types-
|
|
3
|
-
import '
|
|
1
|
+
import { W as WebhookHandlerOptions } from '../types-CqyAhbXM.cjs';
|
|
2
|
+
import '../types-CPnSzOfX.cjs';
|
|
3
|
+
import '@whatalo/protocol/events';
|
|
4
|
+
import '../types-B8BAV362.cjs';
|
|
4
5
|
|
|
5
6
|
type ExpressLikeRequest = {
|
|
6
7
|
body: Buffer | string;
|
|
7
8
|
headers: Record<string, string | string[] | undefined>;
|
|
8
9
|
};
|
|
10
|
+
type ExpressLikeStatusResponse = {
|
|
11
|
+
json: (body: unknown) => void;
|
|
12
|
+
send: (body: string) => void;
|
|
13
|
+
};
|
|
9
14
|
type ExpressLikeResponse = {
|
|
10
|
-
status: (code: number) =>
|
|
11
|
-
json: (body: unknown) => void;
|
|
12
|
-
send: (body: string) => void;
|
|
13
|
-
};
|
|
15
|
+
status: (code: number) => ExpressLikeStatusResponse;
|
|
14
16
|
};
|
|
15
17
|
declare function createWebhookHandler(options: WebhookHandlerOptions): (req: ExpressLikeRequest, res: ExpressLikeResponse) => Promise<void>;
|
|
16
18
|
|
|
@@ -1,16 +1,18 @@
|
|
|
1
|
-
import { W as WebhookHandlerOptions } from '../types-
|
|
2
|
-
import '../types-
|
|
3
|
-
import '
|
|
1
|
+
import { W as WebhookHandlerOptions } from '../types-Bzee9Hvr.js';
|
|
2
|
+
import '../types-CDKGAQ3o.js';
|
|
3
|
+
import '@whatalo/protocol/events';
|
|
4
|
+
import '../types-B8BAV362.js';
|
|
4
5
|
|
|
5
6
|
type ExpressLikeRequest = {
|
|
6
7
|
body: Buffer | string;
|
|
7
8
|
headers: Record<string, string | string[] | undefined>;
|
|
8
9
|
};
|
|
10
|
+
type ExpressLikeStatusResponse = {
|
|
11
|
+
json: (body: unknown) => void;
|
|
12
|
+
send: (body: string) => void;
|
|
13
|
+
};
|
|
9
14
|
type ExpressLikeResponse = {
|
|
10
|
-
status: (code: number) =>
|
|
11
|
-
json: (body: unknown) => void;
|
|
12
|
-
send: (body: string) => void;
|
|
13
|
-
};
|
|
15
|
+
status: (code: number) => ExpressLikeStatusResponse;
|
|
14
16
|
};
|
|
15
17
|
declare function createWebhookHandler(options: WebhookHandlerOptions): (req: ExpressLikeRequest, res: ExpressLikeResponse) => Promise<void>;
|
|
16
18
|
|
|
@@ -1,13 +1,25 @@
|
|
|
1
1
|
// src/webhooks/verify.ts
|
|
2
2
|
import { createHmac, timingSafeEqual } from "crypto";
|
|
3
|
+
var DEFAULT_TOLERANCE_SECONDS = 300;
|
|
3
4
|
function verifyWebhook({
|
|
4
5
|
payload,
|
|
5
6
|
signature,
|
|
6
|
-
|
|
7
|
+
timestamp,
|
|
8
|
+
secret,
|
|
9
|
+
toleranceSeconds = DEFAULT_TOLERANCE_SECONDS,
|
|
10
|
+
currentTime = Math.floor(Date.now() / 1e3)
|
|
7
11
|
}) {
|
|
8
|
-
if (!payload || !signature || !secret) return false;
|
|
9
|
-
const
|
|
12
|
+
if (!payload || !signature || !secret || timestamp === "") return false;
|
|
13
|
+
const timestampString = String(timestamp);
|
|
14
|
+
const timestampValue = typeof timestamp === "number" ? timestamp : Number(timestamp);
|
|
15
|
+
if (!Number.isInteger(timestampValue)) return false;
|
|
16
|
+
if (!Number.isFinite(toleranceSeconds) || toleranceSeconds < 0) return false;
|
|
17
|
+
if (!Number.isFinite(currentTime)) return false;
|
|
18
|
+
const ageSeconds = Math.abs(currentTime - timestampValue);
|
|
19
|
+
if (ageSeconds > toleranceSeconds) return false;
|
|
20
|
+
const expected = createHmac("sha256", secret).update(`${timestampString}.${payload}`, "utf8").digest("hex");
|
|
10
21
|
if (expected.length !== signature.length) return false;
|
|
22
|
+
if (!/^[a-f0-9]+$/i.test(signature)) return false;
|
|
11
23
|
try {
|
|
12
24
|
return timingSafeEqual(
|
|
13
25
|
Buffer.from(expected, "hex"),
|
|
@@ -18,9 +30,74 @@ function verifyWebhook({
|
|
|
18
30
|
}
|
|
19
31
|
}
|
|
20
32
|
|
|
33
|
+
// src/webhooks/types.ts
|
|
34
|
+
import {
|
|
35
|
+
PUBLIC_WEBHOOK_EVENTS,
|
|
36
|
+
isPublicWebhookEvent
|
|
37
|
+
} from "@whatalo/protocol/events";
|
|
38
|
+
var WEBHOOK_EVENTS = PUBLIC_WEBHOOK_EVENTS;
|
|
39
|
+
function isWebhookEvent(value) {
|
|
40
|
+
return isPublicWebhookEvent(value);
|
|
41
|
+
}
|
|
42
|
+
function isRecord(value) {
|
|
43
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
44
|
+
}
|
|
45
|
+
function hasStringId(value) {
|
|
46
|
+
return isRecord(value) && typeof value.id === "string";
|
|
47
|
+
}
|
|
48
|
+
function isOptionalString(value, key) {
|
|
49
|
+
return value[key] === void 0 || typeof value[key] === "string";
|
|
50
|
+
}
|
|
51
|
+
function isRuntimeWebhookStore(value) {
|
|
52
|
+
return isRecord(value) && typeof value.id === "string" && typeof value.timezone === "string" && (value.name === void 0 || typeof value.name === "string");
|
|
53
|
+
}
|
|
54
|
+
function hasValidBasePayloadFields(value) {
|
|
55
|
+
if (!isOptionalString(value, "event_id")) return false;
|
|
56
|
+
if (!isOptionalString(value, "occurred_at")) return false;
|
|
57
|
+
return isRuntimeWebhookStore(value.store);
|
|
58
|
+
}
|
|
59
|
+
function isRuntimeOrderWebhookPayload(value) {
|
|
60
|
+
return hasValidBasePayloadFields(value) && hasStringId(value.order) && (value.customer === void 0 || hasStringId(value.customer));
|
|
61
|
+
}
|
|
62
|
+
function isRuntimeProductWebhookPayload(value) {
|
|
63
|
+
return hasValidBasePayloadFields(value) && hasStringId(value.product);
|
|
64
|
+
}
|
|
65
|
+
function isRuntimeCustomerWebhookPayload(value) {
|
|
66
|
+
return hasValidBasePayloadFields(value) && hasStringId(value.customer);
|
|
67
|
+
}
|
|
68
|
+
function isRuntimeCheckoutCompletedWebhookPayload(value) {
|
|
69
|
+
return hasValidBasePayloadFields(value) && hasStringId(value.order) && hasStringId(value.customer) && isRuntimeWebhookStore(value.store);
|
|
70
|
+
}
|
|
71
|
+
function isRuntimeCheckoutAbandonedWebhookPayload(value) {
|
|
72
|
+
return hasValidBasePayloadFields(value) && hasStringId(value.checkout) && isRuntimeWebhookStore(value.store);
|
|
73
|
+
}
|
|
74
|
+
function isRuntimeWebhookPayload(value, event) {
|
|
75
|
+
if (!isRecord(value)) return false;
|
|
76
|
+
switch (event) {
|
|
77
|
+
case WEBHOOK_EVENTS.ORDER_CREATED:
|
|
78
|
+
case WEBHOOK_EVENTS.ORDER_UPDATED:
|
|
79
|
+
case WEBHOOK_EVENTS.ORDER_CANCELLED:
|
|
80
|
+
case WEBHOOK_EVENTS.ORDER_COMPLETED:
|
|
81
|
+
return isRuntimeOrderWebhookPayload(value);
|
|
82
|
+
case WEBHOOK_EVENTS.PRODUCT_CREATED:
|
|
83
|
+
case WEBHOOK_EVENTS.PRODUCT_UPDATED:
|
|
84
|
+
case WEBHOOK_EVENTS.PRODUCT_DELETED:
|
|
85
|
+
return isRuntimeProductWebhookPayload(value);
|
|
86
|
+
case WEBHOOK_EVENTS.CUSTOMER_CREATED:
|
|
87
|
+
case WEBHOOK_EVENTS.CUSTOMER_UPDATED:
|
|
88
|
+
return isRuntimeCustomerWebhookPayload(value);
|
|
89
|
+
case WEBHOOK_EVENTS.CHECKOUT_COMPLETED:
|
|
90
|
+
return isRuntimeCheckoutCompletedWebhookPayload(value);
|
|
91
|
+
case WEBHOOK_EVENTS.CHECKOUT_ABANDONED:
|
|
92
|
+
return isRuntimeCheckoutAbandonedWebhookPayload(value);
|
|
93
|
+
default:
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
21
98
|
// src/adapters/express.ts
|
|
22
|
-
function
|
|
23
|
-
const value = headers[
|
|
99
|
+
function getHeader(name, headers) {
|
|
100
|
+
const value = headers[name];
|
|
24
101
|
if (Array.isArray(value)) {
|
|
25
102
|
return value[0] ?? "";
|
|
26
103
|
}
|
|
@@ -30,23 +107,45 @@ function createWebhookHandler(options) {
|
|
|
30
107
|
return async function webhookHandler(req, res) {
|
|
31
108
|
try {
|
|
32
109
|
const rawPayload = typeof req.body === "string" ? req.body : req.body.toString("utf8");
|
|
33
|
-
const signature =
|
|
110
|
+
const signature = getHeader("x-webhook-signature", req.headers);
|
|
111
|
+
const timestamp = getHeader("x-webhook-timestamp", req.headers);
|
|
112
|
+
const event = getHeader("x-webhook-event", req.headers);
|
|
113
|
+
const deliveryId = getHeader("x-webhook-id", req.headers);
|
|
34
114
|
const isValid = verifyWebhook({
|
|
35
115
|
payload: rawPayload,
|
|
36
116
|
signature,
|
|
117
|
+
timestamp,
|
|
37
118
|
secret: options.secret
|
|
38
119
|
});
|
|
39
120
|
if (!isValid) {
|
|
40
121
|
res.status(401).json({ error: "Invalid signature" });
|
|
41
122
|
return;
|
|
42
123
|
}
|
|
43
|
-
|
|
44
|
-
|
|
124
|
+
if (!event) {
|
|
125
|
+
res.status(400).json({ error: "Missing event header" });
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
if (!isWebhookEvent(event)) {
|
|
129
|
+
res.status(400).json({ error: "Invalid event header" });
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
let parsedPayload;
|
|
133
|
+
try {
|
|
134
|
+
parsedPayload = JSON.parse(rawPayload);
|
|
135
|
+
} catch {
|
|
136
|
+
res.status(400).json({ error: "Invalid JSON" });
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
if (!isRuntimeWebhookPayload(parsedPayload, event)) {
|
|
140
|
+
res.status(400).json({ error: "Invalid payload" });
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
const context = { deliveryId, event, timestamp };
|
|
45
144
|
const handler = options.handlers[event];
|
|
46
145
|
if (handler) {
|
|
47
|
-
await handler(
|
|
146
|
+
await handler(parsedPayload, context);
|
|
48
147
|
} else if (options.onUnhandledEvent) {
|
|
49
|
-
await options.onUnhandledEvent(event,
|
|
148
|
+
await options.onUnhandledEvent(event, parsedPayload, context);
|
|
50
149
|
}
|
|
51
150
|
res.status(200).send("OK");
|
|
52
151
|
} catch {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/webhooks/verify.ts","../../src/adapters/express.ts"],"sourcesContent":["import { createHmac, timingSafeEqual } from \"node:crypto\";\n\nexport interface VerifyWebhookParams {\n /** Raw request body as a string (NOT parsed JSON) */\n payload: string;\n /** Value of the X-Webhook-Signature header */\n signature: string;\n /** App's webhook secret (provided during app installation) */\n secret: string;\n}\n\n/**\n * Verify webhook signature using HMAC-SHA256.\n * Uses timing-safe comparison to prevent timing attacks.\n */\nexport function verifyWebhook({\n payload,\n signature,\n secret,\n}: VerifyWebhookParams): boolean {\n if (!payload || !signature || !secret) return false;\n\n const expected = createHmac(\"sha256\", secret)\n .update(payload, \"utf8\")\n .digest(\"hex\");\n\n if (expected.length !== signature.length) return false;\n\n try {\n return timingSafeEqual(\n Buffer.from(expected, \"hex\"),\n Buffer.from(signature, \"hex\")\n );\n } catch {\n return false;\n }\n}\n","import { verifyWebhook } from \"../webhooks/verify.js\";\nimport type { WebhookPayload } from \"../webhooks/types.js\";\nimport type { WebhookEventHandler, WebhookHandlerOptions } from \"./types.js\";\n\ntype ExpressLikeRequest = {\n body: Buffer | string;\n headers: Record<string, string | string[] | undefined>;\n};\n\ntype ExpressLikeResponse = {\n status: (code: number) => {\n json: (body: unknown) => void;\n send: (body: string) => void;\n };\n};\n\nfunction getSignature(\n headers: Record<string, string | string[] | undefined>\n): string {\n const value = headers[\"x-webhook-signature\"];\n\n if (Array.isArray(value)) {\n return value[0] ?? \"\";\n }\n\n return value ?? \"\";\n}\n\nexport function createWebhookHandler(\n options: WebhookHandlerOptions\n): (req: ExpressLikeRequest, res: ExpressLikeResponse) => Promise<void> {\n return async function webhookHandler(\n req: ExpressLikeRequest,\n res: ExpressLikeResponse\n ): Promise<void> {\n try {\n const rawPayload =\n typeof req.body === \"string\" ? req.body : req.body.toString(\"utf8\");\n const signature = getSignature(req.headers);\n\n const isValid = verifyWebhook({\n payload: rawPayload,\n signature,\n secret: options.secret,\n });\n\n if (!isValid) {\n res.status(401).json({ error: \"Invalid signature\" });\n return;\n }\n\n const payload = JSON.parse(rawPayload) as WebhookPayload;\n const event = payload.event;\n const handler = options.handlers[event] as\n | WebhookEventHandler<typeof event>\n | undefined;\n\n if (handler) {\n await handler(payload);\n } else if (options.onUnhandledEvent) {\n await options.onUnhandledEvent(event, payload);\n }\n\n res.status(200).send(\"OK\");\n } catch {\n res.status(500).json({ error: \"Internal error\" });\n }\n };\n}\n"],"mappings":";AAAA,SAAS,YAAY,uBAAuB;AAerC,SAAS,cAAc;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AACF,GAAiC;AAC/B,MAAI,CAAC,WAAW,CAAC,aAAa,CAAC,OAAQ,QAAO;AAE9C,QAAM,WAAW,WAAW,UAAU,MAAM,EACzC,OAAO,SAAS,MAAM,EACtB,OAAO,KAAK;AAEf,MAAI,SAAS,WAAW,UAAU,OAAQ,QAAO;AAEjD,MAAI;AACF,WAAO;AAAA,MACL,OAAO,KAAK,UAAU,KAAK;AAAA,MAC3B,OAAO,KAAK,WAAW,KAAK;AAAA,IAC9B;AAAA,EACF,QAAQ;AACN,WAAO;AAAA,EACT;AACF;;;ACpBA,SAAS,aACP,SACQ;AACR,QAAM,QAAQ,QAAQ,qBAAqB;AAE3C,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,WAAO,MAAM,CAAC,KAAK;AAAA,EACrB;AAEA,SAAO,SAAS;AAClB;AAEO,SAAS,qBACd,SACsE;AACtE,SAAO,eAAe,eACpB,KACA,KACe;AACf,QAAI;AACF,YAAM,aACJ,OAAO,IAAI,SAAS,WAAW,IAAI,OAAO,IAAI,KAAK,SAAS,MAAM;AACpE,YAAM,YAAY,aAAa,IAAI,OAAO;AAE1C,YAAM,UAAU,cAAc;AAAA,QAC5B,SAAS;AAAA,QACT;AAAA,QACA,QAAQ,QAAQ;AAAA,MAClB,CAAC;AAED,UAAI,CAAC,SAAS;AACZ,YAAI,OAAO,GAAG,EAAE,KAAK,EAAE,OAAO,oBAAoB,CAAC;AACnD;AAAA,MACF;AAEA,YAAM,UAAU,KAAK,MAAM,UAAU;AACrC,YAAM,QAAQ,QAAQ;AACtB,YAAM,UAAU,QAAQ,SAAS,KAAK;AAItC,UAAI,SAAS;AACX,cAAM,QAAQ,OAAO;AAAA,MACvB,WAAW,QAAQ,kBAAkB;AACnC,cAAM,QAAQ,iBAAiB,OAAO,OAAO;AAAA,MAC/C;AAEA,UAAI,OAAO,GAAG,EAAE,KAAK,IAAI;AAAA,IAC3B,QAAQ;AACN,UAAI,OAAO,GAAG,EAAE,KAAK,EAAE,OAAO,iBAAiB,CAAC;AAAA,IAClD;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/webhooks/verify.ts","../../src/webhooks/types.ts","../../src/adapters/express.ts"],"sourcesContent":["import { createHmac, timingSafeEqual } from \"node:crypto\";\n\nconst DEFAULT_TOLERANCE_SECONDS = 300;\n\nexport interface VerifyWebhookParams {\n /** Raw request body as a string (NOT parsed JSON) */\n payload: string;\n /** Value of the X-Webhook-Signature header */\n signature: string;\n /** Value of the X-Webhook-Timestamp header (Unix epoch in seconds) */\n timestamp: string | number;\n /** App's webhook secret (provided during app installation) */\n secret: string;\n /** Maximum timestamp drift allowed in seconds. Defaults to 300 seconds. */\n toleranceSeconds?: number;\n /** Current Unix epoch time in seconds. Intended for tests. */\n currentTime?: number;\n}\n\n/**\n * Verify webhook signature using HMAC-SHA256 over `${timestamp}.${payload}`.\n * Uses timing-safe comparison to prevent timing attacks.\n */\nexport function verifyWebhook({\n payload,\n signature,\n timestamp,\n secret,\n toleranceSeconds = DEFAULT_TOLERANCE_SECONDS,\n currentTime = Math.floor(Date.now() / 1000),\n}: VerifyWebhookParams): boolean {\n if (!payload || !signature || !secret || timestamp === \"\") return false;\n\n const timestampString = String(timestamp);\n const timestampValue =\n typeof timestamp === \"number\" ? timestamp : Number(timestamp);\n\n if (!Number.isInteger(timestampValue)) return false;\n if (!Number.isFinite(toleranceSeconds) || toleranceSeconds < 0) return false;\n if (!Number.isFinite(currentTime)) return false;\n\n const ageSeconds = Math.abs(currentTime - timestampValue);\n if (ageSeconds > toleranceSeconds) return false;\n\n const expected = createHmac(\"sha256\", secret)\n .update(`${timestampString}.${payload}`, \"utf8\")\n .digest(\"hex\");\n\n if (expected.length !== signature.length) return false;\n if (!/^[a-f0-9]+$/i.test(signature)) return false;\n\n try {\n return timingSafeEqual(\n Buffer.from(expected, \"hex\"),\n Buffer.from(signature, \"hex\")\n );\n } catch {\n return false;\n }\n}\n","import {\n PUBLIC_WEBHOOK_EVENTS,\n isPublicWebhookEvent,\n type PublicWebhookEvent,\n} from \"@whatalo/protocol/events\";\nimport type { Product, Order, Customer } from \"../client/types.js\";\n\nexport const WEBHOOK_EVENTS = PUBLIC_WEBHOOK_EVENTS;\n\n/** All supported webhook event types */\nexport type WebhookEvent = PublicWebhookEvent;\n\n/** Validate an event header against the public runtime webhook event set. */\nexport function isWebhookEvent(value: string): value is WebhookEvent {\n return isPublicWebhookEvent(value);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction hasStringId(value: unknown): value is { id: string } {\n return isRecord(value) && typeof value.id === \"string\";\n}\n\nfunction isOptionalString(\n value: Record<string, unknown>,\n key: string\n): boolean {\n return value[key] === undefined || typeof value[key] === \"string\";\n}\n\nfunction isRuntimeWebhookStore(value: unknown): value is RuntimeWebhookStore {\n return (\n isRecord(value) &&\n typeof value.id === \"string\" &&\n typeof value.timezone === \"string\" &&\n (value.name === undefined || typeof value.name === \"string\")\n );\n}\n\nfunction hasValidBasePayloadFields(value: Record<string, unknown>): boolean {\n if (!isOptionalString(value, \"event_id\")) return false;\n if (!isOptionalString(value, \"occurred_at\")) return false;\n\n return isRuntimeWebhookStore(value.store);\n}\n\nfunction isRuntimeOrderWebhookPayload(value: Record<string, unknown>): boolean {\n return (\n hasValidBasePayloadFields(value) &&\n hasStringId(value.order) &&\n (value.customer === undefined || hasStringId(value.customer))\n );\n}\n\nfunction isRuntimeProductWebhookPayload(value: Record<string, unknown>): boolean {\n return hasValidBasePayloadFields(value) && hasStringId(value.product);\n}\n\nfunction isRuntimeCustomerWebhookPayload(value: Record<string, unknown>): boolean {\n return hasValidBasePayloadFields(value) && hasStringId(value.customer);\n}\n\nfunction isRuntimeCheckoutCompletedWebhookPayload(\n value: Record<string, unknown>\n): boolean {\n return (\n hasValidBasePayloadFields(value) &&\n hasStringId(value.order) &&\n hasStringId(value.customer) &&\n isRuntimeWebhookStore(value.store)\n );\n}\n\nfunction isRuntimeCheckoutAbandonedWebhookPayload(\n value: Record<string, unknown>\n): boolean {\n // An abandoned draft is pre-customer, so `customer` carries no `id` and is not required.\n return (\n hasValidBasePayloadFields(value) &&\n hasStringId(value.checkout) &&\n isRuntimeWebhookStore(value.store)\n );\n}\n\nexport interface OrderCreatedWebhookData {\n order: Order;\n}\n\nexport interface OrderUpdatedWebhookData {\n order: Order;\n changes: string[];\n}\n\nexport interface OrderCancelledWebhookData {\n orderId: string;\n reason?: string;\n}\n\nexport interface OrderCompletedWebhookData {\n order: Order;\n}\n\nexport interface ProductCreatedWebhookData {\n product: Product;\n}\n\nexport interface ProductUpdatedWebhookData {\n product: Product;\n changes: string[];\n}\n\nexport interface ProductDeletedWebhookProduct {\n id: string;\n}\n\nexport interface ProductDeletedWebhookData {\n product: ProductDeletedWebhookProduct;\n}\n\nexport interface CustomerCreatedWebhookData {\n customer: Customer;\n}\n\nexport interface CustomerUpdatedWebhookData {\n customer: Customer;\n changes: string[];\n}\n\nexport interface CheckoutCompletedWebhookData {\n order: RuntimeWebhookOrder;\n customer: RuntimeWebhookCustomer;\n store: RuntimeWebhookStore;\n}\n\n/** Contact captured on an abandoned draft. No `id` — the draft is pre-customer. */\nexport interface CheckoutAbandonedWebhookCustomer {\n name: string | null;\n email: string | null;\n phone: string | null;\n}\n\nexport interface CheckoutAbandonedWebhookData {\n checkout: RuntimeWebhookCheckout;\n customer: CheckoutAbandonedWebhookCustomer;\n store: RuntimeWebhookStore;\n}\n\n/** Map of webhook events to their payload data shapes */\nexport interface WebhookEventData {\n \"order.created\": OrderCreatedWebhookData;\n \"order.updated\": OrderUpdatedWebhookData;\n \"order.cancelled\": OrderCancelledWebhookData;\n \"order.completed\": OrderCompletedWebhookData;\n \"product.created\": ProductCreatedWebhookData;\n \"product.updated\": ProductUpdatedWebhookData;\n \"product.deleted\": ProductDeletedWebhookData;\n \"customer.created\": CustomerCreatedWebhookData;\n \"customer.updated\": CustomerUpdatedWebhookData;\n \"checkout.completed\": CheckoutCompletedWebhookData;\n \"checkout.abandoned\": CheckoutAbandonedWebhookData;\n}\n\n/** Legacy envelope payload. Runtime webhook deliveries do not include the event field in the body. */\nexport interface WebhookPayload<E extends WebhookEvent = WebhookEvent> {\n event: E;\n timestamp: string;\n storeId: string;\n data: WebhookEventData[E];\n}\n\nexport interface RuntimeWebhookStore {\n id: string;\n name?: string;\n timezone: string;\n}\n\nexport interface RuntimeWebhookBasePayload {\n event_id?: string;\n occurred_at?: string;\n store: RuntimeWebhookStore;\n}\n\nexport interface RuntimeWebhookOrder {\n id: string;\n [key: string]: unknown;\n}\n\nexport interface RuntimeWebhookProduct {\n id: string;\n [key: string]: unknown;\n}\n\nexport interface RuntimeWebhookCustomer {\n id: string;\n [key: string]: unknown;\n}\n\nexport interface RuntimeWebhookCheckout {\n id: string;\n [key: string]: unknown;\n}\n\nexport interface RuntimeOrderWebhookPayload extends RuntimeWebhookBasePayload {\n order: RuntimeWebhookOrder;\n customer?: RuntimeWebhookCustomer;\n}\n\nexport interface RuntimeProductWebhookPayload extends RuntimeWebhookBasePayload {\n product: RuntimeWebhookProduct;\n}\n\nexport interface RuntimeCustomerWebhookPayload extends RuntimeWebhookBasePayload {\n customer: RuntimeWebhookCustomer;\n}\n\nexport interface RuntimeCheckoutCompletedWebhookPayload\n extends RuntimeWebhookBasePayload {\n order: RuntimeWebhookOrder;\n customer: RuntimeWebhookCustomer;\n store: RuntimeWebhookStore;\n}\n\nexport interface RuntimeCheckoutAbandonedWebhookPayload\n extends RuntimeWebhookBasePayload {\n checkout: RuntimeWebhookCheckout;\n // Pre-customer draft: contact fields only, no customer id.\n customer?: CheckoutAbandonedWebhookCustomer;\n}\n\nexport interface RuntimeWebhookEventData {\n \"order.created\": RuntimeOrderWebhookPayload;\n \"order.updated\": RuntimeOrderWebhookPayload;\n \"order.cancelled\": RuntimeOrderWebhookPayload;\n \"order.completed\": RuntimeOrderWebhookPayload;\n \"product.created\": RuntimeProductWebhookPayload;\n \"product.updated\": RuntimeProductWebhookPayload;\n \"product.deleted\": RuntimeProductWebhookPayload;\n \"customer.created\": RuntimeCustomerWebhookPayload;\n \"customer.updated\": RuntimeCustomerWebhookPayload;\n \"checkout.completed\": RuntimeCheckoutCompletedWebhookPayload;\n \"checkout.abandoned\": RuntimeCheckoutAbandonedWebhookPayload;\n}\n\n/** Runtime body delivered to subscriber endpoints. The event comes from X-Webhook-Event. */\nexport type RuntimeWebhookPayload<E extends WebhookEvent = WebhookEvent> =\n RuntimeWebhookEventData[E];\n\n/** Validate the minimum runtime payload shape before invoking typed handlers. */\nexport function isRuntimeWebhookPayload<E extends WebhookEvent>(\n value: unknown,\n event: E\n): value is RuntimeWebhookPayload<E> {\n if (!isRecord(value)) return false;\n\n switch (event) {\n case WEBHOOK_EVENTS.ORDER_CREATED:\n case WEBHOOK_EVENTS.ORDER_UPDATED:\n case WEBHOOK_EVENTS.ORDER_CANCELLED:\n case WEBHOOK_EVENTS.ORDER_COMPLETED:\n return isRuntimeOrderWebhookPayload(value);\n case WEBHOOK_EVENTS.PRODUCT_CREATED:\n case WEBHOOK_EVENTS.PRODUCT_UPDATED:\n case WEBHOOK_EVENTS.PRODUCT_DELETED:\n return isRuntimeProductWebhookPayload(value);\n case WEBHOOK_EVENTS.CUSTOMER_CREATED:\n case WEBHOOK_EVENTS.CUSTOMER_UPDATED:\n return isRuntimeCustomerWebhookPayload(value);\n case WEBHOOK_EVENTS.CHECKOUT_COMPLETED:\n return isRuntimeCheckoutCompletedWebhookPayload(value);\n case WEBHOOK_EVENTS.CHECKOUT_ABANDONED:\n return isRuntimeCheckoutAbandonedWebhookPayload(value);\n default:\n return false;\n }\n}\n","import { verifyWebhook } from \"../webhooks/verify.js\";\nimport { isRuntimeWebhookPayload, isWebhookEvent } from \"../webhooks/types.js\";\nimport type { WebhookEventHandler, WebhookHandlerOptions } from \"./types.js\";\n\ntype ExpressLikeRequest = {\n body: Buffer | string;\n headers: Record<string, string | string[] | undefined>;\n};\n\ntype ExpressLikeStatusResponse = {\n json: (body: unknown) => void;\n send: (body: string) => void;\n};\n\ntype ExpressLikeResponse = {\n status: (code: number) => ExpressLikeStatusResponse;\n};\n\nfunction getHeader(\n name: string,\n headers: Record<string, string | string[] | undefined>\n): string {\n const value = headers[name];\n\n if (Array.isArray(value)) {\n return value[0] ?? \"\";\n }\n\n return value ?? \"\";\n}\n\nexport function createWebhookHandler(\n options: WebhookHandlerOptions\n): (req: ExpressLikeRequest, res: ExpressLikeResponse) => Promise<void> {\n return async function webhookHandler(\n req: ExpressLikeRequest,\n res: ExpressLikeResponse\n ): Promise<void> {\n try {\n const rawPayload =\n typeof req.body === \"string\" ? req.body : req.body.toString(\"utf8\");\n const signature = getHeader(\"x-webhook-signature\", req.headers);\n const timestamp = getHeader(\"x-webhook-timestamp\", req.headers);\n const event = getHeader(\"x-webhook-event\", req.headers);\n const deliveryId = getHeader(\"x-webhook-id\", req.headers);\n\n const isValid = verifyWebhook({\n payload: rawPayload,\n signature,\n timestamp,\n secret: options.secret,\n });\n\n if (!isValid) {\n res.status(401).json({ error: \"Invalid signature\" });\n return;\n }\n\n if (!event) {\n res.status(400).json({ error: \"Missing event header\" });\n return;\n }\n\n if (!isWebhookEvent(event)) {\n res.status(400).json({ error: \"Invalid event header\" });\n return;\n }\n\n let parsedPayload: unknown;\n try {\n parsedPayload = JSON.parse(rawPayload) as unknown;\n } catch {\n res.status(400).json({ error: \"Invalid JSON\" });\n return;\n }\n\n if (!isRuntimeWebhookPayload(parsedPayload, event)) {\n res.status(400).json({ error: \"Invalid payload\" });\n return;\n }\n\n const context = { deliveryId, event, timestamp };\n const handler = options.handlers[event] as\n | WebhookEventHandler<typeof event>\n | undefined;\n\n if (handler) {\n await handler(parsedPayload, context);\n } else if (options.onUnhandledEvent) {\n await options.onUnhandledEvent(event, parsedPayload, context);\n }\n\n res.status(200).send(\"OK\");\n } catch {\n res.status(500).json({ error: \"Internal error\" });\n }\n };\n}\n"],"mappings":";AAAA,SAAS,YAAY,uBAAuB;AAE5C,IAAM,4BAA4B;AAqB3B,SAAS,cAAc;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,mBAAmB;AAAA,EACnB,cAAc,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AAC5C,GAAiC;AAC/B,MAAI,CAAC,WAAW,CAAC,aAAa,CAAC,UAAU,cAAc,GAAI,QAAO;AAElE,QAAM,kBAAkB,OAAO,SAAS;AACxC,QAAM,iBACJ,OAAO,cAAc,WAAW,YAAY,OAAO,SAAS;AAE9D,MAAI,CAAC,OAAO,UAAU,cAAc,EAAG,QAAO;AAC9C,MAAI,CAAC,OAAO,SAAS,gBAAgB,KAAK,mBAAmB,EAAG,QAAO;AACvE,MAAI,CAAC,OAAO,SAAS,WAAW,EAAG,QAAO;AAE1C,QAAM,aAAa,KAAK,IAAI,cAAc,cAAc;AACxD,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AiB,CAAC;AAAA,IAClD;AAAA,EACF;AACF;","names":[]}
|
package/dist/adapters/hono.cjs
CHANGED
|
@@ -26,14 +26,26 @@ module.exports = __toCommonJS(hono_exports);
|
|
|
26
26
|
|
|
27
27
|
// src/webhooks/verify.ts
|
|
28
28
|
var import_node_crypto = require("crypto");
|
|
29
|
+
var DEFAULT_TOLERANCE_SECONDS = 300;
|
|
29
30
|
function verifyWebhook({
|
|
30
31
|
payload,
|
|
31
32
|
signature,
|
|
32
|
-
|
|
33
|
+
timestamp,
|
|
34
|
+
secret,
|
|
35
|
+
toleranceSeconds = DEFAULT_TOLERANCE_SECONDS,
|
|
36
|
+
currentTime = Math.floor(Date.now() / 1e3)
|
|
33
37
|
}) {
|
|
34
|
-
if (!payload || !signature || !secret) return false;
|
|
35
|
-
const
|
|
38
|
+
if (!payload || !signature || !secret || timestamp === "") return false;
|
|
39
|
+
const timestampString = String(timestamp);
|
|
40
|
+
const timestampValue = typeof timestamp === "number" ? timestamp : Number(timestamp);
|
|
41
|
+
if (!Number.isInteger(timestampValue)) return false;
|
|
42
|
+
if (!Number.isFinite(toleranceSeconds) || toleranceSeconds < 0) return false;
|
|
43
|
+
if (!Number.isFinite(currentTime)) return false;
|
|
44
|
+
const ageSeconds = Math.abs(currentTime - timestampValue);
|
|
45
|
+
if (ageSeconds > toleranceSeconds) return false;
|
|
46
|
+
const expected = (0, import_node_crypto.createHmac)("sha256", secret).update(`${timestampString}.${payload}`, "utf8").digest("hex");
|
|
36
47
|
if (expected.length !== signature.length) return false;
|
|
48
|
+
if (!/^[a-f0-9]+$/i.test(signature)) return false;
|
|
37
49
|
try {
|
|
38
50
|
return (0, import_node_crypto.timingSafeEqual)(
|
|
39
51
|
Buffer.from(expected, "hex"),
|
|
@@ -44,27 +56,107 @@ function verifyWebhook({
|
|
|
44
56
|
}
|
|
45
57
|
}
|
|
46
58
|
|
|
59
|
+
// src/webhooks/types.ts
|
|
60
|
+
var import_events = require("@whatalo/protocol/events");
|
|
61
|
+
var WEBHOOK_EVENTS = import_events.PUBLIC_WEBHOOK_EVENTS;
|
|
62
|
+
function isWebhookEvent(value) {
|
|
63
|
+
return (0, import_events.isPublicWebhookEvent)(value);
|
|
64
|
+
}
|
|
65
|
+
function isRecord(value) {
|
|
66
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
67
|
+
}
|
|
68
|
+
function hasStringId(value) {
|
|
69
|
+
return isRecord(value) && typeof value.id === "string";
|
|
70
|
+
}
|
|
71
|
+
function isOptionalString(value, key) {
|
|
72
|
+
return value[key] === void 0 || typeof value[key] === "string";
|
|
73
|
+
}
|
|
74
|
+
function isRuntimeWebhookStore(value) {
|
|
75
|
+
return isRecord(value) && typeof value.id === "string" && typeof value.timezone === "string" && (value.name === void 0 || typeof value.name === "string");
|
|
76
|
+
}
|
|
77
|
+
function hasValidBasePayloadFields(value) {
|
|
78
|
+
if (!isOptionalString(value, "event_id")) return false;
|
|
79
|
+
if (!isOptionalString(value, "occurred_at")) return false;
|
|
80
|
+
return isRuntimeWebhookStore(value.store);
|
|
81
|
+
}
|
|
82
|
+
function isRuntimeOrderWebhookPayload(value) {
|
|
83
|
+
return hasValidBasePayloadFields(value) && hasStringId(value.order) && (value.customer === void 0 || hasStringId(value.customer));
|
|
84
|
+
}
|
|
85
|
+
function isRuntimeProductWebhookPayload(value) {
|
|
86
|
+
return hasValidBasePayloadFields(value) && hasStringId(value.product);
|
|
87
|
+
}
|
|
88
|
+
function isRuntimeCustomerWebhookPayload(value) {
|
|
89
|
+
return hasValidBasePayloadFields(value) && hasStringId(value.customer);
|
|
90
|
+
}
|
|
91
|
+
function isRuntimeCheckoutCompletedWebhookPayload(value) {
|
|
92
|
+
return hasValidBasePayloadFields(value) && hasStringId(value.order) && hasStringId(value.customer) && isRuntimeWebhookStore(value.store);
|
|
93
|
+
}
|
|
94
|
+
function isRuntimeCheckoutAbandonedWebhookPayload(value) {
|
|
95
|
+
return hasValidBasePayloadFields(value) && hasStringId(value.checkout) && isRuntimeWebhookStore(value.store);
|
|
96
|
+
}
|
|
97
|
+
function isRuntimeWebhookPayload(value, event) {
|
|
98
|
+
if (!isRecord(value)) return false;
|
|
99
|
+
switch (event) {
|
|
100
|
+
case WEBHOOK_EVENTS.ORDER_CREATED:
|
|
101
|
+
case WEBHOOK_EVENTS.ORDER_UPDATED:
|
|
102
|
+
case WEBHOOK_EVENTS.ORDER_CANCELLED:
|
|
103
|
+
case WEBHOOK_EVENTS.ORDER_COMPLETED:
|
|
104
|
+
return isRuntimeOrderWebhookPayload(value);
|
|
105
|
+
case WEBHOOK_EVENTS.PRODUCT_CREATED:
|
|
106
|
+
case WEBHOOK_EVENTS.PRODUCT_UPDATED:
|
|
107
|
+
case WEBHOOK_EVENTS.PRODUCT_DELETED:
|
|
108
|
+
return isRuntimeProductWebhookPayload(value);
|
|
109
|
+
case WEBHOOK_EVENTS.CUSTOMER_CREATED:
|
|
110
|
+
case WEBHOOK_EVENTS.CUSTOMER_UPDATED:
|
|
111
|
+
return isRuntimeCustomerWebhookPayload(value);
|
|
112
|
+
case WEBHOOK_EVENTS.CHECKOUT_COMPLETED:
|
|
113
|
+
return isRuntimeCheckoutCompletedWebhookPayload(value);
|
|
114
|
+
case WEBHOOK_EVENTS.CHECKOUT_ABANDONED:
|
|
115
|
+
return isRuntimeCheckoutAbandonedWebhookPayload(value);
|
|
116
|
+
default:
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
47
121
|
// src/adapters/hono.ts
|
|
48
122
|
function createWebhookHandler(options) {
|
|
49
123
|
return async function webhookHandler(c) {
|
|
50
124
|
try {
|
|
51
125
|
const rawPayload = await c.req.text();
|
|
52
126
|
const signature = c.req.header("X-Webhook-Signature") ?? "";
|
|
127
|
+
const timestamp = c.req.header("X-Webhook-Timestamp") ?? "";
|
|
128
|
+
const event = c.req.header("X-Webhook-Event") ?? "";
|
|
129
|
+
const deliveryId = c.req.header("X-Webhook-Id") ?? "";
|
|
53
130
|
const isValid = verifyWebhook({
|
|
54
131
|
payload: rawPayload,
|
|
55
132
|
signature,
|
|
133
|
+
timestamp,
|
|
56
134
|
secret: options.secret
|
|
57
135
|
});
|
|
58
136
|
if (!isValid) {
|
|
59
137
|
return c.json({ error: "Invalid signature" }, 401);
|
|
60
138
|
}
|
|
61
|
-
|
|
62
|
-
|
|
139
|
+
if (!event) {
|
|
140
|
+
return c.json({ error: "Missing event header" }, 400);
|
|
141
|
+
}
|
|
142
|
+
if (!isWebhookEvent(event)) {
|
|
143
|
+
return c.json({ error: "Invalid event header" }, 400);
|
|
144
|
+
}
|
|
145
|
+
let parsedPayload;
|
|
146
|
+
try {
|
|
147
|
+
parsedPayload = JSON.parse(rawPayload);
|
|
148
|
+
} catch {
|
|
149
|
+
return c.json({ error: "Invalid JSON" }, 400);
|
|
150
|
+
}
|
|
151
|
+
if (!isRuntimeWebhookPayload(parsedPayload, event)) {
|
|
152
|
+
return c.json({ error: "Invalid payload" }, 400);
|
|
153
|
+
}
|
|
154
|
+
const context = { deliveryId, event, timestamp };
|
|
63
155
|
const handler = options.handlers[event];
|
|
64
156
|
if (handler) {
|
|
65
|
-
await handler(
|
|
157
|
+
await handler(parsedPayload, context);
|
|
66
158
|
} else if (options.onUnhandledEvent) {
|
|
67
|
-
await options.onUnhandledEvent(event,
|
|
159
|
+
await options.onUnhandledEvent(event, parsedPayload, context);
|
|
68
160
|
}
|
|
69
161
|
return c.text("OK", 200);
|
|
70
162
|
} catch {
|