@open-mercato/webhooks 0.6.7-develop.6795.1.8a3f27921c → 0.6.7-develop.6824.1.21fff90682

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.
@@ -68,6 +68,21 @@ test.describe("TC-WEBHOOK-003: Inbound webhook receiver", () => {
68
68
  });
69
69
  expect(replayWithoutMessageIdDuplicateResponse.status()).toBe(200);
70
70
  await expect(replayWithoutMessageIdDuplicateResponse.json()).resolves.toEqual({ ok: true, duplicate: true });
71
+ const staleTimestampResponse = await request.fetch(`${BASE_URL}/api/webhooks/inbound/mock_inbound`, {
72
+ method: "POST",
73
+ headers: {
74
+ "content-type": "application/json",
75
+ "x-mock-webhook-signature": validSignature,
76
+ "webhook-id": `stale-${Date.now()}`,
77
+ "webhook-timestamp": String(Math.floor(Date.now() / 1e3) - 10 * 60),
78
+ "webhook-signature": "v1,mock"
79
+ },
80
+ data: rawBody
81
+ });
82
+ expect(staleTimestampResponse.status()).toBe(400);
83
+ await expect(staleTimestampResponse.json()).resolves.toEqual({
84
+ error: "Webhook timestamp is outside the allowed replay window"
85
+ });
71
86
  const invalidSignatureResponse = await request.fetch(`${BASE_URL}/api/webhooks/inbound/mock_inbound`, {
72
87
  method: "POST",
73
88
  headers: {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/webhooks/__integration__/TC-WEBHOOK-003.spec.ts"],
4
- "sourcesContent": ["import { createHmac } from 'node:crypto';\nimport { expect, test } from '@playwright/test';\n\nconst BASE_URL = process.env.BASE_URL?.trim() || 'http://localhost:3000';\n\n// Mirrors the create-app mock inbound webhook adapter, which verifies an HMAC-SHA256\n// signature over the raw request body in the x-mock-webhook-signature header. The running\n// app resolves its secret from MOCK_INBOUND_WEBHOOK_SECRET (exported by the CI workflow so\n// it works even when `yarn start` forces NODE_ENV=production); we read the SAME env var here\n// so the test signs with the same key. The dev fallback is only a local-default convenience.\nconst MOCK_INBOUND_WEBHOOK_SECRET =\n process.env.MOCK_INBOUND_WEBHOOK_SECRET?.trim() || 'open-mercato-mock-dev-inbound-webhook-secret';\n\nfunction signMockInboundWebhook(rawBody: string): string {\n return createHmac('sha256', MOCK_INBOUND_WEBHOOK_SECRET).update(rawBody, 'utf-8').digest('hex');\n}\n\ntest.describe('TC-WEBHOOK-003: Inbound webhook receiver', () => {\n test('should accept valid inbound webhooks, mark duplicates, and reject invalid endpoints or signatures', async ({ request }) => {\n const messageId = `msg-${Date.now()}`;\n const replayTimestamp = String(Math.floor(Date.now() / 1000));\n const payload = {\n type: 'mock.inbound.received',\n timestamp: new Date().toISOString(),\n data: {\n externalId: `ext-${Date.now()}`,\n },\n };\n const rawBody = JSON.stringify(payload);\n const validSignature = signMockInboundWebhook(rawBody);\n\n const firstResponse = await request.fetch(`${BASE_URL}/api/webhooks/inbound/mock_inbound`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'x-mock-webhook-signature': validSignature,\n 'webhook-id': messageId,\n 'webhook-timestamp': replayTimestamp,\n 'webhook-signature': 'v1,mock',\n },\n data: rawBody,\n });\n expect(firstResponse.status()).toBe(200);\n await expect(firstResponse.json()).resolves.toEqual({ ok: true });\n\n const duplicateResponse = await request.fetch(`${BASE_URL}/api/webhooks/inbound/mock_inbound`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'x-mock-webhook-signature': validSignature,\n 'webhook-id': messageId,\n 'webhook-timestamp': replayTimestamp,\n 'webhook-signature': 'v1,mock',\n },\n data: rawBody,\n });\n expect(duplicateResponse.status()).toBe(200);\n await expect(duplicateResponse.json()).resolves.toEqual({ ok: true, duplicate: true });\n\n const replayWithoutMessageIdResponse = await request.fetch(`${BASE_URL}/api/webhooks/inbound/mock_inbound`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'x-mock-webhook-signature': validSignature,\n 'webhook-timestamp': replayTimestamp,\n 'webhook-signature': 'v1,mock',\n },\n data: rawBody,\n });\n expect(replayWithoutMessageIdResponse.status()).toBe(200);\n await expect(replayWithoutMessageIdResponse.json()).resolves.toEqual({ ok: true });\n\n const replayWithoutMessageIdDuplicateResponse = await request.fetch(`${BASE_URL}/api/webhooks/inbound/mock_inbound`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'x-mock-webhook-signature': validSignature,\n 'webhook-timestamp': replayTimestamp,\n 'webhook-signature': 'v1,mock',\n },\n data: rawBody,\n });\n expect(replayWithoutMessageIdDuplicateResponse.status()).toBe(200);\n await expect(replayWithoutMessageIdDuplicateResponse.json()).resolves.toEqual({ ok: true, duplicate: true });\n\n const invalidSignatureResponse = await request.fetch(`${BASE_URL}/api/webhooks/inbound/mock_inbound`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'x-mock-webhook-signature': 'invalid',\n },\n data: rawBody,\n });\n expect(invalidSignatureResponse.status()).toBe(400);\n await expect(invalidSignatureResponse.json()).resolves.toEqual({ error: 'Verification failed' });\n\n const unknownEndpointResponse = await request.fetch(`${BASE_URL}/api/webhooks/inbound/missing_endpoint`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'x-mock-webhook-signature': validSignature,\n },\n data: rawBody,\n });\n expect(unknownEndpointResponse.status()).toBe(404);\n await expect(unknownEndpointResponse.json()).resolves.toEqual({ error: 'Webhook endpoint not found' });\n });\n});\n"],
5
- "mappings": "AAAA,SAAS,kBAAkB;AAC3B,SAAS,QAAQ,YAAY;AAE7B,MAAM,WAAW,QAAQ,IAAI,UAAU,KAAK,KAAK;AAOjD,MAAM,8BACJ,QAAQ,IAAI,6BAA6B,KAAK,KAAK;AAErD,SAAS,uBAAuB,SAAyB;AACvD,SAAO,WAAW,UAAU,2BAA2B,EAAE,OAAO,SAAS,OAAO,EAAE,OAAO,KAAK;AAChG;AAEA,KAAK,SAAS,4CAA4C,MAAM;AAC9D,OAAK,qGAAqG,OAAO,EAAE,QAAQ,MAAM;AAC/H,UAAM,YAAY,OAAO,KAAK,IAAI,CAA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cesContent": ["import { createHmac } from 'node:crypto';\nimport { expect, test } from '@playwright/test';\n\nconst BASE_URL = process.env.BASE_URL?.trim() || 'http://localhost:3000';\n\n// Mirrors the create-app mock inbound webhook adapter, which verifies an HMAC-SHA256\n// signature over the raw request body in the x-mock-webhook-signature header. The running\n// app resolves its secret from MOCK_INBOUND_WEBHOOK_SECRET (exported by the CI workflow so\n// it works even when `yarn start` forces NODE_ENV=production); we read the SAME env var here\n// so the test signs with the same key. The dev fallback is only a local-default convenience.\nconst MOCK_INBOUND_WEBHOOK_SECRET =\n process.env.MOCK_INBOUND_WEBHOOK_SECRET?.trim() || 'open-mercato-mock-dev-inbound-webhook-secret';\n\nfunction signMockInboundWebhook(rawBody: string): string {\n return createHmac('sha256', MOCK_INBOUND_WEBHOOK_SECRET).update(rawBody, 'utf-8').digest('hex');\n}\n\ntest.describe('TC-WEBHOOK-003: Inbound webhook receiver', () => {\n test('should accept valid inbound webhooks, mark duplicates, and reject invalid endpoints or signatures', async ({ request }) => {\n const messageId = `msg-${Date.now()}`;\n const replayTimestamp = String(Math.floor(Date.now() / 1000));\n const payload = {\n type: 'mock.inbound.received',\n timestamp: new Date().toISOString(),\n data: {\n externalId: `ext-${Date.now()}`,\n },\n };\n const rawBody = JSON.stringify(payload);\n const validSignature = signMockInboundWebhook(rawBody);\n\n const firstResponse = await request.fetch(`${BASE_URL}/api/webhooks/inbound/mock_inbound`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'x-mock-webhook-signature': validSignature,\n 'webhook-id': messageId,\n 'webhook-timestamp': replayTimestamp,\n 'webhook-signature': 'v1,mock',\n },\n data: rawBody,\n });\n expect(firstResponse.status()).toBe(200);\n await expect(firstResponse.json()).resolves.toEqual({ ok: true });\n\n const duplicateResponse = await request.fetch(`${BASE_URL}/api/webhooks/inbound/mock_inbound`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'x-mock-webhook-signature': validSignature,\n 'webhook-id': messageId,\n 'webhook-timestamp': replayTimestamp,\n 'webhook-signature': 'v1,mock',\n },\n data: rawBody,\n });\n expect(duplicateResponse.status()).toBe(200);\n await expect(duplicateResponse.json()).resolves.toEqual({ ok: true, duplicate: true });\n\n const replayWithoutMessageIdResponse = await request.fetch(`${BASE_URL}/api/webhooks/inbound/mock_inbound`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'x-mock-webhook-signature': validSignature,\n 'webhook-timestamp': replayTimestamp,\n 'webhook-signature': 'v1,mock',\n },\n data: rawBody,\n });\n expect(replayWithoutMessageIdResponse.status()).toBe(200);\n await expect(replayWithoutMessageIdResponse.json()).resolves.toEqual({ ok: true });\n\n const replayWithoutMessageIdDuplicateResponse = await request.fetch(`${BASE_URL}/api/webhooks/inbound/mock_inbound`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'x-mock-webhook-signature': validSignature,\n 'webhook-timestamp': replayTimestamp,\n 'webhook-signature': 'v1,mock',\n },\n data: rawBody,\n });\n expect(replayWithoutMessageIdDuplicateResponse.status()).toBe(200);\n await expect(replayWithoutMessageIdDuplicateResponse.json()).resolves.toEqual({ ok: true, duplicate: true });\n\n const staleTimestampResponse = await request.fetch(`${BASE_URL}/api/webhooks/inbound/mock_inbound`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'x-mock-webhook-signature': validSignature,\n 'webhook-id': `stale-${Date.now()}`,\n 'webhook-timestamp': String(Math.floor(Date.now() / 1000) - 10 * 60),\n 'webhook-signature': 'v1,mock',\n },\n data: rawBody,\n });\n expect(staleTimestampResponse.status()).toBe(400);\n await expect(staleTimestampResponse.json()).resolves.toEqual({\n error: 'Webhook timestamp is outside the allowed replay window',\n });\n\n const invalidSignatureResponse = await request.fetch(`${BASE_URL}/api/webhooks/inbound/mock_inbound`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'x-mock-webhook-signature': 'invalid',\n },\n data: rawBody,\n });\n expect(invalidSignatureResponse.status()).toBe(400);\n await expect(invalidSignatureResponse.json()).resolves.toEqual({ error: 'Verification failed' });\n\n const unknownEndpointResponse = await request.fetch(`${BASE_URL}/api/webhooks/inbound/missing_endpoint`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'x-mock-webhook-signature': validSignature,\n },\n data: rawBody,\n });\n expect(unknownEndpointResponse.status()).toBe(404);\n await expect(unknownEndpointResponse.json()).resolves.toEqual({ error: 'Webhook endpoint not found' });\n });\n});\n"],
5
+ "mappings": "AAAA,SAAS,kBAAkB;AAC3B,SAAS,QAAQ,YAAY;AAE7B,MAAM,WAAW,QAAQ,IAAI,UAAU,KAAK,KAAK;AAOjD,MAAM,8BACJ,QAAQ,IAAI,6BAA6B,KAAK,KAAK;AAErD,SAAS,uBAAuB,SAAyB;AACvD,SAAO,WAAW,UAAU,2BAA2B,EAAE,OAAO,SAAS,OAAO,EAAE,OAAO,KAAK;AAChG;AAEA,KAAK,SAAS,4CAA4C,MAAM;AAC9D,OAAK,qGAAqG,OAAO,EAAE,QAAQ,MAAM;AAC/H,UAAM,YAAY,OAAO,KAAK,IAAI,CAAC;AACnC,UAAM,kBAAkB,OAAO,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI,CAAC;AAC5D,UAAM,UAAU;AAAA,MACd,MAAM;AAAA,MACN,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,MAClC,MAAM;AAAA,QACJ,YAAY,OAAO,KAAK,IAAI,CAAC;AAAA,MAC/B;AAAA,IACF;AACA,UAAM,UAAU,KAAK,UAAU,OAAO;AACtC,UAAM,iBAAiB,uBAAuB,OAAO;AAErD,UAAM,gBAAgB,MAAM,QAAQ,MAAM,GAAG,QAAQ,sCAAsC;AAAA,MACzF,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,gBAAgB;AAAA,QAChB,4BAA4B;AAAA,QAC5B,cAAc;AAAA,QACd,qBAAqB;AAAA,QACrB,qBAAqB;AAAA,MACvB;AAAA,MACA,MAAM;AAAA,IACR,CAAC;AACD,WAAO,cAAc,OAAO,CAA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AyB,MAAM,QAAQ,MAAM,GAAG,QAAQ,sCAAsC;AAAA,MAClG,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,gBAAgB;AAAA,QAChB,4BAA4B;AAAA,QAC5B,cAAc,SAAS,KAAK,IAAI,CAAC;AAAA,QACjC,qBAAqB,OAAO,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI,IAAI,KAAK,EAAE;AAAA,QACnE,qBAAqB;AAAA,MACvB;AAAA,MACA,MAAM;AAAA,IACR,CAAC;AACD,WAAO,uBAAuB,OAAO,CAAC,EAAE,KAAK,GAAG;AAChD,UAAM,OAAO,uBAAuB,KAAK,CAAC,EAAE,SAAS,QAAQ;AAAA,MAC3D,OAAO;AAAA,IACT,CAAC;AAED,UAAM,2BAA2B,MAAM,QAAQ,MAAM,GAAG,QAAQ,sCAAsC;AAAA,MACpG,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,gBAAgB;AAAA,QAChB,4BAA4B;AAAA,MAC9B;AAAA,MACA,MAAM;AAAA,IACR,CAAC;AACD,WAAO,yBAAyB,OAAO,CAAC,EAAE,KAAK,GAAG;AAClD,UAAM,OAAO,yBAAyB,KAAK,CAAC,EAAE,SAAS,QAAQ,EAAE,OAAO,sBAAsB,CAAC;AAE/F,UAAM,0BAA0B,MAAM,QAAQ,MAAM,GAAG,QAAQ,0CAA0C;AAAA,MACvG,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,gBAAgB;AAAA,QAChB,4BAA4B;AAAA,MAC9B;AAAA,MACA,MAAM;AAAA,IACR,CAAC;AACD,WAAO,wBAAwB,OAAO,CAAC,EAAE,KAAK,GAAG;AACjD,UAAM,OAAO,wBAAwB,KAAK,CAAC,EAAE,SAAS,QAAQ,EAAE,OAAO,6BAA6B,CAAC;AAAA,EACvG,CAAC;AACH,CAAC;",
6
6
  "names": []
7
7
  }
@@ -2,8 +2,15 @@ import { z } from "zod";
2
2
  import { createHash } from "node:crypto";
3
3
  import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
4
4
  import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
5
+ import { parseNumberWithDefault } from "@open-mercato/shared/lib/number";
5
6
  import { checkRateLimit, getClientIp, RATE_LIMIT_ERROR_FALLBACK, RATE_LIMIT_ERROR_KEY } from "@open-mercato/shared/lib/ratelimit/helpers";
6
7
  import { findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
8
+ import {
9
+ isWebhookTimestampWithinTolerance,
10
+ readBoundedRequestBody,
11
+ WEBHOOK_SIGNATURE_TOLERANCE_SECONDS,
12
+ WebhookBodyTooLargeError
13
+ } from "@open-mercato/shared/lib/webhooks";
7
14
  import { emitWebhooksEvent } from "../../../events.js";
8
15
  import { getWebhookEndpointAdapter } from "../../../lib/adapter-registry.js";
9
16
  import { getWebhookSource } from "../../../lib/inbound-registry.js";
@@ -27,6 +34,8 @@ const inboundResponseSchema = z.object({
27
34
  duplicate: z.boolean().optional()
28
35
  });
29
36
  const errorSchema = z.object({ error: z.string() });
37
+ const INBOUND_TIMESTAMP_TOLERANCE_ENV = "OM_WEBHOOKS_INBOUND_TIMESTAMP_TOLERANCE_SECONDS";
38
+ const STALE_TIMESTAMP_ERROR = "Webhook timestamp is outside the allowed replay window";
30
39
  async function POST(request, context) {
31
40
  const params = await context.params;
32
41
  const source = getWebhookSource(params.endpointId);
@@ -47,17 +56,28 @@ async function POST(request, context) {
47
56
  );
48
57
  if (rateLimitResponse) return rateLimitResponse;
49
58
  }
59
+ let body;
60
+ try {
61
+ body = await readBoundedRequestBody(request);
62
+ } catch (error) {
63
+ if (error instanceof WebhookBodyTooLargeError) {
64
+ return json({ error: "Webhook payload too large" }, { status: 413 });
65
+ }
66
+ throw error;
67
+ }
68
+ const headers = Object.fromEntries(request.headers.entries());
69
+ if (!isInboundWebhookTimestampFresh(headers)) {
70
+ return json({ error: STALE_TIMESTAMP_ERROR }, { status: 400 });
71
+ }
50
72
  if (source) {
51
- const rawBody = await request.text();
52
- const sourceHeaders = Object.fromEntries(request.headers.entries());
53
73
  let parsedBody = {};
54
74
  try {
55
- const parsed = JSON.parse(rawBody);
75
+ const parsed = JSON.parse(body);
56
76
  if (parsed && typeof parsed === "object") parsedBody = parsed;
57
77
  } catch {
58
78
  parsedBody = {};
59
79
  }
60
- const inboundRequest = { body: rawBody, headers: sourceHeaders, parsedBody };
80
+ const inboundRequest = { body, headers, parsedBody };
61
81
  const credentialsService = tryResolve(container, "integrationCredentialsService");
62
82
  const configs = await findWithDecryption(
63
83
  em,
@@ -83,12 +103,12 @@ async function POST(request, context) {
83
103
  if (!verifiedScope) {
84
104
  return json({ error: "Signature verification failed" }, { status: 401 });
85
105
  }
86
- const eventType = source.eventTypeExtractor(parsedBody, sourceHeaders);
87
- const messageId2 = source.messageIdExtractor?.(parsedBody, sourceHeaders) ?? resolveInboundReceiptMessageId({
106
+ const eventType = source.eventTypeExtractor(parsedBody, headers);
107
+ const messageId2 = source.messageIdExtractor?.(parsedBody, headers) ?? resolveInboundReceiptMessageId({
88
108
  endpointId: params.endpointId,
89
109
  providerKey: params.endpointId,
90
- headers: sourceHeaders,
91
- body: rawBody
110
+ headers,
111
+ body
92
112
  });
93
113
  try {
94
114
  em.persist(em.create(WebhookInboundReceiptEntity, {
@@ -112,7 +132,7 @@ async function POST(request, context) {
112
132
  eventType,
113
133
  externalMessageId: messageId2,
114
134
  payload: parsedBody,
115
- headers: sourceHeaders,
135
+ headers,
116
136
  status: "received",
117
137
  handlerCount: 0,
118
138
  organizationId: verifiedScope.organizationId,
@@ -143,8 +163,6 @@ async function POST(request, context) {
143
163
  if (!adapter) {
144
164
  return json({ error: "Webhook endpoint not found" }, { status: 404 });
145
165
  }
146
- const body = await request.text();
147
- const headers = Object.fromEntries(request.headers.entries());
148
166
  let verified;
149
167
  try {
150
168
  verified = await adapter.verifyWebhook({
@@ -211,9 +229,12 @@ const openApi = {
211
229
  summary: "Receive inbound webhook",
212
230
  description: "The endpoint id resolves to a registered webhook source first (module-level handler dispatch), otherwise to a legacy adapter provider key.",
213
231
  pathParams: z.object({ endpointId: z.string().min(1) }),
214
- responses: [{ status: 200, description: "Inbound webhook accepted", schema: inboundResponseSchema }],
232
+ responses: [
233
+ { status: 200, description: "Inbound webhook accepted", schema: inboundResponseSchema },
234
+ { status: 413, description: "Webhook payload too large", schema: errorSchema }
235
+ ],
215
236
  errors: [
216
- { status: 400, description: "Verification failed", schema: errorSchema },
237
+ { status: 400, description: "Verification failed or stale webhook timestamp", schema: errorSchema },
217
238
  { status: 401, description: "Signature verification failed (source flow)", schema: errorSchema },
218
239
  { status: 404, description: "Endpoint not found", schema: errorSchema },
219
240
  { status: 429, description: "Rate limit exceeded", schema: errorSchema },
@@ -236,6 +257,21 @@ function isUniqueViolation(error) {
236
257
  if (!maybeError.cause || typeof maybeError.cause !== "object") return false;
237
258
  return maybeError.cause.code === "23505";
238
259
  }
260
+ function isInboundWebhookTimestampFresh(headers) {
261
+ const timestamps = [
262
+ headers["webhook-timestamp"],
263
+ headers["svix-timestamp"]
264
+ ].filter((timestamp) => typeof timestamp === "string");
265
+ if (timestamps.length === 0) {
266
+ return true;
267
+ }
268
+ const toleranceSeconds = parseNumberWithDefault(
269
+ process.env[INBOUND_TIMESTAMP_TOLERANCE_ENV],
270
+ WEBHOOK_SIGNATURE_TOLERANCE_SECONDS,
271
+ { integer: true, min: 0 }
272
+ );
273
+ return timestamps.every((timestamp) => isWebhookTimestampWithinTolerance(timestamp.trim(), toleranceSeconds));
274
+ }
239
275
  function buildInboundRateLimitKey(endpointId, request, trustProxyDepth) {
240
276
  const clientIp = getClientIp(request, trustProxyDepth);
241
277
  return clientIp ? `${endpointId}:ip:${clientIp}` : `${endpointId}:global`;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/modules/webhooks/api/inbound/%5BendpointId%5D/route.ts"],
4
- "sourcesContent": ["import { z } from 'zod'\nimport { createHash } from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { checkRateLimit, getClientIp, RATE_LIMIT_ERROR_FALLBACK, RATE_LIMIT_ERROR_KEY } from '@open-mercato/shared/lib/ratelimit/helpers'\nimport type { RateLimiterService } from '@open-mercato/shared/lib/ratelimit/service'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport type { InboundWebhookRequest } from '@open-mercato/shared/lib/webhooks'\nimport { emitWebhooksEvent } from '../../../events'\nimport { getWebhookEndpointAdapter } from '../../../lib/adapter-registry'\nimport { getWebhookSource } from '../../../lib/inbound-registry'\nimport { enqueueInboundDispatch } from '../../../lib/queue'\nimport { isWebhookIntegrationEnabled, WEBHOOK_INTEGRATION_DISABLED_MESSAGE } from '../../../lib/integration-state'\nimport { json } from '../../helpers'\nimport { InboundEndpointConfigEntity, WebhookIngestionEntity, WebhookInboundReceiptEntity } from '../../../data/entities'\n\ntype IntegrationCredentialsService = {\n resolve: (\n integrationId: string,\n scope: { organizationId: string; tenantId: string },\n ) => Promise<Record<string, unknown> | null>\n}\n\nfunction toStringCredentials(credentials: Record<string, unknown> | null): Record<string, string> {\n const result: Record<string, string> = {}\n if (!credentials) return result\n for (const [key, value] of Object.entries(credentials)) {\n if (typeof value === 'string') result[key] = value\n }\n return result\n}\n\nexport const metadata = {\n POST: { requireAuth: false },\n}\n\ninterface RouteContext {\n params: Promise<{ endpointId: string }>\n}\n\nconst inboundResponseSchema = z.object({\n ok: z.boolean(),\n duplicate: z.boolean().optional(),\n})\n\nconst errorSchema = z.object({ error: z.string() })\n\nexport async function POST(request: Request, context: RouteContext): Promise<Response> {\n const params = await context.params\n const source = getWebhookSource(params.endpointId)\n const adapter = source ? undefined : getWebhookEndpointAdapter(params.endpointId)\n const { translate } = await resolveTranslations()\n\n if (!source && !adapter) {\n return json({ error: 'Webhook endpoint not found' }, { status: 404 })\n }\n\n const container = await createRequestContainer()\n const em = (container.resolve('em') as EntityManager).fork()\n const rateLimiterService = tryResolve<RateLimiterService>(container, 'rateLimiterService')\n\n if (rateLimiterService) {\n const rateLimitResponse = await checkRateLimit(\n rateLimiterService,\n { points: 60, duration: 60, keyPrefix: `webhooks:inbound:${params.endpointId}` },\n buildInboundRateLimitKey(params.endpointId, request, rateLimiterService.trustProxyDepth),\n translate(RATE_LIMIT_ERROR_KEY, RATE_LIMIT_ERROR_FALLBACK),\n )\n\n if (rateLimitResponse) return rateLimitResponse\n }\n\n if (source) {\n const rawBody = await request.text()\n const sourceHeaders = Object.fromEntries(request.headers.entries())\n let parsedBody: Record<string, unknown> = {}\n try {\n const parsed = JSON.parse(rawBody)\n if (parsed && typeof parsed === 'object') parsedBody = parsed as Record<string, unknown>\n } catch {\n parsedBody = {}\n }\n const inboundRequest: InboundWebhookRequest = { body: rawBody, headers: sourceHeaders, parsedBody }\n\n const credentialsService = tryResolve<IntegrationCredentialsService>(container, 'integrationCredentialsService')\n const configs = await findWithDecryption(\n em,\n InboundEndpointConfigEntity,\n { sourceKey: params.endpointId, isActive: true },\n {},\n )\n\n let verifiedScope: { organizationId: string; tenantId: string } | null = null\n for (const config of configs) {\n const scope = { organizationId: config.organizationId, tenantId: config.tenantId }\n const credentials = credentialsService\n ? await credentialsService.resolve(`webhook_source_${params.endpointId}`, scope)\n : null\n let valid = false\n try {\n valid = await source.verifier(inboundRequest, toStringCredentials(credentials))\n } catch {\n valid = false\n }\n if (valid) {\n verifiedScope = scope\n break\n }\n }\n\n if (!verifiedScope) {\n return json({ error: 'Signature verification failed' }, { status: 401 })\n }\n\n const eventType = source.eventTypeExtractor(parsedBody, sourceHeaders)\n const messageId = source.messageIdExtractor?.(parsedBody, sourceHeaders)\n ?? resolveInboundReceiptMessageId({\n endpointId: params.endpointId,\n providerKey: params.endpointId,\n headers: sourceHeaders,\n body: rawBody,\n })\n\n try {\n em.persist(em.create(WebhookInboundReceiptEntity, {\n endpointId: params.endpointId,\n messageId,\n providerKey: params.endpointId,\n eventType,\n tenantId: verifiedScope.tenantId,\n organizationId: verifiedScope.organizationId,\n createdAt: new Date(),\n }))\n await em.flush()\n } catch (error) {\n if (isUniqueViolation(error)) {\n return json({ ok: true, duplicate: true })\n }\n throw error\n }\n\n const ingestion = em.create(WebhookIngestionEntity, {\n sourceKey: params.endpointId,\n eventType,\n externalMessageId: messageId,\n payload: parsedBody,\n headers: sourceHeaders,\n status: 'received',\n handlerCount: 0,\n organizationId: verifiedScope.organizationId,\n tenantId: verifiedScope.tenantId,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n em.persist(ingestion)\n await em.flush()\n\n await enqueueInboundDispatch({\n ingestionId: ingestion.id,\n sourceKey: params.endpointId,\n eventType,\n tenantId: verifiedScope.tenantId,\n organizationId: verifiedScope.organizationId,\n })\n\n await emitWebhooksEvent('webhooks.inbound.received', {\n providerKey: params.endpointId,\n endpointId: params.endpointId,\n messageId,\n eventType,\n payload: parsedBody,\n tenantId: verifiedScope.tenantId,\n organizationId: verifiedScope.organizationId,\n }, { persistent: true })\n\n return json({ ok: true })\n }\n\n if (!adapter) {\n return json({ error: 'Webhook endpoint not found' }, { status: 404 })\n }\n\n const body = await request.text()\n const headers = Object.fromEntries(request.headers.entries())\n let verified: Awaited<ReturnType<typeof adapter.verifyWebhook>>\n try {\n verified = await adapter.verifyWebhook({\n headers,\n body,\n method: request.method,\n })\n } catch {\n return json({ error: 'Verification failed' }, { status: 400 })\n }\n\n const hasTenantId = Boolean(verified.tenantId)\n const hasOrganizationId = Boolean(verified.organizationId)\n if (hasTenantId !== hasOrganizationId) {\n return json({ error: WEBHOOK_INTEGRATION_DISABLED_MESSAGE }, { status: 503 })\n }\n\n const integrationScope = hasTenantId && hasOrganizationId\n ? { tenantId: verified.tenantId as string, organizationId: verified.organizationId as string }\n : null\n\n if (integrationScope) {\n const integrationEnabled = await isWebhookIntegrationEnabled(em, integrationScope)\n if (!integrationEnabled) {\n return json({ error: WEBHOOK_INTEGRATION_DISABLED_MESSAGE }, { status: 503 })\n }\n } else if (!adapter.allowUnscopedInbound) {\n return json({ error: WEBHOOK_INTEGRATION_DISABLED_MESSAGE }, { status: 503 })\n }\n\n const messageId = resolveInboundReceiptMessageId({\n endpointId: params.endpointId,\n providerKey: adapter.providerKey,\n headers,\n body,\n })\n try {\n em.persist(em.create(WebhookInboundReceiptEntity, {\n endpointId: params.endpointId,\n messageId,\n providerKey: adapter.providerKey,\n eventType: verified.eventType,\n tenantId: verified.tenantId ?? null,\n organizationId: verified.organizationId ?? null,\n createdAt: new Date(),\n }))\n await em.flush()\n } catch (error) {\n if (isUniqueViolation(error)) {\n return json({ ok: true, duplicate: true })\n }\n throw error\n }\n\n await emitWebhooksEvent('webhooks.inbound.received', {\n providerKey: adapter.providerKey,\n endpointId: params.endpointId,\n messageId,\n eventType: verified.eventType,\n payload: verified.payload,\n tenantId: verified.tenantId ?? null,\n organizationId: verified.organizationId ?? null,\n }, { persistent: true })\n\n return json({ ok: true })\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Receive inbound webhook',\n description: 'Verifies, rate limits, deduplicates, and processes an inbound webhook using the registered endpoint adapter.',\n methods: {\n POST: {\n summary: 'Receive inbound webhook',\n description: 'The endpoint id resolves to a registered webhook source first (module-level handler dispatch), otherwise to a legacy adapter provider key.',\n pathParams: z.object({ endpointId: z.string().min(1) }),\n responses: [{ status: 200, description: 'Inbound webhook accepted', schema: inboundResponseSchema }],\n errors: [\n { status: 400, description: 'Verification failed', schema: errorSchema },\n { status: 401, description: 'Signature verification failed (source flow)', schema: errorSchema },\n { status: 404, description: 'Endpoint not found', schema: errorSchema },\n { status: 429, description: 'Rate limit exceeded', schema: errorSchema },\n { status: 503, description: 'Webhook integration disabled', schema: errorSchema },\n ],\n },\n },\n}\n\nfunction tryResolve<T>(container: { resolve: (name: string) => unknown }, name: string): T | null {\n try {\n return container.resolve(name) as T\n } catch {\n return null\n }\n}\n\nfunction isUniqueViolation(error: unknown): boolean {\n if (!error || typeof error !== 'object') return false\n const maybeError = error as { code?: string; cause?: unknown }\n if (maybeError.code === '23505') return true\n if (!maybeError.cause || typeof maybeError.cause !== 'object') return false\n return (maybeError.cause as { code?: string }).code === '23505'\n}\n\ntype ResolveInboundReceiptMessageIdInput = {\n endpointId: string\n providerKey: string\n headers: Record<string, string>\n body: string\n}\n\nexport function buildInboundRateLimitKey(endpointId: string, request: Request, trustProxyDepth: number): string {\n const clientIp = getClientIp(request, trustProxyDepth)\n return clientIp ? `${endpointId}:ip:${clientIp}` : `${endpointId}:global`\n}\n\nexport function resolveInboundReceiptMessageId(\n input: ResolveInboundReceiptMessageIdInput\n): string {\n const explicitMessageId = input.headers['webhook-id'] ?? input.headers['svix-id'] ?? null\n if (typeof explicitMessageId === 'string' && explicitMessageId.trim().length > 0) {\n return explicitMessageId.trim()\n }\n\n const timestamp =\n input.headers['webhook-timestamp'] ??\n input.headers['svix-timestamp'] ??\n null\n\n if (typeof timestamp === 'string' && timestamp.trim().length > 0) {\n const digest = createHash('sha256')\n .update(input.providerKey)\n .update(':')\n .update(input.endpointId)\n .update(':')\n .update(timestamp.trim())\n .update(':')\n .update(input.body)\n .digest('hex')\n\n return `derived:${timestamp.trim()}:${digest}`\n }\n\n const digest = createHash('sha256')\n .update(input.providerKey)\n .update(':')\n .update(input.endpointId)\n .update(':')\n .update(input.body)\n .digest('hex')\n\n return `derived:no-timestamp:${digest}`\n}\n"],
5
- "mappings": "AAAA,SAAS,SAAS;AAClB,SAAS,kBAAkB;AAG3B,SAAS,8BAA8B;AACvC,SAAS,2BAA2B;AACpC,SAAS,gBAAgB,aAAa,2BAA2B,4BAA4B;AAE7F,SAAS,0BAA0B;AAEnC,SAAS,yBAAyB;AAClC,SAAS,iCAAiC;AAC1C,SAAS,wBAAwB;AACjC,SAAS,8BAA8B;AACvC,SAAS,6BAA6B,4CAA4C;AAClF,SAAS,YAAY;AACrB,SAAS,6BAA6B,wBAAwB,mCAAmC;AASjG,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ikro-orm/postgresql'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { parseNumberWithDefault } from '@open-mercato/shared/lib/number'\nimport { checkRateLimit, getClientIp, RATE_LIMIT_ERROR_FALLBACK, RATE_LIMIT_ERROR_KEY } from '@open-mercato/shared/lib/ratelimit/helpers'\nimport type { RateLimiterService } from '@open-mercato/shared/lib/ratelimit/service'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n isWebhookTimestampWithinTolerance,\n readBoundedRequestBody,\n WEBHOOK_SIGNATURE_TOLERANCE_SECONDS,\n WebhookBodyTooLargeError,\n type InboundWebhookRequest,\n} from '@open-mercato/shared/lib/webhooks'\nimport { emitWebhooksEvent } from '../../../events'\nimport { getWebhookEndpointAdapter } from '../../../lib/adapter-registry'\nimport { getWebhookSource } from '../../../lib/inbound-registry'\nimport { enqueueInboundDispatch } from '../../../lib/queue'\nimport { isWebhookIntegrationEnabled, WEBHOOK_INTEGRATION_DISABLED_MESSAGE } from '../../../lib/integration-state'\nimport { json } from '../../helpers'\nimport { InboundEndpointConfigEntity, WebhookIngestionEntity, WebhookInboundReceiptEntity } from '../../../data/entities'\n\ntype IntegrationCredentialsService = {\n resolve: (\n integrationId: string,\n scope: { organizationId: string; tenantId: string },\n ) => Promise<Record<string, unknown> | null>\n}\n\nfunction toStringCredentials(credentials: Record<string, unknown> | null): Record<string, string> {\n const result: Record<string, string> = {}\n if (!credentials) return result\n for (const [key, value] of Object.entries(credentials)) {\n if (typeof value === 'string') result[key] = value\n }\n return result\n}\n\nexport const metadata = {\n POST: { requireAuth: false },\n}\n\ninterface RouteContext {\n params: Promise<{ endpointId: string }>\n}\n\nconst inboundResponseSchema = z.object({\n ok: z.boolean(),\n duplicate: z.boolean().optional(),\n})\n\nconst errorSchema = z.object({ error: z.string() })\nconst INBOUND_TIMESTAMP_TOLERANCE_ENV = 'OM_WEBHOOKS_INBOUND_TIMESTAMP_TOLERANCE_SECONDS'\nconst STALE_TIMESTAMP_ERROR = 'Webhook timestamp is outside the allowed replay window'\n\nexport async function POST(request: Request, context: RouteContext): Promise<Response> {\n const params = await context.params\n const source = getWebhookSource(params.endpointId)\n const adapter = source ? undefined : getWebhookEndpointAdapter(params.endpointId)\n const { translate } = await resolveTranslations()\n\n if (!source && !adapter) {\n return json({ error: 'Webhook endpoint not found' }, { status: 404 })\n }\n\n const container = await createRequestContainer()\n const em = (container.resolve('em') as EntityManager).fork()\n const rateLimiterService = tryResolve<RateLimiterService>(container, 'rateLimiterService')\n\n if (rateLimiterService) {\n const rateLimitResponse = await checkRateLimit(\n rateLimiterService,\n { points: 60, duration: 60, keyPrefix: `webhooks:inbound:${params.endpointId}` },\n buildInboundRateLimitKey(params.endpointId, request, rateLimiterService.trustProxyDepth),\n translate(RATE_LIMIT_ERROR_KEY, RATE_LIMIT_ERROR_FALLBACK),\n )\n\n if (rateLimitResponse) return rateLimitResponse\n }\n\n let body: string\n try {\n body = await readBoundedRequestBody(request)\n } catch (error) {\n if (error instanceof WebhookBodyTooLargeError) {\n return json({ error: 'Webhook payload too large' }, { status: 413 })\n }\n throw error\n }\n const headers = Object.fromEntries(request.headers.entries())\n if (!isInboundWebhookTimestampFresh(headers)) {\n return json({ error: STALE_TIMESTAMP_ERROR }, { status: 400 })\n }\n\n if (source) {\n let parsedBody: Record<string, unknown> = {}\n try {\n const parsed = JSON.parse(body)\n if (parsed && typeof parsed === 'object') parsedBody = parsed as Record<string, unknown>\n } catch {\n parsedBody = {}\n }\n const inboundRequest: InboundWebhookRequest = { body, headers, parsedBody }\n\n const credentialsService = tryResolve<IntegrationCredentialsService>(container, 'integrationCredentialsService')\n const configs = await findWithDecryption(\n em,\n InboundEndpointConfigEntity,\n { sourceKey: params.endpointId, isActive: true },\n {},\n )\n\n let verifiedScope: { organizationId: string; tenantId: string } | null = null\n for (const config of configs) {\n const scope = { organizationId: config.organizationId, tenantId: config.tenantId }\n const credentials = credentialsService\n ? await credentialsService.resolve(`webhook_source_${params.endpointId}`, scope)\n : null\n let valid = false\n try {\n valid = await source.verifier(inboundRequest, toStringCredentials(credentials))\n } catch {\n valid = false\n }\n if (valid) {\n verifiedScope = scope\n break\n }\n }\n\n if (!verifiedScope) {\n return json({ error: 'Signature verification failed' }, { status: 401 })\n }\n\n const eventType = source.eventTypeExtractor(parsedBody, headers)\n const messageId = source.messageIdExtractor?.(parsedBody, headers)\n ?? resolveInboundReceiptMessageId({\n endpointId: params.endpointId,\n providerKey: params.endpointId,\n headers,\n body,\n })\n\n try {\n em.persist(em.create(WebhookInboundReceiptEntity, {\n endpointId: params.endpointId,\n messageId,\n providerKey: params.endpointId,\n eventType,\n tenantId: verifiedScope.tenantId,\n organizationId: verifiedScope.organizationId,\n createdAt: new Date(),\n }))\n await em.flush()\n } catch (error) {\n if (isUniqueViolation(error)) {\n return json({ ok: true, duplicate: true })\n }\n throw error\n }\n\n const ingestion = em.create(WebhookIngestionEntity, {\n sourceKey: params.endpointId,\n eventType,\n externalMessageId: messageId,\n payload: parsedBody,\n headers,\n status: 'received',\n handlerCount: 0,\n organizationId: verifiedScope.organizationId,\n tenantId: verifiedScope.tenantId,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n em.persist(ingestion)\n await em.flush()\n\n await enqueueInboundDispatch({\n ingestionId: ingestion.id,\n sourceKey: params.endpointId,\n eventType,\n tenantId: verifiedScope.tenantId,\n organizationId: verifiedScope.organizationId,\n })\n\n await emitWebhooksEvent('webhooks.inbound.received', {\n providerKey: params.endpointId,\n endpointId: params.endpointId,\n messageId,\n eventType,\n payload: parsedBody,\n tenantId: verifiedScope.tenantId,\n organizationId: verifiedScope.organizationId,\n }, { persistent: true })\n\n return json({ ok: true })\n }\n\n if (!adapter) {\n return json({ error: 'Webhook endpoint not found' }, { status: 404 })\n }\n let verified: Awaited<ReturnType<typeof adapter.verifyWebhook>>\n try {\n verified = await adapter.verifyWebhook({\n headers,\n body,\n method: request.method,\n })\n } catch {\n return json({ error: 'Verification failed' }, { status: 400 })\n }\n\n const hasTenantId = Boolean(verified.tenantId)\n const hasOrganizationId = Boolean(verified.organizationId)\n if (hasTenantId !== hasOrganizationId) {\n return json({ error: WEBHOOK_INTEGRATION_DISABLED_MESSAGE }, { status: 503 })\n }\n\n const integrationScope = hasTenantId && hasOrganizationId\n ? { tenantId: verified.tenantId as string, organizationId: verified.organizationId as string }\n : null\n\n if (integrationScope) {\n const integrationEnabled = await isWebhookIntegrationEnabled(em, integrationScope)\n if (!integrationEnabled) {\n return json({ error: WEBHOOK_INTEGRATION_DISABLED_MESSAGE }, { status: 503 })\n }\n } else if (!adapter.allowUnscopedInbound) {\n return json({ error: WEBHOOK_INTEGRATION_DISABLED_MESSAGE }, { status: 503 })\n }\n\n const messageId = resolveInboundReceiptMessageId({\n endpointId: params.endpointId,\n providerKey: adapter.providerKey,\n headers,\n body,\n })\n try {\n em.persist(em.create(WebhookInboundReceiptEntity, {\n endpointId: params.endpointId,\n messageId,\n providerKey: adapter.providerKey,\n eventType: verified.eventType,\n tenantId: verified.tenantId ?? null,\n organizationId: verified.organizationId ?? null,\n createdAt: new Date(),\n }))\n await em.flush()\n } catch (error) {\n if (isUniqueViolation(error)) {\n return json({ ok: true, duplicate: true })\n }\n throw error\n }\n\n await emitWebhooksEvent('webhooks.inbound.received', {\n providerKey: adapter.providerKey,\n endpointId: params.endpointId,\n messageId,\n eventType: verified.eventType,\n payload: verified.payload,\n tenantId: verified.tenantId ?? null,\n organizationId: verified.organizationId ?? null,\n }, { persistent: true })\n\n return json({ ok: true })\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Receive inbound webhook',\n description: 'Verifies, rate limits, deduplicates, and processes an inbound webhook using the registered endpoint adapter.',\n methods: {\n POST: {\n summary: 'Receive inbound webhook',\n description: 'The endpoint id resolves to a registered webhook source first (module-level handler dispatch), otherwise to a legacy adapter provider key.',\n pathParams: z.object({ endpointId: z.string().min(1) }),\n responses: [\n { status: 200, description: 'Inbound webhook accepted', schema: inboundResponseSchema },\n { status: 413, description: 'Webhook payload too large', schema: errorSchema },\n ],\n errors: [\n { status: 400, description: 'Verification failed or stale webhook timestamp', schema: errorSchema },\n { status: 401, description: 'Signature verification failed (source flow)', schema: errorSchema },\n { status: 404, description: 'Endpoint not found', schema: errorSchema },\n { status: 429, description: 'Rate limit exceeded', schema: errorSchema },\n { status: 503, description: 'Webhook integration disabled', schema: errorSchema },\n ],\n },\n },\n}\n\nfunction tryResolve<T>(container: { resolve: (name: string) => unknown }, name: string): T | null {\n try {\n return container.resolve(name) as T\n } catch {\n return null\n }\n}\n\nfunction isUniqueViolation(error: unknown): boolean {\n if (!error || typeof error !== 'object') return false\n const maybeError = error as { code?: string; cause?: unknown }\n if (maybeError.code === '23505') return true\n if (!maybeError.cause || typeof maybeError.cause !== 'object') return false\n return (maybeError.cause as { code?: string }).code === '23505'\n}\n\nfunction isInboundWebhookTimestampFresh(headers: Record<string, string>): boolean {\n const timestamps = [\n headers['webhook-timestamp'],\n headers['svix-timestamp'],\n ].filter((timestamp): timestamp is string => typeof timestamp === 'string')\n\n if (timestamps.length === 0) {\n return true\n }\n\n const toleranceSeconds = parseNumberWithDefault(\n process.env[INBOUND_TIMESTAMP_TOLERANCE_ENV],\n WEBHOOK_SIGNATURE_TOLERANCE_SECONDS,\n { integer: true, min: 0 },\n )\n return timestamps.every((timestamp) => isWebhookTimestampWithinTolerance(timestamp.trim(), toleranceSeconds))\n}\n\ntype ResolveInboundReceiptMessageIdInput = {\n endpointId: string\n providerKey: string\n headers: Record<string, string>\n body: string\n}\n\nexport function buildInboundRateLimitKey(endpointId: string, request: Request, trustProxyDepth: number): string {\n const clientIp = getClientIp(request, trustProxyDepth)\n return clientIp ? `${endpointId}:ip:${clientIp}` : `${endpointId}:global`\n}\n\nexport function resolveInboundReceiptMessageId(\n input: ResolveInboundReceiptMessageIdInput\n): string {\n const explicitMessageId = input.headers['webhook-id'] ?? input.headers['svix-id'] ?? null\n if (typeof explicitMessageId === 'string' && explicitMessageId.trim().length > 0) {\n return explicitMessageId.trim()\n }\n\n const timestamp =\n input.headers['webhook-timestamp'] ??\n input.headers['svix-timestamp'] ??\n null\n\n if (typeof timestamp === 'string' && timestamp.trim().length > 0) {\n const digest = createHash('sha256')\n .update(input.providerKey)\n .update(':')\n .update(input.endpointId)\n .update(':')\n .update(timestamp.trim())\n .update(':')\n .update(input.body)\n .digest('hex')\n\n return `derived:${timestamp.trim()}:${digest}`\n }\n\n const digest = createHash('sha256')\n .update(input.providerKey)\n .update(':')\n .update(input.endpointId)\n .update(':')\n .update(input.body)\n .digest('hex')\n\n return `derived:no-timestamp:${digest}`\n}\n"],
5
+ "mappings": "AAAA,SAAS,SAAS;AAClB,SAAS,kBAAkB;AAG3B,SAAS,8BAA8B;AACvC,SAAS,2BAA2B;AACpC,SAAS,8BAA8B;AACvC,SAAS,gBAAgB,aAAa,2BAA2B,4BAA4B;AAE7F,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,yBAAyB;AAClC,SAAS,iCAAiC;AAC1C,SAAS,wBAAwB;AACjC,SAAS,8BAA8B;AACvC,SAAS,6BAA6B,4CAA4C;AAClF,SAAS,YAAY;AACrB,SAAS,6BAA6B,wBAAwB,mCAAmC;AASjG,SAAS,oBAAoB,aAAqE;AAChG,QAAM,SAAiC,CAAC;AACxC,MAAI,CAAC,YAAa,QAAO;AACzB,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,WAAW,GAAG;AACtD,QAAI,OAAO,UAAU,SAAU,QAAO,GAAG,IAAI;AAAA,EAC/C;AACA,SAAO;AACT;AAEO,MAAM,WAAW;AAAA,EACtB,MAAM,EAAE,aAAa,MAAM;AAC7B;AAMA,MAAM,wBAAwB,EAAE,OAAO;AAAA,EACrC,IAAI,EAAE,QAAQ;AAAA,EACd,WAAW,EA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AI,EACjB,OAAO,KAAK;AAEf,WAAO,WAAW,UAAU,KAAK,CAAC,IAAIA,OAAM;AAAA,EAC9C;AAEA,QAAM,SAAS,WAAW,QAAQ,EAC/B,OAAO,MAAM,WAAW,EACxB,OAAO,GAAG,EACV,OAAO,MAAM,UAAU,EACvB,OAAO,GAAG,EACV,OAAO,MAAM,IAAI,EACjB,OAAO,KAAK;AAEf,SAAO,wBAAwB,MAAM;AACvC;",
6
6
  "names": ["messageId", "digest"]
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/webhooks",
3
- "version": "0.6.7-develop.6795.1.8a3f27921c",
3
+ "version": "0.6.7-develop.6824.1.21fff90682",
4
4
  "license": "MIT",
5
5
  "description": "Webhooks module for Open Mercato — Standard Webhooks compliant outbound/inbound delivery",
6
6
  "type": "module",
@@ -70,19 +70,19 @@
70
70
  }
71
71
  },
72
72
  "dependencies": {
73
- "@open-mercato/core": "0.6.7-develop.6795.1.8a3f27921c",
74
- "@open-mercato/queue": "0.6.7-develop.6795.1.8a3f27921c",
75
- "@open-mercato/ui": "0.6.7-develop.6795.1.8a3f27921c",
73
+ "@open-mercato/core": "0.6.7-develop.6824.1.21fff90682",
74
+ "@open-mercato/queue": "0.6.7-develop.6824.1.21fff90682",
75
+ "@open-mercato/ui": "0.6.7-develop.6824.1.21fff90682",
76
76
  "svix": "^1.99.1"
77
77
  },
78
78
  "peerDependencies": {
79
79
  "@mikro-orm/postgresql": "^7.0.14",
80
- "@open-mercato/shared": "0.6.7-develop.6795.1.8a3f27921c",
80
+ "@open-mercato/shared": "0.6.7-develop.6824.1.21fff90682",
81
81
  "react": "^19.0.0",
82
82
  "react-dom": "^19.0.0"
83
83
  },
84
84
  "devDependencies": {
85
- "@open-mercato/shared": "0.6.7-develop.6795.1.8a3f27921c",
85
+ "@open-mercato/shared": "0.6.7-develop.6824.1.21fff90682",
86
86
  "@types/jest": "^30.0.0",
87
87
  "@types/react": "^19.2.17",
88
88
  "@types/react-dom": "^19.2.3",
@@ -83,6 +83,22 @@ test.describe('TC-WEBHOOK-003: Inbound webhook receiver', () => {
83
83
  expect(replayWithoutMessageIdDuplicateResponse.status()).toBe(200);
84
84
  await expect(replayWithoutMessageIdDuplicateResponse.json()).resolves.toEqual({ ok: true, duplicate: true });
85
85
 
86
+ const staleTimestampResponse = await request.fetch(`${BASE_URL}/api/webhooks/inbound/mock_inbound`, {
87
+ method: 'POST',
88
+ headers: {
89
+ 'content-type': 'application/json',
90
+ 'x-mock-webhook-signature': validSignature,
91
+ 'webhook-id': `stale-${Date.now()}`,
92
+ 'webhook-timestamp': String(Math.floor(Date.now() / 1000) - 10 * 60),
93
+ 'webhook-signature': 'v1,mock',
94
+ },
95
+ data: rawBody,
96
+ });
97
+ expect(staleTimestampResponse.status()).toBe(400);
98
+ await expect(staleTimestampResponse.json()).resolves.toEqual({
99
+ error: 'Webhook timestamp is outside the allowed replay window',
100
+ });
101
+
86
102
  const invalidSignatureResponse = await request.fetch(`${BASE_URL}/api/webhooks/inbound/mock_inbound`, {
87
103
  method: 'POST',
88
104
  headers: {
@@ -62,12 +62,13 @@ import { POST, buildInboundRateLimitKey, resolveInboundReceiptMessageId } from '
62
62
 
63
63
  const routeContext = { params: Promise.resolve({ endpointId: 'mock_inbound' }) }
64
64
 
65
- function createRequest(body: string = '{"ok":true}') {
65
+ function createRequest(body: string = '{"ok":true}', headers: Record<string, string> = {}) {
66
66
  return new Request('http://localhost/api/webhooks/inbound/mock_inbound', {
67
67
  method: 'POST',
68
68
  headers: {
69
69
  'content-type': 'application/json',
70
70
  'webhook-id': 'msg-1',
71
+ ...headers,
71
72
  },
72
73
  body,
73
74
  })
@@ -95,6 +96,103 @@ describe('POST', () => {
95
96
  translate: (_key: string, fallback?: string) => fallback ?? '',
96
97
  })
97
98
  mockIsWebhookIntegrationEnabled.mockResolvedValue(true)
99
+ mockGetWebhookEndpointAdapter.mockReturnValue(createAdapter(
100
+ {
101
+ eventType: 'mock.inbound.received',
102
+ payload: { ok: true },
103
+ },
104
+ { allowUnscopedInbound: true },
105
+ ))
106
+ })
107
+
108
+ it('rejects stale Standard Webhooks timestamps before persisting a fresh message id', async () => {
109
+ const staleTimestamp = String(Math.floor(Date.now() / 1000) - 10 * 60)
110
+
111
+ const response = await POST(createRequest('{"ok":true}', {
112
+ 'webhook-id': 'fresh-message-id',
113
+ 'webhook-timestamp': staleTimestamp,
114
+ 'webhook-signature': 'v1,mock',
115
+ }), routeContext)
116
+
117
+ expect(response.status).toBe(400)
118
+ await expect(response.json()).resolves.toEqual({ error: 'Webhook timestamp is outside the allowed replay window' })
119
+ expect(mockRouteEm.persist).not.toHaveBeenCalled()
120
+ expect(mockRouteEm.flush).not.toHaveBeenCalled()
121
+ expect(mockEmitWebhooksEvent).not.toHaveBeenCalled()
122
+ })
123
+
124
+ it('rejects when any present Standard or Svix timestamp header is stale', async () => {
125
+ const now = Math.floor(Date.now() / 1000)
126
+
127
+ const response = await POST(createRequest('{"ok":true}', {
128
+ 'webhook-id': 'fresh-message-id',
129
+ 'webhook-timestamp': String(now),
130
+ 'webhook-signature': 'v1,mock',
131
+ 'svix-timestamp': String(now - 10 * 60),
132
+ }), routeContext)
133
+
134
+ expect(response.status).toBe(400)
135
+ await expect(response.json()).resolves.toEqual({ error: 'Webhook timestamp is outside the allowed replay window' })
136
+ expect(mockRouteEm.persist).not.toHaveBeenCalled()
137
+ expect(mockRouteEm.flush).not.toHaveBeenCalled()
138
+ expect(mockEmitWebhooksEvent).not.toHaveBeenCalled()
139
+ })
140
+
141
+ it.each(['', 'not-a-number'])('rejects malformed Standard Webhooks timestamps: %j', async (timestamp) => {
142
+ const response = await POST(createRequest('{"ok":true}', {
143
+ 'webhook-id': 'fresh-message-id',
144
+ 'webhook-timestamp': timestamp,
145
+ 'webhook-signature': 'v1,mock',
146
+ }), routeContext)
147
+
148
+ expect(response.status).toBe(400)
149
+ await expect(response.json()).resolves.toEqual({ error: 'Webhook timestamp is outside the allowed replay window' })
150
+ expect(mockRouteEm.persist).not.toHaveBeenCalled()
151
+ expect(mockRouteEm.flush).not.toHaveBeenCalled()
152
+ expect(mockEmitWebhooksEvent).not.toHaveBeenCalled()
153
+ })
154
+
155
+ it('accepts fresh Standard Webhooks timestamps', async () => {
156
+ mockGetWebhookEndpointAdapter.mockReturnValue(createAdapter(
157
+ {
158
+ eventType: 'mock.inbound.received',
159
+ payload: { ok: true },
160
+ },
161
+ { allowUnscopedInbound: true },
162
+ ))
163
+ const freshTimestamp = String(Math.floor(Date.now() / 1000))
164
+
165
+ const response = await POST(createRequest('{"ok":true}', {
166
+ 'webhook-id': 'fresh-message-id',
167
+ 'webhook-timestamp': freshTimestamp,
168
+ 'webhook-signature': 'v1,mock',
169
+ }), routeContext)
170
+
171
+ expect(response.status).toBe(200)
172
+ await expect(response.json()).resolves.toEqual({ ok: true })
173
+ expect(mockRouteEm.persist).toHaveBeenCalledTimes(1)
174
+ expect(mockRouteEm.flush).toHaveBeenCalledTimes(1)
175
+ expect(mockEmitWebhooksEvent).toHaveBeenCalledTimes(1)
176
+ })
177
+
178
+ it('rejects an oversized declared body before adapter verification', async () => {
179
+ const adapter = createAdapter({
180
+ eventType: 'mock.inbound.received',
181
+ payload: { ok: true },
182
+ tenantId: 'tenant-1',
183
+ organizationId: 'org-1',
184
+ })
185
+ mockGetWebhookEndpointAdapter.mockReturnValue(adapter)
186
+ const request = new Request('http://localhost/api/webhooks/inbound/mock_inbound', {
187
+ method: 'POST',
188
+ headers: { 'content-length': String(1024 * 1024 + 1) },
189
+ body: '{}',
190
+ })
191
+
192
+ const response = await POST(request, routeContext)
193
+
194
+ expect(response.status).toBe(413)
195
+ expect(adapter.verifyWebhook).not.toHaveBeenCalled()
98
196
  })
99
197
 
100
198
  it('rejects verified inbound webhooks without tenant and organization scope before side effects', async () => {
@@ -50,11 +50,15 @@ function makeSource(overrides: Partial<WebhookSourceConfig> = {}): WebhookSource
50
50
  }
51
51
  }
52
52
 
53
- function postTo(endpointId: string, body = '{"type":"payment_intent.succeeded","id":"evt_1"}') {
53
+ function postTo(
54
+ endpointId: string,
55
+ body = '{"type":"payment_intent.succeeded","id":"evt_1"}',
56
+ headers: Record<string, string> = {},
57
+ ) {
54
58
  const request = new Request(`http://localhost/api/webhooks/inbound/${endpointId}`, {
55
59
  method: 'POST',
56
60
  body,
57
- headers: { 'content-type': 'application/json' },
61
+ headers: { 'content-type': 'application/json', ...headers },
58
62
  })
59
63
  return POST(request, { params: Promise.resolve({ endpointId }) })
60
64
  }
@@ -91,6 +95,43 @@ it('accepts a valid source webhook: records ingestion, enqueues dispatch, emits
91
95
  )
92
96
  })
93
97
 
98
+ it('rejects a stale source webhook before signature verification or persistence', async () => {
99
+ const verifier = jest.fn(async () => true)
100
+ registerWebhookSource(makeSource({ verifier }))
101
+
102
+ const res = await postTo('stripe', undefined, { 'webhook-timestamp': '1' })
103
+
104
+ expect(res.status).toBe(400)
105
+ await expect(res.json()).resolves.toEqual({ error: 'Webhook timestamp is outside the allowed replay window' })
106
+ expect(verifier).not.toHaveBeenCalled()
107
+ expect(findWithDecryption).not.toHaveBeenCalled()
108
+ expect(persist).not.toHaveBeenCalled()
109
+ expect(flush).not.toHaveBeenCalled()
110
+ expect(enqueueInboundDispatch).not.toHaveBeenCalled()
111
+ expect(emitWebhooksEvent).not.toHaveBeenCalled()
112
+ })
113
+
114
+ it('rejects an oversized source webhook before verification or persistence', async () => {
115
+ const verifier = jest.fn(async () => true)
116
+ registerWebhookSource(makeSource({ verifier }))
117
+ const request = new Request('http://localhost/api/webhooks/inbound/stripe', {
118
+ method: 'POST',
119
+ body: '{}',
120
+ headers: {
121
+ 'content-length': String(1024 * 1024 + 1),
122
+ 'content-type': 'application/json',
123
+ },
124
+ })
125
+
126
+ const response = await POST(request, { params: Promise.resolve({ endpointId: 'stripe' }) })
127
+
128
+ expect(response.status).toBe(413)
129
+ expect(verifier).not.toHaveBeenCalled()
130
+ expect(findWithDecryption).not.toHaveBeenCalled()
131
+ expect(persist).not.toHaveBeenCalled()
132
+ expect(enqueueInboundDispatch).not.toHaveBeenCalled()
133
+ })
134
+
94
135
  it('rejects with 401 when no candidate scope verifies', async () => {
95
136
  registerWebhookSource(makeSource({ verifier: async () => false }))
96
137
  const res = await postTo('stripe')
@@ -4,10 +4,17 @@ import type { EntityManager } from '@mikro-orm/postgresql'
4
4
  import type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'
5
5
  import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
6
6
  import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
7
+ import { parseNumberWithDefault } from '@open-mercato/shared/lib/number'
7
8
  import { checkRateLimit, getClientIp, RATE_LIMIT_ERROR_FALLBACK, RATE_LIMIT_ERROR_KEY } from '@open-mercato/shared/lib/ratelimit/helpers'
8
9
  import type { RateLimiterService } from '@open-mercato/shared/lib/ratelimit/service'
9
10
  import { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'
10
- import type { InboundWebhookRequest } from '@open-mercato/shared/lib/webhooks'
11
+ import {
12
+ isWebhookTimestampWithinTolerance,
13
+ readBoundedRequestBody,
14
+ WEBHOOK_SIGNATURE_TOLERANCE_SECONDS,
15
+ WebhookBodyTooLargeError,
16
+ type InboundWebhookRequest,
17
+ } from '@open-mercato/shared/lib/webhooks'
11
18
  import { emitWebhooksEvent } from '../../../events'
12
19
  import { getWebhookEndpointAdapter } from '../../../lib/adapter-registry'
13
20
  import { getWebhookSource } from '../../../lib/inbound-registry'
@@ -46,6 +53,8 @@ const inboundResponseSchema = z.object({
46
53
  })
47
54
 
48
55
  const errorSchema = z.object({ error: z.string() })
56
+ const INBOUND_TIMESTAMP_TOLERANCE_ENV = 'OM_WEBHOOKS_INBOUND_TIMESTAMP_TOLERANCE_SECONDS'
57
+ const STALE_TIMESTAMP_ERROR = 'Webhook timestamp is outside the allowed replay window'
49
58
 
50
59
  export async function POST(request: Request, context: RouteContext): Promise<Response> {
51
60
  const params = await context.params
@@ -72,17 +81,29 @@ export async function POST(request: Request, context: RouteContext): Promise<Res
72
81
  if (rateLimitResponse) return rateLimitResponse
73
82
  }
74
83
 
84
+ let body: string
85
+ try {
86
+ body = await readBoundedRequestBody(request)
87
+ } catch (error) {
88
+ if (error instanceof WebhookBodyTooLargeError) {
89
+ return json({ error: 'Webhook payload too large' }, { status: 413 })
90
+ }
91
+ throw error
92
+ }
93
+ const headers = Object.fromEntries(request.headers.entries())
94
+ if (!isInboundWebhookTimestampFresh(headers)) {
95
+ return json({ error: STALE_TIMESTAMP_ERROR }, { status: 400 })
96
+ }
97
+
75
98
  if (source) {
76
- const rawBody = await request.text()
77
- const sourceHeaders = Object.fromEntries(request.headers.entries())
78
99
  let parsedBody: Record<string, unknown> = {}
79
100
  try {
80
- const parsed = JSON.parse(rawBody)
101
+ const parsed = JSON.parse(body)
81
102
  if (parsed && typeof parsed === 'object') parsedBody = parsed as Record<string, unknown>
82
103
  } catch {
83
104
  parsedBody = {}
84
105
  }
85
- const inboundRequest: InboundWebhookRequest = { body: rawBody, headers: sourceHeaders, parsedBody }
106
+ const inboundRequest: InboundWebhookRequest = { body, headers, parsedBody }
86
107
 
87
108
  const credentialsService = tryResolve<IntegrationCredentialsService>(container, 'integrationCredentialsService')
88
109
  const configs = await findWithDecryption(
@@ -114,13 +135,13 @@ export async function POST(request: Request, context: RouteContext): Promise<Res
114
135
  return json({ error: 'Signature verification failed' }, { status: 401 })
115
136
  }
116
137
 
117
- const eventType = source.eventTypeExtractor(parsedBody, sourceHeaders)
118
- const messageId = source.messageIdExtractor?.(parsedBody, sourceHeaders)
138
+ const eventType = source.eventTypeExtractor(parsedBody, headers)
139
+ const messageId = source.messageIdExtractor?.(parsedBody, headers)
119
140
  ?? resolveInboundReceiptMessageId({
120
141
  endpointId: params.endpointId,
121
142
  providerKey: params.endpointId,
122
- headers: sourceHeaders,
123
- body: rawBody,
143
+ headers,
144
+ body,
124
145
  })
125
146
 
126
147
  try {
@@ -146,7 +167,7 @@ export async function POST(request: Request, context: RouteContext): Promise<Res
146
167
  eventType,
147
168
  externalMessageId: messageId,
148
169
  payload: parsedBody,
149
- headers: sourceHeaders,
170
+ headers,
150
171
  status: 'received',
151
172
  handlerCount: 0,
152
173
  organizationId: verifiedScope.organizationId,
@@ -181,9 +202,6 @@ export async function POST(request: Request, context: RouteContext): Promise<Res
181
202
  if (!adapter) {
182
203
  return json({ error: 'Webhook endpoint not found' }, { status: 404 })
183
204
  }
184
-
185
- const body = await request.text()
186
- const headers = Object.fromEntries(request.headers.entries())
187
205
  let verified: Awaited<ReturnType<typeof adapter.verifyWebhook>>
188
206
  try {
189
207
  verified = await adapter.verifyWebhook({
@@ -259,9 +277,12 @@ export const openApi: OpenApiRouteDoc = {
259
277
  summary: 'Receive inbound webhook',
260
278
  description: 'The endpoint id resolves to a registered webhook source first (module-level handler dispatch), otherwise to a legacy adapter provider key.',
261
279
  pathParams: z.object({ endpointId: z.string().min(1) }),
262
- responses: [{ status: 200, description: 'Inbound webhook accepted', schema: inboundResponseSchema }],
280
+ responses: [
281
+ { status: 200, description: 'Inbound webhook accepted', schema: inboundResponseSchema },
282
+ { status: 413, description: 'Webhook payload too large', schema: errorSchema },
283
+ ],
263
284
  errors: [
264
- { status: 400, description: 'Verification failed', schema: errorSchema },
285
+ { status: 400, description: 'Verification failed or stale webhook timestamp', schema: errorSchema },
265
286
  { status: 401, description: 'Signature verification failed (source flow)', schema: errorSchema },
266
287
  { status: 404, description: 'Endpoint not found', schema: errorSchema },
267
288
  { status: 429, description: 'Rate limit exceeded', schema: errorSchema },
@@ -287,6 +308,24 @@ function isUniqueViolation(error: unknown): boolean {
287
308
  return (maybeError.cause as { code?: string }).code === '23505'
288
309
  }
289
310
 
311
+ function isInboundWebhookTimestampFresh(headers: Record<string, string>): boolean {
312
+ const timestamps = [
313
+ headers['webhook-timestamp'],
314
+ headers['svix-timestamp'],
315
+ ].filter((timestamp): timestamp is string => typeof timestamp === 'string')
316
+
317
+ if (timestamps.length === 0) {
318
+ return true
319
+ }
320
+
321
+ const toleranceSeconds = parseNumberWithDefault(
322
+ process.env[INBOUND_TIMESTAMP_TOLERANCE_ENV],
323
+ WEBHOOK_SIGNATURE_TOLERANCE_SECONDS,
324
+ { integer: true, min: 0 },
325
+ )
326
+ return timestamps.every((timestamp) => isWebhookTimestampWithinTolerance(timestamp.trim(), toleranceSeconds))
327
+ }
328
+
290
329
  type ResolveInboundReceiptMessageIdInput = {
291
330
  endpointId: string
292
331
  providerKey: string