@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.
Files changed (59) hide show
  1. package/dist/adapters/express.cjs +106 -10
  2. package/dist/adapters/express.cjs.map +1 -1
  3. package/dist/adapters/express.d.cts +9 -7
  4. package/dist/adapters/express.d.ts +9 -7
  5. package/dist/adapters/express.mjs +109 -10
  6. package/dist/adapters/express.mjs.map +1 -1
  7. package/dist/adapters/hono.cjs +99 -7
  8. package/dist/adapters/hono.cjs.map +1 -1
  9. package/dist/adapters/hono.d.cts +4 -3
  10. package/dist/adapters/hono.d.ts +4 -3
  11. package/dist/adapters/hono.mjs +102 -7
  12. package/dist/adapters/hono.mjs.map +1 -1
  13. package/dist/adapters/nextjs.cjs +99 -7
  14. package/dist/adapters/nextjs.cjs.map +1 -1
  15. package/dist/adapters/nextjs.d.cts +4 -3
  16. package/dist/adapters/nextjs.d.ts +4 -3
  17. package/dist/adapters/nextjs.mjs +102 -7
  18. package/dist/adapters/nextjs.mjs.map +1 -1
  19. package/dist/bridge/index.cjs +60 -5
  20. package/dist/bridge/index.cjs.map +1 -1
  21. package/dist/bridge/index.d.cts +17 -5
  22. package/dist/bridge/index.d.ts +17 -5
  23. package/dist/bridge/index.mjs +60 -5
  24. package/dist/bridge/index.mjs.map +1 -1
  25. package/dist/client/index.cjs +33 -2
  26. package/dist/client/index.cjs.map +1 -1
  27. package/dist/client/index.d.cts +29 -1
  28. package/dist/client/index.d.ts +29 -1
  29. package/dist/client/index.mjs +33 -2
  30. package/dist/client/index.mjs.map +1 -1
  31. package/dist/index.cjs +179 -28
  32. package/dist/index.cjs.map +1 -1
  33. package/dist/index.d.cts +7 -4
  34. package/dist/index.d.ts +7 -4
  35. package/dist/index.mjs +179 -28
  36. package/dist/index.mjs.map +1 -1
  37. package/dist/manifest/index.cjs +2 -17
  38. package/dist/manifest/index.cjs.map +1 -1
  39. package/dist/manifest/index.d.cts +10 -4
  40. package/dist/manifest/index.d.ts +10 -4
  41. package/dist/manifest/index.mjs +2 -17
  42. package/dist/manifest/index.mjs.map +1 -1
  43. package/dist/{types-DcmArIC2.d.ts → types-B8BAV362.d.cts} +24 -1
  44. package/dist/{types-DcmArIC2.d.cts → types-B8BAV362.d.ts} +24 -1
  45. package/dist/types-Bzee9Hvr.d.ts +25 -0
  46. package/dist/types-CDKGAQ3o.d.ts +155 -0
  47. package/dist/types-CPnSzOfX.d.cts +155 -0
  48. package/dist/types-CqyAhbXM.d.cts +25 -0
  49. package/dist/webhooks/index.cjs +83 -3
  50. package/dist/webhooks/index.cjs.map +1 -1
  51. package/dist/webhooks/index.d.cts +11 -4
  52. package/dist/webhooks/index.d.ts +11 -4
  53. package/dist/webhooks/index.mjs +83 -3
  54. package/dist/webhooks/index.mjs.map +1 -1
  55. package/package.json +4 -1
  56. package/dist/types-C9mg4aQg.d.ts +0 -19
  57. package/dist/types-DMuHSL_a.d.cts +0 -19
  58. package/dist/types-DTjA3FHe.d.ts +0 -68
  59. package/dist/types-tHUO9u-c.d.cts +0 -68
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/adapters/hono.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\nexport type HonoContextLike = {\n req: {\n text: () => Promise<string>;\n header: (name: string) => string | undefined;\n };\n json: (body: unknown, status?: number) => unknown;\n text: (body: string, status?: number) => unknown;\n};\n\nexport function createWebhookHandler(\n options: WebhookHandlerOptions\n): (c: HonoContextLike) => Promise<unknown> {\n return async function webhookHandler(c: HonoContextLike): Promise<unknown> {\n try {\n const rawPayload = await c.req.text();\n const signature = c.req.header(\"X-Webhook-Signature\") ?? \"\";\n\n const isValid = verifyWebhook({\n payload: rawPayload,\n signature,\n secret: options.secret,\n });\n\n if (!isValid) {\n return c.json({ error: \"Invalid signature\" }, 401);\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 return c.text(\"OK\", 200);\n } catch {\n return c.json({ error: \"Internal error\" }, 500);\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;;;ADvBO,SAAS,qBACd,SAC0C;AAC1C,SAAO,eAAe,eAAe,GAAsC;AACzE,QAAI;AACF,YAAM,aAAa,MAAM,EAAE,IAAI,KAAK;AACpC,YAAM,YAAY,EAAE,IAAI,OAAO,qBAAqB,KAAK;AAEzD,YAAM,UAAU,cAAc;AAAA,QAC5B,SAAS;AAAA,QACT;AAAA,QACA,QAAQ,QAAQ;AAAA,MAClB,CAAC;AAED,UAAI,CAAC,SAAS;AACZ,eAAO,EAAE,KAAK,EAAE,OAAO,oBAAoB,GAAG,GAAG;AAAA,MACnD;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,aAAO,EAAE,KAAK,MAAM,GAAG;AAAA,IACzB,QAAQ;AACN,aAAO,EAAE,KAAK,EAAE,OAAO,iBAAiB,GAAG,GAAG;AAAA,IAChD;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/adapters/hono.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\nexport type HonoContextLike = {\n req: {\n text: () => Promise<string>;\n header: (name: string) => string | undefined;\n };\n json: (body: unknown, status?: number) => unknown;\n text: (body: string, status?: number) => unknown;\n};\n\nexport function createWebhookHandler(\n options: WebhookHandlerOptions\n): (c: HonoContextLike) => Promise<unknown> {\n return async function webhookHandler(c: HonoContextLike): Promise<unknown> {\n try {\n const rawPayload = await c.req.text();\n const signature = c.req.header(\"X-Webhook-Signature\") ?? \"\";\n const timestamp = c.req.header(\"X-Webhook-Timestamp\") ?? \"\";\n const event = c.req.header(\"X-Webhook-Event\") ?? \"\";\n const deliveryId = c.req.header(\"X-Webhook-Id\") ?? \"\";\n\n const isValid = verifyWebhook({\n payload: rawPayload,\n signature,\n timestamp,\n secret: options.secret,\n });\n\n if (!isValid) {\n return c.json({ error: \"Invalid signature\" }, 401);\n }\n\n if (!event) {\n return c.json({ error: \"Missing event header\" }, 400);\n }\n\n if (!isWebhookEvent(event)) {\n return c.json({ error: \"Invalid event header\" }, 400);\n }\n\n let parsedPayload: unknown;\n try {\n parsedPayload = JSON.parse(rawPayload) as unknown;\n } catch {\n return c.json({ error: \"Invalid JSON\" }, 400);\n }\n\n if (!isRuntimeWebhookPayload(parsedPayload, event)) {\n return c.json({ error: \"Invalid payload\" }, 400);\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 return c.text(\"OK\", 200);\n } catch {\n return c.json({ error: \"Internal error\" }, 500);\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,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,MAAI,aAAa,iBAAkB,QAAO;AAE1C,QAAM,eAAW,+BAAW,UAAU,MAAM,EACzC,OAAO,GAAG,eAAe,IAAI,OAAO,IAAI,MAAM,EAC9C,OAAO,KAAK;AAEf,MAAI,SAAS,WAAW,UAAU,OAAQ,QAAO;AACjD,MAAI,CAAC,eAAe,KAAK,SAAS,EAAG,QAAO;AAE5C,MAAI;A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AAE,OAAO,uBAAuB,GAAG,GAAG;AAAA,MACtD;AAEA,UAAI,CAAC,eAAe,KAAK,GAAG;AAC1B,eAAO,EAAE,KAAK,EAAE,OAAO,uBAAuB,GAAG,GAAG;AAAA,MACtD;AAEA,UAAI;AACJ,UAAI;AACF,wBAAgB,KAAK,MAAM,UAAU;AAAA,MACvC,QAAQ;AACN,eAAO,EAAE,KAAK,EAAE,OAAO,eAAe,GAAG,GAAG;AAAA,MAC9C;AAEA,UAAI,CAAC,wBAAwB,eAAe,KAAK,GAAG;AAClD,eAAO,EAAE,KAAK,EAAE,OAAO,kBAAkB,GAAG,GAAG;AAAA,MACjD;AAEA,YAAM,UAAU,EAAE,YAAY,OAAO,UAAU;AAC/C,YAAM,UAAU,QAAQ,SAAS,KAAK;AAItC,UAAI,SAAS;AACX,cAAM,QAAQ,eAAe,OAAO;AAAA,MACtC,WAAW,QAAQ,kBAAkB;AACnC,cAAM,QAAQ,iBAAiB,OAAO,eAAe,OAAO;AAAA,MAC9D;AAEA,aAAO,EAAE,KAAK,MAAM,GAAG;AAAA,IACzB,QAAQ;AACN,aAAO,EAAE,KAAK,EAAE,OAAO,iBAAiB,GAAG,GAAG;AAAA,IAChD;AAAA,EACF;AACF;","names":[]}
@@ -1,6 +1,7 @@
1
- import { W as WebhookHandlerOptions } from '../types-DMuHSL_a.cjs';
2
- import '../types-tHUO9u-c.cjs';
3
- import '../types-DcmArIC2.cjs';
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 HonoContextLike = {
6
7
  req: {
@@ -1,6 +1,7 @@
1
- import { W as WebhookHandlerOptions } from '../types-C9mg4aQg.js';
2
- import '../types-DTjA3FHe.js';
3
- import '../types-DcmArIC2.js';
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 HonoContextLike = {
6
7
  req: {
@@ -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
- secret
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 expected = createHmac("sha256", secret).update(payload, "utf8").digest("hex");
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,27 +30,110 @@ 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/hono.ts
22
99
  function createWebhookHandler(options) {
23
100
  return async function webhookHandler(c) {
24
101
  try {
25
102
  const rawPayload = await c.req.text();
26
103
  const signature = c.req.header("X-Webhook-Signature") ?? "";
104
+ const timestamp = c.req.header("X-Webhook-Timestamp") ?? "";
105
+ const event = c.req.header("X-Webhook-Event") ?? "";
106
+ const deliveryId = c.req.header("X-Webhook-Id") ?? "";
27
107
  const isValid = verifyWebhook({
28
108
  payload: rawPayload,
29
109
  signature,
110
+ timestamp,
30
111
  secret: options.secret
31
112
  });
32
113
  if (!isValid) {
33
114
  return c.json({ error: "Invalid signature" }, 401);
34
115
  }
35
- const payload = JSON.parse(rawPayload);
36
- const event = payload.event;
116
+ if (!event) {
117
+ return c.json({ error: "Missing event header" }, 400);
118
+ }
119
+ if (!isWebhookEvent(event)) {
120
+ return c.json({ error: "Invalid event header" }, 400);
121
+ }
122
+ let parsedPayload;
123
+ try {
124
+ parsedPayload = JSON.parse(rawPayload);
125
+ } catch {
126
+ return c.json({ error: "Invalid JSON" }, 400);
127
+ }
128
+ if (!isRuntimeWebhookPayload(parsedPayload, event)) {
129
+ return c.json({ error: "Invalid payload" }, 400);
130
+ }
131
+ const context = { deliveryId, event, timestamp };
37
132
  const handler = options.handlers[event];
38
133
  if (handler) {
39
- await handler(payload);
134
+ await handler(parsedPayload, context);
40
135
  } else if (options.onUnhandledEvent) {
41
- await options.onUnhandledEvent(event, payload);
136
+ await options.onUnhandledEvent(event, parsedPayload, context);
42
137
  }
43
138
  return c.text("OK", 200);
44
139
  } catch {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/webhooks/verify.ts","../../src/adapters/hono.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\nexport type HonoContextLike = {\n req: {\n text: () => Promise<string>;\n header: (name: string) => string | undefined;\n };\n json: (body: unknown, status?: number) => unknown;\n text: (body: string, status?: number) => unknown;\n};\n\nexport function createWebhookHandler(\n options: WebhookHandlerOptions\n): (c: HonoContextLike) => Promise<unknown> {\n return async function webhookHandler(c: HonoContextLike): Promise<unknown> {\n try {\n const rawPayload = await c.req.text();\n const signature = c.req.header(\"X-Webhook-Signature\") ?? \"\";\n\n const isValid = verifyWebhook({\n payload: rawPayload,\n signature,\n secret: options.secret,\n });\n\n if (!isValid) {\n return c.json({ error: \"Invalid signature\" }, 401);\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 return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 {"version":3,"sources":["../../src/webhooks/verify.ts","../../src/webhooks/types.ts","../../src/adapters/hono.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\nexport type HonoContextLike = {\n req: {\n text: () => Promise<string>;\n header: (name: string) => string | undefined;\n };\n json: (body: unknown, status?: number) => unknown;\n text: (body: string, status?: number) => unknown;\n};\n\nexport function createWebhookHandler(\n options: WebhookHandlerOptions\n): (c: HonoContextLike) => Promise<unknown> {\n return async function webhookHandler(c: HonoContextLike): Promise<unknown> {\n try {\n const rawPayload = await c.req.text();\n const signature = c.req.header(\"X-Webhook-Signature\") ?? \"\";\n const timestamp = c.req.header(\"X-Webhook-Timestamp\") ?? \"\";\n const event = c.req.header(\"X-Webhook-Event\") ?? \"\";\n const deliveryId = c.req.header(\"X-Webhook-Id\") ?? \"\";\n\n const isValid = verifyWebhook({\n payload: rawPayload,\n signature,\n timestamp,\n secret: options.secret,\n });\n\n if (!isValid) {\n return c.json({ error: \"Invalid signature\" }, 401);\n }\n\n if (!event) {\n return c.json({ error: \"Missing event header\" }, 400);\n }\n\n if (!isWebhookEvent(event)) {\n return c.json({ error: \"Invalid event header\" }, 400);\n }\n\n let parsedPayload: unknown;\n try {\n parsedPayload = JSON.parse(rawPayload) as unknown;\n } catch {\n return c.json({ error: \"Invalid JSON\" }, 400);\n }\n\n if (!isRuntimeWebhookPayload(parsedPayload, event)) {\n return c.json({ error: \"Invalid payload\" }, 400);\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 return c.text(\"OK\", 200);\n } catch {\n return c.json({ error: \"Internal error\" }, 500);\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,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ChD;AAAA,EACF;AACF;","names":[]}
@@ -26,14 +26,26 @@ module.exports = __toCommonJS(nextjs_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
- secret
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 expected = (0, import_node_crypto.createHmac)("sha256", secret).update(payload, "utf8").digest("hex");
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/nextjs.ts
48
122
  function createWebhookHandler(options) {
49
123
  return async function webhookHandler(request) {
50
124
  try {
51
125
  const rawPayload = await request.text();
52
126
  const signature = request.headers.get("X-Webhook-Signature") ?? "";
127
+ const timestamp = request.headers.get("X-Webhook-Timestamp") ?? "";
128
+ const event = request.headers.get("X-Webhook-Event") ?? "";
129
+ const deliveryId = request.headers.get("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 new Response("Invalid signature", { status: 401 });
60
138
  }
61
- const payload = JSON.parse(rawPayload);
62
- const event = payload.event;
139
+ if (!event) {
140
+ return new Response("Missing event header", { status: 400 });
141
+ }
142
+ if (!isWebhookEvent(event)) {
143
+ return new Response("Invalid event header", { status: 400 });
144
+ }
145
+ let parsedPayload;
146
+ try {
147
+ parsedPayload = JSON.parse(rawPayload);
148
+ } catch {
149
+ return new Response("Invalid JSON", { status: 400 });
150
+ }
151
+ if (!isRuntimeWebhookPayload(parsedPayload, event)) {
152
+ return new Response("Invalid payload", { status: 400 });
153
+ }
154
+ const context = { deliveryId, event, timestamp };
63
155
  const handler = options.handlers[event];
64
156
  if (handler) {
65
- await handler(payload);
157
+ await handler(parsedPayload, context);
66
158
  } else if (options.onUnhandledEvent) {
67
- await options.onUnhandledEvent(event, payload);
159
+ await options.onUnhandledEvent(event, parsedPayload, context);
68
160
  }
69
161
  return new Response("OK", { status: 200 });
70
162
  } catch {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/adapters/nextjs.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\nexport function createWebhookHandler(\n options: WebhookHandlerOptions\n): (request: Request) => Promise<Response> {\n return async function webhookHandler(request: Request): Promise<Response> {\n try {\n const rawPayload = await request.text();\n const signature = request.headers.get(\"X-Webhook-Signature\") ?? \"\";\n\n const isValid = verifyWebhook({\n payload: rawPayload,\n signature,\n secret: options.secret,\n });\n\n if (!isValid) {\n return new Response(\"Invalid signature\", { status: 401 });\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 return new Response(\"OK\", { status: 200 });\n } catch {\n return new Response(\"Internal error\", { status: 500 });\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,SAA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hook } from \"../webhooks/verify.js\";\nimport { isRuntimeWebhookPayload, isWebhookEvent } from \"../webhooks/types.js\";\nimport type { WebhookEventHandler, WebhookHandlerOptions } from \"./types.js\";\n\nexport function createWebhookHandler(\n options: WebhookHandlerOptions\n): (request: Request) => Promise<Response> {\n return async function webhookHandler(request: Request): Promise<Response> {\n try {\n const rawPayload = await request.text();\n const signature = request.headers.get(\"X-Webhook-Signature\") ?? \"\";\n const timestamp = request.headers.get(\"X-Webhook-Timestamp\") ?? \"\";\n const event = request.headers.get(\"X-Webhook-Event\") ?? \"\";\n const deliveryId = request.headers.get(\"X-Webhook-Id\") ?? \"\";\n\n const isValid = verifyWebhook({\n payload: rawPayload,\n signature,\n timestamp,\n secret: options.secret,\n });\n\n if (!isValid) {\n return new Response(\"Invalid signature\", { status: 401 });\n }\n\n if (!event) {\n return new Response(\"Missing event header\", { status: 400 });\n }\n\n if (!isWebhookEvent(event)) {\n return new Response(\"Invalid event header\", { status: 400 });\n }\n\n let parsedPayload: unknown;\n try {\n parsedPayload = JSON.parse(rawPayload) as unknown;\n } catch {\n return new Response(\"Invalid JSON\", { status: 400 });\n }\n\n if (!isRuntimeWebhookPayload(parsedPayload, event)) {\n return new Response(\"Invalid payload\", { status: 400 });\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 return new Response(\"OK\", { status: 200 });\n } catch {\n return new Response(\"Internal error\", { status: 500 });\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,QAAO;AAC9C,MAAI,CAAC,OAAO,SAAS,gBAAgB,KAAK,mBAAmB,EAAG,QAAO;AACvE,MAAI,CAAC,OAAO,SAAS,WAAW,EAAG,QAA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Options } from '../types-CqyAhbXM.cjs';
2
+ import '../types-CPnSzOfX.cjs';
3
+ import '@whatalo/protocol/events';
4
+ import '../types-B8BAV362.cjs';
4
5
 
5
6
  declare function createWebhookHandler(options: WebhookHandlerOptions): (request: Request) => Promise<Response>;
6
7
 
@@ -1,6 +1,7 @@
1
- import { W as WebhookHandlerOptions } from '../types-C9mg4aQg.js';
2
- import '../types-DTjA3FHe.js';
3
- import '../types-DcmArIC2.js';
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
  declare function createWebhookHandler(options: WebhookHandlerOptions): (request: Request) => Promise<Response>;
6
7
 
@@ -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
- secret
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 expected = createHmac("sha256", secret).update(payload, "utf8").digest("hex");
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,27 +30,110 @@ 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/nextjs.ts
22
99
  function createWebhookHandler(options) {
23
100
  return async function webhookHandler(request) {
24
101
  try {
25
102
  const rawPayload = await request.text();
26
103
  const signature = request.headers.get("X-Webhook-Signature") ?? "";
104
+ const timestamp = request.headers.get("X-Webhook-Timestamp") ?? "";
105
+ const event = request.headers.get("X-Webhook-Event") ?? "";
106
+ const deliveryId = request.headers.get("X-Webhook-Id") ?? "";
27
107
  const isValid = verifyWebhook({
28
108
  payload: rawPayload,
29
109
  signature,
110
+ timestamp,
30
111
  secret: options.secret
31
112
  });
32
113
  if (!isValid) {
33
114
  return new Response("Invalid signature", { status: 401 });
34
115
  }
35
- const payload = JSON.parse(rawPayload);
36
- const event = payload.event;
116
+ if (!event) {
117
+ return new Response("Missing event header", { status: 400 });
118
+ }
119
+ if (!isWebhookEvent(event)) {
120
+ return new Response("Invalid event header", { status: 400 });
121
+ }
122
+ let parsedPayload;
123
+ try {
124
+ parsedPayload = JSON.parse(rawPayload);
125
+ } catch {
126
+ return new Response("Invalid JSON", { status: 400 });
127
+ }
128
+ if (!isRuntimeWebhookPayload(parsedPayload, event)) {
129
+ return new Response("Invalid payload", { status: 400 });
130
+ }
131
+ const context = { deliveryId, event, timestamp };
37
132
  const handler = options.handlers[event];
38
133
  if (handler) {
39
- await handler(payload);
134
+ await handler(parsedPayload, context);
40
135
  } else if (options.onUnhandledEvent) {
41
- await options.onUnhandledEvent(event, payload);
136
+ await options.onUnhandledEvent(event, parsedPayload, context);
42
137
  }
43
138
  return new Response("OK", { status: 200 });
44
139
  } catch {