@open-mercato/webhooks 0.10.1-develop.7907.1.28240ddda3 → 0.10.1-develop.7917.1.c74e12c1d2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/modules/webhooks/__integration__/TC-WEBHOOK-001.spec.js +24 -0
- package/dist/modules/webhooks/__integration__/TC-WEBHOOK-001.spec.js.map +2 -2
- package/dist/modules/webhooks/api/webhooks/route.js +3 -13
- package/dist/modules/webhooks/api/webhooks/route.js.map +2 -2
- package/dist/modules/webhooks/data/validators.js +1 -0
- package/dist/modules/webhooks/data/validators.js.map +2 -2
- package/package.json +7 -7
- package/src/modules/webhooks/__integration__/TC-WEBHOOK-001.spec.ts +28 -0
- package/src/modules/webhooks/api/webhooks/route.ts +3 -14
- package/src/modules/webhooks/data/__tests__/validators.test.ts +25 -0
- package/src/modules/webhooks/data/validators.ts +1 -0
|
@@ -60,5 +60,29 @@ test.describe("TC-WEBHOOK-001: Webhook configuration CRUD", () => {
|
|
|
60
60
|
await deleteWebhookIfExists(request, token, webhookId);
|
|
61
61
|
}
|
|
62
62
|
});
|
|
63
|
+
test("PUT /api/webhooks/webhooks (the documented makeCrudRoute alias) updates by body id like PUT /api/webhooks/:id (#7504)", async ({ request }) => {
|
|
64
|
+
const token = await getAuthToken(request);
|
|
65
|
+
let webhookId = null;
|
|
66
|
+
try {
|
|
67
|
+
const created = await createWebhookFixture(request, token, {
|
|
68
|
+
name: `Webhook Alias PUT ${Date.now()}`,
|
|
69
|
+
url: "https://example.com/webhook-alias-put",
|
|
70
|
+
subscribedEvents: ["sales.quote.created"]
|
|
71
|
+
});
|
|
72
|
+
webhookId = created.id;
|
|
73
|
+
const renamedName = `Webhook Alias PUT Renamed ${Date.now()}`;
|
|
74
|
+
const aliasUpdateResponse = await apiRequest(request, "PUT", "/api/webhooks/webhooks", {
|
|
75
|
+
token,
|
|
76
|
+
data: { id: created.id, name: renamedName }
|
|
77
|
+
});
|
|
78
|
+
expect(aliasUpdateResponse.status()).toBe(200);
|
|
79
|
+
const aliasUpdated = await readJsonSafe(aliasUpdateResponse);
|
|
80
|
+
expect(aliasUpdated).toEqual({ success: true });
|
|
81
|
+
const detail = await getWebhookDetail(request, token, created.id);
|
|
82
|
+
expect(detail.name).toBe(renamedName);
|
|
83
|
+
} finally {
|
|
84
|
+
await deleteWebhookIfExists(request, token, webhookId);
|
|
85
|
+
}
|
|
86
|
+
});
|
|
63
87
|
});
|
|
64
88
|
//# sourceMappingURL=TC-WEBHOOK-001.spec.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/webhooks/__integration__/TC-WEBHOOK-001.spec.ts"],
|
|
4
|
-
"sourcesContent": ["import { expect, test } from '@playwright/test';\nimport { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api';\nimport { readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures';\nimport {\n createWebhookFixture,\n deleteWebhookIfExists,\n getWebhookDetail,\n listWebhookEvents,\n listWebhooks,\n} from './helpers/fixtures';\n\ntest.describe('TC-WEBHOOK-001: Webhook configuration CRUD', () => {\n test('should create, list, read, update, and delete webhook configurations while masking stored secrets', async ({ request }) => {\n const token = await getAuthToken(request);\n let webhookId: string | null = null;\n\n try {\n const events = await listWebhookEvents(request, token);\n expect(events.total).toBeGreaterThan(0);\n expect(events.data.every((event) => !event.id.startsWith('webhooks.'))).toBe(true);\n\n const created = await createWebhookFixture(request, token, {\n name: `Webhook CRUD ${Date.now()}`,\n url: 'https://example.com/webhook-crud',\n subscribedEvents: ['sales.quote.created'],\n });\n webhookId = created.id;\n\n const canonicalList = await listWebhooks(request, token);\n expect(canonicalList.items.some((item) => item.id === created.id)).toBe(true);\n\n const aliasedList = await listWebhooks(request, token, '/api/webhooks/webhooks');\n expect(aliasedList.items.some((item) => item.id === created.id)).toBe(true);\n\n const detail = await getWebhookDetail(request, token, created.id);\n expect(detail.name).toBe(created.name);\n expect(detail.url).toBe('https://example.com/webhook-crud');\n expect(detail.maskedSecret).toContain(created.secret.slice(0, 6));\n expect(detail.maskedSecret).not.toBe(created.secret);\n expect(detail.previousSecretSetAt).toBeNull();\n\n const aliasedDetail = await getWebhookDetail(request, token, created.id, `/api/webhooks/webhooks/${created.id}`);\n expect(aliasedDetail.id).toBe(created.id);\n\n const updateResponse = await apiRequest(request, 'PUT', `/api/webhooks/${created.id}`, {\n token,\n data: {\n name: `Webhook CRUD Updated ${Date.now()}`,\n description: 'Updated by integration test',\n url: 'https://example.com/webhook-updated',\n subscribedEvents: ['catalog.product.updated'],\n isActive: false,\n customHeaders: {\n 'x-test-suite': 'webhooks',\n },\n },\n });\n expect(updateResponse.status()).toBe(200);\n const updated = await readJsonSafe<Awaited<ReturnType<typeof getWebhookDetail>>>(updateResponse);\n expect(updated?.isActive).toBe(false);\n expect(updated?.customHeaders).toEqual({ 'x-test-suite': 'webhooks' });\n\n const deleteResponse = await apiRequest(request, 'DELETE', `/api/webhooks/${created.id}`, { token });\n expect(deleteResponse.status()).toBe(200);\n webhookId = null;\n\n const deletedDetailResponse = await apiRequest(request, 'GET', `/api/webhooks/${created.id}`, { token });\n expect(deletedDetailResponse.status()).toBe(404);\n } finally {\n await deleteWebhookIfExists(request, token, webhookId);\n }\n });\n});\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,QAAQ,YAAY;AAC7B,SAAS,YAAY,oBAAoB;AACzC,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,KAAK,SAAS,8CAA8C,MAAM;AAChE,OAAK,qGAAqG,OAAO,EAAE,QAAQ,MAAM;AAC/H,UAAM,QAAQ,MAAM,aAAa,OAAO;AACxC,QAAI,YAA2B;AAE/B,QAAI;AACF,YAAM,SAAS,MAAM,kBAAkB,SAAS,KAAK;AACrD,aAAO,OAAO,KAAK,EAAE,gBAAgB,CAA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,yBAAyB;AAAA,UAC5C,UAAU;AAAA,UACV,eAAe;AAAA,YACb,gBAAgB;AAAA,UAClB;AAAA,QACF;AAAA,MACF,CAAC;AACD,aAAO,eAAe,OAAO,CAAC,EAAE,KAAK,GAAG;AACxC,YAAM,UAAU,MAAM,aAA2D,cAAc;AAC/F,aAAO,SAAS,QAAQ,EAAE,KAAK,KAAK;AACpC,aAAO,SAAS,aAAa,EAAE,QAAQ,EAAE,gBAAgB,WAAW,CAAC;AAErE,YAAM,iBAAiB,MAAM,WAAW,SAAS,UAAU,iBAAiB,QAAQ,EAAE,IAAI,EAAE,MAAM,CAAC;AACnG,aAAO,eAAe,OAAO,CAAC,EAAE,KAAK,GAAG;AACxC,kBAAY;AAEZ,YAAM,wBAAwB,MAAM,WAAW,SAAS,OAAO,iBAAiB,QAAQ,EAAE,IAAI,EAAE,MAAM,CAAC;AACvG,aAAO,sBAAsB,OAAO,CAAC,EAAE,KAAK,GAAG;AAAA,IACjD,UAAE;AACA,YAAM,sBAAsB,SAAS,OAAO,SAAS;AAAA,IACvD;AAAA,EACF,CAAC;AACH,CAAC;",
|
|
4
|
+
"sourcesContent": ["import { expect, test } from '@playwright/test';\nimport { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api';\nimport { readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures';\nimport {\n createWebhookFixture,\n deleteWebhookIfExists,\n getWebhookDetail,\n listWebhookEvents,\n listWebhooks,\n} from './helpers/fixtures';\n\ntest.describe('TC-WEBHOOK-001: Webhook configuration CRUD', () => {\n test('should create, list, read, update, and delete webhook configurations while masking stored secrets', async ({ request }) => {\n const token = await getAuthToken(request);\n let webhookId: string | null = null;\n\n try {\n const events = await listWebhookEvents(request, token);\n expect(events.total).toBeGreaterThan(0);\n expect(events.data.every((event) => !event.id.startsWith('webhooks.'))).toBe(true);\n\n const created = await createWebhookFixture(request, token, {\n name: `Webhook CRUD ${Date.now()}`,\n url: 'https://example.com/webhook-crud',\n subscribedEvents: ['sales.quote.created'],\n });\n webhookId = created.id;\n\n const canonicalList = await listWebhooks(request, token);\n expect(canonicalList.items.some((item) => item.id === created.id)).toBe(true);\n\n const aliasedList = await listWebhooks(request, token, '/api/webhooks/webhooks');\n expect(aliasedList.items.some((item) => item.id === created.id)).toBe(true);\n\n const detail = await getWebhookDetail(request, token, created.id);\n expect(detail.name).toBe(created.name);\n expect(detail.url).toBe('https://example.com/webhook-crud');\n expect(detail.maskedSecret).toContain(created.secret.slice(0, 6));\n expect(detail.maskedSecret).not.toBe(created.secret);\n expect(detail.previousSecretSetAt).toBeNull();\n\n const aliasedDetail = await getWebhookDetail(request, token, created.id, `/api/webhooks/webhooks/${created.id}`);\n expect(aliasedDetail.id).toBe(created.id);\n\n const updateResponse = await apiRequest(request, 'PUT', `/api/webhooks/${created.id}`, {\n token,\n data: {\n name: `Webhook CRUD Updated ${Date.now()}`,\n description: 'Updated by integration test',\n url: 'https://example.com/webhook-updated',\n subscribedEvents: ['catalog.product.updated'],\n isActive: false,\n customHeaders: {\n 'x-test-suite': 'webhooks',\n },\n },\n });\n expect(updateResponse.status()).toBe(200);\n const updated = await readJsonSafe<Awaited<ReturnType<typeof getWebhookDetail>>>(updateResponse);\n expect(updated?.isActive).toBe(false);\n expect(updated?.customHeaders).toEqual({ 'x-test-suite': 'webhooks' });\n\n const deleteResponse = await apiRequest(request, 'DELETE', `/api/webhooks/${created.id}`, { token });\n expect(deleteResponse.status()).toBe(200);\n webhookId = null;\n\n const deletedDetailResponse = await apiRequest(request, 'GET', `/api/webhooks/${created.id}`, { token });\n expect(deletedDetailResponse.status()).toBe(404);\n } finally {\n await deleteWebhookIfExists(request, token, webhookId);\n }\n });\n\n test('PUT /api/webhooks/webhooks (the documented makeCrudRoute alias) updates by body id like PUT /api/webhooks/:id (#7504)', async ({ request }) => {\n const token = await getAuthToken(request);\n let webhookId: string | null = null;\n\n try {\n const created = await createWebhookFixture(request, token, {\n name: `Webhook Alias PUT ${Date.now()}`,\n url: 'https://example.com/webhook-alias-put',\n subscribedEvents: ['sales.quote.created'],\n });\n webhookId = created.id;\n\n const renamedName = `Webhook Alias PUT Renamed ${Date.now()}`;\n const aliasUpdateResponse = await apiRequest(request, 'PUT', '/api/webhooks/webhooks', {\n token,\n data: { id: created.id, name: renamedName },\n });\n expect(aliasUpdateResponse.status()).toBe(200);\n const aliasUpdated = await readJsonSafe<{ success: true }>(aliasUpdateResponse);\n expect(aliasUpdated).toEqual({ success: true });\n\n const detail = await getWebhookDetail(request, token, created.id);\n expect(detail.name).toBe(renamedName);\n } finally {\n await deleteWebhookIfExists(request, token, webhookId);\n }\n });\n});\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,QAAQ,YAAY;AAC7B,SAAS,YAAY,oBAAoB;AACzC,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,KAAK,SAAS,8CAA8C,MAAM;AAChE,OAAK,qGAAqG,OAAO,EAAE,QAAQ,MAAM;AAC/H,UAAM,QAAQ,MAAM,aAAa,OAAO;AACxC,QAAI,YAA2B;AAE/B,QAAI;AACF,YAAM,SAAS,MAAM,kBAAkB,SAAS,KAAK;AACrD,aAAO,OAAO,KAAK,EAAE,gBAAgB,CAAC;AACtC,aAAO,OAAO,KAAK,MAAM,CAAC,UAAU,CAAC,MAAM,GAAG,WAAW,WAAW,CAAC,CAAC,EAAE,KAAK,IAAI;AAEjF,YAAM,UAAU,MAAM,qBAAqB,SAAS,OAAO;AAAA,QACzD,MAAM,gBAAgB,KAAK,IAAI,CAAC;AAAA,QAChC,KAAK;AAAA,QACL,kBAAkB,CAAC,qBAAqB;AAAA,MAC1C,CAAC;AACD,kBAAY,QAAQ;AAEpB,YAAM,gBAAgB,MAAM,aAAa,SAAS,KAAK;AACvD,aAAO,cAAc,MAAM,KAAK,CAAC,SAAS,KAAK,OAAO,QAAQ,EAAE,CAAC,EAAE,KAAK,IAAI;AAE5E,YAAM,cAA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|
52
|
-
customHeaders: z.record(z.string(), z.string()).nullable().describe(
|
|
53
|
-
"Credential-like header values are returned as \u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022 unless the caller has webhooks.secrets. Sending \u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022 back on update keeps the stored value."
|
|
54
|
-
),
|
|
55
|
-
strategyConfig: z.record(z.string(), z.unknown()).nullable(),
|
|
56
|
-
timeoutMs: z.number(),
|
|
57
|
-
rateLimitPerMinute: z.number(),
|
|
58
|
-
autoDisableThreshold: z.number(),
|
|
59
|
-
integrationId: z.string().nullable()
|
|
60
|
-
});
|
|
61
|
-
const deleteResponseSchema = z.object({ success: z.literal(true) });
|
|
51
|
+
const successResponseSchema = z.object({ success: z.literal(true) });
|
|
62
52
|
const errorSchema = z.object({ error: z.string() });
|
|
63
53
|
function resolveTenantIdForInvalidation(entity, ctx) {
|
|
64
54
|
const entityTenantId = entity?.tenantId;
|
|
@@ -272,7 +262,7 @@ const openApi = {
|
|
|
272
262
|
summary: "Update webhook",
|
|
273
263
|
description: "Updates an existing webhook configuration.",
|
|
274
264
|
requestBody: { contentType: "application/json", schema: webhookUpdateSchema, description: "Fields to update." },
|
|
275
|
-
responses: [{ status: 200, description: "Webhook updated", schema:
|
|
265
|
+
responses: [{ status: 200, description: "Webhook updated", schema: successResponseSchema }],
|
|
276
266
|
errors: [
|
|
277
267
|
{
|
|
278
268
|
status: 400,
|
|
@@ -286,7 +276,7 @@ const openApi = {
|
|
|
286
276
|
summary: "Delete webhook",
|
|
287
277
|
description: "Soft-deletes a webhook endpoint.",
|
|
288
278
|
query: z.object({ id: z.string().uuid().describe("Webhook ID to delete") }),
|
|
289
|
-
responses: [{ status: 200, description: "Deleted", schema:
|
|
279
|
+
responses: [{ status: 200, description: "Deleted", schema: successResponseSchema }],
|
|
290
280
|
errors: [
|
|
291
281
|
{ status: 404, description: "Not found", schema: errorSchema },
|
|
292
282
|
{ status: 403, description: "Forbidden", schema: errorSchema }
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/modules/webhooks/api/webhooks/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { makeCrudRoute } from '@open-mercato/shared/lib/crud/factory'\nimport type { CrudCtx } from '@open-mercato/shared/lib/crud/factory'\nimport { WebhookEntity } from '../../data/entities'\nimport { webhookCreateSchema, webhookUpdateSchema, webhookListQuerySchema } from '../../data/validators'\nimport { generateWebhookSecret } from '@open-mercato/shared/lib/webhooks'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { escapeLikePattern } from '@open-mercato/shared/lib/db/escapeLikePattern'\nimport { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\nimport type { WebhookCreateInput, WebhookUpdateInput } from '../../data/validators'\nimport { invalidateWebhookSubscriptionCacheFor } from '../../lib/subscription-cache'\nimport { applyWebhookActiveState } from '../../lib/activation'\nimport { planWebhookCustomHeadersUpdate } from '../../lib/custom-headers'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { canRevealWebhookCredentialHeaders, translateWebhookCustomHeadersRejection } from '../helpers'\n\ntype WebhookCrudCtx = CrudCtx & {\n __webhookSecret?: string\n}\n\nfunction json(payload: unknown, init: ResponseInit = { status: 200 }) {\n return new Response(JSON.stringify(payload), {\n ...init,\n headers: { 'content-type': 'application/json', ...(init.headers || {}) },\n })\n}\n\nconst webhookListItemSchema = z.object({\n id: z.string(),\n name: z.string(),\n description: z.string().nullable(),\n url: z.string(),\n subscribedEvents: z.array(z.string()),\n httpMethod: z.string(),\n isActive: z.boolean(),\n deliveryStrategy: z.string(),\n maxRetries: z.number(),\n consecutiveFailures: z.number(),\n lastSuccessAt: z.string().nullable(),\n lastFailureAt: z.string().nullable(),\n createdAt: z.string(),\n updatedAt: z.string(),\n})\n\nconst webhookCollectionResponseSchema = z.object({\n items: z.array(webhookListItemSchema),\n total: z.number().int().nonnegative(),\n page: z.number().int().positive(),\n pageSize: z.number().int().positive(),\n totalPages: z.number().int().nonnegative(),\n})\n\nconst webhookCreateResponseSchema = z.object({\n id: z.string(),\n name: z.string(),\n url: z.string(),\n secret: z.string(),\n subscribedEvents: z.array(z.string()),\n isActive: z.boolean(),\n})\n\nconst webhookDetailResponseSchema = webhookListItemSchema.extend({\n customHeaders: z.record(z.string(), z.string()).nullable().describe(\n 'Credential-like header values are returned as \u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022 unless the caller has webhooks.secrets. Sending \u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022 back on update keeps the stored value.',\n ),\n strategyConfig: z.record(z.string(), z.unknown()).nullable(),\n timeoutMs: z.number(),\n rateLimitPerMinute: z.number(),\n autoDisableThreshold: z.number(),\n integrationId: z.string().nullable(),\n})\n\nconst deleteResponseSchema = z.object({ success: z.literal(true) })\nconst errorSchema = z.object({ error: z.string() })\n\nfunction resolveTenantIdForInvalidation(entity: unknown, ctx: CrudCtx): string | null {\n const entityTenantId = (entity as { tenantId?: unknown } | null)?.tenantId\n if (typeof entityTenantId === 'string' && entityTenantId.length > 0) return entityTenantId\n return ctx.auth?.tenantId ?? null\n}\n\nconst crud = makeCrudRoute<WebhookCreateInput, WebhookUpdateInput, z.infer<typeof webhookListQuerySchema>>({\n metadata: {\n GET: { requireAuth: true, requireFeatures: ['webhooks.view'] },\n POST: { requireAuth: true, requireFeatures: ['webhooks.manage'] },\n PUT: { requireAuth: true, requireFeatures: ['webhooks.manage'] },\n DELETE: { requireAuth: true, requireFeatures: ['webhooks.manage'] },\n },\n orm: { entity: WebhookEntity, orgField: 'organizationId' },\n events: { module: 'webhooks', entity: 'webhook', persistent: true },\n list: { schema: webhookListQuerySchema },\n create: {\n schema: webhookCreateSchema,\n mapToEntity: (input, ctx) => {\n const scopedCtx = ctx as WebhookCrudCtx\n const secret = scopedCtx.__webhookSecret\n if (!secret) throw new Error('Webhook secret not prepared')\n return {\n name: input.name,\n description: input.description ?? null,\n url: input.url,\n secret,\n subscribedEvents: input.subscribedEvents,\n httpMethod: input.httpMethod ?? 'POST',\n customHeaders: input.customHeaders ?? null,\n deliveryStrategy: input.deliveryStrategy ?? 'http',\n strategyConfig: input.strategyConfig ?? null,\n maxRetries: input.maxRetries ?? 10,\n timeoutMs: input.timeoutMs ?? 15000,\n rateLimitPerMinute: input.rateLimitPerMinute ?? 0,\n autoDisableThreshold: input.autoDisableThreshold ?? 100,\n integrationId: input.integrationId ?? null,\n organizationId: ctx.auth?.orgId ?? '',\n tenantId: ctx.auth?.tenantId ?? '',\n }\n },\n response: (entity) => ({\n id: entity.id,\n name: entity.name,\n url: entity.url,\n secret: (entity as WebhookEntity & { __revealSecret?: string }).__revealSecret ?? '***',\n subscribedEvents: entity.subscribedEvents,\n isActive: entity.isActive,\n }),\n },\n update: {\n schema: webhookUpdateSchema,\n applyToEntity: async (entity: WebhookEntity, input, ctx) => {\n const headersUpdate = planWebhookCustomHeadersUpdate({\n current: entity,\n next: input,\n canRevealCredentials: await canRevealWebhookCredentialHeaders(ctx.container, ctx.auth, entity),\n })\n if (!headersUpdate.ok) {\n throw new CrudHttpError(400, { error: await translateWebhookCustomHeadersRejection(headersUpdate) })\n }\n if (input.name !== undefined) entity.name = input.name\n if (input.description !== undefined) entity.description = input.description\n if (input.url !== undefined) entity.url = input.url\n if (input.subscribedEvents !== undefined) entity.subscribedEvents = input.subscribedEvents\n if (input.httpMethod !== undefined) entity.httpMethod = input.httpMethod\n if (headersUpdate.customHeaders !== undefined) entity.customHeaders = headersUpdate.customHeaders\n if (input.deliveryStrategy !== undefined) entity.deliveryStrategy = input.deliveryStrategy\n if (input.strategyConfig !== undefined) entity.strategyConfig = input.strategyConfig\n if (input.maxRetries !== undefined) entity.maxRetries = input.maxRetries\n if (input.timeoutMs !== undefined) entity.timeoutMs = input.timeoutMs\n if (input.rateLimitPerMinute !== undefined) entity.rateLimitPerMinute = input.rateLimitPerMinute\n if (input.autoDisableThreshold !== undefined) entity.autoDisableThreshold = input.autoDisableThreshold\n if (input.integrationId !== undefined) entity.integrationId = input.integrationId\n if (input.isActive !== undefined) applyWebhookActiveState(entity, input.isActive)\n },\n },\n del: { idFrom: 'query' },\n hooks: {\n beforeList: async (query, ctx) => {\n const auth = ctx.auth\n const { translate } = await resolveTranslations()\n if (!auth?.tenantId) throw json({ error: translate('webhooks.errors.tenantRequired', 'Tenant context required') }, { status: 400 })\n\n const page = Math.max(parseInt(query.page ?? '1', 10) || 1, 1)\n const pageSize = Math.min(Math.max(parseInt(query.pageSize ?? '20', 10) || 20, 1), 100)\n const search = (query.search ?? '').trim().toLowerCase()\n\n const organizationIds = Array.isArray(ctx.organizationIds) ? ctx.organizationIds : null\n if (organizationIds && organizationIds.length === 0) {\n throw json({ items: [], total: 0, page, pageSize, totalPages: 0 })\n }\n\n const em = ctx.container.resolve('em') as EntityManager\n const qb = em.createQueryBuilder(WebhookEntity, 'w')\n qb.where({ deletedAt: null })\n qb.andWhere({ tenantId: auth.tenantId })\n\n if (organizationIds && organizationIds.length > 0) {\n qb.andWhere({ organizationId: { $in: organizationIds } })\n } else if (auth.orgId) {\n qb.andWhere({ organizationId: auth.orgId })\n }\n\n if (search) {\n const pattern = `%${escapeLikePattern(search)}%`\n qb.andWhere({\n $or: [\n { name: { $ilike: pattern } },\n { url: { $ilike: pattern } },\n ],\n })\n }\n\n if (query.isActive !== undefined && query.isActive !== '') {\n const active = parseBooleanToken(query.isActive)\n if (active !== null) {\n qb.andWhere({ isActive: active })\n }\n }\n\n qb.orderBy({ createdAt: 'desc' })\n qb.limit(pageSize).offset((page - 1) * pageSize)\n const [items, total] = await qb.getResultAndCount()\n\n const payload = {\n items: items.map((item) => ({\n id: item.id,\n name: item.name,\n description: item.description ?? null,\n url: item.url,\n subscribedEvents: item.subscribedEvents,\n httpMethod: item.httpMethod,\n isActive: item.isActive,\n deliveryStrategy: item.deliveryStrategy,\n maxRetries: item.maxRetries,\n consecutiveFailures: item.consecutiveFailures,\n lastSuccessAt: item.lastSuccessAt?.toISOString() ?? null,\n lastFailureAt: item.lastFailureAt?.toISOString() ?? null,\n createdAt: item.createdAt.toISOString(),\n updatedAt: item.updatedAt.toISOString(),\n })),\n total,\n page,\n pageSize,\n totalPages: Math.ceil(total / pageSize),\n }\n\n throw json(payload)\n },\n beforeCreate: async (input, ctx) => {\n const auth = ctx.auth\n const { translate } = await resolveTranslations()\n if (!auth?.tenantId) throw json({ error: translate('webhooks.errors.tenantRequired', 'Tenant context required') }, { status: 400 })\n if (!auth?.orgId) throw json({ error: translate('webhooks.errors.orgRequired', 'Organization context required') }, { status: 400 })\n\n const scopedCtx = ctx as WebhookCrudCtx\n scopedCtx.__webhookSecret = generateWebhookSecret()\n\n return input\n },\n afterCreate: async (entity, ctx) => {\n const scopedCtx = ctx as WebhookCrudCtx\n if (scopedCtx.__webhookSecret) {\n ;(entity as WebhookEntity & { __revealSecret?: string }).__revealSecret = scopedCtx.__webhookSecret\n }\n await invalidateWebhookSubscriptionCacheFor(ctx.container, resolveTenantIdForInvalidation(entity, ctx))\n },\n afterUpdate: async (entity, ctx) => {\n await invalidateWebhookSubscriptionCacheFor(ctx.container, resolveTenantIdForInvalidation(entity, ctx))\n },\n afterDelete: async (_id, ctx) => {\n await invalidateWebhookSubscriptionCacheFor(ctx.container, ctx.auth?.tenantId ?? null)\n },\n beforeDelete: async (id, ctx) => {\n const auth = ctx.auth\n const { translate } = await resolveTranslations()\n if (!auth?.tenantId) throw json({ error: translate('webhooks.errors.tenantRequired', 'Tenant context required') }, { status: 400 })\n\n const em = ctx.container.resolve('em') as EntityManager\n const record = await em.findOne(WebhookEntity, { id, deletedAt: null, tenantId: auth.tenantId })\n if (!record) throw json({ error: translate('webhooks.errors.notFound', 'Webhook not found') }, { status: 404 })\n\n const allowedIds = ctx.organizationScope?.allowedIds ?? null\n if (record.organizationId && Array.isArray(allowedIds) && allowedIds.length > 0) {\n if (!allowedIds.includes(record.organizationId)) {\n throw json({ error: translate('webhooks.errors.forbidden', 'Forbidden') }, { status: 403 })\n }\n }\n },\n },\n})\n\nexport const metadata = crud.metadata\nexport const GET = crud.GET\nexport const POST = crud.POST\nexport const PUT = crud.PUT\nexport const DELETE = crud.DELETE\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Manage webhooks',\n description: 'CRUD operations for webhook endpoints following the Standard Webhooks specification.',\n methods: {\n GET: {\n summary: 'List webhooks',\n description: 'Returns paginated webhooks for the current tenant and organization.',\n query: webhookListQuerySchema,\n responses: [{ status: 200, description: 'Webhook collection', schema: webhookCollectionResponseSchema }],\n errors: [\n { status: 400, description: 'Tenant context missing', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n ],\n },\n POST: {\n summary: 'Create webhook',\n description: 'Creates a new webhook endpoint. A signing secret (whsec_ prefixed) is auto-generated and returned once.',\n requestBody: { contentType: 'application/json', schema: webhookCreateSchema, description: 'Webhook configuration.' },\n responses: [{ status: 201, description: 'Webhook created', schema: webhookCreateResponseSchema }],\n errors: [\n { status: 400, description: 'Invalid payload', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n ],\n },\n PUT: {\n summary: 'Update webhook',\n description: 'Updates an existing webhook configuration.',\n requestBody: { contentType: 'application/json', schema: webhookUpdateSchema, description: 'Fields to update.' },\n responses: [{ status: 200, description: 'Webhook updated', schema: webhookDetailResponseSchema }],\n errors: [\n {\n status: 400,\n description: 'Invalid payload, a hidden header value with no stored value, or a URL change that keeps hidden header values for a caller without webhooks.secrets',\n schema: errorSchema,\n },\n { status: 404, description: 'Not found', schema: errorSchema },\n ],\n },\n DELETE: {\n summary: 'Delete webhook',\n description: 'Soft-deletes a webhook endpoint.',\n query: z.object({ id: z.string().uuid().describe('Webhook ID to delete') }),\n responses: [{ status: 200, description: 'Deleted', schema: deleteResponseSchema }],\n errors: [\n { status: 404, description: 'Not found', schema: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I,EAAE,YAAY;AAAA,EACpC,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS;AAAA,EAChC,UAAU,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS;AAAA,EACpC,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY;AAC3C,CAAC;AAED,MAAM,8BAA8B,EAAE,OAAO;AAAA,EAC3C,IAAI,EAAE,OAAO;AAAA,EACb,MAAM,EAAE,OAAO;AAAA,EACf,KAAK,EAAE,OAAO;AAAA,EACd,QAAQ,EAAE,OAAO;AAAA,EACjB,kBAAkB,EAAE,MAAM,EAAE,OAAO,CAAC;AAAA,EACpC,UAAU,EAAE,QAAQ;AACtB,CAAC;AAED,MAAM,
|
|
4
|
+
"sourcesContent": ["import { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { makeCrudRoute } from '@open-mercato/shared/lib/crud/factory'\nimport type { CrudCtx } from '@open-mercato/shared/lib/crud/factory'\nimport { WebhookEntity } from '../../data/entities'\nimport { webhookCreateSchema, webhookUpdateSchema, webhookListQuerySchema } from '../../data/validators'\nimport { generateWebhookSecret } from '@open-mercato/shared/lib/webhooks'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { escapeLikePattern } from '@open-mercato/shared/lib/db/escapeLikePattern'\nimport { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\nimport type { WebhookCreateInput, WebhookUpdateInput } from '../../data/validators'\nimport { invalidateWebhookSubscriptionCacheFor } from '../../lib/subscription-cache'\nimport { applyWebhookActiveState } from '../../lib/activation'\nimport { planWebhookCustomHeadersUpdate } from '../../lib/custom-headers'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { canRevealWebhookCredentialHeaders, translateWebhookCustomHeadersRejection } from '../helpers'\n\ntype WebhookCrudCtx = CrudCtx & {\n __webhookSecret?: string\n}\n\nfunction json(payload: unknown, init: ResponseInit = { status: 200 }) {\n return new Response(JSON.stringify(payload), {\n ...init,\n headers: { 'content-type': 'application/json', ...(init.headers || {}) },\n })\n}\n\nconst webhookListItemSchema = z.object({\n id: z.string(),\n name: z.string(),\n description: z.string().nullable(),\n url: z.string(),\n subscribedEvents: z.array(z.string()),\n httpMethod: z.string(),\n isActive: z.boolean(),\n deliveryStrategy: z.string(),\n maxRetries: z.number(),\n consecutiveFailures: z.number(),\n lastSuccessAt: z.string().nullable(),\n lastFailureAt: z.string().nullable(),\n createdAt: z.string(),\n updatedAt: z.string(),\n})\n\nconst webhookCollectionResponseSchema = z.object({\n items: z.array(webhookListItemSchema),\n total: z.number().int().nonnegative(),\n page: z.number().int().positive(),\n pageSize: z.number().int().positive(),\n totalPages: z.number().int().nonnegative(),\n})\n\nconst webhookCreateResponseSchema = z.object({\n id: z.string(),\n name: z.string(),\n url: z.string(),\n secret: z.string(),\n subscribedEvents: z.array(z.string()),\n isActive: z.boolean(),\n})\n\nconst successResponseSchema = z.object({ success: z.literal(true) })\nconst errorSchema = z.object({ error: z.string() })\n\nfunction resolveTenantIdForInvalidation(entity: unknown, ctx: CrudCtx): string | null {\n const entityTenantId = (entity as { tenantId?: unknown } | null)?.tenantId\n if (typeof entityTenantId === 'string' && entityTenantId.length > 0) return entityTenantId\n return ctx.auth?.tenantId ?? null\n}\n\nconst crud = makeCrudRoute<WebhookCreateInput, WebhookUpdateInput, z.infer<typeof webhookListQuerySchema>>({\n metadata: {\n GET: { requireAuth: true, requireFeatures: ['webhooks.view'] },\n POST: { requireAuth: true, requireFeatures: ['webhooks.manage'] },\n PUT: { requireAuth: true, requireFeatures: ['webhooks.manage'] },\n DELETE: { requireAuth: true, requireFeatures: ['webhooks.manage'] },\n },\n orm: { entity: WebhookEntity, orgField: 'organizationId' },\n events: { module: 'webhooks', entity: 'webhook', persistent: true },\n list: { schema: webhookListQuerySchema },\n create: {\n schema: webhookCreateSchema,\n mapToEntity: (input, ctx) => {\n const scopedCtx = ctx as WebhookCrudCtx\n const secret = scopedCtx.__webhookSecret\n if (!secret) throw new Error('Webhook secret not prepared')\n return {\n name: input.name,\n description: input.description ?? null,\n url: input.url,\n secret,\n subscribedEvents: input.subscribedEvents,\n httpMethod: input.httpMethod ?? 'POST',\n customHeaders: input.customHeaders ?? null,\n deliveryStrategy: input.deliveryStrategy ?? 'http',\n strategyConfig: input.strategyConfig ?? null,\n maxRetries: input.maxRetries ?? 10,\n timeoutMs: input.timeoutMs ?? 15000,\n rateLimitPerMinute: input.rateLimitPerMinute ?? 0,\n autoDisableThreshold: input.autoDisableThreshold ?? 100,\n integrationId: input.integrationId ?? null,\n organizationId: ctx.auth?.orgId ?? '',\n tenantId: ctx.auth?.tenantId ?? '',\n }\n },\n response: (entity) => ({\n id: entity.id,\n name: entity.name,\n url: entity.url,\n secret: (entity as WebhookEntity & { __revealSecret?: string }).__revealSecret ?? '***',\n subscribedEvents: entity.subscribedEvents,\n isActive: entity.isActive,\n }),\n },\n update: {\n schema: webhookUpdateSchema,\n applyToEntity: async (entity: WebhookEntity, input, ctx) => {\n const headersUpdate = planWebhookCustomHeadersUpdate({\n current: entity,\n next: input,\n canRevealCredentials: await canRevealWebhookCredentialHeaders(ctx.container, ctx.auth, entity),\n })\n if (!headersUpdate.ok) {\n throw new CrudHttpError(400, { error: await translateWebhookCustomHeadersRejection(headersUpdate) })\n }\n if (input.name !== undefined) entity.name = input.name\n if (input.description !== undefined) entity.description = input.description\n if (input.url !== undefined) entity.url = input.url\n if (input.subscribedEvents !== undefined) entity.subscribedEvents = input.subscribedEvents\n if (input.httpMethod !== undefined) entity.httpMethod = input.httpMethod\n if (headersUpdate.customHeaders !== undefined) entity.customHeaders = headersUpdate.customHeaders\n if (input.deliveryStrategy !== undefined) entity.deliveryStrategy = input.deliveryStrategy\n if (input.strategyConfig !== undefined) entity.strategyConfig = input.strategyConfig\n if (input.maxRetries !== undefined) entity.maxRetries = input.maxRetries\n if (input.timeoutMs !== undefined) entity.timeoutMs = input.timeoutMs\n if (input.rateLimitPerMinute !== undefined) entity.rateLimitPerMinute = input.rateLimitPerMinute\n if (input.autoDisableThreshold !== undefined) entity.autoDisableThreshold = input.autoDisableThreshold\n if (input.integrationId !== undefined) entity.integrationId = input.integrationId\n if (input.isActive !== undefined) applyWebhookActiveState(entity, input.isActive)\n },\n },\n del: { idFrom: 'query' },\n hooks: {\n beforeList: async (query, ctx) => {\n const auth = ctx.auth\n const { translate } = await resolveTranslations()\n if (!auth?.tenantId) throw json({ error: translate('webhooks.errors.tenantRequired', 'Tenant context required') }, { status: 400 })\n\n const page = Math.max(parseInt(query.page ?? '1', 10) || 1, 1)\n const pageSize = Math.min(Math.max(parseInt(query.pageSize ?? '20', 10) || 20, 1), 100)\n const search = (query.search ?? '').trim().toLowerCase()\n\n const organizationIds = Array.isArray(ctx.organizationIds) ? ctx.organizationIds : null\n if (organizationIds && organizationIds.length === 0) {\n throw json({ items: [], total: 0, page, pageSize, totalPages: 0 })\n }\n\n const em = ctx.container.resolve('em') as EntityManager\n const qb = em.createQueryBuilder(WebhookEntity, 'w')\n qb.where({ deletedAt: null })\n qb.andWhere({ tenantId: auth.tenantId })\n\n if (organizationIds && organizationIds.length > 0) {\n qb.andWhere({ organizationId: { $in: organizationIds } })\n } else if (auth.orgId) {\n qb.andWhere({ organizationId: auth.orgId })\n }\n\n if (search) {\n const pattern = `%${escapeLikePattern(search)}%`\n qb.andWhere({\n $or: [\n { name: { $ilike: pattern } },\n { url: { $ilike: pattern } },\n ],\n })\n }\n\n if (query.isActive !== undefined && query.isActive !== '') {\n const active = parseBooleanToken(query.isActive)\n if (active !== null) {\n qb.andWhere({ isActive: active })\n }\n }\n\n qb.orderBy({ createdAt: 'desc' })\n qb.limit(pageSize).offset((page - 1) * pageSize)\n const [items, total] = await qb.getResultAndCount()\n\n const payload = {\n items: items.map((item) => ({\n id: item.id,\n name: item.name,\n description: item.description ?? null,\n url: item.url,\n subscribedEvents: item.subscribedEvents,\n httpMethod: item.httpMethod,\n isActive: item.isActive,\n deliveryStrategy: item.deliveryStrategy,\n maxRetries: item.maxRetries,\n consecutiveFailures: item.consecutiveFailures,\n lastSuccessAt: item.lastSuccessAt?.toISOString() ?? null,\n lastFailureAt: item.lastFailureAt?.toISOString() ?? null,\n createdAt: item.createdAt.toISOString(),\n updatedAt: item.updatedAt.toISOString(),\n })),\n total,\n page,\n pageSize,\n totalPages: Math.ceil(total / pageSize),\n }\n\n throw json(payload)\n },\n beforeCreate: async (input, ctx) => {\n const auth = ctx.auth\n const { translate } = await resolveTranslations()\n if (!auth?.tenantId) throw json({ error: translate('webhooks.errors.tenantRequired', 'Tenant context required') }, { status: 400 })\n if (!auth?.orgId) throw json({ error: translate('webhooks.errors.orgRequired', 'Organization context required') }, { status: 400 })\n\n const scopedCtx = ctx as WebhookCrudCtx\n scopedCtx.__webhookSecret = generateWebhookSecret()\n\n return input\n },\n afterCreate: async (entity, ctx) => {\n const scopedCtx = ctx as WebhookCrudCtx\n if (scopedCtx.__webhookSecret) {\n ;(entity as WebhookEntity & { __revealSecret?: string }).__revealSecret = scopedCtx.__webhookSecret\n }\n await invalidateWebhookSubscriptionCacheFor(ctx.container, resolveTenantIdForInvalidation(entity, ctx))\n },\n afterUpdate: async (entity, ctx) => {\n await invalidateWebhookSubscriptionCacheFor(ctx.container, resolveTenantIdForInvalidation(entity, ctx))\n },\n afterDelete: async (_id, ctx) => {\n await invalidateWebhookSubscriptionCacheFor(ctx.container, ctx.auth?.tenantId ?? null)\n },\n beforeDelete: async (id, ctx) => {\n const auth = ctx.auth\n const { translate } = await resolveTranslations()\n if (!auth?.tenantId) throw json({ error: translate('webhooks.errors.tenantRequired', 'Tenant context required') }, { status: 400 })\n\n const em = ctx.container.resolve('em') as EntityManager\n const record = await em.findOne(WebhookEntity, { id, deletedAt: null, tenantId: auth.tenantId })\n if (!record) throw json({ error: translate('webhooks.errors.notFound', 'Webhook not found') }, { status: 404 })\n\n const allowedIds = ctx.organizationScope?.allowedIds ?? null\n if (record.organizationId && Array.isArray(allowedIds) && allowedIds.length > 0) {\n if (!allowedIds.includes(record.organizationId)) {\n throw json({ error: translate('webhooks.errors.forbidden', 'Forbidden') }, { status: 403 })\n }\n }\n },\n },\n})\n\nexport const metadata = crud.metadata\nexport const GET = crud.GET\nexport const POST = crud.POST\nexport const PUT = crud.PUT\nexport const DELETE = crud.DELETE\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Manage webhooks',\n description: 'CRUD operations for webhook endpoints following the Standard Webhooks specification.',\n methods: {\n GET: {\n summary: 'List webhooks',\n description: 'Returns paginated webhooks for the current tenant and organization.',\n query: webhookListQuerySchema,\n responses: [{ status: 200, description: 'Webhook collection', schema: webhookCollectionResponseSchema }],\n errors: [\n { status: 400, description: 'Tenant context missing', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n ],\n },\n POST: {\n summary: 'Create webhook',\n description: 'Creates a new webhook endpoint. A signing secret (whsec_ prefixed) is auto-generated and returned once.',\n requestBody: { contentType: 'application/json', schema: webhookCreateSchema, description: 'Webhook configuration.' },\n responses: [{ status: 201, description: 'Webhook created', schema: webhookCreateResponseSchema }],\n errors: [\n { status: 400, description: 'Invalid payload', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n ],\n },\n PUT: {\n summary: 'Update webhook',\n description: 'Updates an existing webhook configuration.',\n requestBody: { contentType: 'application/json', schema: webhookUpdateSchema, description: 'Fields to update.' },\n responses: [{ status: 200, description: 'Webhook updated', schema: successResponseSchema }],\n errors: [\n {\n status: 400,\n description: 'Invalid payload, a hidden header value with no stored value, or a URL change that keeps hidden header values for a caller without webhooks.secrets',\n schema: errorSchema,\n },\n { status: 404, description: 'Not found', schema: errorSchema },\n ],\n },\n DELETE: {\n summary: 'Delete webhook',\n description: 'Soft-deletes a webhook endpoint.',\n query: z.object({ id: z.string().uuid().describe('Webhook ID to delete') }),\n responses: [{ status: 200, description: 'Deleted', schema: successResponseSchema }],\n errors: [\n { status: 404, description: 'Not found', schema: err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,KAAK,aAAa,aAAa,QAAQ,YAAY;AAAA,MAC/D;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -44,6 +44,7 @@ const webhookCreateSchema = webhookFieldsSchema.extend({
|
|
|
44
44
|
autoDisableThreshold: webhookFieldsSchema.shape.autoDisableThreshold.default(100)
|
|
45
45
|
});
|
|
46
46
|
const webhookUpdateSchema = webhookFieldsSchema.partial().extend({
|
|
47
|
+
id: z.string().uuid().optional(),
|
|
47
48
|
isActive: z.boolean().optional()
|
|
48
49
|
});
|
|
49
50
|
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\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,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,aA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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 id: z.string().uuid().optional(),\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,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;AAED,MAAM,sBAAsB,EAAE,OAAO;AAAA,EACnC,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG;AAAA,EAC/B,aAAa,EAAE,OAAO,EAAE,IAAI,GAAI,EAAE,SAAS,EAAE,SAAS;AAAA,EACtD,KAAK;AAAA,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ACjC,CAAC;AAIM,MAAM,yBAAyB,EAAE,OAAO;AAAA,EAC7C,MAAM,EAAE,OAAO,EAAE,SAAS;AAAA,EAC1B,UAAU,EAAE,OAAO,EAAE,SAAS;AAAA,EAC9B,QAAQ,EAAE,OAAO,EAAE,SAAS;AAAA,EAC5B,UAAU,EAAE,OAAO,EAAE,SAAS;AAChC,CAAC;AAEM,MAAM,6BAA6B,EAAE,OAAO;AAAA,EACjD,MAAM,EAAE,OAAO,OAAO,EAAE,IAAI,CAAC,EAAE,QAAQ,CAAC;AAAA,EACxC,UAAU,EAAE,OAAO,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,QAAQ,EAAE;AAAA,EACtD,WAAW,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;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.7917.1.c74e12c1d2",
|
|
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.7917.1.c74e12c1d2",
|
|
74
|
+
"@open-mercato/core": "0.10.1-develop.7917.1.c74e12c1d2",
|
|
75
|
+
"@open-mercato/queue": "0.10.1-develop.7917.1.c74e12c1d2",
|
|
76
|
+
"@open-mercato/ui": "0.10.1-develop.7917.1.c74e12c1d2",
|
|
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.7917.1.c74e12c1d2",
|
|
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.7917.1.c74e12c1d2",
|
|
87
87
|
"@types/jest": "^30.0.0",
|
|
88
88
|
"@types/react": "^19.2.18",
|
|
89
89
|
"@types/react-dom": "^19.2.5",
|
|
@@ -70,4 +70,32 @@ test.describe('TC-WEBHOOK-001: Webhook configuration CRUD', () => {
|
|
|
70
70
|
await deleteWebhookIfExists(request, token, webhookId);
|
|
71
71
|
}
|
|
72
72
|
});
|
|
73
|
+
|
|
74
|
+
test('PUT /api/webhooks/webhooks (the documented makeCrudRoute alias) updates by body id like PUT /api/webhooks/:id (#7504)', async ({ request }) => {
|
|
75
|
+
const token = await getAuthToken(request);
|
|
76
|
+
let webhookId: string | null = null;
|
|
77
|
+
|
|
78
|
+
try {
|
|
79
|
+
const created = await createWebhookFixture(request, token, {
|
|
80
|
+
name: `Webhook Alias PUT ${Date.now()}`,
|
|
81
|
+
url: 'https://example.com/webhook-alias-put',
|
|
82
|
+
subscribedEvents: ['sales.quote.created'],
|
|
83
|
+
});
|
|
84
|
+
webhookId = created.id;
|
|
85
|
+
|
|
86
|
+
const renamedName = `Webhook Alias PUT Renamed ${Date.now()}`;
|
|
87
|
+
const aliasUpdateResponse = await apiRequest(request, 'PUT', '/api/webhooks/webhooks', {
|
|
88
|
+
token,
|
|
89
|
+
data: { id: created.id, name: renamedName },
|
|
90
|
+
});
|
|
91
|
+
expect(aliasUpdateResponse.status()).toBe(200);
|
|
92
|
+
const aliasUpdated = await readJsonSafe<{ success: true }>(aliasUpdateResponse);
|
|
93
|
+
expect(aliasUpdated).toEqual({ success: true });
|
|
94
|
+
|
|
95
|
+
const detail = await getWebhookDetail(request, token, created.id);
|
|
96
|
+
expect(detail.name).toBe(renamedName);
|
|
97
|
+
} finally {
|
|
98
|
+
await deleteWebhookIfExists(request, token, webhookId);
|
|
99
|
+
}
|
|
100
|
+
});
|
|
73
101
|
});
|
|
@@ -61,18 +61,7 @@ const webhookCreateResponseSchema = z.object({
|
|
|
61
61
|
isActive: z.boolean(),
|
|
62
62
|
})
|
|
63
63
|
|
|
64
|
-
const
|
|
65
|
-
customHeaders: z.record(z.string(), z.string()).nullable().describe(
|
|
66
|
-
'Credential-like header values are returned as •••••••• unless the caller has webhooks.secrets. Sending •••••••• back on update keeps the stored value.',
|
|
67
|
-
),
|
|
68
|
-
strategyConfig: z.record(z.string(), z.unknown()).nullable(),
|
|
69
|
-
timeoutMs: z.number(),
|
|
70
|
-
rateLimitPerMinute: z.number(),
|
|
71
|
-
autoDisableThreshold: z.number(),
|
|
72
|
-
integrationId: z.string().nullable(),
|
|
73
|
-
})
|
|
74
|
-
|
|
75
|
-
const deleteResponseSchema = z.object({ success: z.literal(true) })
|
|
64
|
+
const successResponseSchema = z.object({ success: z.literal(true) })
|
|
76
65
|
const errorSchema = z.object({ error: z.string() })
|
|
77
66
|
|
|
78
67
|
function resolveTenantIdForInvalidation(entity: unknown, ctx: CrudCtx): string | null {
|
|
@@ -302,7 +291,7 @@ export const openApi: OpenApiRouteDoc = {
|
|
|
302
291
|
summary: 'Update webhook',
|
|
303
292
|
description: 'Updates an existing webhook configuration.',
|
|
304
293
|
requestBody: { contentType: 'application/json', schema: webhookUpdateSchema, description: 'Fields to update.' },
|
|
305
|
-
responses: [{ status: 200, description: 'Webhook updated', schema:
|
|
294
|
+
responses: [{ status: 200, description: 'Webhook updated', schema: successResponseSchema }],
|
|
306
295
|
errors: [
|
|
307
296
|
{
|
|
308
297
|
status: 400,
|
|
@@ -316,7 +305,7 @@ export const openApi: OpenApiRouteDoc = {
|
|
|
316
305
|
summary: 'Delete webhook',
|
|
317
306
|
description: 'Soft-deletes a webhook endpoint.',
|
|
318
307
|
query: z.object({ id: z.string().uuid().describe('Webhook ID to delete') }),
|
|
319
|
-
responses: [{ status: 200, description: 'Deleted', schema:
|
|
308
|
+
responses: [{ status: 200, description: 'Deleted', schema: successResponseSchema }],
|
|
320
309
|
errors: [
|
|
321
310
|
{ status: 404, description: 'Not found', schema: errorSchema },
|
|
322
311
|
{ status: 403, description: 'Forbidden', schema: errorSchema },
|
|
@@ -189,3 +189,28 @@ describe('webhookCreateSchema — defaults', () => {
|
|
|
189
189
|
expect(webhookCreateSchema.safeParse(baseInput({ httpMethod: 'GET' })).success).toBe(false)
|
|
190
190
|
})
|
|
191
191
|
})
|
|
192
|
+
|
|
193
|
+
describe('webhookUpdateSchema — id field (#7504)', () => {
|
|
194
|
+
const WEBHOOK_ID = '123e4567-e89b-12d3-a456-426614174099'
|
|
195
|
+
|
|
196
|
+
it('retains a valid id instead of stripping it', () => {
|
|
197
|
+
const result = webhookUpdateSchema.safeParse({ id: WEBHOOK_ID, name: 'Renamed' })
|
|
198
|
+
expect(result.success).toBe(true)
|
|
199
|
+
if (result.success) {
|
|
200
|
+
expect(result.data.id).toBe(WEBHOOK_ID)
|
|
201
|
+
}
|
|
202
|
+
})
|
|
203
|
+
|
|
204
|
+
it('parses successfully when id is omitted, matching the PUT /:id route body shape', () => {
|
|
205
|
+
const result = webhookUpdateSchema.safeParse({ name: 'Renamed' })
|
|
206
|
+
expect(result.success).toBe(true)
|
|
207
|
+
if (result.success) {
|
|
208
|
+
expect(result.data.id).toBeUndefined()
|
|
209
|
+
}
|
|
210
|
+
})
|
|
211
|
+
|
|
212
|
+
it('rejects a non-uuid id', () => {
|
|
213
|
+
const result = webhookUpdateSchema.safeParse({ id: 'not-a-uuid', name: 'Renamed' })
|
|
214
|
+
expect(result.success).toBe(false)
|
|
215
|
+
})
|
|
216
|
+
})
|
|
@@ -53,6 +53,7 @@ export const webhookCreateSchema = webhookFieldsSchema.extend({
|
|
|
53
53
|
export type WebhookCreateInput = z.infer<typeof webhookCreateSchema>
|
|
54
54
|
|
|
55
55
|
export const webhookUpdateSchema = webhookFieldsSchema.partial().extend({
|
|
56
|
+
id: z.string().uuid().optional(),
|
|
56
57
|
isActive: z.boolean().optional(),
|
|
57
58
|
})
|
|
58
59
|
|