@open-mercato/webhooks 0.10.1-develop.7741.1.61a2652671 → 0.10.1-develop.7748.1.d745ba61aa
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/dist/modules/webhooks/__integration__/TC-WEBHOOK-011.spec.js +134 -0
- package/dist/modules/webhooks/__integration__/TC-WEBHOOK-011.spec.js.map +7 -0
- package/dist/modules/webhooks/data/validators.js +16 -8
- package/dist/modules/webhooks/data/validators.js.map +2 -2
- package/package.json +7 -7
- package/src/modules/webhooks/__integration__/TC-WEBHOOK-011.spec.ts +192 -0
- package/src/modules/webhooks/api/webhooks/[id]/__tests__/partial-update.test.ts +146 -0
- package/src/modules/webhooks/data/__tests__/validators.test.ts +76 -0
- package/src/modules/webhooks/data/validators.ts +17 -8
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
[build:webhooks] found
|
|
1
|
+
[build:webhooks] found 79 entry points
|
|
2
2
|
[build:webhooks] built successfully
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { expect, test } from "@playwright/test";
|
|
2
|
+
import { apiRequest, getAuthToken } from "@open-mercato/core/helpers/integration/api";
|
|
3
|
+
import { login } from "@open-mercato/core/helpers/integration/auth";
|
|
4
|
+
import {
|
|
5
|
+
apiRequestWithSelectedOrg,
|
|
6
|
+
createOrganizationFixture,
|
|
7
|
+
deleteOrganizationIfExists
|
|
8
|
+
} from "@open-mercato/core/helpers/integration/authFixtures";
|
|
9
|
+
import { expectConflictBody, putWithLock } from "@open-mercato/core/helpers/integration/optimisticLockUi";
|
|
10
|
+
import {
|
|
11
|
+
createWebhookFixture,
|
|
12
|
+
deleteWebhookIfExists,
|
|
13
|
+
getWebhookDetail
|
|
14
|
+
} from "./helpers/fixtures.js";
|
|
15
|
+
function pickSettings(detail) {
|
|
16
|
+
return {
|
|
17
|
+
name: detail.name,
|
|
18
|
+
description: detail.description,
|
|
19
|
+
url: detail.url,
|
|
20
|
+
subscribedEvents: detail.subscribedEvents,
|
|
21
|
+
httpMethod: detail.httpMethod,
|
|
22
|
+
isActive: detail.isActive,
|
|
23
|
+
deliveryStrategy: detail.deliveryStrategy,
|
|
24
|
+
maxRetries: detail.maxRetries,
|
|
25
|
+
timeoutMs: detail.timeoutMs,
|
|
26
|
+
rateLimitPerMinute: detail.rateLimitPerMinute,
|
|
27
|
+
autoDisableThreshold: detail.autoDisableThreshold,
|
|
28
|
+
customHeaders: detail.customHeaders,
|
|
29
|
+
integrationId: detail.integrationId
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
async function readSettings(request, token, webhookId) {
|
|
33
|
+
return pickSettings(await getWebhookDetail(request, token, webhookId));
|
|
34
|
+
}
|
|
35
|
+
async function putWebhook(request, token, webhookId, data) {
|
|
36
|
+
const response = await apiRequest(request, "PUT", `/api/webhooks/${webhookId}`, { token, data });
|
|
37
|
+
expect(response.status(), `PUT ${JSON.stringify(data)} should succeed`).toBe(200);
|
|
38
|
+
}
|
|
39
|
+
test.describe("TC-WEBHOOK-011: Partial webhook update keeps omitted delivery settings", () => {
|
|
40
|
+
test("activate/deactivate and single-field updates change only the sent fields", async ({ page }) => {
|
|
41
|
+
test.setTimeout(9e4);
|
|
42
|
+
const request = page.request;
|
|
43
|
+
const token = await getAuthToken(request, "admin");
|
|
44
|
+
const stamp = Date.now();
|
|
45
|
+
let webhookId = null;
|
|
46
|
+
let organizationId = null;
|
|
47
|
+
try {
|
|
48
|
+
const created = await createWebhookFixture(request, token, {
|
|
49
|
+
name: `QA Webhook 011 ${stamp}`,
|
|
50
|
+
description: "Partial update keeps settings",
|
|
51
|
+
url: `https://qa-webhook-011-${stamp}.example.com/hook`,
|
|
52
|
+
subscribedEvents: ["catalog.product.created"],
|
|
53
|
+
httpMethod: "PUT",
|
|
54
|
+
maxRetries: 3,
|
|
55
|
+
timeoutMs: 5e3,
|
|
56
|
+
rateLimitPerMinute: 7,
|
|
57
|
+
autoDisableThreshold: 5,
|
|
58
|
+
customHeaders: { "x-qa-webhook": "011" }
|
|
59
|
+
});
|
|
60
|
+
const id = created.id;
|
|
61
|
+
webhookId = id;
|
|
62
|
+
const initial = await readSettings(request, token, id);
|
|
63
|
+
expect(initial).toMatchObject({
|
|
64
|
+
httpMethod: "PUT",
|
|
65
|
+
isActive: true,
|
|
66
|
+
maxRetries: 3,
|
|
67
|
+
timeoutMs: 5e3,
|
|
68
|
+
rateLimitPerMinute: 7,
|
|
69
|
+
autoDisableThreshold: 5
|
|
70
|
+
});
|
|
71
|
+
let expected = { ...initial };
|
|
72
|
+
await test.step("API deactivate and re-activate keep every other setting", async () => {
|
|
73
|
+
await putWebhook(request, token, id, { isActive: false });
|
|
74
|
+
expect(await readSettings(request, token, id)).toEqual({ ...expected, isActive: false });
|
|
75
|
+
await putWebhook(request, token, id, { isActive: true });
|
|
76
|
+
expect(await readSettings(request, token, id)).toEqual(expected);
|
|
77
|
+
});
|
|
78
|
+
await test.step("API single-field update changes only that field", async () => {
|
|
79
|
+
await putWebhook(request, token, id, { maxRetries: 4 });
|
|
80
|
+
expected = { ...expected, maxRetries: 4 };
|
|
81
|
+
expect(await readSettings(request, token, id)).toEqual(expected);
|
|
82
|
+
});
|
|
83
|
+
await test.step("UI detail-page Deactivate keeps every other setting", async () => {
|
|
84
|
+
await login(page, "admin");
|
|
85
|
+
await page.goto(`/backend/webhooks/${id}`, { waitUntil: "domcontentloaded" });
|
|
86
|
+
await expect(page.getByRole("heading", { name: `QA Webhook 011 ${stamp}` })).toBeVisible({ timeout: 2e4 });
|
|
87
|
+
const trigger = page.getByRole("button", { name: "Actions", exact: true });
|
|
88
|
+
const deactivateItem = page.getByRole("menuitem", { name: /^deactivate$/i });
|
|
89
|
+
await expect(async () => {
|
|
90
|
+
if ((await readSettings(request, token, id)).isActive === false) return;
|
|
91
|
+
if (!await deactivateItem.isVisible().catch(() => false)) {
|
|
92
|
+
await trigger.click({ timeout: 2e3 });
|
|
93
|
+
await expect(deactivateItem).toBeVisible({ timeout: 1500 });
|
|
94
|
+
}
|
|
95
|
+
await deactivateItem.click({ timeout: 2e3 });
|
|
96
|
+
}).toPass({ timeout: 2e4 });
|
|
97
|
+
await expect.poll(async () => (await readSettings(request, token, id)).isActive, { timeout: 15e3 }).toBe(false);
|
|
98
|
+
expect(await readSettings(request, token, id)).toEqual({ ...expected, isActive: false });
|
|
99
|
+
await putWebhook(request, token, id, { isActive: true });
|
|
100
|
+
expect(await readSettings(request, token, id)).toEqual(expected);
|
|
101
|
+
});
|
|
102
|
+
await test.step("stale optimistic-lock header is refused and changes nothing", async () => {
|
|
103
|
+
const staleUpdatedAt = (await getWebhookDetail(request, token, id)).updatedAt;
|
|
104
|
+
await putWebhook(request, token, id, { description: `Bumped ${stamp}` });
|
|
105
|
+
expected = { ...expected, description: `Bumped ${stamp}` };
|
|
106
|
+
const bumped = await getWebhookDetail(request, token, id);
|
|
107
|
+
expect(bumped.updatedAt).not.toBe(staleUpdatedAt);
|
|
108
|
+
const conflict = await putWithLock(request, token, `/api/webhooks/${id}`, { isActive: false }, staleUpdatedAt);
|
|
109
|
+
await expectConflictBody(conflict);
|
|
110
|
+
const after = await getWebhookDetail(request, token, id);
|
|
111
|
+
expect(pickSettings(after)).toEqual(expected);
|
|
112
|
+
expect(after.updatedAt).toBe(bumped.updatedAt);
|
|
113
|
+
});
|
|
114
|
+
await test.step("another selected organization cannot update the webhook", async () => {
|
|
115
|
+
organizationId = await createOrganizationFixture(request, token, { name: `QA Webhook 011 Org ${stamp}` });
|
|
116
|
+
const before = await getWebhookDetail(request, token, id);
|
|
117
|
+
const response = await apiRequestWithSelectedOrg(request, "PUT", `/api/webhooks/${id}`, {
|
|
118
|
+
token,
|
|
119
|
+
selectedOrgId: organizationId,
|
|
120
|
+
data: { isActive: false }
|
|
121
|
+
});
|
|
122
|
+
expect(response.status(), "PUT with a foreign selected organization should be 404").toBe(404);
|
|
123
|
+
const after = await getWebhookDetail(request, token, id);
|
|
124
|
+
expect(pickSettings(after)).toEqual(expected);
|
|
125
|
+
expect(after.isActive).toBe(true);
|
|
126
|
+
expect(after.updatedAt).toBe(before.updatedAt);
|
|
127
|
+
});
|
|
128
|
+
} finally {
|
|
129
|
+
await deleteWebhookIfExists(request, token, webhookId);
|
|
130
|
+
await deleteOrganizationIfExists(request, token, organizationId);
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
//# sourceMappingURL=TC-WEBHOOK-011.spec.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/modules/webhooks/__integration__/TC-WEBHOOK-011.spec.ts"],
|
|
4
|
+
"sourcesContent": ["import { expect, test, type APIRequestContext } from '@playwright/test';\nimport { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api';\nimport { login } from '@open-mercato/core/helpers/integration/auth';\nimport {\n apiRequestWithSelectedOrg,\n createOrganizationFixture,\n deleteOrganizationIfExists,\n} from '@open-mercato/core/helpers/integration/authFixtures';\nimport { expectConflictBody, putWithLock } from '@open-mercato/core/helpers/integration/optimisticLockUi';\nimport {\n createWebhookFixture,\n deleteWebhookIfExists,\n getWebhookDetail,\n type WebhookDetailResponse,\n} from './helpers/fixtures';\n\n/**\n * TC-WEBHOOK-011: A partial webhook update keeps the omitted delivery settings\n *\n * `PUT /api/webhooks/:id` must change only the fields the caller sends. The\n * activate/deactivate actions send `{ isActive }` alone; they must not reset the\n * HTTP method, retries, timeout, rate limit or auto-disable threshold to the\n * create defaults. A stale optimistic-lock header and a foreign selected\n * organization must both leave the row untouched.\n */\n\ntype WebhookSettings = Pick<\n WebhookDetailResponse,\n | 'name'\n | 'description'\n | 'url'\n | 'subscribedEvents'\n | 'httpMethod'\n | 'isActive'\n | 'deliveryStrategy'\n | 'maxRetries'\n | 'timeoutMs'\n | 'rateLimitPerMinute'\n | 'autoDisableThreshold'\n | 'customHeaders'\n | 'integrationId'\n>;\n\nfunction pickSettings(detail: WebhookDetailResponse): WebhookSettings {\n return {\n name: detail.name,\n description: detail.description,\n url: detail.url,\n subscribedEvents: detail.subscribedEvents,\n httpMethod: detail.httpMethod,\n isActive: detail.isActive,\n deliveryStrategy: detail.deliveryStrategy,\n maxRetries: detail.maxRetries,\n timeoutMs: detail.timeoutMs,\n rateLimitPerMinute: detail.rateLimitPerMinute,\n autoDisableThreshold: detail.autoDisableThreshold,\n customHeaders: detail.customHeaders,\n integrationId: detail.integrationId,\n };\n}\n\nasync function readSettings(\n request: APIRequestContext,\n token: string,\n webhookId: string,\n): Promise<WebhookSettings> {\n return pickSettings(await getWebhookDetail(request, token, webhookId));\n}\n\nasync function putWebhook(\n request: APIRequestContext,\n token: string,\n webhookId: string,\n data: Record<string, unknown>,\n): Promise<void> {\n const response = await apiRequest(request, 'PUT', `/api/webhooks/${webhookId}`, { token, data });\n expect(response.status(), `PUT ${JSON.stringify(data)} should succeed`).toBe(200);\n}\n\ntest.describe('TC-WEBHOOK-011: Partial webhook update keeps omitted delivery settings', () => {\n test('activate/deactivate and single-field updates change only the sent fields', async ({ page }) => {\n test.setTimeout(90_000);\n const request = page.request;\n const token = await getAuthToken(request, 'admin');\n const stamp = Date.now();\n let webhookId: string | null = null;\n let organizationId: string | null = null;\n\n try {\n const created = await createWebhookFixture(request, token, {\n name: `QA Webhook 011 ${stamp}`,\n description: 'Partial update keeps settings',\n url: `https://qa-webhook-011-${stamp}.example.com/hook`,\n subscribedEvents: ['catalog.product.created'],\n httpMethod: 'PUT',\n maxRetries: 3,\n timeoutMs: 5_000,\n rateLimitPerMinute: 7,\n autoDisableThreshold: 5,\n customHeaders: { 'x-qa-webhook': '011' },\n });\n const id = created.id;\n webhookId = id;\n\n const initial = await readSettings(request, token, id);\n expect(initial).toMatchObject({\n httpMethod: 'PUT',\n isActive: true,\n maxRetries: 3,\n timeoutMs: 5_000,\n rateLimitPerMinute: 7,\n autoDisableThreshold: 5,\n });\n\n let expected: WebhookSettings = { ...initial };\n\n await test.step('API deactivate and re-activate keep every other setting', async () => {\n await putWebhook(request, token, id, { isActive: false });\n expect(await readSettings(request, token, id)).toEqual({ ...expected, isActive: false });\n\n await putWebhook(request, token, id, { isActive: true });\n expect(await readSettings(request, token, id)).toEqual(expected);\n });\n\n await test.step('API single-field update changes only that field', async () => {\n await putWebhook(request, token, id, { maxRetries: 4 });\n expected = { ...expected, maxRetries: 4 };\n expect(await readSettings(request, token, id)).toEqual(expected);\n });\n\n await test.step('UI detail-page Deactivate keeps every other setting', async () => {\n await login(page, 'admin');\n await page.goto(`/backend/webhooks/${id}`, { waitUntil: 'domcontentloaded' });\n await expect(page.getByRole('heading', { name: `QA Webhook 011 ${stamp}` })).toBeVisible({ timeout: 20_000 });\n\n const trigger = page.getByRole('button', { name: 'Actions', exact: true });\n const deactivateItem = page.getByRole('menuitem', { name: /^deactivate$/i });\n await expect(async () => {\n if ((await readSettings(request, token, id)).isActive === false) return;\n if (!(await deactivateItem.isVisible().catch(() => false))) {\n await trigger.click({ timeout: 2_000 });\n await expect(deactivateItem).toBeVisible({ timeout: 1_500 });\n }\n await deactivateItem.click({ timeout: 2_000 });\n }).toPass({ timeout: 20_000 });\n\n await expect\n .poll(async () => (await readSettings(request, token, id)).isActive, { timeout: 15_000 })\n .toBe(false);\n expect(await readSettings(request, token, id)).toEqual({ ...expected, isActive: false });\n\n await putWebhook(request, token, id, { isActive: true });\n expect(await readSettings(request, token, id)).toEqual(expected);\n });\n\n await test.step('stale optimistic-lock header is refused and changes nothing', async () => {\n const staleUpdatedAt = (await getWebhookDetail(request, token, id)).updatedAt;\n await putWebhook(request, token, id, { description: `Bumped ${stamp}` });\n expected = { ...expected, description: `Bumped ${stamp}` };\n const bumped = await getWebhookDetail(request, token, id);\n expect(bumped.updatedAt).not.toBe(staleUpdatedAt);\n\n const conflict = await putWithLock(request, token, `/api/webhooks/${id}`, { isActive: false }, staleUpdatedAt);\n await expectConflictBody(conflict);\n\n const after = await getWebhookDetail(request, token, id);\n expect(pickSettings(after)).toEqual(expected);\n expect(after.updatedAt).toBe(bumped.updatedAt);\n });\n\n await test.step('another selected organization cannot update the webhook', async () => {\n organizationId = await createOrganizationFixture(request, token, { name: `QA Webhook 011 Org ${stamp}` });\n const before = await getWebhookDetail(request, token, id);\n\n const response = await apiRequestWithSelectedOrg(request, 'PUT', `/api/webhooks/${id}`, {\n token,\n selectedOrgId: organizationId,\n data: { isActive: false },\n });\n expect(response.status(), 'PUT with a foreign selected organization should be 404').toBe(404);\n\n const after = await getWebhookDetail(request, token, id);\n expect(pickSettings(after)).toEqual(expected);\n expect(after.isActive).toBe(true);\n expect(after.updatedAt).toBe(before.updatedAt);\n });\n } finally {\n await deleteWebhookIfExists(request, token, webhookId);\n await deleteOrganizationIfExists(request, token, organizationId);\n }\n });\n});\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,QAAQ,YAAoC;AACrD,SAAS,YAAY,oBAAoB;AACzC,SAAS,aAAa;AACtB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB,mBAAmB;AAChD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AA6BP,SAAS,aAAa,QAAgD;AACpE,SAAO;AAAA,IACL,MAAM,OAAO;AAAA,IACb,aAAa,OAAO;AAAA,IACpB,KAAK,OAAO;AAAA,IACZ,kBAAkB,OAAO;AAAA,IACzB,YAAY,OAAO;AAAA,IACnB,UAAU,OAAO;AAAA,IACjB,kBAAkB,OAAO;AAAA,IACzB,YAAY,OAAO;AAAA,IACnB,WAAW,OAAO;AAAA,IAClB,oBAAoB,OAAO;AAAA,IAC3B,sBAAsB,OAAO;AAAA,IAC7B,eAAe,OAAO;AAAA,IACtB,eAAe,OAAO;AAAA,EACxB;AACF;AAEA,eAAe,aACb,SACA,OACA,WAC0B;AAC1B,SAAO,aAAa,MAAM,iBAAiB,SAAS,OAAO,SAAS,CAAC;AACvE;AAEA,eAAe,WACb,SAC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AO,SAAS,OAAO,GAAG,wDAAwD,EAAE,KAAK,GAAG;AAE5F,cAAM,QAAQ,MAAM,iBAAiB,SAAS,OAAO,EAAE;AACvD,eAAO,aAAa,KAAK,CAAC,EAAE,QAAQ,QAAQ;AAC5C,eAAO,MAAM,QAAQ,EAAE,KAAK,IAAI;AAChC,eAAO,MAAM,SAAS,EAAE,KAAK,OAAO,SAAS;AAAA,MAC/C,CAAC;AAAA,IACH,UAAE;AACA,YAAM,sBAAsB,SAAS,OAAO,SAAS;AACrD,YAAM,2BAA2B,SAAS,OAAO,cAAc;AAAA,IACjE;AAAA,EACF,CAAC;AACH,CAAC;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -20,22 +20,30 @@ const webhookCustomHeaders = z.record(z.string(), z.string()).superRefine((value
|
|
|
20
20
|
}
|
|
21
21
|
}
|
|
22
22
|
});
|
|
23
|
-
const
|
|
23
|
+
const webhookFieldsSchema = z.object({
|
|
24
24
|
name: z.string().min(1).max(255),
|
|
25
25
|
description: z.string().max(1e3).optional().nullable(),
|
|
26
26
|
url: safeWebhookUrl,
|
|
27
27
|
subscribedEvents: z.array(z.string().min(1)).min(1),
|
|
28
|
-
httpMethod: z.enum(["POST", "PUT", "PATCH"])
|
|
28
|
+
httpMethod: z.enum(["POST", "PUT", "PATCH"]),
|
|
29
29
|
customHeaders: webhookCustomHeaders.optional().nullable(),
|
|
30
|
-
deliveryStrategy: z.literal("http")
|
|
30
|
+
deliveryStrategy: z.literal("http"),
|
|
31
31
|
strategyConfig: z.record(z.string(), z.unknown()).optional().nullable(),
|
|
32
|
-
maxRetries: z.number().int().min(0).max(30)
|
|
33
|
-
timeoutMs: z.number().int().min(1e3).max(6e4)
|
|
34
|
-
rateLimitPerMinute: z.number().int().min(0).max(1e4)
|
|
35
|
-
autoDisableThreshold: z.number().int().min(0).max(1e3)
|
|
32
|
+
maxRetries: z.number().int().min(0).max(30),
|
|
33
|
+
timeoutMs: z.number().int().min(1e3).max(6e4),
|
|
34
|
+
rateLimitPerMinute: z.number().int().min(0).max(1e4),
|
|
35
|
+
autoDisableThreshold: z.number().int().min(0).max(1e3),
|
|
36
36
|
integrationId: z.string().optional().nullable()
|
|
37
37
|
});
|
|
38
|
-
const
|
|
38
|
+
const webhookCreateSchema = webhookFieldsSchema.extend({
|
|
39
|
+
httpMethod: webhookFieldsSchema.shape.httpMethod.default("POST"),
|
|
40
|
+
deliveryStrategy: webhookFieldsSchema.shape.deliveryStrategy.default("http"),
|
|
41
|
+
maxRetries: webhookFieldsSchema.shape.maxRetries.default(10),
|
|
42
|
+
timeoutMs: webhookFieldsSchema.shape.timeoutMs.default(15e3),
|
|
43
|
+
rateLimitPerMinute: webhookFieldsSchema.shape.rateLimitPerMinute.default(0),
|
|
44
|
+
autoDisableThreshold: webhookFieldsSchema.shape.autoDisableThreshold.default(100)
|
|
45
|
+
});
|
|
46
|
+
const webhookUpdateSchema = webhookFieldsSchema.partial().extend({
|
|
39
47
|
isActive: z.boolean().optional()
|
|
40
48
|
});
|
|
41
49
|
const webhookListQuerySchema = z.object({
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/webhooks/data/validators.ts"],
|
|
4
|
-
"sourcesContent": ["import { z } from 'zod'\nimport { assertStaticallySafeWebhookUrl, UnsafeWebhookUrlError } from '../lib/url-safety'\nimport { isReservedWebhookCustomHeader } from '../lib/custom-headers'\n\nconst safeWebhookUrl = z.string().url().superRefine((value, ctx) => {\n try {\n assertStaticallySafeWebhookUrl(value)\n } catch (error) {\n const message = error instanceof UnsafeWebhookUrlError\n ? error.message\n : 'Webhook URL is not allowed'\n ctx.addIssue({ code: z.ZodIssueCode.custom, message })\n }\n})\n\nconst webhookCustomHeaders = z.record(z.string(), z.string()).superRefine((value, ctx) => {\n for (const name of Object.keys(value)) {\n if (isReservedWebhookCustomHeader(name)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Header \"${name}\" is reserved for webhook signing and cannot be overridden`,\n path: [name],\n })\n }\n }\n})\n\
|
|
5
|
-
"mappings": "AAAA,SAAS,SAAS;AAClB,SAAS,gCAAgC,6BAA6B;AACtE,SAAS,qCAAqC;AAE9C,MAAM,iBAAiB,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY,CAAC,OAAO,QAAQ;AAClE,MAAI;AACF,mCAA+B,KAAK;AAAA,EACtC,SAAS,OAAO;AACd,UAAM,UAAU,iBAAiB,wBAC7B,MAAM,UACN;AACJ,QAAI,SAAS,EAAE,MAAM,EAAE,aAAa,QAAQ,QAAQ,CAAC;AAAA,EACvD;AACF,CAAC;AAED,MAAM,uBAAuB,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC,EAAE,YAAY,CAAC,OAAO,QAAQ;AACxF,aAAW,QAAQ,OAAO,KAAK,KAAK,GAAG;AACrC,QAAI,8BAA8B,IAAI,GAAG;AACvC,UAAI,SAAS;AAAA,QACX,MAAM,EAAE,aAAa;AAAA,QACrB,SAAS,WAAW,IAAI;AAAA,QACxB,MAAM,CAAC,IAAI;AAAA,MACb,CAAC;AAAA,IACH;AAAA,EACF;AACF,CAAC;
|
|
4
|
+
"sourcesContent": ["import { z } from 'zod'\nimport { assertStaticallySafeWebhookUrl, UnsafeWebhookUrlError } from '../lib/url-safety'\nimport { isReservedWebhookCustomHeader } from '../lib/custom-headers'\n\nconst safeWebhookUrl = z.string().url().superRefine((value, ctx) => {\n try {\n assertStaticallySafeWebhookUrl(value)\n } catch (error) {\n const message = error instanceof UnsafeWebhookUrlError\n ? error.message\n : 'Webhook URL is not allowed'\n ctx.addIssue({ code: z.ZodIssueCode.custom, message })\n }\n})\n\nconst webhookCustomHeaders = z.record(z.string(), z.string()).superRefine((value, ctx) => {\n for (const name of Object.keys(value)) {\n if (isReservedWebhookCustomHeader(name)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Header \"${name}\" is reserved for webhook signing and cannot be overridden`,\n path: [name],\n })\n }\n }\n})\n\nconst webhookFieldsSchema = z.object({\n name: z.string().min(1).max(255),\n description: z.string().max(1000).optional().nullable(),\n url: safeWebhookUrl,\n subscribedEvents: z.array(z.string().min(1)).min(1),\n httpMethod: z.enum(['POST', 'PUT', 'PATCH'] as const),\n customHeaders: webhookCustomHeaders.optional().nullable(),\n deliveryStrategy: z.literal('http'),\n strategyConfig: z.record(z.string(), z.unknown()).optional().nullable(),\n maxRetries: z.number().int().min(0).max(30),\n timeoutMs: z.number().int().min(1000).max(60000),\n rateLimitPerMinute: z.number().int().min(0).max(10000),\n autoDisableThreshold: z.number().int().min(0).max(1000),\n integrationId: z.string().optional().nullable(),\n})\n\nexport const webhookCreateSchema = webhookFieldsSchema.extend({\n httpMethod: webhookFieldsSchema.shape.httpMethod.default('POST'),\n deliveryStrategy: webhookFieldsSchema.shape.deliveryStrategy.default('http'),\n maxRetries: webhookFieldsSchema.shape.maxRetries.default(10),\n timeoutMs: webhookFieldsSchema.shape.timeoutMs.default(15000),\n rateLimitPerMinute: webhookFieldsSchema.shape.rateLimitPerMinute.default(0),\n autoDisableThreshold: webhookFieldsSchema.shape.autoDisableThreshold.default(100),\n})\n\nexport type WebhookCreateInput = z.infer<typeof webhookCreateSchema>\n\nexport const webhookUpdateSchema = webhookFieldsSchema.partial().extend({\n isActive: z.boolean().optional(),\n})\n\nexport type WebhookUpdateInput = z.infer<typeof webhookUpdateSchema>\n\nexport const webhookListQuerySchema = z.object({\n page: z.string().optional(),\n pageSize: z.string().optional(),\n search: z.string().optional(),\n isActive: z.string().optional(),\n})\n\nexport const webhookDeliveryQuerySchema = z.object({\n page: z.coerce.number().min(1).default(1),\n pageSize: z.coerce.number().min(1).max(100).default(50),\n webhookId: z.string().uuid().optional(),\n eventType: z.string().optional(),\n status: z.enum(['pending', 'sending', 'delivered', 'failed', 'expired'] as const).optional(),\n})\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,SAAS;AAClB,SAAS,gCAAgC,6BAA6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AAS;AAAA,EACtC,WAAW,EAAE,OAAO,EAAE,SAAS;AAAA,EAC/B,QAAQ,EAAE,KAAK,CAAC,WAAW,WAAW,aAAa,UAAU,SAAS,CAAU,EAAE,SAAS;AAC7F,CAAC;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/webhooks",
|
|
3
|
-
"version": "0.10.1-develop.
|
|
3
|
+
"version": "0.10.1-develop.7748.1.d745ba61aa",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "Webhooks module for Open Mercato — Standard Webhooks compliant outbound/inbound delivery",
|
|
6
6
|
"type": "module",
|
|
@@ -70,20 +70,20 @@
|
|
|
70
70
|
}
|
|
71
71
|
},
|
|
72
72
|
"dependencies": {
|
|
73
|
-
"@open-mercato/cache": "0.10.1-develop.
|
|
74
|
-
"@open-mercato/core": "0.10.1-develop.
|
|
75
|
-
"@open-mercato/queue": "0.10.1-develop.
|
|
76
|
-
"@open-mercato/ui": "0.10.1-develop.
|
|
73
|
+
"@open-mercato/cache": "0.10.1-develop.7748.1.d745ba61aa",
|
|
74
|
+
"@open-mercato/core": "0.10.1-develop.7748.1.d745ba61aa",
|
|
75
|
+
"@open-mercato/queue": "0.10.1-develop.7748.1.d745ba61aa",
|
|
76
|
+
"@open-mercato/ui": "0.10.1-develop.7748.1.d745ba61aa",
|
|
77
77
|
"svix": "^1.99.1"
|
|
78
78
|
},
|
|
79
79
|
"peerDependencies": {
|
|
80
80
|
"@mikro-orm/postgresql": "^7.0.14",
|
|
81
|
-
"@open-mercato/shared": "0.10.1-develop.
|
|
81
|
+
"@open-mercato/shared": "0.10.1-develop.7748.1.d745ba61aa",
|
|
82
82
|
"react": "^19.0.0",
|
|
83
83
|
"react-dom": "^19.0.0"
|
|
84
84
|
},
|
|
85
85
|
"devDependencies": {
|
|
86
|
-
"@open-mercato/shared": "0.10.1-develop.
|
|
86
|
+
"@open-mercato/shared": "0.10.1-develop.7748.1.d745ba61aa",
|
|
87
87
|
"@types/jest": "^30.0.0",
|
|
88
88
|
"@types/react": "^19.2.18",
|
|
89
89
|
"@types/react-dom": "^19.2.5",
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { expect, test, type APIRequestContext } from '@playwright/test';
|
|
2
|
+
import { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api';
|
|
3
|
+
import { login } from '@open-mercato/core/helpers/integration/auth';
|
|
4
|
+
import {
|
|
5
|
+
apiRequestWithSelectedOrg,
|
|
6
|
+
createOrganizationFixture,
|
|
7
|
+
deleteOrganizationIfExists,
|
|
8
|
+
} from '@open-mercato/core/helpers/integration/authFixtures';
|
|
9
|
+
import { expectConflictBody, putWithLock } from '@open-mercato/core/helpers/integration/optimisticLockUi';
|
|
10
|
+
import {
|
|
11
|
+
createWebhookFixture,
|
|
12
|
+
deleteWebhookIfExists,
|
|
13
|
+
getWebhookDetail,
|
|
14
|
+
type WebhookDetailResponse,
|
|
15
|
+
} from './helpers/fixtures';
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* TC-WEBHOOK-011: A partial webhook update keeps the omitted delivery settings
|
|
19
|
+
*
|
|
20
|
+
* `PUT /api/webhooks/:id` must change only the fields the caller sends. The
|
|
21
|
+
* activate/deactivate actions send `{ isActive }` alone; they must not reset the
|
|
22
|
+
* HTTP method, retries, timeout, rate limit or auto-disable threshold to the
|
|
23
|
+
* create defaults. A stale optimistic-lock header and a foreign selected
|
|
24
|
+
* organization must both leave the row untouched.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
type WebhookSettings = Pick<
|
|
28
|
+
WebhookDetailResponse,
|
|
29
|
+
| 'name'
|
|
30
|
+
| 'description'
|
|
31
|
+
| 'url'
|
|
32
|
+
| 'subscribedEvents'
|
|
33
|
+
| 'httpMethod'
|
|
34
|
+
| 'isActive'
|
|
35
|
+
| 'deliveryStrategy'
|
|
36
|
+
| 'maxRetries'
|
|
37
|
+
| 'timeoutMs'
|
|
38
|
+
| 'rateLimitPerMinute'
|
|
39
|
+
| 'autoDisableThreshold'
|
|
40
|
+
| 'customHeaders'
|
|
41
|
+
| 'integrationId'
|
|
42
|
+
>;
|
|
43
|
+
|
|
44
|
+
function pickSettings(detail: WebhookDetailResponse): WebhookSettings {
|
|
45
|
+
return {
|
|
46
|
+
name: detail.name,
|
|
47
|
+
description: detail.description,
|
|
48
|
+
url: detail.url,
|
|
49
|
+
subscribedEvents: detail.subscribedEvents,
|
|
50
|
+
httpMethod: detail.httpMethod,
|
|
51
|
+
isActive: detail.isActive,
|
|
52
|
+
deliveryStrategy: detail.deliveryStrategy,
|
|
53
|
+
maxRetries: detail.maxRetries,
|
|
54
|
+
timeoutMs: detail.timeoutMs,
|
|
55
|
+
rateLimitPerMinute: detail.rateLimitPerMinute,
|
|
56
|
+
autoDisableThreshold: detail.autoDisableThreshold,
|
|
57
|
+
customHeaders: detail.customHeaders,
|
|
58
|
+
integrationId: detail.integrationId,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function readSettings(
|
|
63
|
+
request: APIRequestContext,
|
|
64
|
+
token: string,
|
|
65
|
+
webhookId: string,
|
|
66
|
+
): Promise<WebhookSettings> {
|
|
67
|
+
return pickSettings(await getWebhookDetail(request, token, webhookId));
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function putWebhook(
|
|
71
|
+
request: APIRequestContext,
|
|
72
|
+
token: string,
|
|
73
|
+
webhookId: string,
|
|
74
|
+
data: Record<string, unknown>,
|
|
75
|
+
): Promise<void> {
|
|
76
|
+
const response = await apiRequest(request, 'PUT', `/api/webhooks/${webhookId}`, { token, data });
|
|
77
|
+
expect(response.status(), `PUT ${JSON.stringify(data)} should succeed`).toBe(200);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
test.describe('TC-WEBHOOK-011: Partial webhook update keeps omitted delivery settings', () => {
|
|
81
|
+
test('activate/deactivate and single-field updates change only the sent fields', async ({ page }) => {
|
|
82
|
+
test.setTimeout(90_000);
|
|
83
|
+
const request = page.request;
|
|
84
|
+
const token = await getAuthToken(request, 'admin');
|
|
85
|
+
const stamp = Date.now();
|
|
86
|
+
let webhookId: string | null = null;
|
|
87
|
+
let organizationId: string | null = null;
|
|
88
|
+
|
|
89
|
+
try {
|
|
90
|
+
const created = await createWebhookFixture(request, token, {
|
|
91
|
+
name: `QA Webhook 011 ${stamp}`,
|
|
92
|
+
description: 'Partial update keeps settings',
|
|
93
|
+
url: `https://qa-webhook-011-${stamp}.example.com/hook`,
|
|
94
|
+
subscribedEvents: ['catalog.product.created'],
|
|
95
|
+
httpMethod: 'PUT',
|
|
96
|
+
maxRetries: 3,
|
|
97
|
+
timeoutMs: 5_000,
|
|
98
|
+
rateLimitPerMinute: 7,
|
|
99
|
+
autoDisableThreshold: 5,
|
|
100
|
+
customHeaders: { 'x-qa-webhook': '011' },
|
|
101
|
+
});
|
|
102
|
+
const id = created.id;
|
|
103
|
+
webhookId = id;
|
|
104
|
+
|
|
105
|
+
const initial = await readSettings(request, token, id);
|
|
106
|
+
expect(initial).toMatchObject({
|
|
107
|
+
httpMethod: 'PUT',
|
|
108
|
+
isActive: true,
|
|
109
|
+
maxRetries: 3,
|
|
110
|
+
timeoutMs: 5_000,
|
|
111
|
+
rateLimitPerMinute: 7,
|
|
112
|
+
autoDisableThreshold: 5,
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
let expected: WebhookSettings = { ...initial };
|
|
116
|
+
|
|
117
|
+
await test.step('API deactivate and re-activate keep every other setting', async () => {
|
|
118
|
+
await putWebhook(request, token, id, { isActive: false });
|
|
119
|
+
expect(await readSettings(request, token, id)).toEqual({ ...expected, isActive: false });
|
|
120
|
+
|
|
121
|
+
await putWebhook(request, token, id, { isActive: true });
|
|
122
|
+
expect(await readSettings(request, token, id)).toEqual(expected);
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
await test.step('API single-field update changes only that field', async () => {
|
|
126
|
+
await putWebhook(request, token, id, { maxRetries: 4 });
|
|
127
|
+
expected = { ...expected, maxRetries: 4 };
|
|
128
|
+
expect(await readSettings(request, token, id)).toEqual(expected);
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
await test.step('UI detail-page Deactivate keeps every other setting', async () => {
|
|
132
|
+
await login(page, 'admin');
|
|
133
|
+
await page.goto(`/backend/webhooks/${id}`, { waitUntil: 'domcontentloaded' });
|
|
134
|
+
await expect(page.getByRole('heading', { name: `QA Webhook 011 ${stamp}` })).toBeVisible({ timeout: 20_000 });
|
|
135
|
+
|
|
136
|
+
const trigger = page.getByRole('button', { name: 'Actions', exact: true });
|
|
137
|
+
const deactivateItem = page.getByRole('menuitem', { name: /^deactivate$/i });
|
|
138
|
+
await expect(async () => {
|
|
139
|
+
if ((await readSettings(request, token, id)).isActive === false) return;
|
|
140
|
+
if (!(await deactivateItem.isVisible().catch(() => false))) {
|
|
141
|
+
await trigger.click({ timeout: 2_000 });
|
|
142
|
+
await expect(deactivateItem).toBeVisible({ timeout: 1_500 });
|
|
143
|
+
}
|
|
144
|
+
await deactivateItem.click({ timeout: 2_000 });
|
|
145
|
+
}).toPass({ timeout: 20_000 });
|
|
146
|
+
|
|
147
|
+
await expect
|
|
148
|
+
.poll(async () => (await readSettings(request, token, id)).isActive, { timeout: 15_000 })
|
|
149
|
+
.toBe(false);
|
|
150
|
+
expect(await readSettings(request, token, id)).toEqual({ ...expected, isActive: false });
|
|
151
|
+
|
|
152
|
+
await putWebhook(request, token, id, { isActive: true });
|
|
153
|
+
expect(await readSettings(request, token, id)).toEqual(expected);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
await test.step('stale optimistic-lock header is refused and changes nothing', async () => {
|
|
157
|
+
const staleUpdatedAt = (await getWebhookDetail(request, token, id)).updatedAt;
|
|
158
|
+
await putWebhook(request, token, id, { description: `Bumped ${stamp}` });
|
|
159
|
+
expected = { ...expected, description: `Bumped ${stamp}` };
|
|
160
|
+
const bumped = await getWebhookDetail(request, token, id);
|
|
161
|
+
expect(bumped.updatedAt).not.toBe(staleUpdatedAt);
|
|
162
|
+
|
|
163
|
+
const conflict = await putWithLock(request, token, `/api/webhooks/${id}`, { isActive: false }, staleUpdatedAt);
|
|
164
|
+
await expectConflictBody(conflict);
|
|
165
|
+
|
|
166
|
+
const after = await getWebhookDetail(request, token, id);
|
|
167
|
+
expect(pickSettings(after)).toEqual(expected);
|
|
168
|
+
expect(after.updatedAt).toBe(bumped.updatedAt);
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
await test.step('another selected organization cannot update the webhook', async () => {
|
|
172
|
+
organizationId = await createOrganizationFixture(request, token, { name: `QA Webhook 011 Org ${stamp}` });
|
|
173
|
+
const before = await getWebhookDetail(request, token, id);
|
|
174
|
+
|
|
175
|
+
const response = await apiRequestWithSelectedOrg(request, 'PUT', `/api/webhooks/${id}`, {
|
|
176
|
+
token,
|
|
177
|
+
selectedOrgId: organizationId,
|
|
178
|
+
data: { isActive: false },
|
|
179
|
+
});
|
|
180
|
+
expect(response.status(), 'PUT with a foreign selected organization should be 404').toBe(404);
|
|
181
|
+
|
|
182
|
+
const after = await getWebhookDetail(request, token, id);
|
|
183
|
+
expect(pickSettings(after)).toEqual(expected);
|
|
184
|
+
expect(after.isActive).toBe(true);
|
|
185
|
+
expect(after.updatedAt).toBe(before.updatedAt);
|
|
186
|
+
});
|
|
187
|
+
} finally {
|
|
188
|
+
await deleteWebhookIfExists(request, token, webhookId);
|
|
189
|
+
await deleteOrganizationIfExists(request, token, organizationId);
|
|
190
|
+
}
|
|
191
|
+
});
|
|
192
|
+
});
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/** @jest-environment node */
|
|
2
|
+
|
|
3
|
+
import { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'
|
|
4
|
+
|
|
5
|
+
const WEBHOOK_ID = '123e4567-e89b-12d3-a456-426614174072'
|
|
6
|
+
|
|
7
|
+
type WebhookFixture = ReturnType<typeof buildWebhook>
|
|
8
|
+
|
|
9
|
+
function buildWebhook() {
|
|
10
|
+
return {
|
|
11
|
+
id: WEBHOOK_ID,
|
|
12
|
+
tenantId: 'tenant-1',
|
|
13
|
+
organizationId: 'org-1',
|
|
14
|
+
name: 'Partial update hook',
|
|
15
|
+
description: 'Keeps its settings',
|
|
16
|
+
url: 'https://example.com/hook',
|
|
17
|
+
subscribedEvents: ['catalog.product.created'],
|
|
18
|
+
httpMethod: 'PUT',
|
|
19
|
+
isActive: true,
|
|
20
|
+
deliveryStrategy: 'http',
|
|
21
|
+
maxRetries: 3,
|
|
22
|
+
timeoutMs: 5000,
|
|
23
|
+
rateLimitPerMinute: 7,
|
|
24
|
+
autoDisableThreshold: 5,
|
|
25
|
+
consecutiveFailures: 0,
|
|
26
|
+
customHeaders: { 'x-api-key': 'value' } as Record<string, string> | null,
|
|
27
|
+
strategyConfig: { region: 'eu' } as Record<string, unknown> | null,
|
|
28
|
+
integrationId: 'integration-1' as string | null,
|
|
29
|
+
updatedAt: new Date('2026-01-01T00:00:00Z'),
|
|
30
|
+
deletedAt: null as Date | null,
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
let currentWebhook: WebhookFixture = buildWebhook()
|
|
35
|
+
|
|
36
|
+
type MockEm = { fork: jest.Mock<MockEm, []>; flush: jest.Mock<Promise<undefined>, []> }
|
|
37
|
+
|
|
38
|
+
const mockEm: MockEm = {
|
|
39
|
+
fork: jest.fn((): MockEm => mockEm),
|
|
40
|
+
flush: jest.fn(async () => undefined),
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const mockEnforceLock = jest.fn(async (_container: unknown, _input: unknown) => undefined)
|
|
44
|
+
const mockInvalidateCache = jest.fn(async (..._args: unknown[]) => undefined)
|
|
45
|
+
const mockEmitWebhooksEvent = jest.fn(async (..._args: unknown[]) => undefined)
|
|
46
|
+
|
|
47
|
+
jest.mock('@open-mercato/shared/lib/crud/optimistic-lock-command', () => ({
|
|
48
|
+
enforceCommandOptimisticLockWithGuards: (container: unknown, input: unknown) => mockEnforceLock(container, input),
|
|
49
|
+
}))
|
|
50
|
+
|
|
51
|
+
jest.mock('../../../../lib/subscription-cache', () => ({
|
|
52
|
+
invalidateWebhookSubscriptionCacheFor: (...args: unknown[]) => mockInvalidateCache(...args),
|
|
53
|
+
}))
|
|
54
|
+
|
|
55
|
+
jest.mock('../../../../events', () => ({
|
|
56
|
+
emitWebhooksEvent: (...args: unknown[]) => mockEmitWebhooksEvent(...args),
|
|
57
|
+
}))
|
|
58
|
+
|
|
59
|
+
jest.mock('../../../helpers', () => ({
|
|
60
|
+
json: (payload: unknown, init: ResponseInit = { status: 200 }) =>
|
|
61
|
+
new Response(JSON.stringify(payload), {
|
|
62
|
+
...init,
|
|
63
|
+
headers: { 'content-type': 'application/json' },
|
|
64
|
+
}),
|
|
65
|
+
resolveWebhookRequestScope: jest.fn(async () => ({
|
|
66
|
+
container: { resolve: () => null },
|
|
67
|
+
em: mockEm,
|
|
68
|
+
tenantId: 'tenant-1',
|
|
69
|
+
organizationId: 'org-1',
|
|
70
|
+
allowedOrganizationIds: null,
|
|
71
|
+
})),
|
|
72
|
+
findScopedWebhook: jest.fn(async () => currentWebhook),
|
|
73
|
+
canRevealWebhookCredentialHeaders: jest.fn(async () => false),
|
|
74
|
+
serializeWebhookDetail: (item: { id: string; isActive: boolean }) => ({ id: item.id, isActive: item.isActive }),
|
|
75
|
+
}))
|
|
76
|
+
|
|
77
|
+
jest.mock('@open-mercato/shared/lib/i18n/server', () => ({
|
|
78
|
+
resolveTranslations: jest.fn(async () => ({ translate: (_key: string, fallback?: string) => fallback ?? '' })),
|
|
79
|
+
}))
|
|
80
|
+
|
|
81
|
+
import { PUT } from '../route'
|
|
82
|
+
|
|
83
|
+
function putRequest(body: unknown) {
|
|
84
|
+
return new Request(`http://localhost/api/webhooks/${WEBHOOK_ID}`, {
|
|
85
|
+
method: 'PUT',
|
|
86
|
+
headers: { 'content-type': 'application/json' },
|
|
87
|
+
body: typeof body === 'string' ? body : JSON.stringify(body),
|
|
88
|
+
})
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const context = () => ({ params: Promise.resolve({ id: WEBHOOK_ID }) })
|
|
92
|
+
|
|
93
|
+
describe('PUT /api/webhooks/:id — partial updates change only the sent fields', () => {
|
|
94
|
+
beforeEach(() => {
|
|
95
|
+
jest.clearAllMocks()
|
|
96
|
+
currentWebhook = buildWebhook()
|
|
97
|
+
})
|
|
98
|
+
|
|
99
|
+
it('deactivating and re-activating changes only isActive', async () => {
|
|
100
|
+
const expected = buildWebhook()
|
|
101
|
+
|
|
102
|
+
const deactivate = await PUT(putRequest({ isActive: false }), context())
|
|
103
|
+
expect(deactivate.status).toBe(200)
|
|
104
|
+
expect(currentWebhook).toEqual({ ...expected, isActive: false })
|
|
105
|
+
|
|
106
|
+
const reactivate = await PUT(putRequest({ isActive: true }), context())
|
|
107
|
+
expect(reactivate.status).toBe(200)
|
|
108
|
+
expect(currentWebhook).toEqual(expected)
|
|
109
|
+
expect(mockEm.flush).toHaveBeenCalledTimes(2)
|
|
110
|
+
})
|
|
111
|
+
|
|
112
|
+
it('a single-field update {maxRetries:4} changes only maxRetries', async () => {
|
|
113
|
+
const response = await PUT(putRequest({ maxRetries: 4 }), context())
|
|
114
|
+
expect(response.status).toBe(200)
|
|
115
|
+
expect(currentWebhook).toEqual({ ...buildWebhook(), maxRetries: 4 })
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
it('applies explicitly sent defaulted fields', async () => {
|
|
119
|
+
const response = await PUT(putRequest({ httpMethod: 'PATCH', timeoutMs: 20000 }), context())
|
|
120
|
+
expect(response.status).toBe(200)
|
|
121
|
+
expect(currentWebhook).toEqual({ ...buildWebhook(), httpMethod: 'PATCH', timeoutMs: 20000 })
|
|
122
|
+
})
|
|
123
|
+
|
|
124
|
+
it('rejects an invalid body with 400 and mutates nothing', async () => {
|
|
125
|
+
const response = await PUT(putRequest({ maxRetries: 31, isActive: false }), context())
|
|
126
|
+
expect(response.status).toBe(400)
|
|
127
|
+
expect(currentWebhook).toEqual(buildWebhook())
|
|
128
|
+
expect(mockEm.flush).not.toHaveBeenCalled()
|
|
129
|
+
expect(mockInvalidateCache).not.toHaveBeenCalled()
|
|
130
|
+
expect(mockEmitWebhooksEvent).not.toHaveBeenCalled()
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
it('returns 409 and mutates nothing when the optimistic-lock guard rejects the request', async () => {
|
|
134
|
+
mockEnforceLock.mockImplementationOnce(async () => {
|
|
135
|
+
throw new CrudHttpError(409, { code: 'optimistic_lock_conflict' })
|
|
136
|
+
})
|
|
137
|
+
const response = await PUT(putRequest({ isActive: false }), context())
|
|
138
|
+
expect(response.status).toBe(409)
|
|
139
|
+
const body = await response.json()
|
|
140
|
+
expect(body.code).toBe('optimistic_lock_conflict')
|
|
141
|
+
expect(currentWebhook).toEqual(buildWebhook())
|
|
142
|
+
expect(mockEm.flush).not.toHaveBeenCalled()
|
|
143
|
+
expect(mockInvalidateCache).not.toHaveBeenCalled()
|
|
144
|
+
expect(mockEmitWebhooksEvent).not.toHaveBeenCalled()
|
|
145
|
+
})
|
|
146
|
+
})
|
|
@@ -113,3 +113,79 @@ describe('webhookCreateSchema — reserved custom headers', () => {
|
|
|
113
113
|
expect(webhookUpdateSchema.safeParse({ customHeaders: { 'x-api-key': 'value' } }).success).toBe(true)
|
|
114
114
|
})
|
|
115
115
|
})
|
|
116
|
+
|
|
117
|
+
describe('webhookUpdateSchema — partial updates do not inject create defaults', () => {
|
|
118
|
+
it('parses {isActive:false} to exactly {isActive:false}', () => {
|
|
119
|
+
expect(webhookUpdateSchema.parse({ isActive: false })).toEqual({ isActive: false })
|
|
120
|
+
})
|
|
121
|
+
|
|
122
|
+
it('parses {maxRetries:4} without adding any other key', () => {
|
|
123
|
+
const parsed = webhookUpdateSchema.parse({ maxRetries: 4 })
|
|
124
|
+
expect(parsed).toEqual({ maxRetries: 4 })
|
|
125
|
+
expect(Object.keys(parsed)).toEqual(['maxRetries'])
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
it.each([
|
|
129
|
+
['maxRetries', 31],
|
|
130
|
+
['maxRetries', -1],
|
|
131
|
+
['timeoutMs', 999],
|
|
132
|
+
['timeoutMs', 60001],
|
|
133
|
+
['rateLimitPerMinute', -1],
|
|
134
|
+
['rateLimitPerMinute', 10001],
|
|
135
|
+
['autoDisableThreshold', 1001],
|
|
136
|
+
['autoDisableThreshold', -1],
|
|
137
|
+
['httpMethod', 'GET'],
|
|
138
|
+
['deliveryStrategy', 'smtp'],
|
|
139
|
+
])('still rejects out-of-bounds %s = %p', (field, value) => {
|
|
140
|
+
expect(webhookUpdateSchema.safeParse({ [field]: value }).success).toBe(false)
|
|
141
|
+
})
|
|
142
|
+
|
|
143
|
+
it('still accepts in-bounds values for the defaulted fields', () => {
|
|
144
|
+
const input = {
|
|
145
|
+
httpMethod: 'PATCH',
|
|
146
|
+
deliveryStrategy: 'http',
|
|
147
|
+
maxRetries: 0,
|
|
148
|
+
timeoutMs: 60000,
|
|
149
|
+
rateLimitPerMinute: 10000,
|
|
150
|
+
autoDisableThreshold: 0,
|
|
151
|
+
}
|
|
152
|
+
expect(webhookUpdateSchema.parse(input)).toEqual(input)
|
|
153
|
+
})
|
|
154
|
+
})
|
|
155
|
+
|
|
156
|
+
describe('webhookCreateSchema — defaults', () => {
|
|
157
|
+
it('applies every create default when the fields are omitted', () => {
|
|
158
|
+
const parsed = webhookCreateSchema.parse(baseInput())
|
|
159
|
+
expect(parsed).toMatchObject({
|
|
160
|
+
httpMethod: 'POST',
|
|
161
|
+
deliveryStrategy: 'http',
|
|
162
|
+
maxRetries: 10,
|
|
163
|
+
timeoutMs: 15000,
|
|
164
|
+
rateLimitPerMinute: 0,
|
|
165
|
+
autoDisableThreshold: 100,
|
|
166
|
+
})
|
|
167
|
+
})
|
|
168
|
+
|
|
169
|
+
it('keeps explicit values over the defaults', () => {
|
|
170
|
+
const parsed = webhookCreateSchema.parse(baseInput({
|
|
171
|
+
httpMethod: 'PUT',
|
|
172
|
+
maxRetries: 3,
|
|
173
|
+
timeoutMs: 5000,
|
|
174
|
+
rateLimitPerMinute: 7,
|
|
175
|
+
autoDisableThreshold: 5,
|
|
176
|
+
}))
|
|
177
|
+
expect(parsed).toMatchObject({
|
|
178
|
+
httpMethod: 'PUT',
|
|
179
|
+
maxRetries: 3,
|
|
180
|
+
timeoutMs: 5000,
|
|
181
|
+
rateLimitPerMinute: 7,
|
|
182
|
+
autoDisableThreshold: 5,
|
|
183
|
+
})
|
|
184
|
+
})
|
|
185
|
+
|
|
186
|
+
it('still rejects out-of-bounds defaulted fields on create', () => {
|
|
187
|
+
expect(webhookCreateSchema.safeParse(baseInput({ maxRetries: 31 })).success).toBe(false)
|
|
188
|
+
expect(webhookCreateSchema.safeParse(baseInput({ timeoutMs: 999 })).success).toBe(false)
|
|
189
|
+
expect(webhookCreateSchema.safeParse(baseInput({ httpMethod: 'GET' })).success).toBe(false)
|
|
190
|
+
})
|
|
191
|
+
})
|
|
@@ -25,25 +25,34 @@ const webhookCustomHeaders = z.record(z.string(), z.string()).superRefine((value
|
|
|
25
25
|
}
|
|
26
26
|
})
|
|
27
27
|
|
|
28
|
-
|
|
28
|
+
const webhookFieldsSchema = z.object({
|
|
29
29
|
name: z.string().min(1).max(255),
|
|
30
30
|
description: z.string().max(1000).optional().nullable(),
|
|
31
31
|
url: safeWebhookUrl,
|
|
32
32
|
subscribedEvents: z.array(z.string().min(1)).min(1),
|
|
33
|
-
httpMethod: z.enum(['POST', 'PUT', 'PATCH'] as const)
|
|
33
|
+
httpMethod: z.enum(['POST', 'PUT', 'PATCH'] as const),
|
|
34
34
|
customHeaders: webhookCustomHeaders.optional().nullable(),
|
|
35
|
-
deliveryStrategy: z.literal('http')
|
|
35
|
+
deliveryStrategy: z.literal('http'),
|
|
36
36
|
strategyConfig: z.record(z.string(), z.unknown()).optional().nullable(),
|
|
37
|
-
maxRetries: z.number().int().min(0).max(30)
|
|
38
|
-
timeoutMs: z.number().int().min(1000).max(60000)
|
|
39
|
-
rateLimitPerMinute: z.number().int().min(0).max(10000)
|
|
40
|
-
autoDisableThreshold: z.number().int().min(0).max(1000)
|
|
37
|
+
maxRetries: z.number().int().min(0).max(30),
|
|
38
|
+
timeoutMs: z.number().int().min(1000).max(60000),
|
|
39
|
+
rateLimitPerMinute: z.number().int().min(0).max(10000),
|
|
40
|
+
autoDisableThreshold: z.number().int().min(0).max(1000),
|
|
41
41
|
integrationId: z.string().optional().nullable(),
|
|
42
42
|
})
|
|
43
43
|
|
|
44
|
+
export const webhookCreateSchema = webhookFieldsSchema.extend({
|
|
45
|
+
httpMethod: webhookFieldsSchema.shape.httpMethod.default('POST'),
|
|
46
|
+
deliveryStrategy: webhookFieldsSchema.shape.deliveryStrategy.default('http'),
|
|
47
|
+
maxRetries: webhookFieldsSchema.shape.maxRetries.default(10),
|
|
48
|
+
timeoutMs: webhookFieldsSchema.shape.timeoutMs.default(15000),
|
|
49
|
+
rateLimitPerMinute: webhookFieldsSchema.shape.rateLimitPerMinute.default(0),
|
|
50
|
+
autoDisableThreshold: webhookFieldsSchema.shape.autoDisableThreshold.default(100),
|
|
51
|
+
})
|
|
52
|
+
|
|
44
53
|
export type WebhookCreateInput = z.infer<typeof webhookCreateSchema>
|
|
45
54
|
|
|
46
|
-
export const webhookUpdateSchema =
|
|
55
|
+
export const webhookUpdateSchema = webhookFieldsSchema.partial().extend({
|
|
47
56
|
isActive: z.boolean().optional(),
|
|
48
57
|
})
|
|
49
58
|
|