@open-mercato/webhooks 0.8.1-develop.7296.1.2111d779db → 0.9.0
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/api/helpers.js +2 -1
- package/dist/modules/webhooks/api/helpers.js.map +2 -2
- package/dist/modules/webhooks/api/webhook-deliveries/route.js +4 -2
- package/dist/modules/webhooks/api/webhook-deliveries/route.js.map +2 -2
- package/package.json +8 -9
- package/src/modules/webhooks/api/__tests__/helpers.scope.test.ts +43 -0
- package/src/modules/webhooks/api/helpers.ts +2 -1
- package/src/modules/webhooks/api/webhook-deliveries/__tests__/route.scope.test.ts +62 -0
- package/src/modules/webhooks/api/webhook-deliveries/route.ts +4 -2
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
|
|
2
2
|
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
|
|
3
|
+
import { resolveSingleOrganizationIdOrDeny } from "@open-mercato/shared/lib/auth/organizationScope";
|
|
3
4
|
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
|
|
4
5
|
import { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
|
|
5
6
|
import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
@@ -19,7 +20,7 @@ async function resolveWebhookRequestScope(request) {
|
|
|
19
20
|
}
|
|
20
21
|
const scope = await resolveOrganizationScopeForRequest({ container, auth, request });
|
|
21
22
|
const tenantId = scope?.tenantId ?? auth.tenantId ?? null;
|
|
22
|
-
const organizationId = scope
|
|
23
|
+
const organizationId = resolveSingleOrganizationIdOrDeny(scope, auth);
|
|
23
24
|
const allowedOrganizationIds = Array.isArray(scope?.allowedIds) ? scope.allowedIds : null;
|
|
24
25
|
if (!tenantId) {
|
|
25
26
|
return json({ error: translate("webhooks.errors.tenantRequired", "Tenant context required") }, { status: 400 });
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/webhooks/api/helpers.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { WebhookDeliveryEntity, WebhookEntity } from '../data/entities'\n\nexport type WebhookRequestScope = {\n container: Awaited<ReturnType<typeof createRequestContainer>>\n em: EntityManager\n tenantId: string\n organizationId: string | null\n allowedOrganizationIds: string[] | null\n}\n\nexport function json(payload: unknown, init: ResponseInit = { status: 200 }): Response {\n return new Response(JSON.stringify(payload), {\n ...init,\n headers: { 'content-type': 'application/json', ...(init.headers || {}) },\n })\n}\n\nexport async function resolveWebhookRequestScope(request: Request): Promise<WebhookRequestScope | Response> {\n const container = await createRequestContainer()\n const auth = await getAuthFromRequest(request)\n const { translate } = await resolveTranslations()\n\n if (!auth) {\n return json({ error: translate('api.errors.unauthorized', 'Unauthorized') }, { status: 401 })\n }\n\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request })\n const tenantId = scope?.tenantId ?? auth.tenantId ?? null\n const organizationId = scope
|
|
5
|
-
"mappings": "AACA,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,2BAA2B;AACpC,SAAS,0CAA0C;AACnD,SAAS,6BAA6B;AACtC,SAAS,uBAAuB,qBAAqB;AAU9C,SAAS,KAAK,SAAkB,OAAqB,EAAE,QAAQ,IAAI,GAAa;AACrF,SAAO,IAAI,SAAS,KAAK,UAAU,OAAO,GAAG;AAAA,IAC3C,GAAG;AAAA,IACH,SAAS,EAAE,gBAAgB,oBAAoB,GAAI,KAAK,WAAW,CAAC,EAAG;AAAA,EACzE,CAAC;AACH;AAEA,eAAsB,2BAA2B,SAA2D;AAC1G,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,OAAO,MAAM,mBAAmB,OAAO;AAC7C,QAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAEhD,MAAI,CAAC,MAAM;AACT,WAAO,KAAK,EAAE,OAAO,UAAU,2BAA2B,cAAc,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC9F;AAEA,QAAM,QAAQ,MAAM,mCAAmC,EAAE,WAAW,MAAM,QAAQ,CAAC;AACnF,QAAM,WAAW,OAAO,YAAY,KAAK,YAAY;AACrD,QAAM,iBAAiB,OAAO,
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveSingleOrganizationIdOrDeny } from '@open-mercato/shared/lib/auth/organizationScope'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { WebhookDeliveryEntity, WebhookEntity } from '../data/entities'\n\nexport type WebhookRequestScope = {\n container: Awaited<ReturnType<typeof createRequestContainer>>\n em: EntityManager\n tenantId: string\n organizationId: string | null\n allowedOrganizationIds: string[] | null\n}\n\nexport function json(payload: unknown, init: ResponseInit = { status: 200 }): Response {\n return new Response(JSON.stringify(payload), {\n ...init,\n headers: { 'content-type': 'application/json', ...(init.headers || {}) },\n })\n}\n\nexport async function resolveWebhookRequestScope(request: Request): Promise<WebhookRequestScope | Response> {\n const container = await createRequestContainer()\n const auth = await getAuthFromRequest(request)\n const { translate } = await resolveTranslations()\n\n if (!auth) {\n return json({ error: translate('api.errors.unauthorized', 'Unauthorized') }, { status: 401 })\n }\n\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request })\n const tenantId = scope?.tenantId ?? auth.tenantId ?? null\n const organizationId = resolveSingleOrganizationIdOrDeny(scope, auth)\n const allowedOrganizationIds = Array.isArray(scope?.allowedIds) ? scope.allowedIds : null\n\n if (!tenantId) {\n return json({ error: translate('webhooks.errors.tenantRequired', 'Tenant context required') }, { status: 400 })\n }\n\n return {\n container,\n em: container.resolve('em') as EntityManager,\n tenantId,\n organizationId,\n allowedOrganizationIds,\n }\n}\n\nexport async function findScopedWebhook(\n em: EntityManager,\n scope: Pick<WebhookRequestScope, 'tenantId' | 'organizationId' | 'allowedOrganizationIds'>,\n webhookId: string,\n): Promise<WebhookEntity | null> {\n const webhook = await findOneWithDecryption(\n em,\n WebhookEntity,\n { id: webhookId, tenantId: scope.tenantId, deletedAt: null },\n {},\n { tenantId: scope.tenantId, organizationId: scope.organizationId ?? '' },\n )\n\n if (!webhook) return null\n if (scope.allowedOrganizationIds && scope.allowedOrganizationIds.length > 0 && !scope.allowedOrganizationIds.includes(webhook.organizationId)) {\n return null\n }\n if (!scope.allowedOrganizationIds && scope.organizationId && webhook.organizationId !== scope.organizationId) {\n return null\n }\n\n return webhook\n}\n\nexport async function findScopedDelivery(\n em: EntityManager,\n scope: Pick<WebhookRequestScope, 'tenantId' | 'organizationId' | 'allowedOrganizationIds'>,\n deliveryId: string,\n): Promise<WebhookDeliveryEntity | null> {\n const delivery = await em.findOne(WebhookDeliveryEntity, { id: deliveryId, tenantId: scope.tenantId })\n if (!delivery) return null\n\n if (scope.allowedOrganizationIds && scope.allowedOrganizationIds.length > 0 && !scope.allowedOrganizationIds.includes(delivery.organizationId)) {\n return null\n }\n if (!scope.allowedOrganizationIds && scope.organizationId && delivery.organizationId !== scope.organizationId) {\n return null\n }\n\n return delivery\n}\n\nexport function serializeWebhookListItem(item: WebhookEntity) {\n return {\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}\n\nexport function serializeWebhookDetail(item: WebhookEntity) {\n return {\n ...serializeWebhookListItem(item),\n customHeaders: item.customHeaders ?? null,\n strategyConfig: item.strategyConfig ?? null,\n timeoutMs: item.timeoutMs,\n rateLimitPerMinute: item.rateLimitPerMinute,\n autoDisableThreshold: item.autoDisableThreshold,\n integrationId: item.integrationId ?? null,\n maskedSecret: maskSecret(item.secret),\n previousSecretSetAt: item.previousSecretSetAt?.toISOString() ?? null,\n }\n}\n\nexport function serializeDeliveryListItem(\n item: WebhookDeliveryEntity,\n options: { webhookName?: string | null } = {},\n) {\n return {\n id: item.id,\n webhookId: item.webhookId,\n webhookName: options.webhookName ?? null,\n eventType: item.eventType,\n messageId: item.messageId,\n status: item.status,\n responseStatus: item.responseStatus ?? null,\n errorMessage: item.errorMessage ?? null,\n attemptNumber: item.attemptNumber,\n maxAttempts: item.maxAttempts,\n targetUrl: item.targetUrl,\n durationMs: item.durationMs ?? null,\n enqueuedAt: item.enqueuedAt.toISOString(),\n lastAttemptAt: item.lastAttemptAt?.toISOString() ?? null,\n deliveredAt: item.deliveredAt?.toISOString() ?? null,\n createdAt: item.createdAt.toISOString(),\n }\n}\n\nexport function serializeDeliveryDetail(item: WebhookDeliveryEntity) {\n return {\n ...serializeDeliveryListItem(item),\n payload: item.payload,\n responseBody: item.responseBody ?? null,\n responseHeaders: item.responseHeaders ?? null,\n nextRetryAt: item.nextRetryAt?.toISOString() ?? null,\n updatedAt: item.updatedAt.toISOString(),\n }\n}\n\nfunction maskSecret(secret: string): string {\n if (!secret) return '\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022'\n return `${secret.sl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,WAAW,QAAwB;AAC1C,MAAI,CAAC,OAAQ,QAAO;AACpB,SAAO,GAAG,OAAO,MAAM,GAAG,CAAC,CAAC;AAC9B;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -4,6 +4,7 @@ import { findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
|
4
4
|
import { WebhookDeliveryEntity, WebhookEntity } from "../../data/entities.js";
|
|
5
5
|
import { webhookDeliveryQuerySchema } from "../../data/validators.js";
|
|
6
6
|
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
|
|
7
|
+
import { resolveSingleOrganizationIdOrDeny } from "@open-mercato/shared/lib/auth/organizationScope";
|
|
7
8
|
import { serializeDeliveryListItem } from "../helpers.js";
|
|
8
9
|
function json(payload, init = { status: 200 }) {
|
|
9
10
|
return new Response(JSON.stringify(payload), {
|
|
@@ -46,6 +47,7 @@ const crud = makeCrudRoute({
|
|
|
46
47
|
hooks: {
|
|
47
48
|
beforeList: async (query, ctx) => {
|
|
48
49
|
const auth = ctx.auth;
|
|
50
|
+
const scopedOrganizationId = resolveSingleOrganizationIdOrDeny(ctx.organizationScope, auth);
|
|
49
51
|
const { translate } = await resolveTranslations();
|
|
50
52
|
if (!auth?.tenantId) throw json({ error: translate("webhooks.errors.tenantRequired", "Tenant context required") }, { status: 400 });
|
|
51
53
|
const page = query.page ?? 1;
|
|
@@ -56,8 +58,8 @@ const crud = makeCrudRoute({
|
|
|
56
58
|
const allowedIds = ctx.organizationScope?.allowedIds ?? null;
|
|
57
59
|
if (allowedIds && allowedIds.length > 0) {
|
|
58
60
|
qb.andWhere({ organizationId: { $in: allowedIds } });
|
|
59
|
-
} else if (
|
|
60
|
-
qb.andWhere({ organizationId:
|
|
61
|
+
} else if (scopedOrganizationId) {
|
|
62
|
+
qb.andWhere({ organizationId: scopedOrganizationId });
|
|
61
63
|
}
|
|
62
64
|
if (query.webhookId) {
|
|
63
65
|
qb.andWhere({ webhookId: query.webhookId });
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/modules/webhooks/api/webhook-deliveries/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 { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { WebhookDeliveryEntity, WebhookEntity } from '../../data/entities'\nimport { webhookDeliveryQuerySchema } from '../../data/validators'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { serializeDeliveryListItem } from '../helpers'\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 deliveryItemSchema = z.object({\n id: z.string(),\n webhookId: z.string(),\n webhookName: z.string().nullable(),\n eventType: z.string(),\n messageId: z.string(),\n status: z.string(),\n responseStatus: z.number().nullable(),\n errorMessage: z.string().nullable(),\n attemptNumber: z.number(),\n maxAttempts: z.number(),\n targetUrl: z.string(),\n durationMs: z.number().nullable(),\n enqueuedAt: z.string(),\n lastAttemptAt: z.string().nullable(),\n deliveredAt: z.string().nullable(),\n createdAt: z.string(),\n})\n\nconst deliveryCollectionResponseSchema = z.object({\n items: z.array(deliveryItemSchema),\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 errorSchema = z.object({ error: z.string() })\n\nconst crud = makeCrudRoute<never, never, z.infer<typeof webhookDeliveryQuerySchema>>({\n metadata: {\n GET: { requireAuth: true, requireFeatures: ['webhooks.view'] },\n },\n orm: { entity: WebhookDeliveryEntity, orgField: 'organizationId' },\n list: { schema: webhookDeliveryQuerySchema },\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 = query.page ?? 1\n const pageSize = Math.min(query.pageSize ?? 50, 100)\n\n const em = ctx.container.resolve('em') as EntityManager\n const qb = em.createQueryBuilder(WebhookDeliveryEntity, 'd')\n qb.where({ tenantId: auth.tenantId })\n\n const allowedIds = ctx.organizationScope?.allowedIds ?? null\n if (allowedIds && allowedIds.length > 0) {\n qb.andWhere({ organizationId: { $in: allowedIds } })\n } else if (
|
|
5
|
-
"mappings": "AAAA,SAAS,SAAS;AAGlB,SAAS,qBAAqB;AAE9B,SAAS,0BAA0B;AACnC,SAAS,uBAAuB,qBAAqB;AACrD,SAAS,kCAAkC;AAC3C,SAAS,2BAA2B;AACpC,SAAS,iCAAiC;AAE1C,SAAS,KAAK,SAAkB,OAAqB,EAAE,QAAQ,IAAI,GAAG;AACpE,SAAO,IAAI,SAAS,KAAK,UAAU,OAAO,GAAG;AAAA,IAC3C,GAAG;AAAA,IACH,SAAS,EAAE,gBAAgB,oBAAoB,GAAI,KAAK,WAAW,CAAC,EAAG;AAAA,EACzE,CAAC;AACH;AAEA,MAAM,qBAAqB,EAAE,OAAO;AAAA,EAClC,IAAI,EAAE,OAAO;AAAA,EACb,WAAW,EAAE,OAAO;AAAA,EACpB,aAAa,EAAE,OAAO,EAAE,SAAS;AAAA,EACjC,WAAW,EAAE,OAAO;AAAA,EACpB,WAAW,EAAE,OAAO;AAAA,EACpB,QAAQ,EAAE,OAAO;AAAA,EACjB,gBAAgB,EAAE,OAAO,EAAE,SAAS;AAAA,EACpC,cAAc,EAAE,OAAO,EAAE,SAAS;AAAA,EAClC,eAAe,EAAE,OAAO;AAAA,EACxB,aAAa,EAAE,OAAO;AAAA,EACtB,WAAW,EAAE,OAAO;AAAA,EACpB,YAAY,EAAE,OAAO,EAAE,SA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B,cAAc;AACxD,UAAI,cAAc,WAAW,SAAS,GAAG;AACvC,WAAG,SAAS,EAAE,gBAAgB,EAAE,KAAK,WAAW,EAAE,CAAC;AAAA,MACrD,WAAW,
|
|
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 { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { WebhookDeliveryEntity, WebhookEntity } from '../../data/entities'\nimport { webhookDeliveryQuerySchema } from '../../data/validators'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { resolveSingleOrganizationIdOrDeny } from '@open-mercato/shared/lib/auth/organizationScope'\nimport { serializeDeliveryListItem } from '../helpers'\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 deliveryItemSchema = z.object({\n id: z.string(),\n webhookId: z.string(),\n webhookName: z.string().nullable(),\n eventType: z.string(),\n messageId: z.string(),\n status: z.string(),\n responseStatus: z.number().nullable(),\n errorMessage: z.string().nullable(),\n attemptNumber: z.number(),\n maxAttempts: z.number(),\n targetUrl: z.string(),\n durationMs: z.number().nullable(),\n enqueuedAt: z.string(),\n lastAttemptAt: z.string().nullable(),\n deliveredAt: z.string().nullable(),\n createdAt: z.string(),\n})\n\nconst deliveryCollectionResponseSchema = z.object({\n items: z.array(deliveryItemSchema),\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 errorSchema = z.object({ error: z.string() })\n\nconst crud = makeCrudRoute<never, never, z.infer<typeof webhookDeliveryQuerySchema>>({\n metadata: {\n GET: { requireAuth: true, requireFeatures: ['webhooks.view'] },\n },\n orm: { entity: WebhookDeliveryEntity, orgField: 'organizationId' },\n list: { schema: webhookDeliveryQuerySchema },\n hooks: {\n beforeList: async (query, ctx) => {\n const auth = ctx.auth\n const scopedOrganizationId = resolveSingleOrganizationIdOrDeny(ctx.organizationScope, 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 = query.page ?? 1\n const pageSize = Math.min(query.pageSize ?? 50, 100)\n\n const em = ctx.container.resolve('em') as EntityManager\n const qb = em.createQueryBuilder(WebhookDeliveryEntity, 'd')\n qb.where({ tenantId: auth.tenantId })\n\n const allowedIds = ctx.organizationScope?.allowedIds ?? null\n if (allowedIds && allowedIds.length > 0) {\n qb.andWhere({ organizationId: { $in: allowedIds } })\n } else if (scopedOrganizationId) {\n qb.andWhere({ organizationId: scopedOrganizationId })\n }\n\n if (query.webhookId) {\n qb.andWhere({ webhookId: query.webhookId })\n }\n\n if (query.eventType) {\n qb.andWhere({ eventType: query.eventType })\n }\n\n if (query.status) {\n qb.andWhere({ status: query.status })\n }\n\n qb.orderBy({ createdAt: 'desc' })\n qb.limit(pageSize).offset((page - 1) * pageSize)\n const [items, total] = await qb.getResultAndCount()\n const webhookIds = Array.from(new Set(items.map((item) => item.webhookId)))\n const webhooks = webhookIds.length > 0\n ? await findWithDecryption(\n em,\n WebhookEntity,\n {\n id: { $in: webhookIds },\n tenantId: auth.tenantId,\n deletedAt: null,\n },\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId ?? '' },\n )\n : []\n const webhookNames = new Map(webhooks.map((webhook) => [webhook.id, webhook.name]))\n\n const payload = {\n items: items.map((item) => serializeDeliveryListItem(item, {\n webhookName: webhookNames.get(item.webhookId) ?? null,\n })),\n total,\n page,\n pageSize,\n totalPages: Math.ceil(total / pageSize),\n }\n\n throw json(payload)\n },\n },\n})\n\nexport const metadata = crud.metadata\nexport const GET = crud.GET\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Webhook delivery logs',\n description: 'View delivery attempts for webhook endpoints.',\n methods: {\n GET: {\n summary: 'List delivery logs',\n description: 'Returns paginated webhook delivery attempts with filtering by webhook, event type, and status.',\n query: webhookDeliveryQuerySchema,\n responses: [{ status: 200, description: 'Delivery log collection', schema: deliveryCollectionResponseSchema }],\n errors: [\n { status: 400, description: 'Tenant context missing', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,SAAS;AAGlB,SAAS,qBAAqB;AAE9B,SAAS,0BAA0B;AACnC,SAAS,uBAAuB,qBAAqB;AACrD,SAAS,kCAAkC;AAC3C,SAAS,2BAA2B;AACpC,SAAS,yCAAyC;AAClD,SAAS,iCAAiC;AAE1C,SAAS,KAAK,SAAkB,OAAqB,EAAE,QAAQ,IAAI,GAAG;AACpE,SAAO,IAAI,SAAS,KAAK,UAAU,OAAO,GAAG;AAAA,IAC3C,GAAG;AAAA,IACH,SAAS,EAAE,gBAAgB,oBAAoB,GAAI,KAAK,WAAW,CAAC,EAAG;AAAA,EACzE,CAAC;AACH;AAEA,MAAM,qBAAqB,EAAE,OAAO;AAAA,EAClC,IAAI,EAAE,OAAO;AAAA,EACb,WAAW,EAAE,OAAO;AAAA,EACpB,aAAa,EAAE,OAAO,EAAE,SAAS;AAAA,EACjC,WAAW,EAAE,OAAO;AAAA,EACpB,WAAW,EAAE,OAAO;AAAA,EACpB,QAAQ,EAAE,OAAO;AAAA,EACjB,gBAAgB,EAAE,OAAO,EAAE,SAAS;AAAA,EACpC,cAAc,EAAE,OAAO,EAAE,SAAS;AAAA,EAClC,eAAe,EAAE,OAAO;AAAA,EACxB,aAAa,EAAE,OAAO;AAAA,EACtB,WAAW,EAAE,OAAO;AAAA,EACpB,YAAY,EAAE,OAAO,EAAE,SAAS;AAAA,EAChC,YAAY,EAAE,OAAO;AAAA,EACrB,eAAe,EAAE,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,QACA,YAAY,KAAK,KAAK,QAAQ,QAAQ;AAAA,MACxC;AAEA,YAAM,KAAK,OAAO;AAAA,IACpB;AAAA,EACF;AACF,CAAC;AAEM,MAAM,WAAW,KAAK;AACtB,MAAM,MAAM,KAAK;AAEjB,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,SAAS;AAAA,IACP,KAAK;AAAA,MACH,SAAS;AAAA,MACT,aAAa;AAAA,MACb,OAAO;AAAA,MACP,WAAW,CAAC,EAAE,QAAQ,KAAK,aAAa,2BAA2B,QAAQ,iCAAiC,CAAC;AAAA,MAC7G,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,0BAA0B,QAAQ,YAAY;AAAA,QAC1E,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,YAAY;AAAA,MAClE;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/webhooks",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
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.
|
|
74
|
-
"@open-mercato/core": "0.
|
|
75
|
-
"@open-mercato/queue": "0.
|
|
76
|
-
"@open-mercato/ui": "0.
|
|
73
|
+
"@open-mercato/cache": "0.9.0",
|
|
74
|
+
"@open-mercato/core": "0.9.0",
|
|
75
|
+
"@open-mercato/queue": "0.9.0",
|
|
76
|
+
"@open-mercato/ui": "0.9.0",
|
|
77
77
|
"svix": "^1.99.1"
|
|
78
78
|
},
|
|
79
79
|
"peerDependencies": {
|
|
80
80
|
"@mikro-orm/postgresql": "^7.0.14",
|
|
81
|
-
"@open-mercato/shared": "0.
|
|
81
|
+
"@open-mercato/shared": "0.9.0",
|
|
82
82
|
"react": "^19.0.0",
|
|
83
83
|
"react-dom": "^19.0.0"
|
|
84
84
|
},
|
|
85
85
|
"devDependencies": {
|
|
86
|
-
"@open-mercato/shared": "0.
|
|
86
|
+
"@open-mercato/shared": "0.9.0",
|
|
87
87
|
"@types/jest": "^30.0.0",
|
|
88
88
|
"@types/react": "^19.2.18",
|
|
89
89
|
"@types/react-dom": "^19.2.5",
|
|
@@ -102,6 +102,5 @@
|
|
|
102
102
|
"type": "git",
|
|
103
103
|
"url": "https://github.com/open-mercato/open-mercato",
|
|
104
104
|
"directory": "packages/webhooks"
|
|
105
|
-
}
|
|
106
|
-
"stableVersion": "0.8.0"
|
|
105
|
+
}
|
|
107
106
|
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { resolveWebhookRequestScope } from '../helpers'
|
|
2
|
+
|
|
3
|
+
const resolveContainerValue = jest.fn()
|
|
4
|
+
const createRequestContainerMock = jest.fn(async () => ({ resolve: resolveContainerValue }))
|
|
5
|
+
const getAuthFromRequestMock = jest.fn()
|
|
6
|
+
const resolveOrganizationScopeForRequestMock = jest.fn()
|
|
7
|
+
|
|
8
|
+
jest.mock('@open-mercato/shared/lib/di/container', () => ({
|
|
9
|
+
createRequestContainer: () => createRequestContainerMock(),
|
|
10
|
+
}))
|
|
11
|
+
|
|
12
|
+
jest.mock('@open-mercato/shared/lib/auth/server', () => ({
|
|
13
|
+
getAuthFromRequest: (request: Request) => getAuthFromRequestMock(request),
|
|
14
|
+
}))
|
|
15
|
+
|
|
16
|
+
jest.mock('@open-mercato/shared/lib/i18n/server', () => ({
|
|
17
|
+
resolveTranslations: async () => ({ translate: (_key: string, fallback: string) => fallback }),
|
|
18
|
+
}))
|
|
19
|
+
|
|
20
|
+
jest.mock('@open-mercato/core/modules/directory/utils/organizationScope', () => ({
|
|
21
|
+
resolveOrganizationScopeForRequest: (input: unknown) => resolveOrganizationScopeForRequestMock(input),
|
|
22
|
+
}))
|
|
23
|
+
|
|
24
|
+
describe('resolveWebhookRequestScope', () => {
|
|
25
|
+
beforeEach(() => {
|
|
26
|
+
jest.clearAllMocks()
|
|
27
|
+
getAuthFromRequestMock.mockResolvedValue({ tenantId: 'tenant-1', orgId: 'org-home' })
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
it('denies an explicit empty organization scope before resolving the entity manager', async () => {
|
|
31
|
+
resolveOrganizationScopeForRequestMock.mockResolvedValue({
|
|
32
|
+
tenantId: 'tenant-1',
|
|
33
|
+
selectedId: null,
|
|
34
|
+
filterIds: [],
|
|
35
|
+
allowedIds: [],
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
await expect(resolveWebhookRequestScope(new Request('http://localhost/api/webhooks'))).rejects.toEqual(
|
|
39
|
+
expect.objectContaining({ status: 403, body: { error: 'Forbidden' } }),
|
|
40
|
+
)
|
|
41
|
+
expect(resolveContainerValue).not.toHaveBeenCalled()
|
|
42
|
+
})
|
|
43
|
+
})
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { EntityManager } from '@mikro-orm/postgresql'
|
|
2
2
|
import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
|
|
3
3
|
import { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'
|
|
4
|
+
import { resolveSingleOrganizationIdOrDeny } from '@open-mercato/shared/lib/auth/organizationScope'
|
|
4
5
|
import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
|
|
5
6
|
import { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'
|
|
6
7
|
import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
|
|
@@ -32,7 +33,7 @@ export async function resolveWebhookRequestScope(request: Request): Promise<Webh
|
|
|
32
33
|
|
|
33
34
|
const scope = await resolveOrganizationScopeForRequest({ container, auth, request })
|
|
34
35
|
const tenantId = scope?.tenantId ?? auth.tenantId ?? null
|
|
35
|
-
const organizationId = scope
|
|
36
|
+
const organizationId = resolveSingleOrganizationIdOrDeny(scope, auth)
|
|
36
37
|
const allowedOrganizationIds = Array.isArray(scope?.allowedIds) ? scope.allowedIds : null
|
|
37
38
|
|
|
38
39
|
if (!tenantId) {
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/** @jest-environment node */
|
|
2
|
+
|
|
3
|
+
jest.mock('@open-mercato/cache', () => ({
|
|
4
|
+
runWithCacheTenant: async (_tenantId: string | null, fn: () => Promise<unknown>) => fn(),
|
|
5
|
+
}), { virtual: true })
|
|
6
|
+
|
|
7
|
+
const resolveContainerValue = jest.fn()
|
|
8
|
+
const resolveTranslations = jest.fn(async () => ({
|
|
9
|
+
translate: (_key: string, fallback: string) => fallback,
|
|
10
|
+
}))
|
|
11
|
+
const tenantId = '11111111-1111-4111-8111-111111111111'
|
|
12
|
+
const organizationId = '22222222-2222-4222-8222-222222222222'
|
|
13
|
+
|
|
14
|
+
jest.mock('@open-mercato/shared/lib/di/container', () => ({
|
|
15
|
+
createRequestContainer: async () => ({ resolve: resolveContainerValue }),
|
|
16
|
+
}))
|
|
17
|
+
|
|
18
|
+
jest.mock('@open-mercato/shared/lib/auth/server', () => ({
|
|
19
|
+
getAuthFromRequest: async () => ({
|
|
20
|
+
sub: 'user-1',
|
|
21
|
+
tenantId,
|
|
22
|
+
orgId: organizationId,
|
|
23
|
+
roles: ['admin'],
|
|
24
|
+
}),
|
|
25
|
+
getAuthFromCookies: async () => null,
|
|
26
|
+
}))
|
|
27
|
+
|
|
28
|
+
jest.mock('@open-mercato/core/modules/directory/utils/organizationScope', () => ({
|
|
29
|
+
resolveOrganizationScopeForRequest: async () => ({
|
|
30
|
+
tenantId,
|
|
31
|
+
selectedId: organizationId,
|
|
32
|
+
filterIds: [],
|
|
33
|
+
allowedIds: [],
|
|
34
|
+
}),
|
|
35
|
+
}))
|
|
36
|
+
|
|
37
|
+
jest.mock('@open-mercato/shared/lib/i18n/server', () => ({
|
|
38
|
+
resolveTranslations: () => resolveTranslations(),
|
|
39
|
+
}))
|
|
40
|
+
|
|
41
|
+
import { GET } from '../route'
|
|
42
|
+
|
|
43
|
+
describe('webhook delivery list organization scope', () => {
|
|
44
|
+
beforeEach(() => {
|
|
45
|
+
jest.clearAllMocks()
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
it('returns an empty page before beforeList, cache, or entity-manager access', async () => {
|
|
49
|
+
const response = await GET(new Request('http://localhost/api/webhook-deliveries?page=2&pageSize=25'))
|
|
50
|
+
|
|
51
|
+
expect(response.status).toBe(200)
|
|
52
|
+
await expect(response.json()).resolves.toEqual({
|
|
53
|
+
items: [],
|
|
54
|
+
total: 0,
|
|
55
|
+
page: 2,
|
|
56
|
+
pageSize: 25,
|
|
57
|
+
totalPages: 0,
|
|
58
|
+
})
|
|
59
|
+
expect(resolveTranslations).not.toHaveBeenCalled()
|
|
60
|
+
expect(resolveContainerValue).not.toHaveBeenCalled()
|
|
61
|
+
})
|
|
62
|
+
})
|
|
@@ -7,6 +7,7 @@ import { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'
|
|
|
7
7
|
import { WebhookDeliveryEntity, WebhookEntity } from '../../data/entities'
|
|
8
8
|
import { webhookDeliveryQuerySchema } from '../../data/validators'
|
|
9
9
|
import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
|
|
10
|
+
import { resolveSingleOrganizationIdOrDeny } from '@open-mercato/shared/lib/auth/organizationScope'
|
|
10
11
|
import { serializeDeliveryListItem } from '../helpers'
|
|
11
12
|
|
|
12
13
|
function json(payload: unknown, init: ResponseInit = { status: 200 }) {
|
|
@@ -54,6 +55,7 @@ const crud = makeCrudRoute<never, never, z.infer<typeof webhookDeliveryQuerySche
|
|
|
54
55
|
hooks: {
|
|
55
56
|
beforeList: async (query, ctx) => {
|
|
56
57
|
const auth = ctx.auth
|
|
58
|
+
const scopedOrganizationId = resolveSingleOrganizationIdOrDeny(ctx.organizationScope, auth)
|
|
57
59
|
const { translate } = await resolveTranslations()
|
|
58
60
|
if (!auth?.tenantId) throw json({ error: translate('webhooks.errors.tenantRequired', 'Tenant context required') }, { status: 400 })
|
|
59
61
|
|
|
@@ -67,8 +69,8 @@ const crud = makeCrudRoute<never, never, z.infer<typeof webhookDeliveryQuerySche
|
|
|
67
69
|
const allowedIds = ctx.organizationScope?.allowedIds ?? null
|
|
68
70
|
if (allowedIds && allowedIds.length > 0) {
|
|
69
71
|
qb.andWhere({ organizationId: { $in: allowedIds } })
|
|
70
|
-
} else if (
|
|
71
|
-
qb.andWhere({ organizationId:
|
|
72
|
+
} else if (scopedOrganizationId) {
|
|
73
|
+
qb.andWhere({ organizationId: scopedOrganizationId })
|
|
72
74
|
}
|
|
73
75
|
|
|
74
76
|
if (query.webhookId) {
|