|
| 1 | +import { createHash } from 'node:crypto' |
| 2 | + |
| 3 | +import type { |
| 4 | + WebhookDeliveryListQuery, |
| 5 | + WebhookDeliveryQueryRepository, |
| 6 | +} from './ports/webhook-delivery-query-repository.ts' |
| 7 | +import { DomainError, assertDomain } from '../domain/errors.ts' |
| 8 | +import { |
| 9 | + WEBHOOK_DELIVERY_STATUSES, |
| 10 | + type WebhookDeliveryStatus, |
| 11 | +} from '../domain/webhook.ts' |
| 12 | + |
| 13 | +const SAFE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{2,127}$/ |
| 14 | +const UUID_V4_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/ |
| 15 | +const CURSOR_PATTERN = /^[A-Za-z0-9_-]{8,1024}$/ |
| 16 | +const SHA256_PATTERN = /^[a-f0-9]{64}$/ |
| 17 | + |
| 18 | +interface WebhookDeliveryCursor { |
| 19 | + v: 1 |
| 20 | + createdAt: string |
| 21 | + id: string |
| 22 | + filterHash: string |
| 23 | +} |
| 24 | + |
| 25 | +function safeId(value: string, field: string): string { |
| 26 | + const normalized = value.trim() |
| 27 | + assertDomain( |
| 28 | + SAFE_ID_PATTERN.test(normalized), |
| 29 | + 'INVALID_ARGUMENT', |
| 30 | + `${field} must contain 3 to 128 safe characters`, |
| 31 | + ) |
| 32 | + return normalized |
| 33 | +} |
| 34 | + |
| 35 | +function optionalUuid(value: string | undefined, field: string): string | undefined { |
| 36 | + const normalized = value?.trim().toLowerCase() |
| 37 | + if (!normalized) return undefined |
| 38 | + assertDomain(UUID_V4_PATTERN.test(normalized), 'INVALID_ARGUMENT', `${field} must be a UUID v4`) |
| 39 | + return normalized |
| 40 | +} |
| 41 | + |
| 42 | +function createFilterHash(input: { |
| 43 | + workspaceId: string |
| 44 | + status?: WebhookDeliveryStatus |
| 45 | + endpointId?: string |
| 46 | + eventId?: string |
| 47 | +}): string { |
| 48 | + return createHash('sha256') |
| 49 | + .update(JSON.stringify({ |
| 50 | + workspaceId: input.workspaceId, |
| 51 | + status: input.status ?? null, |
| 52 | + endpointId: input.endpointId ?? null, |
| 53 | + eventId: input.eventId ?? null, |
| 54 | + })) |
| 55 | + .digest('hex') |
| 56 | +} |
| 57 | + |
| 58 | +function encodeCursor(cursor: WebhookDeliveryCursor): string { |
| 59 | + return Buffer.from(JSON.stringify(cursor), 'utf8').toString('base64url') |
| 60 | +} |
| 61 | + |
| 62 | +function decodeCursor(value: string, expectedFilterHash: string): WebhookDeliveryCursor { |
| 63 | + assertDomain(CURSOR_PATTERN.test(value), 'INVALID_ARGUMENT', 'after is not a valid webhook delivery cursor') |
| 64 | + try { |
| 65 | + const parsed = JSON.parse(Buffer.from(value, 'base64url').toString('utf8')) as unknown |
| 66 | + assertDomain( |
| 67 | + typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed), |
| 68 | + 'INVALID_ARGUMENT', |
| 69 | + 'after is not a valid webhook delivery cursor', |
| 70 | + ) |
| 71 | + const cursor = parsed as Record<string, unknown> |
| 72 | + assertDomain( |
| 73 | + Object.keys(cursor).length === 4 && |
| 74 | + cursor.v === 1 && |
| 75 | + typeof cursor.createdAt === 'string' && |
| 76 | + new Date(cursor.createdAt).toISOString() === cursor.createdAt && |
| 77 | + typeof cursor.id === 'string' && |
| 78 | + UUID_V4_PATTERN.test(cursor.id) && |
| 79 | + typeof cursor.filterHash === 'string' && |
| 80 | + SHA256_PATTERN.test(cursor.filterHash) && |
| 81 | + cursor.filterHash === expectedFilterHash, |
| 82 | + 'INVALID_ARGUMENT', |
| 83 | + 'after does not match this webhook delivery query', |
| 84 | + ) |
| 85 | + return cursor as unknown as WebhookDeliveryCursor |
| 86 | + } catch (error) { |
| 87 | + if (error instanceof DomainError) throw error |
| 88 | + throw new DomainError('INVALID_ARGUMENT', 'after is not a valid webhook delivery cursor') |
| 89 | + } |
| 90 | +} |
| 91 | + |
| 92 | +export function listWebhookDeliveriesService(dependencies: { |
| 93 | + deliveries: WebhookDeliveryQueryRepository |
| 94 | +}) { |
| 95 | + return async function listWebhookDeliveries(request: { |
| 96 | + workspaceId: string |
| 97 | + limit?: number |
| 98 | + after?: string |
| 99 | + status?: string |
| 100 | + endpointId?: string |
| 101 | + eventId?: string |
| 102 | + }) { |
| 103 | + const workspaceId = safeId(request.workspaceId, 'workspaceId') |
| 104 | + const limit = request.limit ?? 20 |
| 105 | + assertDomain( |
| 106 | + Number.isSafeInteger(limit) && limit >= 1 && limit <= 100, |
| 107 | + 'INVALID_ARGUMENT', |
| 108 | + 'limit must be an integer from 1 to 100', |
| 109 | + ) |
| 110 | + const statusValue = request.status?.trim() |
| 111 | + assertDomain( |
| 112 | + !statusValue || WEBHOOK_DELIVERY_STATUSES.includes(statusValue as WebhookDeliveryStatus), |
| 113 | + 'INVALID_ARGUMENT', |
| 114 | + 'status is not supported', |
| 115 | + ) |
| 116 | + const status = statusValue as WebhookDeliveryStatus | undefined |
| 117 | + const endpointId = optionalUuid(request.endpointId, 'endpointId') |
| 118 | + const eventId = optionalUuid(request.eventId, 'eventId') |
| 119 | + const queryFilterHash = createFilterHash({ workspaceId, status, endpointId, eventId }) |
| 120 | + const cursorValue = request.after?.trim() |
| 121 | + const after = cursorValue ? decodeCursor(cursorValue, queryFilterHash) : undefined |
| 122 | + const query: WebhookDeliveryListQuery = { |
| 123 | + workspaceId, |
| 124 | + limit: limit + 1, |
| 125 | + ...(status ? { status } : {}), |
| 126 | + ...(endpointId ? { endpointId } : {}), |
| 127 | + ...(eventId ? { eventId } : {}), |
| 128 | + ...(after ? { after: { createdAt: after.createdAt, id: after.id } } : {}), |
| 129 | + } |
| 130 | + const records = await dependencies.deliveries.list(query) |
| 131 | + assertDomain( |
| 132 | + records.length <= limit + 1, |
| 133 | + 'PERSISTENCE_CONFLICT', |
| 134 | + 'Webhook delivery query returned too many records', |
| 135 | + ) |
| 136 | + const hasNextPage = records.length > limit |
| 137 | + const page = records.slice(0, limit) |
| 138 | + const last = page.at(-1)?.delivery |
| 139 | + return Object.freeze({ |
| 140 | + deliveries: Object.freeze(page), |
| 141 | + ...(hasNextPage && last |
| 142 | + ? { |
| 143 | + nextCursor: encodeCursor({ |
| 144 | + v: 1, |
| 145 | + createdAt: last.createdAt, |
| 146 | + id: last.id, |
| 147 | + filterHash: queryFilterHash, |
| 148 | + }), |
| 149 | + } |
| 150 | + : {}), |
| 151 | + }) |
| 152 | + } |
| 153 | +} |
0 commit comments