@antasphere/chassis-server 1.1.0 → 1.2.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.
Files changed (172) hide show
  1. package/dist/api/apikeys.d.ts +4 -1
  2. package/dist/api/apikeys.d.ts.map +1 -1
  3. package/dist/api/apikeys.js +11 -1
  4. package/dist/api/apikeys.js.map +1 -1
  5. package/dist/api/create-api.d.ts +3 -0
  6. package/dist/api/create-api.d.ts.map +1 -1
  7. package/dist/api/create-api.js +8 -3
  8. package/dist/api/create-api.js.map +1 -1
  9. package/dist/api/invitations.d.ts.map +1 -1
  10. package/dist/api/invitations.js +6 -0
  11. package/dist/api/invitations.js.map +1 -1
  12. package/dist/api/members.d.ts +5 -2
  13. package/dist/api/members.d.ts.map +1 -1
  14. package/dist/api/members.js +1 -0
  15. package/dist/api/members.js.map +1 -1
  16. package/dist/api/projects.d.ts +3 -0
  17. package/dist/api/projects.d.ts.map +1 -1
  18. package/dist/api/projects.js +13 -1
  19. package/dist/api/projects.js.map +1 -1
  20. package/dist/api/webhooks.d.ts +24 -0
  21. package/dist/api/webhooks.d.ts.map +1 -0
  22. package/dist/api/webhooks.js +170 -0
  23. package/dist/api/webhooks.js.map +1 -0
  24. package/dist/boot.d.ts.map +1 -1
  25. package/dist/boot.js +47 -4
  26. package/dist/boot.js.map +1 -1
  27. package/dist/email/index.d.ts +1 -0
  28. package/dist/email/index.d.ts.map +1 -1
  29. package/dist/email/index.js +1 -0
  30. package/dist/email/index.js.map +1 -1
  31. package/dist/env.d.ts +9 -0
  32. package/dist/env.d.ts.map +1 -1
  33. package/dist/env.js +11 -0
  34. package/dist/env.js.map +1 -1
  35. package/dist/identity/demo-pass-rules.d.ts.map +1 -1
  36. package/dist/identity/demo-pass-rules.js +6 -1
  37. package/dist/identity/demo-pass-rules.js.map +1 -1
  38. package/dist/identity/hub-reconcile.d.ts +2 -2
  39. package/dist/identity/hub-reconcile.d.ts.map +1 -1
  40. package/dist/identity/hub-reconcile.js.map +1 -1
  41. package/dist/index.d.ts +2 -1
  42. package/dist/index.d.ts.map +1 -1
  43. package/dist/jobs/index.d.ts +1 -1
  44. package/dist/jobs/index.d.ts.map +1 -1
  45. package/dist/jobs/index.js.map +1 -1
  46. package/dist/jobs/pgboss.d.ts +34 -0
  47. package/dist/jobs/pgboss.d.ts.map +1 -1
  48. package/dist/jobs/pgboss.js +32 -9
  49. package/dist/jobs/pgboss.js.map +1 -1
  50. package/dist/mcp/index.d.ts +1 -0
  51. package/dist/mcp/index.d.ts.map +1 -1
  52. package/dist/mcp/index.js +1 -0
  53. package/dist/mcp/index.js.map +1 -1
  54. package/dist/mcp/server.d.ts +1 -1
  55. package/dist/mcp/server.d.ts.map +1 -1
  56. package/dist/mcp/server.js +11 -2
  57. package/dist/mcp/server.js.map +1 -1
  58. package/dist/mcp/tool-kit.d.ts +2 -0
  59. package/dist/mcp/tool-kit.d.ts.map +1 -1
  60. package/dist/mcp/tool-kit.js +5 -1
  61. package/dist/mcp/tool-kit.js.map +1 -1
  62. package/dist/mcp/webhooks.d.ts +16 -0
  63. package/dist/mcp/webhooks.d.ts.map +1 -0
  64. package/dist/mcp/webhooks.js +226 -0
  65. package/dist/mcp/webhooks.js.map +1 -0
  66. package/dist/members/removal.d.ts +10 -2
  67. package/dist/members/removal.d.ts.map +1 -1
  68. package/dist/members/removal.js +3 -0
  69. package/dist/members/removal.js.map +1 -1
  70. package/dist/middleware/idempotency.d.ts.map +1 -1
  71. package/dist/middleware/idempotency.js +3 -1
  72. package/dist/middleware/idempotency.js.map +1 -1
  73. package/dist/middleware/scopes.d.ts +9 -1
  74. package/dist/middleware/scopes.d.ts.map +1 -1
  75. package/dist/middleware/scopes.js +8 -1
  76. package/dist/middleware/scopes.js.map +1 -1
  77. package/dist/secret-box.d.ts +10 -0
  78. package/dist/secret-box.d.ts.map +1 -0
  79. package/dist/secret-box.js +87 -0
  80. package/dist/secret-box.js.map +1 -0
  81. package/dist/testing/helpers.d.ts +8 -0
  82. package/dist/testing/helpers.d.ts.map +1 -1
  83. package/dist/testing/helpers.js.map +1 -1
  84. package/dist/tool-definition.d.ts +24 -0
  85. package/dist/tool-definition.d.ts.map +1 -1
  86. package/dist/tool-definition.js.map +1 -1
  87. package/dist/webhooks/catalog.d.ts +80 -0
  88. package/dist/webhooks/catalog.d.ts.map +1 -0
  89. package/dist/webhooks/catalog.js +134 -0
  90. package/dist/webhooks/catalog.js.map +1 -0
  91. package/dist/webhooks/index.d.ts +9 -0
  92. package/dist/webhooks/index.d.ts.map +1 -0
  93. package/dist/webhooks/index.js +9 -0
  94. package/dist/webhooks/index.js.map +1 -0
  95. package/dist/webhooks/jobs.d.ts +12 -0
  96. package/dist/webhooks/jobs.d.ts.map +1 -0
  97. package/dist/webhooks/jobs.js +77 -0
  98. package/dist/webhooks/jobs.js.map +1 -0
  99. package/dist/webhooks/mail.d.ts +24 -0
  100. package/dist/webhooks/mail.d.ts.map +1 -0
  101. package/dist/webhooks/mail.js +21 -0
  102. package/dist/webhooks/mail.js.map +1 -0
  103. package/dist/webhooks/match.d.ts +22 -0
  104. package/dist/webhooks/match.d.ts.map +1 -0
  105. package/dist/webhooks/match.js +40 -0
  106. package/dist/webhooks/match.js.map +1 -0
  107. package/dist/webhooks/safe-fetch.d.ts +94 -0
  108. package/dist/webhooks/safe-fetch.d.ts.map +1 -0
  109. package/dist/webhooks/safe-fetch.js +263 -0
  110. package/dist/webhooks/safe-fetch.js.map +1 -0
  111. package/dist/webhooks/service.d.ts +245 -0
  112. package/dist/webhooks/service.d.ts.map +1 -0
  113. package/dist/webhooks/service.js +861 -0
  114. package/dist/webhooks/service.js.map +1 -0
  115. package/dist/webhooks/signing.d.ts +40 -0
  116. package/dist/webhooks/signing.d.ts.map +1 -0
  117. package/dist/webhooks/signing.js +108 -0
  118. package/dist/webhooks/signing.js.map +1 -0
  119. package/dist/webhooks/tx-send.d.ts +31 -0
  120. package/dist/webhooks/tx-send.d.ts.map +1 -0
  121. package/dist/webhooks/tx-send.js +22 -0
  122. package/dist/webhooks/tx-send.js.map +1 -0
  123. package/package.json +7 -3
  124. package/src/api/apikeys.ts +12 -1
  125. package/src/api/create-api.ts +17 -3
  126. package/src/api/invitations.ts +6 -0
  127. package/src/api/members.ts +6 -2
  128. package/src/api/projects.ts +16 -1
  129. package/src/api/webhooks.ts +205 -0
  130. package/src/boot.ts +48 -4
  131. package/src/email/index.ts +1 -0
  132. package/src/env.ts +11 -0
  133. package/src/identity/demo-pass-rules.ts +6 -1
  134. package/src/identity/hub-reconcile.ts +2 -2
  135. package/src/index.ts +13 -1
  136. package/src/jobs/index.ts +1 -0
  137. package/src/jobs/pgboss.ts +71 -9
  138. package/src/mcp/index.ts +1 -0
  139. package/src/mcp/server.ts +10 -2
  140. package/src/mcp/tool-kit.ts +7 -1
  141. package/src/mcp/webhooks.ts +370 -0
  142. package/src/members/removal.ts +21 -1
  143. package/src/middleware/idempotency.ts +3 -1
  144. package/src/middleware/scopes.ts +14 -0
  145. package/src/secret-box.ts +93 -0
  146. package/src/testing/helpers.ts +8 -0
  147. package/src/tool-definition.ts +29 -0
  148. package/src/webhooks/catalog.ts +205 -0
  149. package/src/webhooks/index.ts +58 -0
  150. package/src/webhooks/jobs.ts +92 -0
  151. package/src/webhooks/mail.ts +48 -0
  152. package/src/webhooks/match.ts +52 -0
  153. package/src/webhooks/safe-fetch.ts +335 -0
  154. package/src/webhooks/service.ts +1089 -0
  155. package/src/webhooks/signing.ts +132 -0
  156. package/src/webhooks/tx-send.ts +53 -0
  157. package/test/host/drizzle/0002_webhooks.sql +49 -0
  158. package/test/host/drizzle/meta/0002_snapshot.json +3952 -0
  159. package/test/host/drizzle/meta/_journal.json +8 -1
  160. package/test/host/identity.ts +6 -1
  161. package/test/host/minimal-host.ts +2 -1
  162. package/test/host/minimal-tool.ts +32 -4
  163. package/test/integration/mcp-webhooks.test.ts +360 -0
  164. package/test/integration/webhooks.test.ts +1684 -0
  165. package/test/unit/secret-box.test.ts +124 -0
  166. package/test/unit/tx-send.test.ts +23 -0
  167. package/test/unit/webhook-catalog.test.ts +151 -0
  168. package/test/unit/webhook-env.test.ts +60 -0
  169. package/test/unit/webhook-jobs.test.ts +92 -0
  170. package/test/unit/webhook-match.test.ts +81 -0
  171. package/test/unit/webhook-safe-fetch.test.ts +330 -0
  172. package/test/unit/webhook-signing.test.ts +169 -0
@@ -0,0 +1,861 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { and, desc, eq, sql } from 'drizzle-orm';
3
+ import { Counter } from 'prom-client';
4
+ import { user as userTable, webhookDeliveries, webhookEndpoints, workspaceMembers, workspaces } from '@antasphere/chassis-db';
5
+ import { createSecretBox } from '../secret-box.js';
6
+ import { createdAtText, decodeKeysetCursor, encodeKeysetCursor, keysetBeforeValue } from '../pagination.js';
7
+ import { WEBHOOK_PING_EVENT } from './catalog.js';
8
+ import { endpointWants } from './match.js';
9
+ import { buildWebhookDisabledEmail } from './mail.js';
10
+ import { checkWebhookUrl, safePost, WebhookUrlRefusedError } from './safe-fetch.js';
11
+ import { generateWebhookSecret, webhookHeaders } from './signing.js';
12
+ import { sendInTx } from './tx-send.js';
13
+ /**
14
+ * Outbound webhooks (PRDCT-3482): the chassis's machinery, tool-neutral.
15
+ *
16
+ * EMIT: a domain write calls `emit(tx, …)` INSIDE its own transaction; one
17
+ * pg-boss job (the event's envelope) is written by the same connection, so
18
+ * the event is durable with the write and never exists for a rolled-back
19
+ * one. A per-replica cache of "does any enabled endpoint of this workspace
20
+ * want this type" (`listenerTtlMs`) makes an emit nobody listens to cost
21
+ * one map lookup: a view with no endpoint costs no job.
22
+ *
23
+ * FAN-OUT (`webhook-events`): the event is matched against the workspace's
24
+ * enabled endpoints (type, then filters); one `webhook_deliveries` row and
25
+ * one delivery job per match, in one transaction.
26
+ *
27
+ * DELIVERY (`webhook-deliveries`): the envelope is signed (Standard
28
+ * Webhooks, two signatures during a rotation overlap) and POSTed through the
29
+ * guarded fetch. A 2xx is `delivered`; anything else fails the job, which
30
+ * pg-boss retries on the queue's budget (ten retries from thirty seconds,
31
+ * about eight and a half hours), then moves to `webhook-deliveries-held`:
32
+ * the row is marked `held`, logged, counted, and queued again an hour later
33
+ * with the whole budget once more, round after round, until the receiver
34
+ * takes it or the endpoint is disabled. A streak of
35
+ * `disableAfterFailures` failures spanning `disableAfterMs` switches the
36
+ * endpoint off and mails its creator once.
37
+ *
38
+ * The secret is stored sealed (`secret-box.ts`, info `chassis:webhook-endpoint`)
39
+ * and shown once, at creation and at rotation.
40
+ */
41
+ export const WEBHOOK_EVENTS_QUEUE = 'webhook-events';
42
+ export const WEBHOOK_DELIVERIES_QUEUE = 'webhook-deliveries';
43
+ export const WEBHOOK_DELIVERIES_HELD_QUEUE = 'webhook-deliveries-held';
44
+ export const WEBHOOK_PURGE_QUEUE = 'webhook-purge';
45
+ /** The HKDF info of the endpoints' secret box: never the idempotency one. */
46
+ export const WEBHOOK_SECRET_BOX_INFO = 'chassis:webhook-endpoint';
47
+ export const DEFAULT_WEBHOOK_DIALS = {
48
+ retryLimit: 10,
49
+ retryDelaySeconds: 30,
50
+ heldDelaySeconds: 3600,
51
+ disableAfterFailures: 20,
52
+ disableAfterMs: 2 * 24 * 3600 * 1000,
53
+ listenerTtlMs: 30_000,
54
+ previousSecretOverlapMs: 24 * 3600 * 1000,
55
+ timeoutMs: 10_000
56
+ };
57
+ export class WebhookRefusedError extends Error {
58
+ code;
59
+ constructor(code, message) {
60
+ super(message);
61
+ this.code = code;
62
+ this.name = 'WebhookRefusedError';
63
+ }
64
+ }
65
+ /**
66
+ * Thrown by an attempt that did not run because the endpoint already holds
67
+ * its share of this replica's pollers (`MAX_IN_FLIGHT_PER_ENDPOINT`): the
68
+ * worker puts the job back in the queue a moment later, its retry budget
69
+ * untouched, so one dead receiver can never take every slot (verifier
70
+ * round 2, MJ-R2-1).
71
+ */
72
+ export class WebhookDeliveryDeferred extends Error {
73
+ deliveryId;
74
+ constructor(deliveryId) {
75
+ super('deferred');
76
+ this.deliveryId = deliveryId;
77
+ this.name = 'WebhookDeliveryDeferred';
78
+ }
79
+ }
80
+ /** How many attempts one endpoint may have in flight on one replica at once. */
81
+ export const MAX_IN_FLIGHT_PER_ENDPOINT = 2;
82
+ /** Thrown by a retryable attempt that failed, so pg-boss retries the job. */
83
+ export class WebhookDeliveryFailed extends Error {
84
+ deliveryId;
85
+ constructor(deliveryId, message) {
86
+ super(message);
87
+ this.deliveryId = deliveryId;
88
+ this.name = 'WebhookDeliveryFailed';
89
+ }
90
+ }
91
+ const MAX_ERROR_TEXT = 300;
92
+ export class WebhookService {
93
+ deps;
94
+ dials;
95
+ promMetrics;
96
+ box;
97
+ listeners = new Map();
98
+ deliveries;
99
+ held;
100
+ disabled;
101
+ now;
102
+ /** Filled by boot once pg-boss exists (`attach`); the jobs are declared before it. */
103
+ boss = null;
104
+ /** Attempts in flight per endpoint on this replica (the per-endpoint bound). */
105
+ inFlight = new Map();
106
+ constructor(deps) {
107
+ this.deps = deps;
108
+ this.dials = { ...DEFAULT_WEBHOOK_DIALS, ...deps.dials };
109
+ this.box = createSecretBox(deps.authSecret, WEBHOOK_SECRET_BOX_INFO);
110
+ this.now = deps.now ?? (() => new Date());
111
+ this.deliveries = new Counter({
112
+ name: 'webhook_delivery_attempts_total',
113
+ help: 'Webhook delivery attempts by outcome: delivered, failed (will retry), refused (the endpoint off or the address refused)',
114
+ labelNames: ['outcome'],
115
+ registers: []
116
+ });
117
+ this.held = new Counter({
118
+ name: 'webhook_deliveries_held_total',
119
+ help: 'Webhook deliveries that ran out of retries and were held for an hourly re-drive',
120
+ registers: []
121
+ });
122
+ this.disabled = new Counter({
123
+ name: 'webhook_endpoints_disabled_total',
124
+ help: 'Webhook endpoints switched off after a failure streak',
125
+ registers: []
126
+ });
127
+ this.promMetrics = [this.deliveries, this.held, this.disabled];
128
+ }
129
+ attach(boss) {
130
+ this.boss = boss;
131
+ }
132
+ get catalog() {
133
+ return this.deps.catalog;
134
+ }
135
+ // ── Emit ─────────────────────────────────────────────────────────────────
136
+ async emit(conn, event) {
137
+ const declared = this.deps.catalog.events.get(event.type);
138
+ if (!declared) {
139
+ // A type the catalog does not know is a programming error, not a runtime condition.
140
+ throw new Error(`webhooks: "${event.type}" is not a declared event type`);
141
+ }
142
+ if (!(await this.wants(event.workspaceId, event.type)))
143
+ return null;
144
+ const parsed = declared.data.safeParse(event.data);
145
+ if (!parsed.success) {
146
+ this.deps.logger.error({ type: event.type, issues: parsed.error.issues.slice(0, 3) }, 'webhooks: an emit carried data outside its declared schema — skipped');
147
+ return null;
148
+ }
149
+ const subjects = {};
150
+ for (const key of declared.subjects) {
151
+ const value = event.subjects?.[key];
152
+ if (value === undefined) {
153
+ this.deps.logger.error({ type: event.type, subject: key }, 'webhooks: an emit left out a declared subject — skipped');
154
+ return null;
155
+ }
156
+ const declaredSubject = this.deps.catalog.subjects[key];
157
+ if (declaredSubject?.list === true) {
158
+ subjects[key] = typeof value === 'string' ? [value] : [...value];
159
+ }
160
+ else if (typeof value === 'string') {
161
+ subjects[key] = value;
162
+ }
163
+ else {
164
+ this.deps.logger.error({ type: event.type, subject: key }, 'webhooks: an emit gave a list for a subject declared as one id — skipped');
165
+ return null;
166
+ }
167
+ }
168
+ const boss = this.requireBoss();
169
+ const job = {
170
+ id: randomUUID(),
171
+ type: event.type,
172
+ occurredAt: this.now().toISOString(),
173
+ workspaceId: event.workspaceId,
174
+ subjects,
175
+ data: parsed.data
176
+ };
177
+ // The fan-out's own retries are short: it only reads and inserts locally.
178
+ const sent = await sendInTx(boss, conn, WEBHOOK_EVENTS_QUEUE, job, {
179
+ retryLimit: 5,
180
+ retryDelay: 5,
181
+ retryBackoff: true
182
+ });
183
+ if (sent === null)
184
+ throw new Error(`webhooks: the queue ${WEBHOOK_EVENTS_QUEUE} does not exist`);
185
+ return job.id;
186
+ }
187
+ /** Does any enabled endpoint of the workspace subscribe to this type? Cached per replica. */
188
+ async wants(workspaceId, type) {
189
+ const cached = this.listeners.get(workspaceId);
190
+ const patterns = cached && this.now().getTime() - cached.at < this.dials.listenerTtlMs
191
+ ? cached.patterns
192
+ : await this.loadListeners(workspaceId);
193
+ return patterns.some((p) => endpointWants({ enabled: true, events: p, filters: {} }, type, {}));
194
+ }
195
+ async loadListeners(workspaceId) {
196
+ const rows = await this.deps.db
197
+ .select({ events: webhookEndpoints.events })
198
+ .from(webhookEndpoints)
199
+ .where(and(eq(webhookEndpoints.workspaceId, workspaceId), eq(webhookEndpoints.enabled, true)));
200
+ const patterns = rows.map((r) => r.events);
201
+ this.listeners.set(workspaceId, { at: this.now().getTime(), patterns });
202
+ return patterns;
203
+ }
204
+ /** Forget the cached answer of a workspace (every write of its endpoints calls it). */
205
+ invalidateListeners(workspaceId) {
206
+ this.listeners.delete(workspaceId);
207
+ }
208
+ /**
209
+ * The chassis's own events, bridged from the in-process bus: fired after
210
+ * the write committed, so never for a rolled-back one, and at most once
211
+ * per replica that saw it. The events emitted inside a transaction the
212
+ * chassis owns (projects) do not pass here.
213
+ */
214
+ bindBus(events) {
215
+ const emit = async (event) => {
216
+ try {
217
+ await this.emit(this.deps.db, event);
218
+ }
219
+ catch (err) {
220
+ this.deps.logger.error({ err, type: event.type }, 'webhooks: a bus-bridged emit failed');
221
+ }
222
+ };
223
+ events.on('member.joined', ({ workspaceId, userId, role }) => emit({ workspaceId, type: 'member.joined', data: { userId, role } }));
224
+ events.on('member.removed', ({ workspaceId, userId }) => emit({ workspaceId, type: 'member.removed', data: { userId } }));
225
+ events.on('workspace.created', ({ workspaceId, ownerUserId }) => emit({ workspaceId, type: 'workspace.created', data: { ownerUserId } }));
226
+ events.on('apikey.created', ({ workspaceId, apiKeyId }) => emit({ workspaceId, type: 'apikey.created', data: { apiKeyId } }));
227
+ events.on('apikey.revoked', ({ workspaceId, apiKeyId }) => emit({ workspaceId, type: 'apikey.revoked', data: { apiKeyId } }));
228
+ }
229
+ // ── Fan-out ───────────────────────────────────────────────────────────────
230
+ /** One delivery row and one delivery job per endpoint that wants the event; answers how many. */
231
+ async fanOut(job) {
232
+ const endpoints = await this.deps.db
233
+ .select()
234
+ .from(webhookEndpoints)
235
+ .where(and(eq(webhookEndpoints.workspaceId, job.workspaceId), eq(webhookEndpoints.enabled, true)));
236
+ const matching = endpoints.filter((e) => endpointWants({ enabled: e.enabled, events: e.events, filters: e.filters }, job.type, job.subjects));
237
+ if (matching.length === 0)
238
+ return 0;
239
+ const payload = this.envelopeOf(job);
240
+ await this.deps.db.transaction(async (tx) => {
241
+ for (const endpoint of matching) {
242
+ const [row] = await tx
243
+ .insert(webhookDeliveries)
244
+ .values({
245
+ endpointId: endpoint.id,
246
+ workspaceId: job.workspaceId,
247
+ eventId: job.id,
248
+ eventType: job.type,
249
+ payload,
250
+ status: 'pending'
251
+ })
252
+ .returning({ id: webhookDeliveries.id });
253
+ await this.queueDelivery(tx, row.id);
254
+ }
255
+ });
256
+ return matching.length;
257
+ }
258
+ /** The envelope as the receiver reads it (without `attempt`, stamped at each send). */
259
+ envelopeOf(job) {
260
+ const subjects = {};
261
+ for (const [key, value] of Object.entries(job.subjects)) {
262
+ const field = this.deps.catalog.subjects[key]?.field ?? key;
263
+ subjects[field] = value;
264
+ }
265
+ return {
266
+ id: job.id,
267
+ type: job.type,
268
+ occurredAt: job.occurredAt,
269
+ workspaceId: job.workspaceId,
270
+ subjects,
271
+ data: job.data
272
+ };
273
+ }
274
+ async queueDelivery(conn, deliveryId, startAfterSeconds = 0) {
275
+ const sent = await sendInTx(this.requireBoss(), conn, WEBHOOK_DELIVERIES_QUEUE, { deliveryId }, {
276
+ retryLimit: this.dials.retryLimit,
277
+ retryDelay: this.dials.retryDelaySeconds,
278
+ retryBackoff: true,
279
+ ...(startAfterSeconds > 0 ? { startAfter: startAfterSeconds } : {})
280
+ });
281
+ if (sent === null)
282
+ throw new Error(`webhooks: the queue ${WEBHOOK_DELIVERIES_QUEUE} does not exist`);
283
+ }
284
+ // ── Delivery ──────────────────────────────────────────────────────────────
285
+ /**
286
+ * One attempt of a delivery. `retryable` (the queue's worker): a failure
287
+ * throws `WebhookDeliveryFailed` so pg-boss retries. Not retryable (the
288
+ * test ping, run inline): a failure marks the row `failed` and answers it.
289
+ * Answers the row as it is after the attempt.
290
+ */
291
+ async attempt(deliveryId, opts) {
292
+ const [delivery] = await this.deps.db
293
+ .select()
294
+ .from(webhookDeliveries)
295
+ .where(eq(webhookDeliveries.id, deliveryId))
296
+ .limit(1);
297
+ if (!delivery)
298
+ return null; // the endpoint (and its rows) are gone
299
+ if (delivery.status === 'delivered')
300
+ return delivery;
301
+ const [endpoint] = await this.deps.db
302
+ .select()
303
+ .from(webhookEndpoints)
304
+ .where(eq(webhookEndpoints.id, delivery.endpointId))
305
+ .limit(1);
306
+ const now = this.now();
307
+ if (!endpoint || !endpoint.enabled) {
308
+ this.deliveries.inc({ outcome: 'refused' });
309
+ return this.finish(delivery, {
310
+ status: 'failed',
311
+ lastError: 'endpoint_disabled',
312
+ lastStatusCode: null,
313
+ now
314
+ });
315
+ }
316
+ const attempt = delivery.attempt + 1;
317
+ const body = JSON.stringify({ ...delivery.payload, attempt });
318
+ // The secret is opened INSIDE the attempt's own handling: a row whose
319
+ // secret cannot be opened (a rotated auth secret, a damaged row) ends the
320
+ // delivery as failed `secret_unreadable`, visible on the page, never a
321
+ // throw that loops through the retries with nothing recorded (verifier
322
+ // round 1, MN3).
323
+ let headers;
324
+ try {
325
+ const secrets = [this.box.open(endpoint.secret)];
326
+ if (endpoint.previousSecret &&
327
+ endpoint.previousSecretExpiresAt &&
328
+ endpoint.previousSecretExpiresAt > now) {
329
+ secrets.push(this.box.open(endpoint.previousSecret));
330
+ }
331
+ headers = {
332
+ ...webhookHeaders(secrets, delivery.eventId, Math.floor(now.getTime() / 1000), body),
333
+ 'user-agent': `${this.deps.identity.slug}-webhooks/${this.deps.version}`
334
+ };
335
+ }
336
+ catch (e) {
337
+ this.deliveries.inc({ outcome: 'refused' });
338
+ this.deps.logger.error({ err: e, endpointId: endpoint.id, deliveryId: delivery.id }, 'webhooks: the endpoint’s secret cannot be opened — the delivery is failed and the endpoint switched off');
339
+ // An endpoint whose secret never opens would fail every event for ever
340
+ // (verifier round 2, N-R2-2): it is switched off here, with its reason.
341
+ await this.deps.db
342
+ .update(webhookEndpoints)
343
+ .set({ enabled: false, disabledAt: now, disabledReason: 'secret_unreadable', updatedAt: now })
344
+ .where(and(eq(webhookEndpoints.id, endpoint.id), eq(webhookEndpoints.enabled, true)));
345
+ this.invalidateListeners(endpoint.workspaceId);
346
+ return this.finish(delivery, {
347
+ status: 'failed',
348
+ attempt,
349
+ lastError: 'secret_unreadable',
350
+ lastStatusCode: null,
351
+ now
352
+ });
353
+ }
354
+ if (opts.retryable && (this.inFlight.get(endpoint.id) ?? 0) >= MAX_IN_FLIGHT_PER_ENDPOINT) {
355
+ throw new WebhookDeliveryDeferred(delivery.id);
356
+ }
357
+ this.inFlight.set(endpoint.id, (this.inFlight.get(endpoint.id) ?? 0) + 1);
358
+ let statusCode = null;
359
+ let error = null;
360
+ try {
361
+ const res = await safePost(endpoint.url, headers, body, this.deps.policy, {
362
+ timeoutMs: this.dials.timeoutMs,
363
+ ...this.deps.fetchOptions
364
+ });
365
+ statusCode = res.status;
366
+ if (res.status < 200 || res.status >= 300)
367
+ error = `HTTP ${res.status}`;
368
+ }
369
+ catch (e) {
370
+ error =
371
+ e instanceof WebhookUrlRefusedError
372
+ ? `url_refused:${e.code}`
373
+ : e.name === 'TimeoutError' || e.name === 'AbortError'
374
+ ? 'timeout'
375
+ : String(e.message ?? e).slice(0, MAX_ERROR_TEXT);
376
+ }
377
+ finally {
378
+ const left = (this.inFlight.get(endpoint.id) ?? 1) - 1;
379
+ if (left <= 0)
380
+ this.inFlight.delete(endpoint.id);
381
+ else
382
+ this.inFlight.set(endpoint.id, left);
383
+ }
384
+ if (error === null) {
385
+ this.deliveries.inc({ outcome: 'delivered' });
386
+ await this.deps.db
387
+ .update(webhookEndpoints)
388
+ .set({
389
+ consecutiveFailures: 0,
390
+ firstFailureAt: null,
391
+ lastDeliveryAt: now,
392
+ lastDeliveryStatus: 'delivered',
393
+ updatedAt: now
394
+ })
395
+ .where(eq(webhookEndpoints.id, endpoint.id));
396
+ return this.finish(delivery, {
397
+ status: 'delivered',
398
+ attempt,
399
+ lastStatusCode: statusCode,
400
+ lastError: null,
401
+ now,
402
+ deliveredAt: now
403
+ });
404
+ }
405
+ this.deliveries.inc({ outcome: 'failed' });
406
+ // The streak is counted IN the statement (never read then written):
407
+ // replicas failing the same endpoint at once each add their one, and the
408
+ // switch-off below is a second conditional statement only one of them
409
+ // wins (verifier round 1, MN5).
410
+ const [counted] = await this.deps.db
411
+ .update(webhookEndpoints)
412
+ .set({
413
+ consecutiveFailures: sql `${webhookEndpoints.consecutiveFailures} + 1`,
414
+ firstFailureAt: sql `COALESCE(${webhookEndpoints.firstFailureAt}, ${now})`,
415
+ lastDeliveryAt: now,
416
+ lastDeliveryStatus: 'failed',
417
+ updatedAt: now
418
+ })
419
+ .where(eq(webhookEndpoints.id, endpoint.id))
420
+ .returning({
421
+ streak: webhookEndpoints.consecutiveFailures,
422
+ firstFailureAt: webhookEndpoints.firstFailureAt
423
+ });
424
+ const streak = counted?.streak ?? endpoint.consecutiveFailures + 1;
425
+ const firstFailureAt = counted?.firstFailureAt ?? now;
426
+ let disable = streak >= this.dials.disableAfterFailures &&
427
+ now.getTime() - firstFailureAt.getTime() >= this.dials.disableAfterMs;
428
+ if (disable) {
429
+ const [won] = await this.deps.db
430
+ .update(webhookEndpoints)
431
+ .set({ enabled: false, disabledAt: now, disabledReason: 'delivery_failures', updatedAt: now })
432
+ .where(and(eq(webhookEndpoints.id, endpoint.id), eq(webhookEndpoints.enabled, true)))
433
+ .returning({ id: webhookEndpoints.id });
434
+ disable = won !== undefined;
435
+ }
436
+ if (disable) {
437
+ this.invalidateListeners(endpoint.workspaceId);
438
+ this.disabled.inc();
439
+ this.deps.logger.error({
440
+ endpointId: endpoint.id,
441
+ workspaceId: endpoint.workspaceId,
442
+ streak,
443
+ since: firstFailureAt.toISOString()
444
+ }, 'webhooks: an endpoint was switched off after a failure streak (webhook_endpoints_disabled_total)');
445
+ await this.mailDisabled(endpoint, streak, firstFailureAt).catch((err) => this.deps.logger.error({ err, endpointId: endpoint.id }, 'webhooks: the auto-disable mail failed'));
446
+ }
447
+ const nextAttemptAt = opts.retryable && attempt <= this.dials.retryLimit
448
+ ? new Date(now.getTime() + this.dials.retryDelaySeconds * 2 ** (attempt - 1) * 1000)
449
+ : null;
450
+ const row = await this.finish(delivery, {
451
+ status: opts.retryable ? 'pending' : 'failed',
452
+ attempt,
453
+ lastStatusCode: statusCode,
454
+ lastError: error,
455
+ nextAttemptAt,
456
+ now
457
+ });
458
+ if (opts.retryable)
459
+ throw new WebhookDeliveryFailed(delivery.id, error);
460
+ return row;
461
+ }
462
+ async finish(delivery, patch) {
463
+ const [row] = await this.deps.db
464
+ .update(webhookDeliveries)
465
+ .set({
466
+ status: patch.status,
467
+ attempt: patch.attempt ?? delivery.attempt,
468
+ lastStatusCode: patch.lastStatusCode,
469
+ lastError: patch.lastError,
470
+ nextAttemptAt: patch.nextAttemptAt ?? null,
471
+ deliveredAt: patch.deliveredAt ?? null,
472
+ updatedAt: patch.now
473
+ })
474
+ .where(eq(webhookDeliveries.id, delivery.id))
475
+ .returning();
476
+ return row;
477
+ }
478
+ /** Put a delivery back in the queue after `inSeconds` (a deferred attempt). */
479
+ async requeue(deliveryId, inSeconds) {
480
+ await this.queueDelivery(this.deps.db, deliveryId, inSeconds);
481
+ }
482
+ /**
483
+ * The held queue's work: mark the row held and queue it again after the
484
+ * hold, in ONE transaction, so a re-send that fails leaves the row pending
485
+ * and the held job's own retry finds it again (the chassis suite's round 1:
486
+ * a row marked held outside the transaction was never re-driven once its
487
+ * send had failed). A row already delivered, failed or gone is left alone.
488
+ */
489
+ async hold(deliveryId) {
490
+ const now = this.now();
491
+ const row = await this.deps.db.transaction(async (tx) => {
492
+ const [updated] = await tx
493
+ .update(webhookDeliveries)
494
+ .set({
495
+ status: 'held',
496
+ nextAttemptAt: new Date(now.getTime() + this.dials.heldDelaySeconds * 1000),
497
+ updatedAt: now
498
+ })
499
+ .where(and(eq(webhookDeliveries.id, deliveryId), eq(webhookDeliveries.status, 'pending')))
500
+ .returning({ id: webhookDeliveries.id, endpointId: webhookDeliveries.endpointId });
501
+ if (!updated)
502
+ return null;
503
+ await this.queueDelivery(tx, deliveryId, this.dials.heldDelaySeconds);
504
+ return updated;
505
+ });
506
+ if (!row)
507
+ return;
508
+ // Counted and logged once the hold committed: a rolled-back hold is not one.
509
+ this.held.inc();
510
+ this.deps.logger.error({ deliveryId, endpointId: row.endpointId, retryAfterSeconds: this.dials.heldDelaySeconds }, 'webhooks: a delivery exhausted its retries — held, re-driven after the hold (webhook_deliveries_held_total)');
511
+ }
512
+ async mailDisabled(endpoint, streak, since) {
513
+ if (!endpoint.createdBy || !this.deps.email.delivers)
514
+ return;
515
+ // Only a person still an ACTIVE member of the workspace is told: a
516
+ // creator who left takes no workspace name and no link with them
517
+ // (verifier round 1, MN4).
518
+ const [creator] = await this.deps.db
519
+ .select({ email: userTable.email, name: userTable.name })
520
+ .from(userTable)
521
+ .innerJoin(workspaceMembers, and(eq(workspaceMembers.userId, userTable.id), eq(workspaceMembers.workspaceId, endpoint.workspaceId), eq(workspaceMembers.isActive, true)))
522
+ .where(eq(userTable.id, endpoint.createdBy))
523
+ .limit(1);
524
+ if (!creator)
525
+ return;
526
+ const [workspace] = await this.deps.db
527
+ .select({ name: workspaces.name })
528
+ .from(workspaces)
529
+ .where(eq(workspaces.id, endpoint.workspaceId))
530
+ .limit(1);
531
+ const mail = buildWebhookDisabledEmail({
532
+ brand: this.deps.brand,
533
+ recipientName: creator.name,
534
+ url: endpoint.url,
535
+ description: endpoint.description,
536
+ workspaceName: workspace?.name ?? 'your workspace',
537
+ consecutiveFailures: streak,
538
+ firstFailureAt: since,
539
+ manageUrl: `${this.deps.publicBaseUrl}/webhooks?endpoint=${endpoint.id}`
540
+ });
541
+ await this.deps.email.send({ to: creator.email, ...mail });
542
+ }
543
+ /** The nightly purge: deliveries older than `retentionDays`, in bounded batches. */
544
+ async purge(retentionDays) {
545
+ if (retentionDays <= 0)
546
+ return 0;
547
+ const BATCH = 5000;
548
+ let total = 0;
549
+ for (let i = 0; i < 10_000; i++) {
550
+ const res = await this.deps.db.execute(sql `
551
+ DELETE FROM webhook_deliveries
552
+ WHERE id IN (
553
+ SELECT id FROM webhook_deliveries
554
+ WHERE created_at < now() - make_interval(days => ${retentionDays})
555
+ ORDER BY created_at
556
+ LIMIT ${BATCH}
557
+ )
558
+ `);
559
+ const deleted = res.rowCount ?? 0;
560
+ total += deleted;
561
+ if (deleted < BATCH)
562
+ break;
563
+ }
564
+ return total;
565
+ }
566
+ // ── Endpoints ─────────────────────────────────────────────────────────────
567
+ /** The URL rule at registration (the address itself is judged at every delivery). */
568
+ checkUrl(url) {
569
+ try {
570
+ checkWebhookUrl(url, this.deps.policy);
571
+ }
572
+ catch (e) {
573
+ if (e instanceof WebhookUrlRefusedError)
574
+ throw new WebhookRefusedError('url_refused', e.message);
575
+ throw e;
576
+ }
577
+ }
578
+ /**
579
+ * The subscription is checked against the catalog at registration
580
+ * (verifier round 1, MN1): an exact type must be declared, a family must
581
+ * have at least one declared type, `*` is always right; every filter key
582
+ * must be a declared subject. A typo would otherwise subscribe to nothing,
583
+ * silently.
584
+ */
585
+ checkSubscription(events, filters) {
586
+ const known = this.deps.catalog.events;
587
+ const families = new Set([...known.keys()].map((t) => t.slice(0, t.indexOf('.'))));
588
+ for (const pattern of events ?? []) {
589
+ if (pattern === '*')
590
+ continue;
591
+ if (pattern.endsWith('.*')) {
592
+ if (!families.has(pattern.slice(0, -2))) {
593
+ throw new WebhookRefusedError('unknown_event', `"${pattern}" matches no event family of this instance`);
594
+ }
595
+ }
596
+ else if (!known.has(pattern)) {
597
+ throw new WebhookRefusedError('unknown_event', `"${pattern}" is not an event type of this instance`);
598
+ }
599
+ }
600
+ for (const key of Object.keys(filters ?? {})) {
601
+ if (!(key in this.deps.catalog.subjects)) {
602
+ throw new WebhookRefusedError('unknown_subject', `"${key}" is not a subject of this instance`);
603
+ }
604
+ }
605
+ }
606
+ async create(workspaceId, createdBy, input) {
607
+ this.checkUrl(input.url);
608
+ this.checkSubscription(input.events, input.filters);
609
+ const secret = generateWebhookSecret();
610
+ const [row] = await this.deps.db
611
+ .insert(webhookEndpoints)
612
+ .values({
613
+ workspaceId,
614
+ createdBy,
615
+ url: input.url,
616
+ description: input.description ?? '',
617
+ events: [...input.events],
618
+ filters: normalizeFilters(input.filters),
619
+ enabled: input.enabled ?? true,
620
+ secret: this.box.seal(secret)
621
+ })
622
+ .returning();
623
+ this.invalidateListeners(workspaceId);
624
+ return { endpoint: endpointToWire(row), secret };
625
+ }
626
+ async get(workspaceId, id) {
627
+ const row = await this.row(workspaceId, id);
628
+ return row ? endpointToWire(row) : null;
629
+ }
630
+ async list(workspaceId, cursor, limit) {
631
+ const after = decodeKeysetCursor(cursor);
632
+ const rows = await this.deps.db
633
+ .select({ row: webhookEndpoints, createdAtText: createdAtText(webhookEndpoints.createdAt) })
634
+ .from(webhookEndpoints)
635
+ .where(and(eq(webhookEndpoints.workspaceId, workspaceId), ...(after
636
+ ? [
637
+ keysetBeforeValue({
638
+ id: webhookEndpoints.id,
639
+ createdAt: webhookEndpoints.createdAt,
640
+ cursor: after
641
+ })
642
+ ]
643
+ : [])))
644
+ .orderBy(desc(webhookEndpoints.createdAt), desc(webhookEndpoints.id))
645
+ .limit(limit + 1);
646
+ const page = rows.slice(0, limit);
647
+ const last = rows.length > limit ? page[page.length - 1] : undefined;
648
+ return {
649
+ webhooks: page.map((r) => endpointToWire(r.row)),
650
+ nextCursor: last ? encodeKeysetCursor({ id: last.row.id, createdAtText: last.createdAtText }) : null
651
+ };
652
+ }
653
+ /** Endpoints of the workspace, for the plan limit's count hook. */
654
+ async count(workspaceId) {
655
+ const [row] = await this.deps.db
656
+ .select({ n: sql `count(*)::int` })
657
+ .from(webhookEndpoints)
658
+ .where(eq(webhookEndpoints.workspaceId, workspaceId));
659
+ return Number(row?.n ?? 0);
660
+ }
661
+ async update(workspaceId, id, patch) {
662
+ if (patch.url !== undefined)
663
+ this.checkUrl(patch.url);
664
+ this.checkSubscription(patch.events, patch.filters);
665
+ const now = this.now();
666
+ const reEnabled = patch.enabled === true;
667
+ const [row] = await this.deps.db
668
+ .update(webhookEndpoints)
669
+ .set({
670
+ ...(patch.url !== undefined ? { url: patch.url } : {}),
671
+ ...(patch.description !== undefined ? { description: patch.description } : {}),
672
+ ...(patch.events !== undefined ? { events: [...patch.events] } : {}),
673
+ ...(patch.filters !== undefined ? { filters: normalizeFilters(patch.filters) } : {}),
674
+ ...(patch.enabled !== undefined ? { enabled: patch.enabled } : {}),
675
+ // Switching an endpoint back on clears the auto-disable and its streak.
676
+ ...(reEnabled
677
+ ? { disabledAt: null, disabledReason: null, consecutiveFailures: 0, firstFailureAt: null }
678
+ : {}),
679
+ updatedAt: now
680
+ })
681
+ .where(and(eq(webhookEndpoints.id, id), eq(webhookEndpoints.workspaceId, workspaceId)))
682
+ .returning();
683
+ this.invalidateListeners(workspaceId);
684
+ return row ? endpointToWire(row) : null;
685
+ }
686
+ async remove(workspaceId, id) {
687
+ const [row] = await this.deps.db
688
+ .delete(webhookEndpoints)
689
+ .where(and(eq(webhookEndpoints.id, id), eq(webhookEndpoints.workspaceId, workspaceId)))
690
+ .returning();
691
+ this.invalidateListeners(workspaceId);
692
+ return row ? endpointToWire(row) : null;
693
+ }
694
+ async rotateSecret(workspaceId, id) {
695
+ const current = await this.row(workspaceId, id);
696
+ if (!current)
697
+ return null;
698
+ const now = this.now();
699
+ const secret = generateWebhookSecret();
700
+ const previousSecretExpiresAt = new Date(now.getTime() + this.dials.previousSecretOverlapMs);
701
+ const [row] = await this.deps.db
702
+ .update(webhookEndpoints)
703
+ .set({
704
+ secret: this.box.seal(secret),
705
+ previousSecret: current.secret,
706
+ previousSecretExpiresAt,
707
+ updatedAt: now
708
+ })
709
+ .where(eq(webhookEndpoints.id, id))
710
+ .returning();
711
+ return {
712
+ endpoint: endpointToWire(row),
713
+ secret,
714
+ previousSecretExpiresAt: previousSecretExpiresAt.toISOString()
715
+ };
716
+ }
717
+ /** A signed `webhook.ping`, attempted inline, once; the row says how it went. */
718
+ async test(workspaceId, id, sentBy) {
719
+ const endpoint = await this.row(workspaceId, id);
720
+ if (!endpoint)
721
+ return null;
722
+ const job = {
723
+ id: randomUUID(),
724
+ type: WEBHOOK_PING_EVENT,
725
+ occurredAt: this.now().toISOString(),
726
+ workspaceId,
727
+ subjects: {},
728
+ data: { endpointId: id, sentBy }
729
+ };
730
+ const [row] = await this.deps.db
731
+ .insert(webhookDeliveries)
732
+ .values({
733
+ endpointId: id,
734
+ workspaceId,
735
+ eventId: job.id,
736
+ eventType: job.type,
737
+ payload: this.envelopeOf(job),
738
+ status: 'pending'
739
+ })
740
+ .returning({ id: webhookDeliveries.id });
741
+ const result = await this.attempt(row.id, { retryable: false });
742
+ return result ? deliveryToWire(result) : null;
743
+ }
744
+ async listDeliveries(workspaceId, id, query) {
745
+ const endpoint = await this.row(workspaceId, id);
746
+ if (!endpoint)
747
+ return null;
748
+ const after = decodeKeysetCursor(query.cursor);
749
+ const rows = await this.deps.db
750
+ .select({ row: webhookDeliveries, createdAtText: createdAtText(webhookDeliveries.createdAt) })
751
+ .from(webhookDeliveries)
752
+ .where(and(eq(webhookDeliveries.endpointId, id), ...(query.status ? [eq(webhookDeliveries.status, query.status)] : []), ...(after
753
+ ? [
754
+ keysetBeforeValue({
755
+ id: webhookDeliveries.id,
756
+ createdAt: webhookDeliveries.createdAt,
757
+ cursor: after
758
+ })
759
+ ]
760
+ : [])))
761
+ .orderBy(desc(webhookDeliveries.createdAt), desc(webhookDeliveries.id))
762
+ .limit(query.limit + 1);
763
+ const page = rows.slice(0, query.limit);
764
+ const last = rows.length > query.limit ? page[page.length - 1] : undefined;
765
+ return {
766
+ deliveries: page.map((r) => deliveryToWire(r.row)),
767
+ nextCursor: last ? encodeKeysetCursor({ id: last.row.id, createdAtText: last.createdAtText }) : null
768
+ };
769
+ }
770
+ async getDelivery(workspaceId, id, deliveryId) {
771
+ const row = await this.deliveryRow(workspaceId, id, deliveryId);
772
+ return row ? deliveryToWire(row) : null;
773
+ }
774
+ /** The same event queued again for the endpoint, as a new row (the event id unchanged: the receiver's dedupe key). */
775
+ async redeliver(workspaceId, id, deliveryId) {
776
+ const source = await this.deliveryRow(workspaceId, id, deliveryId);
777
+ if (!source)
778
+ return null;
779
+ const row = await this.deps.db.transaction(async (tx) => {
780
+ const [inserted] = await tx
781
+ .insert(webhookDeliveries)
782
+ .values({
783
+ endpointId: source.endpointId,
784
+ workspaceId: source.workspaceId,
785
+ eventId: source.eventId,
786
+ eventType: source.eventType,
787
+ payload: source.payload,
788
+ status: 'pending'
789
+ })
790
+ .returning();
791
+ await this.queueDelivery(tx, inserted.id);
792
+ return inserted;
793
+ });
794
+ return deliveryToWire(row);
795
+ }
796
+ async row(workspaceId, id) {
797
+ const [row] = await this.deps.db
798
+ .select()
799
+ .from(webhookEndpoints)
800
+ .where(and(eq(webhookEndpoints.id, id), eq(webhookEndpoints.workspaceId, workspaceId)))
801
+ .limit(1);
802
+ return row;
803
+ }
804
+ async deliveryRow(workspaceId, id, deliveryId) {
805
+ const [row] = await this.deps.db
806
+ .select()
807
+ .from(webhookDeliveries)
808
+ .where(and(eq(webhookDeliveries.id, deliveryId), eq(webhookDeliveries.endpointId, id), eq(webhookDeliveries.workspaceId, workspaceId)))
809
+ .limit(1);
810
+ return row;
811
+ }
812
+ requireBoss() {
813
+ if (!this.boss)
814
+ throw new Error('webhooks: the job runtime is not attached yet (boot order)');
815
+ return this.boss;
816
+ }
817
+ }
818
+ /** Filters as stored: every key kept, its ids deduplicated; an empty object when none. */
819
+ function normalizeFilters(filters) {
820
+ const out = {};
821
+ for (const [key, ids] of Object.entries(filters ?? {}))
822
+ out[key] = [...new Set(ids)];
823
+ return out;
824
+ }
825
+ export function endpointToWire(row) {
826
+ return {
827
+ id: row.id,
828
+ url: row.url,
829
+ description: row.description,
830
+ events: row.events,
831
+ filters: row.filters,
832
+ enabled: row.enabled,
833
+ createdBy: row.createdBy,
834
+ createdAt: row.createdAt.toISOString(),
835
+ updatedAt: row.updatedAt.toISOString(),
836
+ disabledAt: row.disabledAt?.toISOString() ?? null,
837
+ disabledReason: row.disabledReason,
838
+ consecutiveFailures: row.consecutiveFailures,
839
+ lastDeliveryAt: row.lastDeliveryAt?.toISOString() ?? null,
840
+ lastDeliveryStatus: row.lastDeliveryStatus,
841
+ previousSecretExpiresAt: row.previousSecretExpiresAt?.toISOString() ?? null
842
+ };
843
+ }
844
+ export function deliveryToWire(row) {
845
+ return {
846
+ id: row.id,
847
+ endpointId: row.endpointId,
848
+ eventId: row.eventId,
849
+ eventType: row.eventType,
850
+ status: row.status,
851
+ attempt: row.attempt,
852
+ lastStatusCode: row.lastStatusCode,
853
+ lastError: row.lastError,
854
+ nextAttemptAt: row.nextAttemptAt?.toISOString() ?? null,
855
+ deliveredAt: row.deliveredAt?.toISOString() ?? null,
856
+ createdAt: row.createdAt.toISOString(),
857
+ updatedAt: row.updatedAt.toISOString(),
858
+ payload: row.payload
859
+ };
860
+ }
861
+ //# sourceMappingURL=service.js.map