@open-mercato/webhooks 0.6.7 → 0.6.8-develop.6875.1.871a4afc94
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-003.spec.js +15 -0
- package/dist/modules/webhooks/__integration__/TC-WEBHOOK-003.spec.js.map +2 -2
- package/dist/modules/webhooks/api/inbound/[endpointId]/route.js +152 -7
- package/dist/modules/webhooks/api/inbound/[endpointId]/route.js.map +3 -3
- package/dist/modules/webhooks/backend/webhooks/[id]/page.js +5 -4
- package/dist/modules/webhooks/backend/webhooks/[id]/page.js.map +2 -2
- package/dist/modules/webhooks/backend/webhooks/page.js +3 -2
- package/dist/modules/webhooks/backend/webhooks/page.js.map +2 -2
- package/dist/modules/webhooks/components/WebhookSecretPanel.js +3 -3
- package/dist/modules/webhooks/components/WebhookSecretPanel.js.map +2 -2
- package/dist/modules/webhooks/components/webhook-form-config.js +6 -6
- package/dist/modules/webhooks/components/webhook-form-config.js.map +2 -2
- package/dist/modules/webhooks/data/entities.js +101 -1
- package/dist/modules/webhooks/data/entities.js.map +2 -2
- package/dist/modules/webhooks/encryption.js +7 -0
- package/dist/modules/webhooks/encryption.js.map +2 -2
- package/dist/modules/webhooks/events.js +2 -0
- package/dist/modules/webhooks/events.js.map +2 -2
- package/dist/modules/webhooks/extension-points.js +15 -0
- package/dist/modules/webhooks/extension-points.js.map +7 -0
- package/dist/modules/webhooks/generators.js +57 -0
- package/dist/modules/webhooks/generators.js.map +7 -0
- package/dist/modules/webhooks/lib/inbound-dispatch.js +105 -0
- package/dist/modules/webhooks/lib/inbound-dispatch.js.map +7 -0
- package/dist/modules/webhooks/lib/inbound-registry.js +76 -0
- package/dist/modules/webhooks/lib/inbound-registry.js.map +7 -0
- package/dist/modules/webhooks/lib/module-webhook-registry.js +12 -0
- package/dist/modules/webhooks/lib/module-webhook-registry.js.map +7 -0
- package/dist/modules/webhooks/lib/queue.js +47 -0
- package/dist/modules/webhooks/lib/queue.js.map +2 -2
- package/dist/modules/webhooks/migrations/Migration20260617141327_webhooks.js +16 -0
- package/dist/modules/webhooks/migrations/Migration20260617141327_webhooks.js.map +7 -0
- package/dist/modules/webhooks/widgets/injection/integration-deliveries/widget.client.js +2 -1
- package/dist/modules/webhooks/widgets/injection/integration-deliveries/widget.client.js.map +2 -2
- package/dist/modules/webhooks/workers/inbound-dispatch.js +29 -0
- package/dist/modules/webhooks/workers/inbound-dispatch.js.map +7 -0
- package/generated/entities/inbound_endpoint_config_entity/index.ts +8 -0
- package/generated/entities/webhook_ingestion_entity/index.ts +16 -0
- package/generated/entities.ids.generated.ts +3 -1
- package/generated/entity-fields-registry.ts +28 -0
- package/package.json +12 -11
- package/src/modules/webhooks/__integration__/TC-WEBHOOK-003.spec.ts +16 -0
- package/src/modules/webhooks/api/inbound/[endpointId]/__tests__/route.test.ts +99 -1
- package/src/modules/webhooks/api/inbound/[endpointId]/__tests__/route.unify.test.ts +149 -0
- package/src/modules/webhooks/api/inbound/[endpointId]/route.ts +178 -7
- package/src/modules/webhooks/backend/webhooks/[id]/page.tsx +5 -4
- package/src/modules/webhooks/backend/webhooks/page.tsx +3 -2
- package/src/modules/webhooks/components/WebhookSecretPanel.tsx +3 -3
- package/src/modules/webhooks/components/webhook-form-config.tsx +6 -6
- package/src/modules/webhooks/data/entities.ts +84 -0
- package/src/modules/webhooks/encryption.ts +7 -0
- package/src/modules/webhooks/events.ts +2 -0
- package/src/modules/webhooks/extension-points.ts +12 -0
- package/src/modules/webhooks/generators.ts +57 -0
- package/src/modules/webhooks/i18n/de.json +1 -1
- package/src/modules/webhooks/i18n/en.json +1 -1
- package/src/modules/webhooks/i18n/es.json +1 -1
- package/src/modules/webhooks/i18n/ko.json +161 -0
- package/src/modules/webhooks/i18n/pl.json +1 -1
- package/src/modules/webhooks/lib/__tests__/inbound-dispatch.test.ts +186 -0
- package/src/modules/webhooks/lib/__tests__/inbound-registry.test.ts +102 -0
- package/src/modules/webhooks/lib/__tests__/module-webhook-registry.test.ts +53 -0
- package/src/modules/webhooks/lib/inbound-dispatch.ts +147 -0
- package/src/modules/webhooks/lib/inbound-registry.ts +92 -0
- package/src/modules/webhooks/lib/module-webhook-registry.ts +33 -0
- package/src/modules/webhooks/lib/queue.ts +60 -0
- package/src/modules/webhooks/migrations/.snapshot-open-mercato.json +907 -338
- package/src/modules/webhooks/migrations/Migration20260617141327_webhooks.ts +16 -0
- package/src/modules/webhooks/widgets/injection/integration-deliveries/widget.client.tsx +2 -1
- package/src/modules/webhooks/workers/inbound-dispatch.ts +31 -0
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import type { WebhookSourceConfig } from '@open-mercato/shared/lib/webhooks'
|
|
2
|
+
|
|
3
|
+
const enqueueInboundDispatch = jest.fn(async () => 'job-1')
|
|
4
|
+
const emitWebhooksEvent = jest.fn(async () => undefined)
|
|
5
|
+
const findWithDecryption = jest.fn()
|
|
6
|
+
const credentialsResolve = jest.fn(async () => ({ webhookSigningSecret: 'whsec' }))
|
|
7
|
+
|
|
8
|
+
const flush = jest.fn(async () => undefined)
|
|
9
|
+
const persist = jest.fn()
|
|
10
|
+
const em = {
|
|
11
|
+
fork: () => em,
|
|
12
|
+
create: (_entity: unknown, data: Record<string, unknown>) => ({ id: 'ing-1', ...data }),
|
|
13
|
+
persist,
|
|
14
|
+
flush,
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
jest.mock('@open-mercato/shared/lib/di/container', () => ({
|
|
18
|
+
createRequestContainer: async () => ({
|
|
19
|
+
resolve: (name: string) => {
|
|
20
|
+
if (name === 'em') return em
|
|
21
|
+
if (name === 'integrationCredentialsService') return { resolve: credentialsResolve }
|
|
22
|
+
throw new Error(`[internal] no mock for ${name}`)
|
|
23
|
+
},
|
|
24
|
+
}),
|
|
25
|
+
}))
|
|
26
|
+
jest.mock('@open-mercato/shared/lib/i18n/server', () => ({
|
|
27
|
+
resolveTranslations: async () => ({ translate: (_key: string, fallback: string) => fallback }),
|
|
28
|
+
}))
|
|
29
|
+
jest.mock('@open-mercato/shared/lib/encryption/find', () => ({
|
|
30
|
+
findWithDecryption: (...args: unknown[]) => findWithDecryption(...args),
|
|
31
|
+
}))
|
|
32
|
+
jest.mock('../../../../events', () => ({
|
|
33
|
+
emitWebhooksEvent: (...args: unknown[]) => emitWebhooksEvent(...args),
|
|
34
|
+
}))
|
|
35
|
+
jest.mock('../../../../lib/queue', () => ({
|
|
36
|
+
enqueueInboundDispatch: (...args: unknown[]) => enqueueInboundDispatch(...args),
|
|
37
|
+
}))
|
|
38
|
+
|
|
39
|
+
import { POST } from '../route'
|
|
40
|
+
import { clearWebhookSources, registerWebhookSource } from '../../../../lib/inbound-registry'
|
|
41
|
+
|
|
42
|
+
function makeSource(overrides: Partial<WebhookSourceConfig> = {}): WebhookSourceConfig {
|
|
43
|
+
return {
|
|
44
|
+
key: 'stripe',
|
|
45
|
+
label: 'Stripe',
|
|
46
|
+
verifier: async () => true,
|
|
47
|
+
eventTypeExtractor: (body) => String((body as { type?: string }).type ?? ''),
|
|
48
|
+
messageIdExtractor: (body) => String((body as { id?: string }).id ?? ''),
|
|
49
|
+
...overrides,
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function postTo(
|
|
54
|
+
endpointId: string,
|
|
55
|
+
body = '{"type":"payment_intent.succeeded","id":"evt_1"}',
|
|
56
|
+
headers: Record<string, string> = {},
|
|
57
|
+
) {
|
|
58
|
+
const request = new Request(`http://localhost/api/webhooks/inbound/${endpointId}`, {
|
|
59
|
+
method: 'POST',
|
|
60
|
+
body,
|
|
61
|
+
headers: { 'content-type': 'application/json', ...headers },
|
|
62
|
+
})
|
|
63
|
+
return POST(request, { params: Promise.resolve({ endpointId }) })
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
beforeEach(() => {
|
|
67
|
+
clearWebhookSources()
|
|
68
|
+
enqueueInboundDispatch.mockClear()
|
|
69
|
+
emitWebhooksEvent.mockClear()
|
|
70
|
+
persist.mockClear()
|
|
71
|
+
flush.mockReset()
|
|
72
|
+
flush.mockResolvedValue(undefined)
|
|
73
|
+
findWithDecryption.mockReset()
|
|
74
|
+
findWithDecryption.mockResolvedValue([{ organizationId: 'o1', tenantId: 't1', sourceKey: 'stripe', isActive: true }])
|
|
75
|
+
credentialsResolve.mockClear()
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
it('returns 404 when neither a source nor an adapter matches the segment', async () => {
|
|
79
|
+
const res = await postTo('totally-unknown')
|
|
80
|
+
expect(res.status).toBe(404)
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
it('accepts a valid source webhook: records ingestion, enqueues dispatch, emits received', async () => {
|
|
84
|
+
registerWebhookSource(makeSource({ verifier: async () => true }))
|
|
85
|
+
const res = await postTo('stripe')
|
|
86
|
+
expect(res.status).toBe(200)
|
|
87
|
+
await expect(res.json()).resolves.toEqual({ ok: true })
|
|
88
|
+
expect(enqueueInboundDispatch).toHaveBeenCalledWith(
|
|
89
|
+
expect.objectContaining({ ingestionId: 'ing-1', sourceKey: 'stripe', eventType: 'payment_intent.succeeded', tenantId: 't1', organizationId: 'o1' }),
|
|
90
|
+
)
|
|
91
|
+
expect(emitWebhooksEvent).toHaveBeenCalledWith(
|
|
92
|
+
'webhooks.inbound.received',
|
|
93
|
+
expect.objectContaining({ endpointId: 'stripe', eventType: 'payment_intent.succeeded' }),
|
|
94
|
+
{ persistent: true },
|
|
95
|
+
)
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
it('rejects a stale source webhook before signature verification or persistence', async () => {
|
|
99
|
+
const verifier = jest.fn(async () => true)
|
|
100
|
+
registerWebhookSource(makeSource({ verifier }))
|
|
101
|
+
|
|
102
|
+
const res = await postTo('stripe', undefined, { 'webhook-timestamp': '1' })
|
|
103
|
+
|
|
104
|
+
expect(res.status).toBe(400)
|
|
105
|
+
await expect(res.json()).resolves.toEqual({ error: 'Webhook timestamp is outside the allowed replay window' })
|
|
106
|
+
expect(verifier).not.toHaveBeenCalled()
|
|
107
|
+
expect(findWithDecryption).not.toHaveBeenCalled()
|
|
108
|
+
expect(persist).not.toHaveBeenCalled()
|
|
109
|
+
expect(flush).not.toHaveBeenCalled()
|
|
110
|
+
expect(enqueueInboundDispatch).not.toHaveBeenCalled()
|
|
111
|
+
expect(emitWebhooksEvent).not.toHaveBeenCalled()
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
it('rejects an oversized source webhook before verification or persistence', async () => {
|
|
115
|
+
const verifier = jest.fn(async () => true)
|
|
116
|
+
registerWebhookSource(makeSource({ verifier }))
|
|
117
|
+
const request = new Request('http://localhost/api/webhooks/inbound/stripe', {
|
|
118
|
+
method: 'POST',
|
|
119
|
+
body: '{}',
|
|
120
|
+
headers: {
|
|
121
|
+
'content-length': String(1024 * 1024 + 1),
|
|
122
|
+
'content-type': 'application/json',
|
|
123
|
+
},
|
|
124
|
+
})
|
|
125
|
+
|
|
126
|
+
const response = await POST(request, { params: Promise.resolve({ endpointId: 'stripe' }) })
|
|
127
|
+
|
|
128
|
+
expect(response.status).toBe(413)
|
|
129
|
+
expect(verifier).not.toHaveBeenCalled()
|
|
130
|
+
expect(findWithDecryption).not.toHaveBeenCalled()
|
|
131
|
+
expect(persist).not.toHaveBeenCalled()
|
|
132
|
+
expect(enqueueInboundDispatch).not.toHaveBeenCalled()
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
it('rejects with 401 when no candidate scope verifies', async () => {
|
|
136
|
+
registerWebhookSource(makeSource({ verifier: async () => false }))
|
|
137
|
+
const res = await postTo('stripe')
|
|
138
|
+
expect(res.status).toBe(401)
|
|
139
|
+
expect(enqueueInboundDispatch).not.toHaveBeenCalled()
|
|
140
|
+
})
|
|
141
|
+
|
|
142
|
+
it('returns duplicate when the receipt unique constraint is violated', async () => {
|
|
143
|
+
registerWebhookSource(makeSource())
|
|
144
|
+
flush.mockRejectedValueOnce({ code: '23505' })
|
|
145
|
+
const res = await postTo('stripe')
|
|
146
|
+
expect(res.status).toBe(200)
|
|
147
|
+
await expect(res.json()).resolves.toEqual({ ok: true, duplicate: true })
|
|
148
|
+
expect(enqueueInboundDispatch).not.toHaveBeenCalled()
|
|
149
|
+
})
|
|
@@ -4,13 +4,40 @@ import type { EntityManager } from '@mikro-orm/postgresql'
|
|
|
4
4
|
import type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'
|
|
5
5
|
import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
|
|
6
6
|
import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
|
|
7
|
+
import { parseNumberWithDefault } from '@open-mercato/shared/lib/number'
|
|
7
8
|
import { checkRateLimit, getClientIp, RATE_LIMIT_ERROR_FALLBACK, RATE_LIMIT_ERROR_KEY } from '@open-mercato/shared/lib/ratelimit/helpers'
|
|
8
9
|
import type { RateLimiterService } from '@open-mercato/shared/lib/ratelimit/service'
|
|
10
|
+
import { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'
|
|
11
|
+
import {
|
|
12
|
+
isWebhookTimestampWithinTolerance,
|
|
13
|
+
readBoundedRequestBody,
|
|
14
|
+
WEBHOOK_SIGNATURE_TOLERANCE_SECONDS,
|
|
15
|
+
WebhookBodyTooLargeError,
|
|
16
|
+
type InboundWebhookRequest,
|
|
17
|
+
} from '@open-mercato/shared/lib/webhooks'
|
|
9
18
|
import { emitWebhooksEvent } from '../../../events'
|
|
10
19
|
import { getWebhookEndpointAdapter } from '../../../lib/adapter-registry'
|
|
20
|
+
import { getWebhookSource } from '../../../lib/inbound-registry'
|
|
21
|
+
import { enqueueInboundDispatch } from '../../../lib/queue'
|
|
11
22
|
import { isWebhookIntegrationEnabled, WEBHOOK_INTEGRATION_DISABLED_MESSAGE } from '../../../lib/integration-state'
|
|
12
23
|
import { json } from '../../helpers'
|
|
13
|
-
import { WebhookInboundReceiptEntity } from '../../../data/entities'
|
|
24
|
+
import { InboundEndpointConfigEntity, WebhookIngestionEntity, WebhookInboundReceiptEntity } from '../../../data/entities'
|
|
25
|
+
|
|
26
|
+
type IntegrationCredentialsService = {
|
|
27
|
+
resolve: (
|
|
28
|
+
integrationId: string,
|
|
29
|
+
scope: { organizationId: string; tenantId: string },
|
|
30
|
+
) => Promise<Record<string, unknown> | null>
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function toStringCredentials(credentials: Record<string, unknown> | null): Record<string, string> {
|
|
34
|
+
const result: Record<string, string> = {}
|
|
35
|
+
if (!credentials) return result
|
|
36
|
+
for (const [key, value] of Object.entries(credentials)) {
|
|
37
|
+
if (typeof value === 'string') result[key] = value
|
|
38
|
+
}
|
|
39
|
+
return result
|
|
40
|
+
}
|
|
14
41
|
|
|
15
42
|
export const metadata = {
|
|
16
43
|
POST: { requireAuth: false },
|
|
@@ -26,13 +53,16 @@ const inboundResponseSchema = z.object({
|
|
|
26
53
|
})
|
|
27
54
|
|
|
28
55
|
const errorSchema = z.object({ error: z.string() })
|
|
56
|
+
const INBOUND_TIMESTAMP_TOLERANCE_ENV = 'OM_WEBHOOKS_INBOUND_TIMESTAMP_TOLERANCE_SECONDS'
|
|
57
|
+
const STALE_TIMESTAMP_ERROR = 'Webhook timestamp is outside the allowed replay window'
|
|
29
58
|
|
|
30
59
|
export async function POST(request: Request, context: RouteContext): Promise<Response> {
|
|
31
60
|
const params = await context.params
|
|
32
|
-
const
|
|
61
|
+
const source = getWebhookSource(params.endpointId)
|
|
62
|
+
const adapter = source ? undefined : getWebhookEndpointAdapter(params.endpointId)
|
|
33
63
|
const { translate } = await resolveTranslations()
|
|
34
64
|
|
|
35
|
-
if (!adapter) {
|
|
65
|
+
if (!source && !adapter) {
|
|
36
66
|
return json({ error: 'Webhook endpoint not found' }, { status: 404 })
|
|
37
67
|
}
|
|
38
68
|
|
|
@@ -51,8 +81,127 @@ export async function POST(request: Request, context: RouteContext): Promise<Res
|
|
|
51
81
|
if (rateLimitResponse) return rateLimitResponse
|
|
52
82
|
}
|
|
53
83
|
|
|
54
|
-
|
|
84
|
+
let body: string
|
|
85
|
+
try {
|
|
86
|
+
body = await readBoundedRequestBody(request)
|
|
87
|
+
} catch (error) {
|
|
88
|
+
if (error instanceof WebhookBodyTooLargeError) {
|
|
89
|
+
return json({ error: 'Webhook payload too large' }, { status: 413 })
|
|
90
|
+
}
|
|
91
|
+
throw error
|
|
92
|
+
}
|
|
55
93
|
const headers = Object.fromEntries(request.headers.entries())
|
|
94
|
+
if (!isInboundWebhookTimestampFresh(headers)) {
|
|
95
|
+
return json({ error: STALE_TIMESTAMP_ERROR }, { status: 400 })
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (source) {
|
|
99
|
+
let parsedBody: Record<string, unknown> = {}
|
|
100
|
+
try {
|
|
101
|
+
const parsed = JSON.parse(body)
|
|
102
|
+
if (parsed && typeof parsed === 'object') parsedBody = parsed as Record<string, unknown>
|
|
103
|
+
} catch {
|
|
104
|
+
parsedBody = {}
|
|
105
|
+
}
|
|
106
|
+
const inboundRequest: InboundWebhookRequest = { body, headers, parsedBody }
|
|
107
|
+
|
|
108
|
+
const credentialsService = tryResolve<IntegrationCredentialsService>(container, 'integrationCredentialsService')
|
|
109
|
+
const configs = await findWithDecryption(
|
|
110
|
+
em,
|
|
111
|
+
InboundEndpointConfigEntity,
|
|
112
|
+
{ sourceKey: params.endpointId, isActive: true },
|
|
113
|
+
{},
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
let verifiedScope: { organizationId: string; tenantId: string } | null = null
|
|
117
|
+
for (const config of configs) {
|
|
118
|
+
const scope = { organizationId: config.organizationId, tenantId: config.tenantId }
|
|
119
|
+
const credentials = credentialsService
|
|
120
|
+
? await credentialsService.resolve(`webhook_source_${params.endpointId}`, scope)
|
|
121
|
+
: null
|
|
122
|
+
let valid = false
|
|
123
|
+
try {
|
|
124
|
+
valid = await source.verifier(inboundRequest, toStringCredentials(credentials))
|
|
125
|
+
} catch {
|
|
126
|
+
valid = false
|
|
127
|
+
}
|
|
128
|
+
if (valid) {
|
|
129
|
+
verifiedScope = scope
|
|
130
|
+
break
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (!verifiedScope) {
|
|
135
|
+
return json({ error: 'Signature verification failed' }, { status: 401 })
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const eventType = source.eventTypeExtractor(parsedBody, headers)
|
|
139
|
+
const messageId = source.messageIdExtractor?.(parsedBody, headers)
|
|
140
|
+
?? resolveInboundReceiptMessageId({
|
|
141
|
+
endpointId: params.endpointId,
|
|
142
|
+
providerKey: params.endpointId,
|
|
143
|
+
headers,
|
|
144
|
+
body,
|
|
145
|
+
})
|
|
146
|
+
|
|
147
|
+
try {
|
|
148
|
+
em.persist(em.create(WebhookInboundReceiptEntity, {
|
|
149
|
+
endpointId: params.endpointId,
|
|
150
|
+
messageId,
|
|
151
|
+
providerKey: params.endpointId,
|
|
152
|
+
eventType,
|
|
153
|
+
tenantId: verifiedScope.tenantId,
|
|
154
|
+
organizationId: verifiedScope.organizationId,
|
|
155
|
+
createdAt: new Date(),
|
|
156
|
+
}))
|
|
157
|
+
await em.flush()
|
|
158
|
+
} catch (error) {
|
|
159
|
+
if (isUniqueViolation(error)) {
|
|
160
|
+
return json({ ok: true, duplicate: true })
|
|
161
|
+
}
|
|
162
|
+
throw error
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const ingestion = em.create(WebhookIngestionEntity, {
|
|
166
|
+
sourceKey: params.endpointId,
|
|
167
|
+
eventType,
|
|
168
|
+
externalMessageId: messageId,
|
|
169
|
+
payload: parsedBody,
|
|
170
|
+
headers,
|
|
171
|
+
status: 'received',
|
|
172
|
+
handlerCount: 0,
|
|
173
|
+
organizationId: verifiedScope.organizationId,
|
|
174
|
+
tenantId: verifiedScope.tenantId,
|
|
175
|
+
createdAt: new Date(),
|
|
176
|
+
updatedAt: new Date(),
|
|
177
|
+
})
|
|
178
|
+
em.persist(ingestion)
|
|
179
|
+
await em.flush()
|
|
180
|
+
|
|
181
|
+
await enqueueInboundDispatch({
|
|
182
|
+
ingestionId: ingestion.id,
|
|
183
|
+
sourceKey: params.endpointId,
|
|
184
|
+
eventType,
|
|
185
|
+
tenantId: verifiedScope.tenantId,
|
|
186
|
+
organizationId: verifiedScope.organizationId,
|
|
187
|
+
})
|
|
188
|
+
|
|
189
|
+
await emitWebhooksEvent('webhooks.inbound.received', {
|
|
190
|
+
providerKey: params.endpointId,
|
|
191
|
+
endpointId: params.endpointId,
|
|
192
|
+
messageId,
|
|
193
|
+
eventType,
|
|
194
|
+
payload: parsedBody,
|
|
195
|
+
tenantId: verifiedScope.tenantId,
|
|
196
|
+
organizationId: verifiedScope.organizationId,
|
|
197
|
+
}, { persistent: true })
|
|
198
|
+
|
|
199
|
+
return json({ ok: true })
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
if (!adapter) {
|
|
203
|
+
return json({ error: 'Webhook endpoint not found' }, { status: 404 })
|
|
204
|
+
}
|
|
56
205
|
let verified: Awaited<ReturnType<typeof adapter.verifyWebhook>>
|
|
57
206
|
try {
|
|
58
207
|
verified = await adapter.verifyWebhook({
|
|
@@ -126,11 +275,15 @@ export const openApi: OpenApiRouteDoc = {
|
|
|
126
275
|
methods: {
|
|
127
276
|
POST: {
|
|
128
277
|
summary: 'Receive inbound webhook',
|
|
129
|
-
description: '
|
|
278
|
+
description: 'The endpoint id resolves to a registered webhook source first (module-level handler dispatch), otherwise to a legacy adapter provider key.',
|
|
130
279
|
pathParams: z.object({ endpointId: z.string().min(1) }),
|
|
131
|
-
responses: [
|
|
280
|
+
responses: [
|
|
281
|
+
{ status: 200, description: 'Inbound webhook accepted', schema: inboundResponseSchema },
|
|
282
|
+
{ status: 413, description: 'Webhook payload too large', schema: errorSchema },
|
|
283
|
+
],
|
|
132
284
|
errors: [
|
|
133
|
-
{ status: 400, description: 'Verification failed', schema: errorSchema },
|
|
285
|
+
{ status: 400, description: 'Verification failed or stale webhook timestamp', schema: errorSchema },
|
|
286
|
+
{ status: 401, description: 'Signature verification failed (source flow)', schema: errorSchema },
|
|
134
287
|
{ status: 404, description: 'Endpoint not found', schema: errorSchema },
|
|
135
288
|
{ status: 429, description: 'Rate limit exceeded', schema: errorSchema },
|
|
136
289
|
{ status: 503, description: 'Webhook integration disabled', schema: errorSchema },
|
|
@@ -155,6 +308,24 @@ function isUniqueViolation(error: unknown): boolean {
|
|
|
155
308
|
return (maybeError.cause as { code?: string }).code === '23505'
|
|
156
309
|
}
|
|
157
310
|
|
|
311
|
+
function isInboundWebhookTimestampFresh(headers: Record<string, string>): boolean {
|
|
312
|
+
const timestamps = [
|
|
313
|
+
headers['webhook-timestamp'],
|
|
314
|
+
headers['svix-timestamp'],
|
|
315
|
+
].filter((timestamp): timestamp is string => typeof timestamp === 'string')
|
|
316
|
+
|
|
317
|
+
if (timestamps.length === 0) {
|
|
318
|
+
return true
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
const toleranceSeconds = parseNumberWithDefault(
|
|
322
|
+
process.env[INBOUND_TIMESTAMP_TOLERANCE_ENV],
|
|
323
|
+
WEBHOOK_SIGNATURE_TOLERANCE_SECONDS,
|
|
324
|
+
{ integer: true, min: 0 },
|
|
325
|
+
)
|
|
326
|
+
return timestamps.every((timestamp) => isWebhookTimestampWithinTolerance(timestamp.trim(), toleranceSeconds))
|
|
327
|
+
}
|
|
328
|
+
|
|
158
329
|
type ResolveInboundReceiptMessageIdInput = {
|
|
159
330
|
endpointId: string
|
|
160
331
|
providerKey: string
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"use client"
|
|
2
2
|
import * as React from 'react'
|
|
3
|
+
import { extensionPoints } from '@open-mercato/webhooks/modules/webhooks/extension-points'
|
|
3
4
|
import { useParams, usePathname, useRouter } from 'next/navigation'
|
|
4
5
|
import { RotateCw } from 'lucide-react'
|
|
5
6
|
import { Page, PageBody } from '@open-mercato/ui/backend/Page'
|
|
@@ -546,15 +547,15 @@ export default function WebhookDetailPage() {
|
|
|
546
547
|
|
|
547
548
|
<div className="mt-6 space-y-4">
|
|
548
549
|
{!access.isLoading && !access.canManage && !access.canSecrets && !access.canTest ? (
|
|
549
|
-
<Alert
|
|
550
|
+
<Alert status="information">
|
|
550
551
|
<AlertDescription>{t('webhooks.detail.readOnlyTip')}</AlertDescription>
|
|
551
552
|
</Alert>
|
|
552
553
|
) : null}
|
|
553
554
|
<div className="grid gap-3 lg:grid-cols-2">
|
|
554
|
-
<Alert
|
|
555
|
+
<Alert status="information">
|
|
555
556
|
<AlertDescription>{t('webhooks.detail.deliveryTip')}</AlertDescription>
|
|
556
557
|
</Alert>
|
|
557
|
-
<Alert
|
|
558
|
+
<Alert status="information">
|
|
558
559
|
<AlertDescription>{t('webhooks.detail.signatureTip')}</AlertDescription>
|
|
559
560
|
</Alert>
|
|
560
561
|
</div>
|
|
@@ -679,7 +680,7 @@ export default function WebhookDetailPage() {
|
|
|
679
680
|
|
|
680
681
|
return <RowActions items={items} />
|
|
681
682
|
}}
|
|
682
|
-
perspective={{ tableId:
|
|
683
|
+
perspective={{ tableId: extensionPoints.hosts.deliveriesTable.tableId }}
|
|
683
684
|
pagination={{
|
|
684
685
|
page: deliveryPage,
|
|
685
686
|
pageSize: 20,
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"use client"
|
|
2
2
|
import * as React from 'react'
|
|
3
|
+
import { extensionPoints } from '@open-mercato/webhooks/modules/webhooks/extension-points'
|
|
3
4
|
import Link from 'next/link'
|
|
4
5
|
import { useRouter } from 'next/navigation'
|
|
5
6
|
import { Page, PageBody } from '@open-mercato/ui/backend/Page'
|
|
@@ -231,7 +232,7 @@ export default function WebhooksListPage() {
|
|
|
231
232
|
return (
|
|
232
233
|
<Page>
|
|
233
234
|
<PageBody className="space-y-4">
|
|
234
|
-
<Alert
|
|
235
|
+
<Alert status="information">
|
|
235
236
|
<AlertTitle>{t('webhooks.list.description')}</AlertTitle>
|
|
236
237
|
<AlertDescription>{t('webhooks.list.operatorTip')}</AlertDescription>
|
|
237
238
|
</Alert>
|
|
@@ -256,7 +257,7 @@ export default function WebhooksListPage() {
|
|
|
256
257
|
setFilterValues({})
|
|
257
258
|
setPage(1)
|
|
258
259
|
}}
|
|
259
|
-
perspective={{ tableId:
|
|
260
|
+
perspective={{ tableId: extensionPoints.hosts.webhooksTable.tableId }}
|
|
260
261
|
rowActions={(row) => {
|
|
261
262
|
const items = [
|
|
262
263
|
{
|
|
@@ -37,7 +37,7 @@ export function WebhookSecretPanel({ secret, onClose }: WebhookSecretPanelProps)
|
|
|
37
37
|
<p className="mt-2 text-sm text-muted-foreground">{t('webhooks.form.secretVisibleOnce')}</p>
|
|
38
38
|
</div>
|
|
39
39
|
<div className="space-y-4 p-6">
|
|
40
|
-
<Alert
|
|
40
|
+
<Alert status="warning">
|
|
41
41
|
<AlertDescription>{t('webhooks.form.secretUsageTip')}</AlertDescription>
|
|
42
42
|
</Alert>
|
|
43
43
|
<div className="flex items-start gap-3 rounded-md border bg-muted/40 p-4">
|
|
@@ -57,10 +57,10 @@ export function WebhookSecretPanel({ secret, onClose }: WebhookSecretPanelProps)
|
|
|
57
57
|
</Button>
|
|
58
58
|
</div>
|
|
59
59
|
<div className="grid gap-3 md:grid-cols-2">
|
|
60
|
-
<Alert
|
|
60
|
+
<Alert status="information">
|
|
61
61
|
<AlertDescription>{t('webhooks.form.secretVerificationTip')}</AlertDescription>
|
|
62
62
|
</Alert>
|
|
63
|
-
<Alert
|
|
63
|
+
<Alert status="information">
|
|
64
64
|
<AlertDescription>{t('webhooks.form.secretRotationTip')}</AlertDescription>
|
|
65
65
|
</Alert>
|
|
66
66
|
</div>
|
|
@@ -137,7 +137,7 @@ export function buildWebhookFormGroups(t: TranslateFn): CrudFormGroup[] {
|
|
|
137
137
|
title: t('webhooks.form.group.events'),
|
|
138
138
|
column: 1,
|
|
139
139
|
component: () => (
|
|
140
|
-
<Alert
|
|
140
|
+
<Alert status="information">
|
|
141
141
|
<AlertDescription>{t('webhooks.form.eventsPatternTip')}</AlertDescription>
|
|
142
142
|
</Alert>
|
|
143
143
|
),
|
|
@@ -148,7 +148,7 @@ export function buildWebhookFormGroups(t: TranslateFn): CrudFormGroup[] {
|
|
|
148
148
|
title: t('webhooks.form.group.delivery'),
|
|
149
149
|
column: 2,
|
|
150
150
|
component: () => (
|
|
151
|
-
<Alert
|
|
151
|
+
<Alert status="information">
|
|
152
152
|
<AlertDescription>{t('webhooks.form.deliveryDefaultsTip')}</AlertDescription>
|
|
153
153
|
</Alert>
|
|
154
154
|
),
|
|
@@ -159,7 +159,7 @@ export function buildWebhookFormGroups(t: TranslateFn): CrudFormGroup[] {
|
|
|
159
159
|
title: t('webhooks.form.group.advanced'),
|
|
160
160
|
column: 2,
|
|
161
161
|
component: () => (
|
|
162
|
-
<Alert
|
|
162
|
+
<Alert status="information">
|
|
163
163
|
<AlertDescription>{t('webhooks.form.advancedStrategyTip')}</AlertDescription>
|
|
164
164
|
</Alert>
|
|
165
165
|
),
|
|
@@ -227,11 +227,11 @@ export function normalizeWebhookFormPayload(values: WebhookFormValues, t: Transl
|
|
|
227
227
|
export function buildWebhookFormContentHeader(t: TranslateFn) {
|
|
228
228
|
return (
|
|
229
229
|
<div className="grid gap-3 lg:grid-cols-2">
|
|
230
|
-
<Alert
|
|
230
|
+
<Alert status="information">
|
|
231
231
|
<AlertTitle>{t('webhooks.form.guidanceTitle')}</AlertTitle>
|
|
232
232
|
<AlertDescription>{t('webhooks.form.guidanceBody')}</AlertDescription>
|
|
233
233
|
</Alert>
|
|
234
|
-
<Alert
|
|
234
|
+
<Alert status="warning">
|
|
235
235
|
<AlertTitle>{t('webhooks.form.guidanceSecurityTitle')}</AlertTitle>
|
|
236
236
|
<AlertDescription>{t('webhooks.form.guidanceSecurityBody')}</AlertDescription>
|
|
237
237
|
</Alert>
|
|
@@ -245,7 +245,7 @@ function WebhookCustomHeadersField(props: CrudCustomFieldRenderProps) {
|
|
|
245
245
|
|
|
246
246
|
return (
|
|
247
247
|
<div className="space-y-3">
|
|
248
|
-
<Alert
|
|
248
|
+
<Alert status="information">
|
|
249
249
|
<AlertDescription>{t('webhooks.form.customHeadersTip')}</AlertDescription>
|
|
250
250
|
</Alert>
|
|
251
251
|
<JsonBuilder
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Entity, Index, PrimaryKey, Property, Unique } from '@mikro-orm/decorators/legacy'
|
|
2
|
+
import type { WebhookHandlerResult, WebhookIngestionStatus } from '@open-mercato/shared/lib/webhooks'
|
|
2
3
|
|
|
3
4
|
@Entity({ tableName: 'webhooks' })
|
|
4
5
|
@Index({ properties: ['organizationId', 'tenantId', 'isActive'] })
|
|
@@ -184,3 +185,86 @@ export class WebhookInboundReceiptEntity {
|
|
|
184
185
|
@Property({ name: 'created_at', type: Date, onCreate: () => new Date() })
|
|
185
186
|
createdAt: Date = new Date()
|
|
186
187
|
}
|
|
188
|
+
|
|
189
|
+
@Entity({ tableName: 'webhook_ingestions' })
|
|
190
|
+
@Index({ properties: ['sourceKey', 'status', 'createdAt'] })
|
|
191
|
+
@Index({ properties: ['organizationId', 'tenantId', 'createdAt'] })
|
|
192
|
+
@Index({ properties: ['externalMessageId'] })
|
|
193
|
+
export class WebhookIngestionEntity {
|
|
194
|
+
@PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })
|
|
195
|
+
id!: string
|
|
196
|
+
|
|
197
|
+
@Property({ name: 'source_key', type: 'text' })
|
|
198
|
+
sourceKey!: string
|
|
199
|
+
|
|
200
|
+
@Property({ name: 'event_type', type: 'text' })
|
|
201
|
+
eventType!: string
|
|
202
|
+
|
|
203
|
+
@Property({ name: 'external_message_id', type: 'text', nullable: true })
|
|
204
|
+
externalMessageId?: string | null
|
|
205
|
+
|
|
206
|
+
@Property({ name: 'payload', type: 'json' })
|
|
207
|
+
payload!: Record<string, unknown>
|
|
208
|
+
|
|
209
|
+
@Property({ name: 'headers', type: 'json', nullable: true })
|
|
210
|
+
headers?: Record<string, string> | null
|
|
211
|
+
|
|
212
|
+
@Property({ name: 'status', type: 'text', default: 'received' })
|
|
213
|
+
status: WebhookIngestionStatus = 'received'
|
|
214
|
+
|
|
215
|
+
@Property({ name: 'error_message', type: 'text', nullable: true })
|
|
216
|
+
errorMessage?: string | null
|
|
217
|
+
|
|
218
|
+
@Property({ name: 'processed_at', type: Date, nullable: true })
|
|
219
|
+
processedAt?: Date | null
|
|
220
|
+
|
|
221
|
+
@Property({ name: 'handler_count', type: 'int', default: 0 })
|
|
222
|
+
handlerCount: number = 0
|
|
223
|
+
|
|
224
|
+
@Property({ name: 'handler_results', type: 'json', nullable: true })
|
|
225
|
+
handlerResults?: WebhookHandlerResult[] | null
|
|
226
|
+
|
|
227
|
+
@Property({ name: 'duration_ms', type: 'int', nullable: true })
|
|
228
|
+
durationMs?: number | null
|
|
229
|
+
|
|
230
|
+
@Property({ name: 'organization_id', type: 'uuid' })
|
|
231
|
+
organizationId!: string
|
|
232
|
+
|
|
233
|
+
@Property({ name: 'tenant_id', type: 'uuid' })
|
|
234
|
+
tenantId!: string
|
|
235
|
+
|
|
236
|
+
@Property({ name: 'created_at', type: Date, onCreate: () => new Date() })
|
|
237
|
+
createdAt: Date = new Date()
|
|
238
|
+
|
|
239
|
+
@Property({ name: 'updated_at', type: Date, onUpdate: () => new Date() })
|
|
240
|
+
updatedAt: Date = new Date()
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
@Entity({ tableName: 'webhook_inbound_configs' })
|
|
244
|
+
@Unique({ name: 'webhook_inbound_configs_source_scope_unique', properties: ['sourceKey', 'organizationId', 'tenantId'] })
|
|
245
|
+
@Index({ properties: ['sourceKey', 'isActive'] })
|
|
246
|
+
export class InboundEndpointConfigEntity {
|
|
247
|
+
@PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })
|
|
248
|
+
id!: string
|
|
249
|
+
|
|
250
|
+
@Property({ name: 'source_key', type: 'text' })
|
|
251
|
+
sourceKey!: string
|
|
252
|
+
|
|
253
|
+
@Property({ name: 'is_active', type: 'boolean', default: true })
|
|
254
|
+
isActive: boolean = true
|
|
255
|
+
|
|
256
|
+
@Property({ name: 'integration_id', type: 'text', nullable: true })
|
|
257
|
+
integrationId?: string | null
|
|
258
|
+
|
|
259
|
+
@Property({ name: 'organization_id', type: 'uuid' })
|
|
260
|
+
organizationId!: string
|
|
261
|
+
|
|
262
|
+
@Property({ name: 'tenant_id', type: 'uuid' })
|
|
263
|
+
tenantId!: string
|
|
264
|
+
|
|
265
|
+
@Property({ name: 'created_at', type: Date, onCreate: () => new Date() })
|
|
266
|
+
createdAt: Date = new Date()
|
|
267
|
+
|
|
268
|
+
@Property({ name: 'updated_at', type: Date, onUpdate: () => new Date() })
|
|
269
|
+
updatedAt: Date = new Date()
|
|
270
|
+
}
|
|
@@ -8,6 +8,13 @@ export const defaultEncryptionMaps: ModuleEncryptionMap[] = [
|
|
|
8
8
|
{ field: 'previous_secret' },
|
|
9
9
|
],
|
|
10
10
|
},
|
|
11
|
+
{
|
|
12
|
+
entityId: 'webhooks:webhook_ingestion_entity',
|
|
13
|
+
fields: [
|
|
14
|
+
{ field: 'payload' },
|
|
15
|
+
{ field: 'headers' },
|
|
16
|
+
],
|
|
17
|
+
},
|
|
11
18
|
]
|
|
12
19
|
|
|
13
20
|
export default defaultEncryptionMaps
|
|
@@ -10,6 +10,8 @@ const events = [
|
|
|
10
10
|
{ id: 'webhooks.delivery.exhausted', label: 'Webhook Delivery Retries Exhausted', entity: 'delivery', category: 'lifecycle' as const, clientBroadcast: true },
|
|
11
11
|
{ id: 'webhooks.webhook.disabled', label: 'Webhook Auto-Disabled', entity: 'webhook', category: 'lifecycle' as const, clientBroadcast: true },
|
|
12
12
|
{ id: 'webhooks.inbound.received', label: 'Inbound Webhook Received', entity: 'inbound', category: 'custom' as const },
|
|
13
|
+
{ id: 'webhooks.inbound.processed', label: 'Inbound Webhook Processed', entity: 'inbound', category: 'lifecycle' as const },
|
|
14
|
+
{ id: 'webhooks.inbound.handler_failed', label: 'Inbound Handler Failed', entity: 'inbound', category: 'lifecycle' as const, clientBroadcast: true },
|
|
13
15
|
{ id: 'webhooks.secret.rotated', label: 'Webhook Secret Rotated', entity: 'webhook', category: 'lifecycle' as const },
|
|
14
16
|
] as const
|
|
15
17
|
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { dataTableExtensionHost, defineModuleExtensionPoints } from '@open-mercato/shared/modules/widgets/extension-points'
|
|
2
|
+
|
|
3
|
+
export const extensionPoints = defineModuleExtensionPoints({
|
|
4
|
+
moduleId: 'webhooks',
|
|
5
|
+
hosts: {
|
|
6
|
+
webhooksTable: dataTableExtensionHost({ tableId: 'webhooks.list', source: 'backend/webhooks/page.tsx' }),
|
|
7
|
+
deliveriesTable: dataTableExtensionHost({ tableId: 'webhooks.deliveries', source: 'backend/webhooks/[id]/page.tsx' }),
|
|
8
|
+
integrationDeliveriesTable: dataTableExtensionHost({ tableId: 'webhooks.integration-deliveries', source: 'widgets/injection/integration-deliveries/widget.client.tsx' }),
|
|
9
|
+
},
|
|
10
|
+
})
|
|
11
|
+
|
|
12
|
+
export default extensionPoints
|