@hogsend/engine 0.7.0 → 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.
Files changed (41) hide show
  1. package/package.json +7 -6
  2. package/src/app.ts +36 -1
  3. package/src/container.ts +80 -8
  4. package/src/destinations/define-destination.ts +104 -0
  5. package/src/destinations/presets/index.ts +94 -0
  6. package/src/destinations/presets/posthog.ts +71 -0
  7. package/src/destinations/presets/segment.ts +75 -0
  8. package/src/destinations/presets/slack.ts +66 -0
  9. package/src/destinations/presets/webhook.ts +37 -0
  10. package/src/destinations/registry-singleton.ts +78 -0
  11. package/src/env.ts +40 -0
  12. package/src/index.ts +59 -1
  13. package/src/journeys/define-journey.ts +26 -3
  14. package/src/journeys/journey-context.ts +1 -17
  15. package/src/lib/analytics-singleton.ts +7 -0
  16. package/src/lib/bucket-emit.ts +45 -0
  17. package/src/lib/contacts.ts +28 -6
  18. package/src/lib/mailer.ts +102 -0
  19. package/src/lib/outbound.ts +223 -0
  20. package/src/lib/preferences.ts +31 -0
  21. package/src/lib/seed-posthog-destination.ts +93 -0
  22. package/src/lib/tracked.ts +45 -3
  23. package/src/lib/tracking-events.ts +77 -10
  24. package/src/lib/webhook-signing.ts +152 -0
  25. package/src/routes/admin/contacts.ts +43 -3
  26. package/src/routes/admin/index.ts +2 -0
  27. package/src/routes/admin/webhooks.ts +557 -0
  28. package/src/routes/contacts/index.ts +48 -5
  29. package/src/routes/lists/index.ts +41 -5
  30. package/src/routes/tracking/click.ts +58 -22
  31. package/src/routes/tracking/open.ts +53 -22
  32. package/src/routes/webhooks/sources.ts +69 -10
  33. package/src/webhook-sources/define-webhook-source.ts +57 -5
  34. package/src/webhook-sources/presets/clerk.ts +185 -0
  35. package/src/webhook-sources/presets/index.ts +80 -0
  36. package/src/webhook-sources/presets/segment.ts +120 -0
  37. package/src/webhook-sources/presets/stripe.ts +147 -0
  38. package/src/webhook-sources/presets/supabase.ts +131 -0
  39. package/src/webhook-sources/verify.ts +172 -0
  40. package/src/worker.ts +6 -0
  41. package/src/workflows/deliver-webhook.ts +484 -0
@@ -0,0 +1,557 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { webhookDeliveries, webhookEndpoints } from "@hogsend/db";
3
+ import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
4
+ import { count, desc, eq } from "drizzle-orm";
5
+ import type { AppEnv } from "../../app.js";
6
+ import { PRESET_DESTINATIONS } from "../../destinations/presets/index.js";
7
+ import { errorSchema } from "../../lib/schemas.js";
8
+ import {
9
+ generateWebhookSecret,
10
+ WEBHOOK_EVENT_TYPES,
11
+ type WebhookEventType,
12
+ } from "../../lib/webhook-signing.js";
13
+ import { deliverWebhookTask } from "../../workflows/deliver-webhook.js";
14
+
15
+ /**
16
+ * Admin outbound-webhook management (Section 1.8). Mounted at
17
+ * `/v1/admin/webhooks`, it inherits `requireAdmin` + `rateLimit` +
18
+ * `auditMiddleware` from the admin router root — no per-route auth here.
19
+ *
20
+ * Secret-once invariant (LOCKED decision 1): the full `whsec_…` secret is
21
+ * returned ONLY on create + rotate-secret. `serializeEndpoint` NEVER includes
22
+ * it; list/get/patch expose `secretPrefix` only. Anything that returns the full
23
+ * secret is an explicit, audited create/rotate response.
24
+ */
25
+
26
+ // The catalog enum for request validation — derived from the SINGLE source of
27
+ // truth in `webhook-signing.ts` (Section 1.3). `z.enum` needs a non-empty tuple,
28
+ // which `WEBHOOK_EVENT_TYPES` (13 strings, `as const`) satisfies.
29
+ const eventTypeEnum = z.enum(
30
+ WEBHOOK_EVENT_TYPES as unknown as [WebhookEventType, ...WebhookEventType[]],
31
+ );
32
+
33
+ // The destination `kind` enum. "webhook" (default) is the signed POST; any
34
+ // other value selects a delivery-time transform adapter keyed by this column.
35
+ // This MUST cover every shipped preset (the skills + env.example tell operators
36
+ // to create segment/slack endpoints via this admin API / the `hs.webhooks` SDK),
37
+ // so it is derived from `PRESET_DESTINATIONS` — the single source of truth for
38
+ // the shipped `kind`s — rather than a hand-maintained literal list. A `kind`
39
+ // whose transform is not REGISTERED at delivery time still fails its delivery as
40
+ // a config error (DLQ); the registry, not the env, decides resolvability — so we
41
+ // accept any shipped preset id here regardless of `ENABLED_DESTINATION_PRESETS`.
42
+ const kindEnum = z.enum(
43
+ Object.keys(PRESET_DESTINATIONS) as unknown as [string, ...string[]],
44
+ );
45
+
46
+ const webhookEndpointSchema = z.object({
47
+ id: z.string(),
48
+ url: z.string(),
49
+ description: z.string().nullable(),
50
+ eventTypes: z.array(z.string()),
51
+ // Keyed destinations have no signing secret (null secretPrefix).
52
+ secretPrefix: z.string().nullable(),
53
+ kind: z.string(),
54
+ // REDACTED config view — credentials (e.g. config.apiKey) are masked.
55
+ config: z.record(z.string(), z.unknown()).nullable(),
56
+ status: z.enum(["enabled", "disabled"]),
57
+ organizationId: z.string().nullable(),
58
+ lastDeliveryAt: z.string().nullable(),
59
+ createdAt: z.string(),
60
+ updatedAt: z.string(),
61
+ });
62
+
63
+ const listRoute = createRoute({
64
+ method: "get",
65
+ path: "/",
66
+ tags: ["Admin — Webhooks"],
67
+ summary: "List outbound webhook endpoints",
68
+ request: {
69
+ query: z.object({
70
+ limit: z.coerce.number().min(1).max(100).default(50),
71
+ offset: z.coerce.number().min(0).default(0),
72
+ includeDisabled: z.enum(["true", "false"]).default("true"),
73
+ }),
74
+ },
75
+ responses: {
76
+ 200: {
77
+ content: {
78
+ "application/json": {
79
+ schema: z.object({
80
+ endpoints: z.array(webhookEndpointSchema),
81
+ total: z.number(),
82
+ limit: z.number(),
83
+ offset: z.number(),
84
+ }),
85
+ },
86
+ },
87
+ description: "Paginated webhook endpoint list (secret never included)",
88
+ },
89
+ },
90
+ });
91
+
92
+ const createEndpointRoute = createRoute({
93
+ method: "post",
94
+ path: "/",
95
+ tags: ["Admin — Webhooks"],
96
+ summary: "Create a webhook endpoint",
97
+ request: {
98
+ body: {
99
+ content: {
100
+ "application/json": {
101
+ schema: z.object({
102
+ url: z.string().url(),
103
+ eventTypes: z.array(eventTypeEnum).min(1),
104
+ description: z.string().max(500).optional(),
105
+ disabled: z.boolean().optional(),
106
+ // Destination selector. Defaults to "webhook" (signed POST).
107
+ kind: kindEnum.optional(),
108
+ // Per-destination config for keyed adapters (e.g. PostHog's
109
+ // `{ apiKey, host }`). Ignored for kind="webhook".
110
+ config: z.record(z.string(), z.unknown()).optional(),
111
+ }),
112
+ },
113
+ },
114
+ },
115
+ },
116
+ responses: {
117
+ 201: {
118
+ content: {
119
+ "application/json": {
120
+ // `secret` is present ONLY for kind="webhook" (the one-time signing
121
+ // secret). Keyed destinations carry no secret.
122
+ schema: webhookEndpointSchema.extend({
123
+ secret: z.string().optional(),
124
+ }),
125
+ },
126
+ },
127
+ description: "Endpoint created — signing secret shown only once",
128
+ },
129
+ },
130
+ });
131
+
132
+ const getEndpointRoute = createRoute({
133
+ method: "get",
134
+ path: "/{id}",
135
+ tags: ["Admin — Webhooks"],
136
+ summary: "Get a webhook endpoint",
137
+ request: {
138
+ params: z.object({ id: z.string().uuid() }),
139
+ },
140
+ responses: {
141
+ 200: {
142
+ content: {
143
+ "application/json": { schema: webhookEndpointSchema },
144
+ },
145
+ description: "Webhook endpoint (secret never included)",
146
+ },
147
+ 404: {
148
+ content: { "application/json": { schema: errorSchema } },
149
+ description: "Endpoint not found",
150
+ },
151
+ },
152
+ });
153
+
154
+ const updateEndpointRoute = createRoute({
155
+ method: "patch",
156
+ path: "/{id}",
157
+ tags: ["Admin — Webhooks"],
158
+ summary: "Update a webhook endpoint",
159
+ request: {
160
+ params: z.object({ id: z.string().uuid() }),
161
+ body: {
162
+ content: {
163
+ "application/json": {
164
+ schema: z.object({
165
+ url: z.string().url().optional(),
166
+ eventTypes: z.array(eventTypeEnum).min(1).optional(),
167
+ description: z.string().max(500).nullable().optional(),
168
+ disabled: z.boolean().optional(),
169
+ kind: kindEnum.optional(),
170
+ config: z.record(z.string(), z.unknown()).nullable().optional(),
171
+ }),
172
+ },
173
+ },
174
+ },
175
+ },
176
+ responses: {
177
+ 200: {
178
+ content: {
179
+ "application/json": { schema: webhookEndpointSchema },
180
+ },
181
+ description: "Updated webhook endpoint (secret never included)",
182
+ },
183
+ 404: {
184
+ content: { "application/json": { schema: errorSchema } },
185
+ description: "Endpoint not found",
186
+ },
187
+ },
188
+ });
189
+
190
+ const deleteEndpointRoute = createRoute({
191
+ method: "delete",
192
+ path: "/{id}",
193
+ tags: ["Admin — Webhooks"],
194
+ summary: "Delete a webhook endpoint",
195
+ request: {
196
+ params: z.object({ id: z.string().uuid() }),
197
+ },
198
+ responses: {
199
+ 200: {
200
+ content: {
201
+ "application/json": {
202
+ schema: z.object({ deleted: z.boolean() }),
203
+ },
204
+ },
205
+ description: "Endpoint hard-deleted (deliveries cascade)",
206
+ },
207
+ 404: {
208
+ content: { "application/json": { schema: errorSchema } },
209
+ description: "Endpoint not found",
210
+ },
211
+ },
212
+ });
213
+
214
+ const rotateSecretRoute = createRoute({
215
+ method: "post",
216
+ path: "/{id}/rotate-secret",
217
+ tags: ["Admin — Webhooks"],
218
+ summary: "Rotate a webhook endpoint's signing secret",
219
+ request: {
220
+ params: z.object({ id: z.string().uuid() }),
221
+ },
222
+ responses: {
223
+ 200: {
224
+ content: {
225
+ "application/json": {
226
+ schema: z.object({
227
+ id: z.string(),
228
+ secret: z.string(),
229
+ secretPrefix: z.string(),
230
+ }),
231
+ },
232
+ },
233
+ description: "New signing secret — shown only once (hard cutover)",
234
+ },
235
+ 404: {
236
+ content: { "application/json": { schema: errorSchema } },
237
+ description: "Endpoint not found",
238
+ },
239
+ },
240
+ });
241
+
242
+ const testRoute = createRoute({
243
+ method: "post",
244
+ path: "/{id}/test",
245
+ tags: ["Admin — Webhooks"],
246
+ summary: "Send a test event to a webhook endpoint",
247
+ request: {
248
+ params: z.object({ id: z.string().uuid() }),
249
+ },
250
+ responses: {
251
+ 202: {
252
+ content: {
253
+ "application/json": {
254
+ schema: z.object({
255
+ enqueued: z.boolean(),
256
+ eventType: z.literal("webhook.test"),
257
+ }),
258
+ },
259
+ },
260
+ description: "Out-of-band test event enqueued for delivery",
261
+ },
262
+ 404: {
263
+ content: { "application/json": { schema: errorSchema } },
264
+ description: "Endpoint not found",
265
+ },
266
+ },
267
+ });
268
+
269
+ /** Config keys whose values are credentials and must be masked in responses. */
270
+ const REDACTED_CONFIG_KEYS = new Set(["apiKey", "apikey", "api_key"]);
271
+
272
+ /**
273
+ * Mask credential values in a keyed destination's `config` for API responses —
274
+ * `config.apiKey` becomes `"***"` so a list/get never leaks the secret. Returns
275
+ * null when there is no config (kind="webhook").
276
+ */
277
+ function redactConfig(
278
+ config: Record<string, unknown> | null,
279
+ ): Record<string, unknown> | null {
280
+ if (!config) return null;
281
+ const out: Record<string, unknown> = {};
282
+ for (const [key, value] of Object.entries(config)) {
283
+ out[key] = REDACTED_CONFIG_KEYS.has(key) ? "***" : value;
284
+ }
285
+ return out;
286
+ }
287
+
288
+ /**
289
+ * Serialize an endpoint row for an API response. NEVER includes `secret` — the
290
+ * full `whsec_…` is surfaced only on create + rotate-secret via the dedicated
291
+ * response shapes. `config` is REDACTED (credentials masked). `status` is
292
+ * derived from the `disabled` boolean.
293
+ */
294
+ function serializeEndpoint(row: typeof webhookEndpoints.$inferSelect) {
295
+ return {
296
+ id: row.id,
297
+ url: row.url,
298
+ description: row.description,
299
+ eventTypes: row.eventTypes as string[],
300
+ secretPrefix: row.secretPrefix,
301
+ kind: row.kind,
302
+ config: redactConfig(row.config),
303
+ status: (row.disabled ? "disabled" : "enabled") as "enabled" | "disabled",
304
+ organizationId: row.organizationId,
305
+ lastDeliveryAt: row.lastDeliveryAt?.toISOString() ?? null,
306
+ createdAt: row.createdAt.toISOString(),
307
+ updatedAt: row.updatedAt.toISOString(),
308
+ };
309
+ }
310
+
311
+ export const webhooksRouter = new OpenAPIHono<AppEnv>()
312
+ .openapi(listRoute, async (c) => {
313
+ const { db } = c.get("container");
314
+ const { limit, offset, includeDisabled } = c.req.valid("query");
315
+
316
+ const where =
317
+ includeDisabled === "true"
318
+ ? undefined
319
+ : eq(webhookEndpoints.disabled, false);
320
+
321
+ const [rows, totalRows] = await Promise.all([
322
+ db
323
+ .select()
324
+ .from(webhookEndpoints)
325
+ .where(where)
326
+ .orderBy(desc(webhookEndpoints.createdAt))
327
+ .limit(limit)
328
+ .offset(offset),
329
+ db.select({ count: count() }).from(webhookEndpoints).where(where),
330
+ ]);
331
+
332
+ return c.json(
333
+ {
334
+ endpoints: rows.map(serializeEndpoint),
335
+ total: totalRows[0]?.count ?? 0,
336
+ limit,
337
+ offset,
338
+ },
339
+ 200,
340
+ );
341
+ })
342
+ .openapi(createEndpointRoute, async (c) => {
343
+ const { db } = c.get("container");
344
+ const body = c.req.valid("json");
345
+
346
+ const kind = body.kind ?? "webhook";
347
+ // Only the signed "webhook" kind gets a signing secret; keyed destinations
348
+ // authenticate via `config` (their secret/secretPrefix stay null).
349
+ const credentials =
350
+ kind === "webhook"
351
+ ? generateWebhookSecret()
352
+ : { secret: null, secretPrefix: null };
353
+
354
+ const [created] = await db
355
+ .insert(webhookEndpoints)
356
+ .values({
357
+ url: body.url,
358
+ eventTypes: body.eventTypes,
359
+ description: body.description ?? null,
360
+ disabled: body.disabled ?? false,
361
+ kind,
362
+ config: body.config ?? null,
363
+ secret: credentials.secret,
364
+ secretPrefix: credentials.secretPrefix,
365
+ })
366
+ .returning();
367
+
368
+ if (!created) throw new Error("Failed to create webhook endpoint");
369
+
370
+ // The ONLY list/get-shaped response that also carries the full secret — and
371
+ // ONLY for kind="webhook" (keyed destinations have no secret to surface).
372
+ if (kind === "webhook" && credentials.secret) {
373
+ return c.json(
374
+ { ...serializeEndpoint(created), secret: credentials.secret },
375
+ 201,
376
+ );
377
+ }
378
+ return c.json(serializeEndpoint(created), 201);
379
+ })
380
+ .openapi(getEndpointRoute, async (c) => {
381
+ const { db } = c.get("container");
382
+ const { id } = c.req.valid("param");
383
+
384
+ const [row] = await db
385
+ .select()
386
+ .from(webhookEndpoints)
387
+ .where(eq(webhookEndpoints.id, id))
388
+ .limit(1);
389
+
390
+ if (!row) {
391
+ return c.json({ error: "Webhook endpoint not found" }, 404);
392
+ }
393
+
394
+ return c.json(serializeEndpoint(row), 200);
395
+ })
396
+ .openapi(updateEndpointRoute, async (c) => {
397
+ const { db } = c.get("container");
398
+ const { id } = c.req.valid("param");
399
+ const body = c.req.valid("json");
400
+
401
+ const [existing] = await db
402
+ .select()
403
+ .from(webhookEndpoints)
404
+ .where(eq(webhookEndpoints.id, id))
405
+ .limit(1);
406
+
407
+ if (!existing) {
408
+ return c.json({ error: "Webhook endpoint not found" }, 404);
409
+ }
410
+
411
+ const patch: Partial<typeof webhookEndpoints.$inferInsert> = {
412
+ updatedAt: new Date(),
413
+ };
414
+ if (body.url !== undefined) patch.url = body.url;
415
+ if (body.eventTypes !== undefined) patch.eventTypes = body.eventTypes;
416
+ if (body.description !== undefined) patch.description = body.description;
417
+ if (body.disabled !== undefined) patch.disabled = body.disabled;
418
+ if (body.kind !== undefined) patch.kind = body.kind;
419
+ if (body.config !== undefined) patch.config = body.config;
420
+
421
+ // Foot-gun guard: an endpoint that ends up as a signed "webhook" with no
422
+ // secret would dead-letter every delivery (the webhook transform signs with
423
+ // the live secret). Mint one when switching to (or back to) kind="webhook"
424
+ // without an existing secret. Keyed kinds keep their null secret — harmless.
425
+ const effectiveKind = body.kind ?? existing.kind;
426
+ if (effectiveKind === "webhook" && !existing.secret) {
427
+ const { secret, secretPrefix } = generateWebhookSecret();
428
+ patch.secret = secret;
429
+ patch.secretPrefix = secretPrefix;
430
+ }
431
+
432
+ const [updated] = await db
433
+ .update(webhookEndpoints)
434
+ .set(patch)
435
+ .where(eq(webhookEndpoints.id, id))
436
+ .returning();
437
+
438
+ if (!updated) {
439
+ return c.json({ error: "Webhook endpoint not found" }, 404);
440
+ }
441
+
442
+ return c.json(serializeEndpoint(updated), 200);
443
+ })
444
+ .openapi(deleteEndpointRoute, async (c) => {
445
+ const { db } = c.get("container");
446
+ const { id } = c.req.valid("param");
447
+
448
+ // Hard delete (LOCKED: no soft-delete column). The FK cascade on
449
+ // `webhook_deliveries.endpoint_id` drops this endpoint's delivery rows.
450
+ const deleted = await db
451
+ .delete(webhookEndpoints)
452
+ .where(eq(webhookEndpoints.id, id))
453
+ .returning({ id: webhookEndpoints.id });
454
+
455
+ if (deleted.length === 0) {
456
+ return c.json({ error: "Webhook endpoint not found" }, 404);
457
+ }
458
+
459
+ return c.json({ deleted: true }, 200);
460
+ })
461
+ .openapi(rotateSecretRoute, async (c) => {
462
+ const { db } = c.get("container");
463
+ const { id } = c.req.valid("param");
464
+
465
+ const { secret, secretPrefix } = generateWebhookSecret();
466
+
467
+ // Hard cutover (LOCKED decision 10): the old secret is invalid immediately.
468
+ // The delivery task reads the LIVE endpoint secret, so in-flight deliveries
469
+ // re-sign with the new secret on their next attempt.
470
+ const [updated] = await db
471
+ .update(webhookEndpoints)
472
+ .set({ secret, secretPrefix, updatedAt: new Date() })
473
+ .where(eq(webhookEndpoints.id, id))
474
+ .returning({ id: webhookEndpoints.id });
475
+
476
+ if (!updated) {
477
+ return c.json({ error: "Webhook endpoint not found" }, 404);
478
+ }
479
+
480
+ return c.json({ id: updated.id, secret, secretPrefix }, 200);
481
+ })
482
+ .openapi(testRoute, async (c) => {
483
+ const { db, logger } = c.get("container");
484
+ const { id } = c.req.valid("param");
485
+
486
+ const [endpoint] = await db
487
+ .select()
488
+ .from(webhookEndpoints)
489
+ .where(eq(webhookEndpoints.id, id))
490
+ .limit(1);
491
+
492
+ if (!endpoint) {
493
+ return c.json({ error: "Webhook endpoint not found" }, 404);
494
+ }
495
+
496
+ // Out-of-band test (LOCKED decision 11): delivered regardless of the
497
+ // endpoint's `eventTypes`. Build a synthetic delivery row directly — it does
498
+ // NOT go through `emitOutbound` (which filters by subscription) — then enqueue
499
+ // the same durable delivery task the live emit path uses.
500
+ //
501
+ // The synthetic envelope routes THROUGH the per-kind delivery adapter (the
502
+ // delivery task resolves it by `endpoint.kind`), so the `data` must carry the
503
+ // fields every adapter needs to build a VALID request. For `kind="webhook"`
504
+ // the adapter only signs the frozen bytes, so the extra fields are harmless;
505
+ // for `kind="posthog"` the capture adapter coalesces `distinct_id` from
506
+ // `userId`/`to`/`userEmail`, so a synthetic recipient (`to`) is required or
507
+ // the test would POST a malformed capture with no distinct_id.
508
+ const webhookId = `msg_${randomUUID()}`;
509
+ const timestamp = new Date();
510
+ const envelope = {
511
+ id: webhookId,
512
+ type: "webhook.test" as const,
513
+ timestamp: timestamp.toISOString(),
514
+ data: {
515
+ message: "Hogsend test event",
516
+ endpointId: endpoint.id,
517
+ sentAt: timestamp.toISOString(),
518
+ // Adapter-friendly synthetic identity so a keyed destination (e.g.
519
+ // posthog) builds a valid request from the test envelope.
520
+ userId: `test_${endpoint.id}`,
521
+ to: "test@hogsend.com",
522
+ },
523
+ };
524
+
525
+ const [delivery] = await db
526
+ .insert(webhookDeliveries)
527
+ .values({
528
+ endpointId: endpoint.id,
529
+ organizationId: endpoint.organizationId,
530
+ webhookId,
531
+ eventType: "webhook.test",
532
+ dedupeKey: null,
533
+ payload: envelope,
534
+ status: "pending",
535
+ attemptCount: 0,
536
+ nextRetryAt: timestamp,
537
+ })
538
+ .returning({ id: webhookDeliveries.id });
539
+
540
+ if (!delivery) throw new Error("Failed to enqueue webhook test delivery");
541
+
542
+ // Enqueue-and-202 (LOCKED): tolerate a broker hiccup — the row is already
543
+ // `pending` with `nextRetryAt <= now`, so the reaper re-drives it. Enqueue
544
+ // fire-and-forget (mirrors the emit spine) so a slow/unreachable broker never
545
+ // blocks the 202; a failed enqueue is logged, not surfaced as an error.
546
+ void deliverWebhookTask
547
+ .runNoWait({ deliveryId: delivery.id })
548
+ .catch((error: unknown) => {
549
+ logger.warn("webhooks/test: deliverWebhookTask enqueue failed", {
550
+ endpointId: endpoint.id,
551
+ deliveryId: delivery.id,
552
+ error: error instanceof Error ? error.message : String(error),
553
+ });
554
+ });
555
+
556
+ return c.json({ enqueued: true, eventType: "webhook.test" as const }, 202);
557
+ });
@@ -2,10 +2,12 @@ import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
2
2
  import type { AppEnv } from "../../app.js";
3
3
  import {
4
4
  findContacts,
5
+ resolveContact,
5
6
  resolveOrCreateContact,
6
7
  serializeContact,
7
8
  softDeleteContact,
8
9
  } from "../../lib/contacts.js";
10
+ import { emitOutbound } from "../../lib/outbound.js";
9
11
  import { applyListMembership } from "../../lib/preferences.js";
10
12
  import { errorSchema } from "../../lib/schemas.js";
11
13
  import { listMembershipError, requireIdentity } from "../_shared.js";
@@ -130,19 +132,44 @@ const deleteRoute = createRoute({
130
132
 
131
133
  export const contactsRouter = new OpenAPIHono<AppEnv>()
132
134
  .openapi(upsertRoute, async (c) => {
133
- const { db } = c.get("container");
135
+ const { db, hatchet, logger } = c.get("container");
134
136
  const body = c.req.valid("json");
135
137
 
136
138
  const guard = requireIdentity(c, body);
137
139
  if (guard) return guard;
138
140
 
139
- const { id, created, linked } = await resolveOrCreateContact({
141
+ const { id, created, linked, merged } = await resolveOrCreateContact({
140
142
  db,
141
143
  userId: body.userId,
142
144
  email: body.email,
143
145
  contactProperties: body.properties,
144
146
  });
145
147
 
148
+ // INTENT-LAYER outbound emit (decision #3): fire `contact.created` on a real
149
+ // creation, `contact.updated` only when an existing contact was linked/merged
150
+ // AND the request carried a non-empty property delta — NEVER inside
151
+ // `resolveOrCreateContact` (which runs on every event → would emit on every
152
+ // pageview). The emit is fire-and-forget; a read-back serializes the full
153
+ // contact payload the catalog expects.
154
+ const hadPropertyDelta = Boolean(
155
+ body.properties && Object.keys(body.properties).length > 0,
156
+ );
157
+ if (created || (linked || merged ? hadPropertyDelta : false)) {
158
+ const event = created ? "contact.created" : "contact.updated";
159
+ void resolveContact({ db, id })
160
+ .then((row) => {
161
+ if (!row) return;
162
+ return emitOutbound({
163
+ db,
164
+ hatchet,
165
+ logger,
166
+ event,
167
+ payload: serializeContact(row),
168
+ });
169
+ })
170
+ .catch(logger.warn);
171
+ }
172
+
146
173
  // Lists applied AFTER the resolve so the contact exists (§2.5 lists
147
174
  // ordering). `applyListMembership` requires a resolvable email — surface the
148
175
  // "no email" case as a 400 rather than a 500.
@@ -173,16 +200,32 @@ export const contactsRouter = new OpenAPIHono<AppEnv>()
173
200
  return c.json({ contacts: rows.map((row) => serializeContact(row)) }, 200);
174
201
  })
175
202
  .openapi(deleteRoute, async (c) => {
176
- const { db } = c.get("container");
203
+ const { db, hatchet, logger } = c.get("container");
177
204
  const { email, userId } = c.req.valid("json");
178
205
 
179
206
  const guard = requireIdentity(c, { email, userId });
180
207
  if (guard) return guard;
181
208
 
182
- const deleted = await softDeleteContact({ db, email, userId });
183
- if (!deleted) {
209
+ const result = await softDeleteContact({ db, email, userId });
210
+ if (!result.deleted) {
184
211
  return c.json({ error: "Contact not found" }, 404);
185
212
  }
186
213
 
214
+ // The widened `softDeleteContact` returns the deleted row's identity so the
215
+ // `contact.deleted` outbound webhook carries it without a second read-back.
216
+ if (result.id) {
217
+ void emitOutbound({
218
+ db,
219
+ hatchet,
220
+ logger,
221
+ event: "contact.deleted",
222
+ payload: {
223
+ id: result.id,
224
+ externalId: result.externalId ?? null,
225
+ email: result.email ?? null,
226
+ },
227
+ }).catch(logger.warn);
228
+ }
229
+
187
230
  return c.json({ deleted: true as const }, 200);
188
231
  });